content stringlengths 1 1.04M | input_ids listlengths 1 774k | ratio_char_token float64 0.38 22.9 | token_count int64 1 774k |
|---|---|---|---|
from bs4 import BeautifulSoup
import requests
import nltk
from nltk import sent_tokenize
from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords
from nltk.probability import FreqDist
from collections import Counter
from nltk import Tree
import re
'''
url = 'https://www.lifewire.com/how-to-edit-videos-on-android-4770052'
print("From URL:",url,"\n")
r = requests.get(url)
s = BeautifulSoup(r.content, 'html.parser')
ol_read = [tag.text for tag in s.find_all('ol')]
ol = [m+'' for m in ol_read]
ol_list = "".join(ol)
with open('D:\instructions.txt', 'w') as file:
file.write(ol_list)
file = open("D:\instructions.txt").read()
sent = nltk.sent_tokenize(file)
ls=len(sent)
with open('D:\out.txt', 'w') as outfile:
outfile.write("\n".join(sent))
'''
with open('D:\out1.txt', 'r') as outfile:
o=outfile.readlines()
for i in range(len(o)):
tokens = nltk.word_tokenize(o[i])
words = [word for word in tokens if word.isalpha()]
stop_words = set(stopwords.words('english'))
words = [w for w in words if not w in stop_words]
p=nltk.pos_tag(words)
#print(p)
nes = nltk.ne_chunk(p)
#print(nes)
#print ("Line No-",i)
print('\nInstruction')
print (o[i])
#print (o[i].startswith('Tap'))
first_word = o[i].split()
first = first_word[:2]
print('Action-phrase')
print(first)
n=nltk.pos_tag(first)
#print(n)
'''
op = list(filter(lambda x:x[1]=='VB',p))
print("Operations:",op,"\n")
obj = list(filter(lambda x:x[1]=='NN',p))
print("Objects:",obj,"\n")
for word, tag in n:
if tag in ('VB'):
i
print (o[i])
print("Line No-",i," => Instruction")
else:
i
print (o[i])
print("Line No-",i," => Not an Instruction")
t=o[i].startswith('Tap')
print(t)
if o[i].startswith("Tap")==True:
i
#print("Line No-",i," = Instruction \n")
#print(o[i])
if o[i].startswith("Add")==True:
i
#print("Line No-",i," = Instruction \n")
#print(o[i])
if o[i].startswith("Open")==True:
i
#print("Line No-",i," = Instruction \n")
#print(o[i])
p=nltk.pos_tag(words)
print(p)
pattern = """NP: {<DT>?<JJ>*<NN>}
VBD: {<VBD>}
IN: {<IN>}"""
NPChunker = nltk.RegexpParser(pattern)
result = NPChunker.parse(p)
print(result)
#print(result.leaves())
#result.draw()
'''
| [
6738,
275,
82,
19,
1330,
23762,
50,
10486,
198,
11748,
7007,
198,
11748,
299,
2528,
74,
198,
6738,
299,
2528,
74,
1330,
1908,
62,
30001,
1096,
198,
6738,
299,
2528,
74,
13,
30001,
1096,
1330,
1573,
62,
30001,
1096,
198,
6738,
299,
2... | 2.078086 | 1,191 |
import pytest
@pytest.fixture
@pytest.fixture
| [
11748,
12972,
9288,
628,
198,
31,
9078,
9288,
13,
69,
9602,
628,
198,
31,
9078,
9288,
13,
69,
9602,
198
] | 2.5 | 20 |
# Getting all the elements in a list — a better way, using a "for" loop
shopping_list = ["Tomatoes", "Bananas", "Crackers",
"Sugar", "Icecream", "Bread", "Bananas", "Chocolate"]
print("Shopping list:")
for item in shopping_list:
print(item)
| [
198,
2,
18067,
477,
262,
4847,
287,
257,
1351,
851,
257,
1365,
835,
11,
1262,
257,
366,
1640,
1,
9052,
198,
198,
1477,
33307,
62,
4868,
796,
14631,
13787,
15048,
1600,
366,
30457,
15991,
1600,
366,
13916,
28874,
1600,
198,
220,
220,
... | 2.582524 | 103 |
#
# PySNMP MIB module A3COM-SWITCHING-SYSTEMS-POLL-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/A3COM-SWITCHING-SYSTEMS-POLL-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:08:25 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
OctetString, Integer, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "OctetString", "Integer", "ObjectIdentifier")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ConstraintsUnion, ValueRangeConstraint, ConstraintsIntersection, SingleValueConstraint, ValueSizeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsUnion", "ValueRangeConstraint", "ConstraintsIntersection", "SingleValueConstraint", "ValueSizeConstraint")
ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup")
Gauge32, ModuleIdentity, TimeTicks, Unsigned32, Integer32, Counter32, NotificationType, MibScalar, MibTable, MibTableRow, MibTableColumn, Counter64, MibIdentifier, ObjectIdentity, iso, NotificationType, Bits, enterprises, IpAddress = mibBuilder.importSymbols("SNMPv2-SMI", "Gauge32", "ModuleIdentity", "TimeTicks", "Unsigned32", "Integer32", "Counter32", "NotificationType", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Counter64", "MibIdentifier", "ObjectIdentity", "iso", "NotificationType", "Bits", "enterprises", "IpAddress")
TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString")
a3Com = MibIdentifier((1, 3, 6, 1, 4, 1, 43))
switchingSystemsMibs = MibIdentifier((1, 3, 6, 1, 4, 1, 43, 29))
a3ComSwitchingSystemsMib = MibIdentifier((1, 3, 6, 1, 4, 1, 43, 29, 4))
a3ComPoll = MibIdentifier((1, 3, 6, 1, 4, 1, 43, 29, 4, 22))
a3ComPollTable = MibTable((1, 3, 6, 1, 4, 1, 43, 29, 4, 22, 1), )
if mibBuilder.loadTexts: a3ComPollTable.setStatus('mandatory')
if mibBuilder.loadTexts: a3ComPollTable.setDescription('This table is used to provide remote device monitoring facilities. The implementation allows a list of network devices to be set up and polled regularly (or only once) by a variety of protocols. The table can be configured to inform the management station(s) of devices that are not responding to polls or that have started to respond after a period of silence. The minimum effort required to do a single poll is 1. In one packet, write the address and set a3ComPollAction to activate(2). 2. In the next packet, read the a3ComPollReport. The minimum effort required to monitor a device is 1. In one packet, write the address, set a3ComPollAttempts to 1, set a3ComPollCount to 0 and set a3ComPollAction to activate(2). 2. Wait for traps to come in. A row in this table is created by setting any read-write member, indexed by the next available index (a3ComPollNextFreeIndex). This method of creation makes the table very user friendly, although a bit harder to detect racing conditions. The suggested method for racing condition detection is by checking the a3ComPollAddress and a3ComPollOwner objects while the a3ComPollReport object is set to active. An example of the indexing of this table is a3ComPollRate.2')
a3ComPollEntry = MibTableRow((1, 3, 6, 1, 4, 1, 43, 29, 4, 22, 1, 1), ).setIndexNames((0, "A3COM-SWITCHING-SYSTEMS-POLL-MIB", "a3ComPollIndex"))
if mibBuilder.loadTexts: a3ComPollEntry.setStatus('mandatory')
if mibBuilder.loadTexts: a3ComPollEntry.setDescription('A table used to define device monitoring. A row in this table is created by setting any read-write member, indexed by the next available index (a3ComPollNextFreeIndex). An entry in this table is deleted by setting a3ComPollAction to destroy(5). An example of the indexing of this table is a3ComPollRate.2 This method of creation makes the table very user friendly, although a bit harder to detect racing conditions. The suggested method for racing condition detection is by checking the a3ComPollAddress and a3ComPollOwner objects while the a3ComPollReport object is set to active.')
a3ComPollIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 29, 4, 22, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 255))).setMaxAccess("readonly")
if mibBuilder.loadTexts: a3ComPollIndex.setStatus('mandatory')
if mibBuilder.loadTexts: a3ComPollIndex.setDescription('Unique identifier of a row in the Poll Table. The actual number of rows that can be created on any particular device depends on the memory and processing resources available at the time.')
a3ComPollAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 29, 4, 22, 1, 1, 2), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 50))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: a3ComPollAddress.setStatus('mandatory')
if mibBuilder.loadTexts: a3ComPollAddress.setDescription("This DisplayString is the network address of the device to monitor. Typically this is an IP, dotted IP format, IP's hostname, IPX or AppleTalk. The following formats can be used: IP cccc - ipAddress MIB IP nnn.nnn.nnn.nnn - dotted format IP hostname IPX AABBCCDD:AABBCCDDEEFF - network : node AppleTalk n[...].n[...] - dotted notation The object a3ComPollAddressType is used to indicate how this object will be interpreted. This object may not be modified if the associated a3ComPollReport is equal to busy(2). When this object is successfully set, a3ComPollReport will be set to idle(1).")
a3ComPollAddressType = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 29, 4, 22, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6))).clone(namedValues=NamedValues(("unknown", 1), ("ip", 2), ("ipdotted", 3), ("ipname", 4), ("ipx", 5), ("appletalk", 6))).clone('unknown')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: a3ComPollAddressType.setStatus('mandatory')
if mibBuilder.loadTexts: a3ComPollAddressType.setDescription('This defines the method used to interpret the a3ComPollAddress, which implies on the protocol to be used. Writing an address to the a3ComPollAddress object causes a default a3ComPollAddressType value to be setup. The default value is derived from the format of the address - four octets means ip(2), four sets of numeric values separated by dot means ipdotted(3), eight and twelve octets separated by colon means ipx(5), and two sets of numeric values separated by a dot means appletalk(6). If the address type cannot be figured out, and this object is not currently set to ipname(4), it will then be set to unknown(1). In other words, this object will remain unchanged if its current value is ipname(4) and a more specific type cannot be given to it. Thus, for the mot part, when setting this object manually, that needs to be done after setting a3ComPollAddress. For ip hostname(4), this field must be set manually. Furthermore, DNS client must be locally enabled to allow for conversion from name to ip address. If the requested protocol is not supported or is not compatible with the a3ComPollAddress, an error is returned when an attempt is made to set a3ComPollAction to activate(2), and a3ComPollReport will be set to noResource(4). This object may not be modified if the associated a3ComPollReport is equal to busy(2). When this object is successfully set, a3ComPollReport will be set to idle(1).')
a3ComPollCount = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 29, 4, 22, 1, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 9999)).clone(1)).setMaxAccess("readwrite")
if mibBuilder.loadTexts: a3ComPollCount.setStatus('mandatory')
if mibBuilder.loadTexts: a3ComPollCount.setDescription('This integer is the number of ping packets to be sent out until completion of a polling command. If count is set to continuous(0), the remote device will be kept monitored and the a3ComPollReport will be normally set to busy(2) upon poll activation. This object may not be modified if the associated a3ComPollReport is equal to busy(2). When this object is successfully set, a3ComPollReport will be set to idle(1).')
a3ComPollAttempts = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 29, 4, 22, 1, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 255))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: a3ComPollAttempts.setStatus('mandatory')
if mibBuilder.loadTexts: a3ComPollAttempts.setDescription('The number of unsuccessful or successful requests necessary before deciding that the device is definitely not responding or responding. In order to use traps, a value greater than one must be used. Conversely, a value of zero, which is the default, would imply that traps are disabled. This object may not be modified if the associated a3ComPollReport object is equal to busy(2). When this object is successfully set, a3ComPollReport will be set to idle(1).')
a3ComPollRate = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 29, 4, 22, 1, 1, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 5400)).clone(3)).setMaxAccess("readwrite")
if mibBuilder.loadTexts: a3ComPollRate.setStatus('mandatory')
if mibBuilder.loadTexts: a3ComPollRate.setDescription('This defines how often, in seconds, a poll packet is sent to the device being polled. If burst mode(0) is chosen, then number of packets selected will be sent out as fast as possible when the a3ComPollAction is set to activate(2). Common values the a3ComPollRate can be set to: every 3 seconds (3) default every minute (60) every 5 minutes (300) every 15 minutes (900) every 30 minutes (1800) every hour (3600) This object may not be modified if the associated a3ComPollReport is equal to busy(2). When this object is successfully set, a3ComPollReport will be set to idle(1).')
a3ComPollResponseTimeOut = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 29, 4, 22, 1, 1, 7), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: a3ComPollResponseTimeOut.setStatus('mandatory')
if mibBuilder.loadTexts: a3ComPollResponseTimeOut.setDescription('Maximum wait time, in msecs, for a response packet before deciding that no response arrived. This object differs from a3ComPollRate as the device have the sending and receiving queues independent, making it possible to send ping requests at rates faster than receiving. The value of 0 (default) will be interpreted as a request for time-out by the time a new packet is sent, and 65535 as a request for maximum wait. Assuming that burst is used and this object is set to one, most likely all packets sent will be interpreted as timed out. This object may not be modified if the associated a3ComPollReport is equal to busy(2). When this object is successfully set, a3ComPollReport will be set to idle(1).')
a3ComPollPacketSize = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 29, 4, 22, 1, 1, 8), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 8191))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: a3ComPollPacketSize.setStatus('mandatory')
if mibBuilder.loadTexts: a3ComPollPacketSize.setDescription('Size, in bytes, of ping packet to be sent out. If set to 0, the default size for ping packet under the protocol chosen will be used. If value given is to too large or too small, the biggest or smallest possible packets will be used, respectively, and no errors will be issued. This object may not be modified if the associated a3ComPollReport is equal to busy(2). When this object is successfully set, a3ComPollReport will be set to idle(1).')
a3ComPollSourceAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 29, 4, 22, 1, 1, 9), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 50))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: a3ComPollSourceAddress.setStatus('mandatory')
if mibBuilder.loadTexts: a3ComPollSourceAddress.setDescription('This DisplayString is the network address of the local interface to receive ping query. Typically this is an IP, IPX or AppleTalk. The following formats can be used. IP cccc - ipAddress MIB IP nnn.nnn.nnn.nnn - dotted format IPX AABBCCDD:AABBCCDDEEFF - network : node AppleTalk n[...].n[...] - dotted notation If a3ComPollSourceAddress is set to empty, which is the default value, the sending device will pick the best interface to receive the response for its queries. The object a3ComPollAddressType is used to indicate how this object will be interpreted, as well as a3ComPollAddress. An exception exists when a3ComPollAddressType is set to ipname(4): this object will be parsed as if a3ComPollAddressType was set to ip(2) or as ipdotted(3), depending on the length of the object value. Therefore, ip name is not supported for a3ComPollSourceAddress. This object may not be modified if the associated a3ComPollReport is equal to busy(2). When this object is successfully set, a3ComPollReport will be set to idle(1).')
a3ComPollMinRoundTripTime = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 29, 4, 22, 1, 1, 10), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: a3ComPollMinRoundTripTime.setStatus('mandatory')
if mibBuilder.loadTexts: a3ComPollMinRoundTripTime.setDescription('The minimum amount of time taken, in msecs, for the round trip of a ping packet.')
a3ComPollAvgRoundTripTime = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 29, 4, 22, 1, 1, 11), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: a3ComPollAvgRoundTripTime.setStatus('mandatory')
if mibBuilder.loadTexts: a3ComPollAvgRoundTripTime.setDescription('The average amount of time taken, in msecs, for the round trip of a ping packet.')
a3ComPollMaxRoundTripTime = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 29, 4, 22, 1, 1, 12), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: a3ComPollMaxRoundTripTime.setStatus('mandatory')
if mibBuilder.loadTexts: a3ComPollMaxRoundTripTime.setDescription('The maximum amount of time taken, in msecs, for the round trip of a ping packet.')
a3ComPollFramesSent = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 29, 4, 22, 1, 1, 13), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: a3ComPollFramesSent.setStatus('mandatory')
if mibBuilder.loadTexts: a3ComPollFramesSent.setDescription('The number of ping packets sent to remote device so far.')
a3ComPollFramesReceived = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 29, 4, 22, 1, 1, 14), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: a3ComPollFramesReceived.setStatus('mandatory')
if mibBuilder.loadTexts: a3ComPollFramesReceived.setDescription('The number of ping packets responded by remote device so far. If a3ComPollResponseTimeOut is a non-zero value, and the poll response arrives after the specified timeout, this object will not increment.')
a3ComPollInformation = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 29, 4, 22, 1, 1, 15), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 255))).setMaxAccess("readonly")
if mibBuilder.loadTexts: a3ComPollInformation.setStatus('mandatory')
if mibBuilder.loadTexts: a3ComPollInformation.setDescription('Depending on the protocol being used, this object contains extra information obtained through the device poll. For IP, the value is the number of packets that arrived out of sequence. If Apple Talk is used, this value represents the number of hops. An empty string, which is the default, stands for no extra information available. This object will reset every time a change is observed on a3ComPollAddressType.')
a3ComPollOwner = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 29, 4, 22, 1, 1, 16), DisplayString()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: a3ComPollOwner.setStatus('mandatory')
if mibBuilder.loadTexts: a3ComPollOwner.setDescription('The RMON OwnerString conventions are used here to help control the multi-manager situations.')
a3ComPollReport = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 29, 4, 22, 1, 1, 17), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8))).clone(namedValues=NamedValues(("idle", 1), ("busy", 2), ("badArgument", 3), ("noResource", 4), ("nameLookupFailed", 5), ("hostAlive", 6), ("hostUnreachable", 7), ("hostNotResponding", 8)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: a3ComPollReport.setStatus('mandatory')
if mibBuilder.loadTexts: a3ComPollReport.setDescription('This integer contains the current status of the poll entry. When the state changes from busy to any other, the entry is no longer active. In situations where the a3ComPollCount field is set to continuous(0), this object will normally be set to busy(2) upon successful activation.')
a3ComPollAction = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 29, 4, 22, 1, 1, 18), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5))).clone(namedValues=NamedValues(("noop", 1), ("activate", 2), ("deactivate", 3), ("reset", 4), ("destroy", 5))).clone('noop')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: a3ComPollAction.setStatus('mandatory')
if mibBuilder.loadTexts: a3ComPollAction.setDescription('This object is the trigger for initiating, stopping, resetting and destroying a poll entry. In order to read the current status of an entry, a3ComPollReport is the object to be queried. If reset(4) action is requested, the poll entry will unconditionally be moved to the idle(1) state and all objects, except for the pollAddress and pollAddressType will be set to initial values. Another object that is not affected by reset(4) is the owner object. Activating an entry that is in the busy(2) state has no effect.')
a3ComPollNextFreeIndex = MibScalar((1, 3, 6, 1, 4, 1, 43, 29, 4, 22, 2), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: a3ComPollNextFreeIndex.setStatus('mandatory')
if mibBuilder.loadTexts: a3ComPollNextFreeIndex.setDescription('The index for the next available remote polling entry in the table.')
a3ComPollTableInformation = MibScalar((1, 3, 6, 1, 4, 1, 43, 29, 4, 22, 3), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 255))).setMaxAccess("readonly")
if mibBuilder.loadTexts: a3ComPollTableInformation.setStatus('mandatory')
if mibBuilder.loadTexts: a3ComPollTableInformation.setDescription('This object provides a summary on the entire poll table. Internal thresholds, such as the maximum number of entries, as well the number of entries that can be active simultaneously are commonly provided here. Another information that can be given is the list of protocols the agent can handle. An empty string for a3ComPollTableInformation stands for no table information available.')
a3ComPollTableActionAll = MibScalar((1, 3, 6, 1, 4, 1, 43, 29, 4, 22, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5))).clone(namedValues=NamedValues(("noop", 1), ("activate", 2), ("deactivate", 3), ("reset", 4), ("destroy", 5))).clone('noop')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: a3ComPollTableActionAll.setStatus('mandatory')
if mibBuilder.loadTexts: a3ComPollTableActionAll.setDescription('This object works exactly as a3ComPollAction, except that it affects every entry in the table, in one snmp transaction. If a3ComPollTableActionAll is called with destroy(5), the table is purged.')
a3ComPollResponseReceived = NotificationType((1, 3, 6, 1, 4, 1, 43, 29, 4) + (0,61)).setObjects(("A3COM-SWITCHING-SYSTEMS-POLL-MIB", "a3ComPollAddress"), ("A3COM-SWITCHING-SYSTEMS-POLL-MIB", "a3ComPollAddressType"), ("A3COM-SWITCHING-SYSTEMS-POLL-MIB", "a3ComPollAttempts"), ("A3COM-SWITCHING-SYSTEMS-POLL-MIB", "a3ComPollRate"), ("A3COM-SWITCHING-SYSTEMS-POLL-MIB", "a3ComPollFramesSent"), ("A3COM-SWITCHING-SYSTEMS-POLL-MIB", "a3ComPollFramesReceived"))
if mibBuilder.loadTexts: a3ComPollResponseReceived.setDescription('This trap is generated when the PollTable in the managed agent receives replies to a poll after a sequence of unsuccessful polls. The number of packets in such sequence is determined from the a3ComPollAttempts object. The variables are: a3ComPollAddress - the address of the device polled. a3ComPollAddressType - the type of the address above. a3ComPollAttempts - number of replies received in sequence before this trap was triggered. a3ComPollRate - rate at which device is being polled. 0 = burst. a3ComPollFramesSent - total number of frames sent. a3ComPollFramesReceived - total number of frames received. This event is generated at most once per monitored device per operation of a sequence of ping response when the event is first observed.')
a3ComPollResponseNotReceived = NotificationType((1, 3, 6, 1, 4, 1, 43, 29, 4) + (0,62)).setObjects(("A3COM-SWITCHING-SYSTEMS-POLL-MIB", "a3ComPollAddress"), ("A3COM-SWITCHING-SYSTEMS-POLL-MIB", "a3ComPollAddressType"), ("A3COM-SWITCHING-SYSTEMS-POLL-MIB", "a3ComPollAttempts"), ("A3COM-SWITCHING-SYSTEMS-POLL-MIB", "a3ComPollRate"), ("A3COM-SWITCHING-SYSTEMS-POLL-MIB", "a3ComPollFramesSent"), ("A3COM-SWITCHING-SYSTEMS-POLL-MIB", "a3ComPollFramesReceived"))
if mibBuilder.loadTexts: a3ComPollResponseNotReceived.setDescription('This trap is generated when the PollTable in the managed agent receives no replies to a poll after a sequence of successful polls. The number of packets in such sequence is determined from the a3ComPollAttempts object. The variables are: a3ComPollAddress - the address of the device polled. a3ComPollAddressType - the type of the address above. a3ComPollAttempts - number of replies missed in sequence before this trap was triggered. a3ComPollRate - rate at which device is being polled. 0 = burst. a3ComPollFramesSent - total number of frames sent. a3ComPollFramesReceived - total number of frames received. This event is generated at most once per monitored device per operation of a sequence of ping fails when the event is first observed.')
mibBuilder.exportSymbols("A3COM-SWITCHING-SYSTEMS-POLL-MIB", a3ComPollAvgRoundTripTime=a3ComPollAvgRoundTripTime, a3ComPollIndex=a3ComPollIndex, a3ComPollFramesReceived=a3ComPollFramesReceived, a3ComPollFramesSent=a3ComPollFramesSent, a3ComPollEntry=a3ComPollEntry, a3ComPollMinRoundTripTime=a3ComPollMinRoundTripTime, a3ComSwitchingSystemsMib=a3ComSwitchingSystemsMib, a3ComPollResponseReceived=a3ComPollResponseReceived, a3ComPollInformation=a3ComPollInformation, a3ComPollReport=a3ComPollReport, a3ComPoll=a3ComPoll, a3ComPollSourceAddress=a3ComPollSourceAddress, a3ComPollRate=a3ComPollRate, a3ComPollAddressType=a3ComPollAddressType, a3ComPollOwner=a3ComPollOwner, a3ComPollResponseTimeOut=a3ComPollResponseTimeOut, a3ComPollNextFreeIndex=a3ComPollNextFreeIndex, a3ComPollTableActionAll=a3ComPollTableActionAll, a3ComPollTableInformation=a3ComPollTableInformation, a3ComPollCount=a3ComPollCount, a3ComPollMaxRoundTripTime=a3ComPollMaxRoundTripTime, a3ComPollAction=a3ComPollAction, a3ComPollAttempts=a3ComPollAttempts, a3ComPollResponseNotReceived=a3ComPollResponseNotReceived, a3ComPollTable=a3ComPollTable, switchingSystemsMibs=switchingSystemsMibs, a3ComPollAddress=a3ComPollAddress, a3Com=a3Com, a3ComPollPacketSize=a3ComPollPacketSize)
| [
2,
198,
2,
9485,
15571,
7378,
337,
9865,
8265,
317,
18,
9858,
12,
17887,
31949,
2751,
12,
23060,
25361,
50,
12,
16402,
3069,
12,
8895,
33,
357,
4023,
1378,
16184,
76,
489,
8937,
13,
785,
14,
79,
893,
11632,
8,
198,
2,
7054,
45,
... | 3.317594 | 6,883 |
# -- coding: utf-8 --
import argparse
if __name__=='__main__':
para=parameter(argparse.ArgumentParser())
print(para.get_para().batch_size) | [
2,
1377,
19617,
25,
3384,
69,
12,
23,
1377,
198,
11748,
1822,
29572,
198,
198,
361,
11593,
3672,
834,
855,
6,
834,
12417,
834,
10354,
198,
220,
220,
220,
31215,
28,
17143,
2357,
7,
853,
29572,
13,
28100,
1713,
46677,
28955,
628,
220... | 2.508475 | 59 |
from typing import List, Literal, Union
from botoy import FriendMsg, GroupMsg
from pydantic import BaseModel, Field
| [
6738,
19720,
1330,
7343,
11,
25659,
1691,
11,
4479,
198,
198,
6738,
10214,
726,
1330,
9182,
50108,
11,
4912,
50108,
198,
6738,
279,
5173,
5109,
1330,
7308,
17633,
11,
7663,
628
] | 3.806452 | 31 |
import numpy as np
from tensorflow.keras.utils import Sequence, to_categorical
import random
from tqdm import tqdm
from transforms import jitter, time_warp, rotation, rand_sampling
from transforms import get_ENMO, get_angle_z, get_LIDS
from collections import Counter
| [
11748,
299,
32152,
355,
45941,
198,
6738,
11192,
273,
11125,
13,
6122,
292,
13,
26791,
1330,
45835,
11,
284,
62,
66,
2397,
12409,
198,
11748,
4738,
198,
6738,
256,
80,
36020,
1330,
256,
80,
36020,
198,
6738,
31408,
1330,
474,
1967,
11... | 3.435897 | 78 |
# -*- coding: utf-8 -*-
# Copyright 2017 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Send swarming-proxy latency monitoring data to ts_mon."""
from __future__ import absolute_import
from __future__ import print_function
import sys
import time
from chromite.cbuildbot import commands
from chromite.cbuildbot import swarming_lib
from chromite.lib import commandline
from chromite.lib import cros_build_lib
from chromite.lib import metrics
from chromite.lib import timeout_util
from chromite.lib import ts_mon_config
assert sys.version_info >= (3, 6), 'This module requires Python 3.6+'
if __name__ == '__main__':
main(sys.argv)
| [
2,
532,
9,
12,
19617,
25,
3384,
69,
12,
23,
532,
9,
12,
198,
2,
15069,
2177,
383,
18255,
1505,
7294,
46665,
13,
1439,
2489,
10395,
13,
198,
2,
5765,
286,
428,
2723,
2438,
318,
21825,
416,
257,
347,
10305,
12,
7635,
5964,
326,
46... | 3.371041 | 221 |
import logging
logger = logging.getLogger(__name__)
NAME = 'Common Components'
INSTALL = ('AccountsSite',)
__version__ = '3.5.5'
logger.debug('"%s"/"%s"' % (NAME, __version__))
| [
11748,
18931,
198,
198,
6404,
1362,
796,
18931,
13,
1136,
11187,
1362,
7,
834,
3672,
834,
8,
198,
198,
20608,
796,
705,
17227,
36109,
6,
198,
38604,
7036,
796,
19203,
30116,
82,
29123,
3256,
8,
198,
198,
834,
9641,
834,
796,
705,
18... | 2.513889 | 72 |
import numpy as np
import matplotlib.pyplot as plt
INTERVAL = 30
WINDOW = 5
data_gamma = read_avg_speed('statistics.gamma.log')
data_simple = read_avg_speed('statistics.ttc.log')
fig, axs = plt.subplots(figsize=(17.5, 8))
axs.set_xlabel('Simulation Time (s)', fontsize=34)
axs.set_ylabel('Average Speed (m/s)', fontsize=34)
plt.xlim(0, 1200)
plt.ylim(0, 6)
plt.rc('legend',fontsize=26)
axs.tick_params(axis='x', labelsize=32)
axs.tick_params(axis='y', labelsize=32)
# GAMMA Car.
axs.plot(
[x[0] for x in data_gamma],
[x[1] for x in data_gamma],
label='Car (C-GAMMA)',
color='red',
linestyle='solid',
linewidth=3)
# TTC Car.
axs.plot(
[x[0] for x in data_simple],
[x[1] for x in data_simple],
label='Car (TTC)',
color='red',
linestyle=(0, (5, 5)),
linewidth=3)
# GAMMA Bike.
axs.plot(
[x[0] for x in data_gamma],
[x[2] for x in data_gamma],
label='Bike (C-GAMMA)',
color='green',
linestyle='solid',
linewidth=3)
# TTC Bike.
axs.plot(
[x[0] for x in data_simple],
[x[2] for x in data_simple],
label='Bike (TTC)',
color='green',
linestyle=(0, (5, 5)),
linewidth=3)
# GAMMA Pedestrian.
axs.plot(
[x[0] for x in data_gamma],
[x[3] for x in data_gamma],
label='Pedestrian (C-GAMMA)',
color='blue',
linestyle='solid',
linewidth=3)
# TTC Pededestrian.
axs.plot(
[x[0] for x in data_simple],
[x[3] for x in data_simple],
label='Pedestrian (TTC)',
color='blue',
linestyle=(0, (5, 5)),
linewidth=3)
axs.legend(loc="upper right", ncol=3)
fig.tight_layout()
plt.show()
| [
11748,
299,
32152,
355,
45941,
198,
11748,
2603,
29487,
8019,
13,
9078,
29487,
355,
458,
83,
198,
198,
41358,
23428,
796,
1542,
198,
28929,
3913,
796,
642,
198,
198,
7890,
62,
28483,
2611,
796,
1100,
62,
615,
70,
62,
12287,
10786,
142... | 1.89451 | 929 |
"""joblib parallel backend for IPython Parallel"""
# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
from __future__ import absolute_import
import ipyparallel as ipp
from joblib.parallel import ParallelBackendBase, AutoBatchingMixin
| [
37811,
21858,
8019,
10730,
30203,
329,
6101,
7535,
42945,
37811,
198,
2,
15069,
357,
66,
8,
6101,
7535,
7712,
4816,
13,
198,
2,
4307,
6169,
739,
262,
2846,
286,
262,
40499,
347,
10305,
13789,
13,
198,
198,
6738,
11593,
37443,
834,
133... | 3.84 | 75 |
from celery import Task
from video_streaming.core.tasks import BaseTask
from video_streaming.ffmpeg.tasks.base import BaseStreamingTask
from .check import BaseCheckMixin
| [
6738,
18725,
1924,
1330,
15941,
198,
6738,
2008,
62,
5532,
278,
13,
7295,
13,
83,
6791,
1330,
7308,
25714,
198,
6738,
2008,
62,
5532,
278,
13,
487,
43913,
13,
83,
6791,
13,
8692,
1330,
7308,
12124,
278,
25714,
198,
6738,
764,
9122,
... | 3.5625 | 48 |
keyboard.send_keys("<shift>+<alt>+<left>") | [
2539,
3526,
13,
21280,
62,
13083,
7203,
27,
30846,
29,
10,
27,
2501,
29,
10,
27,
9464,
29,
4943
] | 2.210526 | 19 |
from ggplot import *
import pandas as pd
df = pd.DataFrame({'a': range(0,3), 'b': range(1,4)})
df['x'] = df.index
df = pd.melt(df, id_vars='x')
print df
print ggplot(aes(x='x', y='value', color='variable'), df) + geom_line() + geom_point()
| [
6738,
308,
70,
29487,
1330,
1635,
198,
11748,
19798,
292,
355,
279,
67,
198,
198,
7568,
796,
279,
67,
13,
6601,
19778,
15090,
6,
64,
10354,
2837,
7,
15,
11,
18,
828,
705,
65,
10354,
2837,
7,
16,
11,
19,
8,
30072,
198,
7568,
1781... | 2.220183 | 109 |
import requests
from templates.text import TextTemplate
from random import choice
import json
import config
| [
11748,
7007,
198,
6738,
24019,
13,
5239,
1330,
8255,
30800,
198,
6738,
4738,
1330,
3572,
198,
11748,
33918,
198,
11748,
4566,
198
] | 4.909091 | 22 |
import pandas as pd
import numpy as np
import xarray as xr
import sys
import os
from glob import glob
import re
from datetime import datetime
import tempfile
import shutil
from .gw import set_gw_depth
HP1_DIR=os.path.join(os.getcwd(),'HP1')
HP1_EXE=os.path.join(HP1_DIR,'hp1.exe')
DEFAULT_OUTPUTS={
'Volume':{
'time':True,
'file':'T_LEVEL',
'column':'Volume'
},
'pH':{
'dims':[
'time',
'dist_x'
],
'file':'nod_inf_chem',
'column':'pH'
},
'pe':{
'dims':[
'time',
'dist_x'
],
'file':'nod_inf_chem',
'column':'pe'
},
'k_pyrite':{
'dims':[
'time',
'dist_x'
],
'file':'nod_inf_chem',
'column':'k_pyrite'
},
'dk_pyrite':{
'dims':[
'time',
'dist_x'
],
'file':'nod_inf_chem',
'column':'dk_pyrite'
},
'mass_H2O':{
'dims':[
'time',
'dist_x'
],
'file':'nod_inf_chem',
'column':'mass_H2O'
},
'm_O2':{
'dims':[
'time',
'dist_x'
],
'file':'nod_inf_chem',
'column':'m_O2'
}
# mass_H2O Fe(2) Fe(3) S(-2) S(6) Na K Mg Ca C(4) Cl Al m_O2 si_O2(g) si_CO2(g) si_Ferrihydrite si_Fe(OH)2 si_H-Jarosite si_Na-Jarosite si_K-Jarosite si_calcite si_gibbsite si_gypsum si_pyrite pressure total_mol volume g_O2(g) g_CO2(g) k_pyrite PressureHead siFerri gCl gK gCa gMg gNa gSO4 gAl gS2 gFe2 gFe3 '
}
DEFAULT_SIM_START=datetime(2000,1,1)
DEFAULT_SIM_END=datetime(2000,1,10)
M_TO_MM = 1e-3
ATMOS_HEADER='''Pcp_File_Version=4
*** BLOCK I: ATMOSPHERIC INFORMATION **********************************
MaxAL (MaxAL = number of atmospheric data-records)
%s
DailyVar SinusVar lLay lBCCycles lInterc lDummy lDummy lDummy lDummy lDummy
f f f f f f f f f f
hCritS (max. allowed pressure head at the soil surface)
0
'''
ATMOS_FOOTER="end*** END OF INPUT FILE 'ATMOSPH.IN' **********************************"
DEFAULT_CSV_OPTIONS={
'sep':r'\s+'
}
CSV_OPTIONS={
'A_LEVEL':{
'header':0,
'skiprows':[0,1,3,4],
'skipfooter':1
},
'^solute':{
'header':0,
'skiprows':[0,1,3],
'skipfooter':1
},
'BALANCE':{
'skiprows':[0,1,2,3,4,5,6,7,8,10],
'skipfooter':3
},
'NOD_INF':{
'skiprows':[0,1,2,3,4,5,6,7,8,9,11,12],
'skipfooter':1
},
'PROFILE':{
'skiprows':[0,1,2,3,4,5,6,8],
'skipfooter':1
},
'T_LEVEL':{
'skiprows':[0,1,2,3,4,6,7,8],
'skipfooter':1
},
'RUN_INF':{
'skiprows':[0,1,2,3,4,5,6,8],
'skipfooter':1
},
'OBS_NODE':{
'skiprows':10,
'skipfooter':1
}
}
# def grid_parameters(grid,precision=3,format_str=None,numeric=False):
# y_step = float(grid.y[5]-grid.y[0])/5
# x_step = float(grid.x[5]-grid.x[0])/5
# y0 = grid.y[0]
# x0 = grid.x[0]
# y_i = lambda lat: int(y0 + lat*y_step)
# x_i = lambda lng: int(x0 + lng*x_step)
# if numeric:
# return lambda lat,lng:float(grid.sel(y=lat,x=lng,method='nearest',tolerance=1e-4))
# if format_str is None:
# format_str = '%.'+str(precision)+'f'
# return lambda lat,lng: format_str%grid.sel(y=lat,x=lng,method='nearest',tolerance=1e-4)
| [
11748,
19798,
292,
355,
279,
67,
201,
198,
11748,
299,
32152,
355,
45941,
201,
198,
11748,
2124,
18747,
355,
2124,
81,
201,
198,
11748,
25064,
201,
198,
11748,
28686,
201,
198,
6738,
15095,
1330,
15095,
201,
198,
11748,
302,
201,
198,
... | 1.579368 | 2,501 |
# Copyright 2015 OpenStack Foundation
#
# 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.
#
"""nsxv
Revision ID: 4dbe243cd84d
Revises: 38495dc99731
Create Date: 2015-01-05 23:22:04.501609
"""
# revision identifiers, used by Alembic.
revision = '4dbe243cd84d'
down_revision = '38495dc99731'
from alembic import op
import sqlalchemy as sa
appliance_sizes_enum = sa.Enum('compact', 'large', 'xlarge', 'quadlarge',
name='nsxv_router_bindings_appliance_size')
edge_types_enum = sa.Enum('service', 'vdr',
name='nsxv_router_bindings_edge_type')
internal_network_purpose_enum = sa.Enum('inter_edge_net',
name='nsxv_internal_networks_purpose')
internal_edge_purpose_enum = sa.Enum('inter_edge_net',
name='nsxv_internal_edges_purpose')
tz_binding_type_enum = sa.Enum('flat', 'vlan', 'portgroup',
name='nsxv_tz_network_bindings_binding_type')
| [
2,
15069,
1853,
4946,
25896,
5693,
198,
2,
198,
2,
220,
220,
220,
49962,
739,
262,
24843,
13789,
11,
10628,
362,
13,
15,
357,
1169,
366,
34156,
15341,
345,
743,
198,
2,
220,
220,
220,
407,
779,
428,
2393,
2845,
287,
11846,
351,
26... | 2.410742 | 633 |
import os
import shutil
import git
import copy
import sys
import subprocess
import glob
import json
from ismo.ensemble import ChangeFolder
from ismo.submit import get_current_repository
| [
11748,
28686,
198,
11748,
4423,
346,
198,
11748,
17606,
198,
11748,
4866,
198,
11748,
25064,
198,
11748,
850,
14681,
198,
11748,
15095,
198,
11748,
33918,
198,
6738,
318,
5908,
13,
1072,
11306,
1330,
9794,
41092,
198,
6738,
318,
5908,
13,... | 3.622642 | 53 |
# @title Modint
from typing import Union
class modint:
"""Modint
Not so fast.
"""
__slots__ = ("v",)
mod: int = 0
def using_modint(modulo: int):
"""using modint
set modulo to modint class
Parameters
----------
modulo
Returns
-------
modint class mod = modulo
"""
return Mint
modint998244353 = using_modint(998244353)
modint1000000007 = using_modint(1000000007)
| [
2,
2488,
7839,
3401,
600,
198,
6738,
19720,
1330,
4479,
628,
198,
4871,
953,
600,
25,
198,
220,
220,
220,
37227,
5841,
600,
198,
220,
220,
220,
1892,
523,
3049,
13,
198,
220,
220,
220,
37227,
628,
220,
220,
220,
11593,
6649,
1747,
... | 2.463277 | 177 |
from validate_version_code import validate_version_code
from random_dict.__version__ import __version__ | [
6738,
26571,
62,
9641,
62,
8189,
1330,
26571,
62,
9641,
62,
8189,
198,
6738,
4738,
62,
11600,
13,
834,
9641,
834,
1330,
11593,
9641,
834
] | 4.12 | 25 |
import numpy as np
import time
#
# OK, thats simple
#
#
# Kind of goal seek:
# Find x where interpolator(x) first meets (and firstly equals)
# the given density y.
#
# Find the in-fact zone for the given density
# and return the numeric difference to given zone
# as *negative* number.
#
# N.B. The result is negative as used in darkroom analysis.
| [
11748,
299,
32152,
355,
45941,
198,
11748,
640,
628,
198,
220,
220,
220,
1303,
198,
220,
220,
220,
1303,
7477,
11,
29294,
2829,
198,
220,
220,
220,
1303,
628,
198,
220,
220,
220,
1303,
198,
220,
220,
220,
1303,
14927,
286,
3061,
538... | 2.787671 | 146 |
from django.test import TestCase, Client
from binder.json import jsonloads
from django.contrib.auth.models import User
from ..testapp.models import Zoo, Caretaker, Gate
| [
6738,
42625,
14208,
13,
9288,
1330,
6208,
20448,
11,
20985,
198,
198,
6738,
275,
5540,
13,
17752,
1330,
33918,
46030,
198,
6738,
42625,
14208,
13,
3642,
822,
13,
18439,
13,
27530,
1330,
11787,
198,
198,
6738,
11485,
9288,
1324,
13,
2753... | 3.46 | 50 |
'Hint: Page Source'
#https://github.com/Vinay26k/pythonchallenge
import requests
url = r'http://www.pythonchallenge.com/pc/def/equality.html'
r = requests.get(url).text
import re
print(''.join((re.findall("[^A-Z]+[A-Z]{3}([a-z])[A-Z]{3}[^A-Z]+",r))))
| [
201,
198,
6,
39,
600,
25,
7873,
8090,
6,
201,
198,
2,
5450,
1378,
12567,
13,
785,
14,
53,
259,
323,
2075,
74,
14,
29412,
36747,
3540,
201,
198,
11748,
7007,
201,
198,
201,
198,
6371,
796,
374,
6,
4023,
1378,
2503,
13,
29412,
367... | 2.129032 | 124 |
from .QiskitEducation import *
from .__version__ import *
| [
6738,
764,
48,
1984,
270,
41183,
1330,
1635,
198,
6738,
764,
834,
9641,
834,
1330,
1635,
198
] | 3.411765 | 17 |
import os
import re
import setuptools
from pkg_resources import parse_requirements
from setuptools import find_packages
base_path = os.path.dirname(__file__)
with open(os.path.join(base_path, 'README.md')) as readme:
README = readme.read()
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
packages = find_packages()
exclude_packages = []
reqs = get_requirements(os.path.join(base_path, 'requirements.txt'), exclude=exclude_packages)
setuptools.setup(
name="afbmq",
version="0.0.1",
author_email="yurmarkin97@gmail.com",
description="Python asyncio facebook messenger",
long_description=README,
long_description_content_type="text/markdown",
packages=setuptools.find_packages(),
install_requires=reqs,
classifiers=(
"Development Status :: 3 - Alpha",
"Environment :: Console",
"Framework :: AsyncIO",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Intended Audience :: Developers",
"Programming Language :: Python :: 3.7",
),
)
| [
11748,
28686,
198,
11748,
302,
198,
198,
11748,
900,
37623,
10141,
198,
6738,
279,
10025,
62,
37540,
1330,
21136,
62,
8897,
18883,
198,
6738,
900,
37623,
10141,
1330,
1064,
62,
43789,
198,
198,
8692,
62,
6978,
796,
28686,
13,
6978,
13,
... | 2.653012 | 415 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import os
if __name__ == "__main__":
mac = os.getenv('TIVIBG_MAC', False)
if not mac:
sys.exit('TIVIBG_MAC is not set\nTIVIBG_MAC=aa:bb:cc:dd:ee:ff %s' % (sys.argv[0]))
import server
server.log_cb = __log
server.my_serv = server.serv(host=os.uname()[1])
main()
del server.my_serv
| [
2,
48443,
14629,
14,
8800,
14,
29412,
198,
2,
532,
9,
12,
19617,
25,
3384,
69,
12,
23,
532,
9,
12,
198,
198,
11748,
25064,
198,
11748,
28686,
198,
198,
361,
11593,
3672,
834,
6624,
366,
834,
12417,
834,
1298,
198,
220,
8352,
796,
... | 2.177914 | 163 |
#!/usr/bin/env python
import requests, json, random, string, time, sys
try:
response_time_threshold = int(sys.argv[1])
except IndexError:
response_time_threshold = 500 #default value of response_time_threshold
url = "http://tvpapi.as.tvinci.com/v3_4/gateways/jsonpostgw.aspx"
querystring = {"m":"SearchAssets"}
search_query = ' '.join(random.choice(string.ascii_uppercase + string.ascii_lowercase) for _ in range(2))
print "search_query:'%s'" %(search_query)
payload = "{\n \"initObj\": {\n \"Locale\": {\n \"LocaleLanguage\": \"\",\n \"LocaleCountry\": \"\",\n \"LocaleDevice\": \"\",\n \"LocaleUserState\": \"Unknown\"\n },\n \"Platform\": \"Web\",\n \"SiteGuid\": \"\",\n \"DomainID\": 0,\n \"UDID\": \"\",\n \"ApiUser\": \"tvpapi_225\",\n \"ApiPass\": \"11111\"\n },\n \"filter_types\": [389,390,391],\n \"filter\": \"seriesMainTitle^'%s'\",\n \"order_by\": \"a_to_z\",\n \"with\": ['files'],\n \"page_index\": 0,\n \"page_size\": 50\n\n}" %(search_query)
headers = {
'cache-control': "no-cache",
'postman-token': "42c89c49-2fbd-5c35-29e8-8b0e9f8bb5fb"
}
#start = int(time.time() * 1000000) / 1000
response = requests.request("POST", url, data=payload, headers=headers, params=querystring)
#finish = int(time.time() * 1000000) / 1000
response_time = int(response.elapsed.microseconds / 1000)
print "response time threshold:%d ms" %(response_time_threshold)
print "response time:%d ms" %(response_time)
try:
assert response.status_code == 200
print "HTTP status:%d" %(response.status_code)
json_response = json.loads(response.text)
assert json_response['status']['code'] == 0, 'responsebody.status.code was: %d instead of %s' %(json_response['status']['code'], 0)
assert json_response['total_items'] >= 0, 'responsebody.total_items was: %d, expected >=0' %(json_response['total_items'])
print "total_items:%d" %(json_response['total_items'])
assert json_response['assets'] is not None, 'response-body did not contain "assets" key'
assert response_time < response_time_threshold, 'response time was:%d ms, should be < threshold:%d ms' %(response_time, response_time_threshold)
except Exception, e:
error = str(e)
print "[FAIL] %s" %(error)
# with open('/tmp/searchAssets.error', 'w') as f:
# f.write(error)
sys.exit(1) | [
2,
48443,
14629,
14,
8800,
14,
24330,
21015,
198,
198,
11748,
7007,
11,
33918,
11,
4738,
11,
4731,
11,
640,
11,
25064,
198,
198,
28311,
25,
198,
220,
220,
220,
2882,
62,
2435,
62,
400,
10126,
796,
493,
7,
17597,
13,
853,
85,
58,
... | 2.438 | 1,000 |
__________________________________________________________________________________________________
sample 28 ms submission
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
__________________________________________________________________________________________________
sample 13028 kb submission
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
__________________________________________________________________________________________________
| [
27193,
10221,
834,
198,
39873,
2579,
13845,
14498,
198,
2,
30396,
329,
1702,
306,
12,
25614,
1351,
13,
198,
2,
1398,
7343,
19667,
25,
198,
2,
220,
220,
220,
220,
825,
11593,
15003,
834,
7,
944,
11,
2124,
2599,
198,
2,
220,
220,
22... | 4.248276 | 145 |
# pyright: reportOptionalMemberAccess=none
from store.constants import discordClientID, isUnix, processID
from typing import Any, Optional
from utils.logging import logger
import asyncio
import json
import models.discord
import os
import struct
import time
| [
2,
279,
4766,
25,
989,
30719,
27608,
15457,
28,
23108,
198,
198,
6738,
3650,
13,
9979,
1187,
1330,
36446,
11792,
2389,
11,
318,
47000,
11,
1429,
2389,
198,
6738,
19720,
1330,
4377,
11,
32233,
198,
6738,
3384,
4487,
13,
6404,
2667,
133... | 3.909091 | 66 |
import pytest
import floto.decisions
import floto.api
import json
| [
11748,
12972,
9288,
198,
11748,
781,
2069,
13,
12501,
3279,
198,
11748,
781,
2069,
13,
15042,
198,
198,
11748,
33918,
628,
198
] | 3.136364 | 22 |
#!/usr/bin/python
import urllib.request
import json
import os
import itertools
import re
API_KEY="" # TODO: get from console.google.com
VIDSBASE='{}/Videos/YouTubes/'.format(os.path.expanduser("~")) # TODO: set where all vids will be saved
channels=[
"UC7SeFWZYFmsm1tqWxfuOTPQ", # dankula
"UCwW_vaMPlq8J4weKDsfeJzw", # Bearing
"UC-yewGHQbNFpDrGM0diZOLA", # Sargon
"UCpiCH7qvGVlzMOqy3dncA5Q", # The Thinkery
"UCx_SEanFxmYdkylVM1v3RDg", # The Incredible Salt Mine
"UCDc_MCu3ZstNXmAqqT36SNA", # Sugartits
"UC-EREEErQQqgYNyNB4YGQnQ", # Patrick
"UCG749Dj4V2fKa143f8sE60Q", # Tim Pool
]
################################################################################
# Probably no need to change anything below
################################################################################
COUNT="5" # TODO: tune me if desired
archive = '{}/archive.txt'.format(VIDSBASE)
youtubedlopts='{}/%(uploader)s/%(upload_date)s - %(id)s - %(title)s.%(ext)s'.format(VIDSBASE)
################################################################################
# Very little need to change anything below...
################################################################################
vidlist=[] # list of all video urls to fetch
for chan in channels:
vidlist.extend(get_videos_in_channel(chan,COUNT))
for url in vidlist:
if check_archive(get_vid(url)) == False :
cmdstring = 'youtube-dl --download-archive {} -f best --write-info-json -o \'{}\' "{}"'.format(archive,youtubedlopts,url)
#os.system(cmdstring)
print(cmdstring)
| [
2,
48443,
14629,
14,
8800,
14,
29412,
198,
198,
11748,
2956,
297,
571,
13,
25927,
198,
11748,
33918,
198,
11748,
28686,
198,
11748,
340,
861,
10141,
198,
11748,
302,
198,
198,
17614,
62,
20373,
33151,
1303,
16926,
46,
25,
651,
422,
86... | 2.723368 | 582 |
import numpy as np
import pytest
import warnings
from numpy.testing import assert_array_equal
from xeofs.models._array_transformer import _ArrayTransformer
warnings.filterwarnings("ignore", message="numpy.dtype size changed")
warnings.filterwarnings("ignore", message="numpy.ufunc size changed")
@pytest.mark.parametrize('input_shape, axis', [
((100, 10), 0),
((100, 10), 1),
((100, 10, 10), 0),
((100, 10, 10), [1, 2]),
])
@pytest.mark.parametrize('input_shape, axis', [
((10, 4) , 2),
((10, 4) , [0, 2]),
])
@pytest.mark.parametrize('shape', [
(10, 5, 5),
(10, 5, 4, 2),
])
@pytest.mark.parametrize('shape, axis', [
((10, 2), 0),
((10, 2, 5), 1),
((10, 2, 5), [1, 2]),
])
@pytest.mark.parametrize('shape, axis', [
((10, 2), 0),
((10, 2, 5), 1),
((10, 2, 5), [1, 2]),
])
| [
11748,
299,
32152,
355,
45941,
198,
11748,
12972,
9288,
198,
11748,
14601,
198,
6738,
299,
32152,
13,
33407,
1330,
6818,
62,
18747,
62,
40496,
198,
6738,
2124,
68,
1659,
82,
13,
27530,
13557,
18747,
62,
7645,
16354,
1330,
4808,
19182,
8... | 2.279133 | 369 |
from deepend.layers import * | [
6738,
390,
2690,
13,
75,
6962,
1330,
1635
] | 3.5 | 8 |
total_checker_all([0, 1, 2, 2, 3, 4], 4)
| [
198,
23350,
62,
9122,
263,
62,
439,
26933,
15,
11,
352,
11,
362,
11,
362,
11,
513,
11,
604,
4357,
604,
8,
628,
628
] | 1.875 | 24 |
# Copyright 2019 Catalyst Cloud Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from oslo_config import cfg
from oslo_log import log as logging
from magnum.common import clients
from novaclient import exceptions as nova_exception
LOG = logging.getLogger(__name__)
CONF = cfg.CONF
| [
2,
15069,
13130,
48238,
10130,
12052,
13,
198,
2,
198,
2,
220,
220,
220,
49962,
739,
262,
24843,
13789,
11,
10628,
362,
13,
15,
357,
1169,
366,
34156,
15341,
198,
2,
220,
220,
220,
345,
743,
407,
779,
428,
2393,
2845,
287,
11846,
... | 3.349794 | 243 |
import numpy as np
import os
import torch
import torch.nn as nn
import torchvision
import torch.utils.data as Data
import torchvision.datasets as dates
from torch.autograd import Variable
from torch.nn import functional as F
import utils.transforms as trans
import utils.utils as util
import layer.loss as ls
import utils.metric as mc
import shutil
import cv2
### options = ['TSUNAMI','GSV','CMU','CD2014']
datasets = 'TSUNAMI'
if datasets == 'TSUNAMI':
import cfgs.TSUNAMIconfig as cfg
import dataset.TSUNAMI as dates
if datasets == 'GSV':
import cfgs.GSVconfig as cfg
import dataset.GSV as dates
if datasets == 'CMU':
import cfgs.CMUconfig as cfg
import dataset.CMU as dates
if datasets == 'CD2014':
import cfgs.CD2014config as cfg
import dataset.CD2014 as dates
resume = 0
if __name__ == '__main__':
main()
| [
11748,
299,
32152,
355,
45941,
198,
11748,
28686,
198,
11748,
28034,
198,
11748,
28034,
13,
20471,
355,
299,
77,
198,
11748,
28034,
10178,
198,
11748,
28034,
13,
26791,
13,
7890,
355,
6060,
198,
11748,
28034,
10178,
13,
19608,
292,
1039,
... | 2.924138 | 290 |
import asyncio
import logging
from slack_sdk.web.async_client import AsyncSlackResponse, AsyncWebClient
from slack_bolt.async_app import AsyncApp, AsyncAck
from slack_bolt.workflows.step.async_step import (
AsyncConfigure,
AsyncUpdate,
AsyncComplete,
AsyncFail,
AsyncWorkflowStep,
)
logging.basicConfig(level=logging.DEBUG)
# export SLACK_SIGNING_SECRET=***
# export SLACK_BOT_TOKEN=xoxb-***
app = AsyncApp()
# https://api.slack.com/tutorials/workflow-builder-steps
copy_review_step = AsyncWorkflowStep.builder("copy_review")
@copy_review_step.edit
@copy_review_step.save
pseudo_database = {}
@copy_review_step.execute(
matchers=[additional_matcher],
middleware=[noop_middleware],
lazy=[notify_execution],
)
app.step(copy_review_step)
if __name__ == "__main__":
app.start(3000) # POST http://localhost:3000/slack/events
| [
11748,
30351,
952,
198,
11748,
18931,
198,
198,
6738,
30740,
62,
21282,
74,
13,
12384,
13,
292,
13361,
62,
16366,
1330,
1081,
13361,
11122,
441,
31077,
11,
1081,
13361,
13908,
11792,
198,
6738,
30740,
62,
25593,
13,
292,
13361,
62,
1324... | 2.602374 | 337 |
import re
import io
import base64
# import numpy as np
import tokenize
# from PIL import Image
# Code manipulation
magic_var_name = "__run_py__"
'''
Reference:
https://stackoverflow.com/questions/1769332/script-to-remove-python-comments-docstrings
'''
#Getting test comment lines
# Image Processing
# Convert PIL.Image to html
# Convert ndarray to PIL.Image
# Convert list of lists to ndarray
| [
11748,
302,
198,
11748,
33245,
198,
11748,
2779,
2414,
198,
2,
1330,
299,
32152,
355,
45941,
198,
11748,
11241,
1096,
198,
2,
422,
350,
4146,
1330,
7412,
198,
198,
2,
6127,
17512,
198,
198,
32707,
62,
7785,
62,
3672,
796,
366,
834,
... | 3.068702 | 131 |
#!/usr/bin/env python
# coding=utf-8
"""
# pyORM : Implementation of DummyEngine
Summary :
<summary of module/class being implemented>
Use Case :
As a <actor> I want <outcome> So that <justification>
Testable Statements :
Can I <Boolean statement>
....
"""
from unittest.mock import MagicMock
from pyorm.db.engine.core import EngineCore
from pyorm.db.models._core import _Field
__version__ = "0.1"
__author__ = 'Tony Flury : anthony.flury@btinternet.com'
__created__ = '27 Aug 2017'
class DummyEngine(EngineCore):
"""Concrete Engine implementation, with mocked connections"""
_step = 0
@classmethod
# Dummy methods to match abstract methods - they don't need to do anything here.
@classmethod
class MockedEngine(MagicMock(spec=EngineCore)):
"""A Completely mocked DB Engine"""
pass | [
2,
48443,
14629,
14,
8800,
14,
24330,
21015,
198,
2,
19617,
28,
40477,
12,
23,
198,
37811,
198,
2,
12972,
1581,
44,
1058,
46333,
286,
360,
13513,
13798,
198,
198,
22093,
1058,
220,
198,
220,
220,
220,
1279,
49736,
286,
8265,
14,
487... | 3.003584 | 279 |
from axes.models import AccessAttempt
from wagtail.contrib.modeladmin.options import (ModelAdmin, modeladmin_register)
from wagtail.core import hooks
from wagtail.admin import widgets as wagtailadmin_widgets
from .models.nav import Menu, Footer
from contentPages.models import HomePage, CreateNewResourceType
from .models.config import MethodsRedirect
modeladmin_register(MenuAdmin)
modeladmin_register(FooterAdmin)
modeladmin_register(AccessAttemptAdmin)
modeladmin_register(CreateNewResourceTypeAdmin)
modeladmin_register(MethodsRedirectAdmin)
@hooks.register('register_page_listing_buttons')
@hooks.register('register_rich_text_features')
@hooks.register('register_rich_text_features')
# Remove the default wagtail redirect object
for item in hooks._hooks['register_settings_menu_item']:
if (item[0].__name__ == 'register_redirects_menu_item'):
hooks._hooks['register_settings_menu_item'].remove(item)
| [
6738,
34197,
13,
27530,
1330,
8798,
37177,
198,
198,
6738,
266,
363,
13199,
13,
3642,
822,
13,
19849,
28482,
13,
25811,
1330,
357,
17633,
46787,
11,
2746,
28482,
62,
30238,
8,
198,
6738,
266,
363,
13199,
13,
7295,
1330,
26569,
198,
67... | 3.319149 | 282 |
#!/usr/bin/env python3
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
import argparse
import concurrent.futures
import json
import os
import subprocess
from typing import List
from usort import config as usort_config, usort
from utils import as_posix, LintMessage, LintSeverity
if __name__ == "__main__":
main()
| [
2,
48443,
14629,
14,
8800,
14,
24330,
21015,
18,
198,
2,
15069,
357,
66,
8,
30277,
19193,
82,
11,
3457,
13,
290,
29116,
13,
198,
2,
1439,
2489,
10395,
13,
198,
2,
198,
2,
770,
2723,
2438,
318,
11971,
739,
262,
347,
10305,
12,
76... | 3.337931 | 145 |
#!/usr/bin/python3
from ReadData import read_train, read_test
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.pipeline import FeatureUnion
from sklearn.compose import ColumnTransformer
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.preprocessing import FunctionTransformer
from sklearn.pipeline import Pipeline
from sklearn.feature_selection import SelectKBest, chi2
from sklearn.svm import LinearSVC
import numpy as np
import plac
class ItemSelector(BaseEstimator, TransformerMixin):
"""For data grouped by feature, select subset of data at a provided key.
The data is expected to be stored in a 2D data structure, where the first
index is over features and the second is over samples. i.e.
>> len(data[key]) == n_samples
Please note that this is the opposite convention to scikit-learn feature
matrixes (where the first index corresponds to sample).
ItemSelector only requires that the collection implement getitem
(data[key]). Examples include: a dict of lists, 2D numpy array, Pandas
DataFrame, numpy record array, etc.
>> data = {'a': [1, 5, 2, 5, 2, 8],
'b': [9, 4, 1, 4, 1, 3]}
>> ds = ItemSelector(key='a')
>> data['a'] == ds.transform(data)
ItemSelector is not designed to handle data grouped by sample. (e.g. a
list of dicts). If your data is structured this way, consider a
transformer along the lines of `sklearn.feature_extraction.DictVectorizer`.
Parameters
----------
key : hashable, required
The key corresponding to the desired value in a mappable.
"""
@plac.annotations(
kbest=('Number of best features to select with SelectKBest/Chi2', 'option', 'K', int),
ngram_hi=('Max length of n-grams to generate, (2, G)', 'option', 'G', int),
jobs=('Model: number of jobs', 'option', 'j', int),
seed=('Model: RNG seed value', 'option', 's', int),
)
if __name__ == "__main__":
plac.call(main)
| [
2,
48443,
14629,
14,
8800,
14,
29412,
18,
198,
198,
6738,
4149,
6601,
1330,
1100,
62,
27432,
11,
1100,
62,
9288,
198,
198,
6738,
1341,
35720,
13,
8692,
1330,
7308,
22362,
320,
1352,
11,
3602,
16354,
35608,
259,
198,
6738,
1341,
35720,... | 3.007553 | 662 |
import json
import os
import fcntl
import sys
| [
11748,
33918,
198,
11748,
28686,
198,
11748,
277,
66,
429,
75,
198,
11748,
25064,
628
] | 3.133333 | 15 |
import random
if __name__ == "__main__":
arr = []
for i in range(10):
arr.append(random.randint(-20, 20))
print(arr)
MergeSort.mergeSort(arr)
print(arr)
| [
11748,
4738,
198,
220,
220,
220,
220,
220,
220,
220,
220,
220,
220,
220,
220,
198,
220,
220,
220,
220,
220,
220,
220,
220,
220,
220,
220,
220,
198,
361,
11593,
3672,
834,
6624,
366,
834,
12417,
834,
1298,
198,
220,
220,
220,
5240,... | 1.883929 | 112 |
import os
from downloadutil.util import BUFFER_SIZE_BYTES
from typing import Any
import re
import hashlib
SHA256_CHECKSUM_RE = re.compile(r'^[0-9a-f]{64}$')
SHA256_CHECKSUM_FILE_SUFFIX = '.sha256'
def validate_sha256sum(checksum_str: str) -> None:
"""
Validtes the given SHA256 checksum. Raises an exception if it is invalid.
"""
if not SHA256_CHECKSUM_RE.match(checksum_str):
raise ValueError(
"Invalid SHA256 checksum: '%s', expected 64 hex characters" % checksum_str)
def update_hash_with_file(hash: Any, filename: str, block_size: int = BUFFER_SIZE_BYTES) -> str:
"""
Compute the hash sun of a file by updating the existing hash object.
"""
# TODO: use a more precise argument type for hash.
with open(filename, "rb") as f:
for block in iter(lambda: f.read(block_size), b""):
hash.update(block)
return hash.hexdigest()
| [
11748,
28686,
198,
6738,
4321,
22602,
13,
22602,
1330,
20571,
45746,
62,
33489,
62,
17513,
51,
1546,
198,
6738,
19720,
1330,
4377,
198,
198,
11748,
302,
198,
11748,
12234,
8019,
628,
198,
37596,
11645,
62,
50084,
50,
5883,
62,
2200,
796... | 2.577465 | 355 |
from collections import defaultdict
from queue import Queue, Empty
from threading import Thread
test_input = [line.split() for line in """
set a 1
add a 2
mul a a
mod a 5
snd a
set a 0
rcv a
jgz a -1
set a 1
jgz a -2
""".strip().splitlines()]
test_input2 = [line.split() for line in """
snd 1
snd 2
snd p
rcv a
rcv b
rcv c
rcv d""".strip().splitlines()]
with open('d18_input.txt') as f:
puzzle_input = [line.strip().split() for line in f.readlines()]
print(run_program(test_input))
print(run_program(puzzle_input))
print(run_concurrent(test_input2)[1])
print(run_concurrent(puzzle_input)[1])
| [
6738,
17268,
1330,
4277,
11600,
198,
6738,
16834,
1330,
4670,
518,
11,
33523,
198,
6738,
4704,
278,
1330,
14122,
198,
198,
9288,
62,
15414,
796,
685,
1370,
13,
35312,
3419,
329,
1627,
287,
37227,
198,
2617,
257,
352,
198,
2860,
257,
3... | 2.559322 | 236 |
#TODO
#def addPhysObjBox(id, x, y, w, h, d, r, f): pass
#def addCirc(id, x, y, r, d, r, f): pass
#def addTri(id, x1, y1, x2, y2, x3, y3): pass
#def addDJoint(id, b1_id, b2_id, x1, y1, x2, y2, dist, freq): pass
# DEATH/REMOVAL
# TODO
# def rm_Object(id): pass
# def rm_Joint(id): pass
# world shit
"""
all of the functions prepended with request
request the data after update finishes,
if you need this data this *game loop*,
(not this (script)update loop because that is impossible)-
then just return 1 in update and this data will be
requested and (most likely) updated for you,
update will run again without the game loop progressing-
this(above) is only supposed to be a fallback mechanism for
special circumstances. try to program with the requests in
mind as to not slow down game
"""
| [
198,
198,
2,
51,
3727,
46,
198,
2,
4299,
751,
43215,
49201,
14253,
7,
312,
11,
2124,
11,
331,
11,
266,
11,
289,
11,
288,
11,
374,
11,
277,
2599,
1208,
198,
2,
4299,
751,
31560,
7,
312,
11,
2124,
11,
331,
11,
374,
11,
288,
11... | 2.898917 | 277 |
import json
import logging
import asyncio
import random
import socket
from hbmqtt.client import MQTTClient, ClientException
from hbmqtt.mqtt.constants import QOS_1
logging.basicConfig(format='%(asctime)s - %(name)14s - '
'%(levelname)5s - %(message)s')
logger = logging.getLogger("mqtt_test_node")
MQTT_URL = 'mqtt://localhost:1886/'
NODE_ID = 'mqtt_test_node'
LED_VALUE = '0'
DELAY_CHECK = 30 # seconds
NODE_RESOURCES = {'name': {'delay': 0,
'value': lambda x=None: "MQTT test node"},
'os': {'delay': 0,
'value': lambda x=None: "riot"},
'ip': {'delay': 0,
'value': (lambda x=None:
socket.gethostbyname(
socket.gethostname()))},
'board': {'delay': 0, 'value': lambda x=None: "HP"},
'led': {'delay': 0,
'value': lambda x=None: LED_VALUE},
'temperature': {'delay': 5,
'value': (lambda x=None:
'{}°C'
.format(random.randrange(
20, 30, 1)))},
'pressure': {'delay': 10,
'value': (lambda x=None:
'{}hPa'
.format(random.randrange(
990, 1015, 1)))}
}
async def start_client():
"""Connect to MQTT broker and subscribe to node check resource."""
global __LED_VALUE__
mqtt_client = MQTTClient()
await mqtt_client.connect(MQTT_URL)
# Subscribe to 'gateway/check' with QOS=1
await mqtt_client.subscribe([('gateway/{}/discover'
.format(NODE_ID), QOS_1)])
await mqtt_client.subscribe([('gateway/{}/led/set'
.format(NODE_ID), QOS_1)])
asyncio.get_event_loop().create_task(send_check(mqtt_client))
asyncio.get_event_loop().create_task(send_values(mqtt_client))
while True:
try:
logger.debug("Waiting for incoming MQTT messages from gateway")
# Blocked here until a message is received
message = await mqtt_client.deliver_message()
except ClientException as ce:
logger.error("Client exception: {}".format(ce))
break
except Exception as exc:
logger.error("General exception: {}".format(exc))
break
packet = message.publish_packet
topic_name = packet.variable_header.topic_name
data = packet.payload.data.decode()
logger.debug("Received message from gateway: {} => {}"
.format(topic_name, data))
if topic_name.endswith("/discover"):
if data == "resources":
topic = 'node/{}/resources'.format(NODE_ID)
value = json.dumps(list(NODE_RESOURCES.keys())).encode()
asyncio.get_event_loop().create_task(
publish(mqtt_client, topic, value))
else:
for resource in NODE_RESOURCES:
topic = 'node/{}/{}'.format(NODE_ID, resource)
value = NODE_RESOURCES[resource]['value']
msg = json.dumps({'value': value()})
asyncio.get_event_loop().create_task(
publish(mqtt_client, topic, msg))
elif topic_name.endswith("/led/set"):
LED_VALUE = data
topic = 'node/{}/led'.format(NODE_ID)
data = json.dumps({'value': data}, ensure_ascii=False)
asyncio.get_event_loop().create_task(
publish(mqtt_client, topic, data.encode()))
else:
logger.debug("Topic not supported: {}".format(topic_name))
if __name__ == '__main__':
logger.setLevel(logging.DEBUG)
try:
asyncio.get_event_loop().run_until_complete(start_client())
except KeyboardInterrupt:
logger.info("Exiting")
asyncio.get_event_loop().stop()
| [
11748,
33918,
198,
11748,
18931,
198,
11748,
30351,
952,
198,
11748,
4738,
198,
11748,
17802,
198,
198,
6738,
289,
20475,
80,
926,
13,
16366,
1330,
337,
48,
15751,
11792,
11,
20985,
16922,
198,
6738,
289,
20475,
80,
926,
13,
76,
80,
9... | 1.828448 | 2,320 |
import pyarrow.parquet as pq
import pandas as pd
import json
from typing import List, Callable, Iterator, Union, Optional
from sportsdataverse.config import MBB_BASE_URL, MBB_TEAM_BOX_URL, MBB_PLAYER_BOX_URL, MBB_TEAM_SCHEDULE_URL
from sportsdataverse.errors import SeasonNotFoundError
from sportsdataverse.dl_utils import download
def load_mbb_pbp(seasons: List[int]) -> pd.DataFrame:
"""Load men's college basketball play by play data going back to 2002
Example:
`mbb_df = sportsdataverse.mbb.load_mbb_pbp(seasons=range(2002,2022))`
Args:
seasons (list): Used to define different seasons. 2002 is the earliest available season.
Returns:
pd.DataFrame: Pandas dataframe containing the
play-by-plays available for the requested seasons.
Raises:
ValueError: If `season` is less than 2002.
"""
data = pd.DataFrame()
if type(seasons) is int:
seasons = [seasons]
for i in seasons:
if int(i) < 2002:
raise SeasonNotFoundError("season cannot be less than 2002")
i_data = pd.read_parquet(MBB_BASE_URL.format(season=i), engine='auto', columns=None)
data = data.append(i_data)
#Give each row a unique index
data.reset_index(drop=True, inplace=True)
return data
def load_mbb_team_boxscore(seasons: List[int]) -> pd.DataFrame:
"""Load men's college basketball team boxscore data
Example:
`mbb_df = sportsdataverse.mbb.load_mbb_team_boxscore(seasons=range(2002,2022))`
Args:
seasons (list): Used to define different seasons. 2002 is the earliest available season.
Returns:
pd.DataFrame: Pandas dataframe containing the
team boxscores available for the requested seasons.
Raises:
ValueError: If `season` is less than 2002.
"""
data = pd.DataFrame()
if type(seasons) is int:
seasons = [seasons]
for i in seasons:
if int(i) < 2002:
raise SeasonNotFoundError("season cannot be less than 2002")
i_data = pd.read_parquet(MBB_TEAM_BOX_URL.format(season = i), engine='auto', columns=None)
data = data.append(i_data)
#Give each row a unique index
data.reset_index(drop=True, inplace=True)
return data
def load_mbb_player_boxscore(seasons: List[int]) -> pd.DataFrame:
"""Load men's college basketball player boxscore data
Example:
`mbb_df = sportsdataverse.mbb.load_mbb_player_boxscore(seasons=range(2002,2022))`
Args:
seasons (list): Used to define different seasons. 2002 is the earliest available season.
Returns:
pd.DataFrame: Pandas dataframe containing the
player boxscores available for the requested seasons.
Raises:
ValueError: If `season` is less than 2002.
"""
data = pd.DataFrame()
if type(seasons) is int:
seasons = [seasons]
for i in seasons:
if int(i) < 2002:
raise SeasonNotFoundError("season cannot be less than 2002")
i_data = pd.read_parquet(MBB_PLAYER_BOX_URL.format(season = i), engine='auto', columns=None)
data = data.append(i_data)
#Give each row a unique index
data.reset_index(drop=True, inplace=True)
return data
def load_mbb_schedule(seasons: List[int]) -> pd.DataFrame:
"""Load men's college basketball schedule data
Example:
`mbb_df = sportsdataverse.mbb.load_mbb_schedule(seasons=range(2002,2022))`
Args:
seasons (list): Used to define different seasons. 2002 is the earliest available season.
Returns:
pd.DataFrame: Pandas dataframe containing the
schedule for the requested seasons.
Raises:
ValueError: If `season` is less than 2002.
"""
data = pd.DataFrame()
if type(seasons) is int:
seasons = [seasons]
for i in seasons:
if int(i) < 2002:
raise SeasonNotFoundError("season cannot be less than 2002")
i_data = pd.read_parquet(MBB_TEAM_SCHEDULE_URL.format(season = i), engine='auto', columns=None)
data = data.append(i_data)
#Give each row a unique index
data.reset_index(drop=True, inplace=True)
return data
| [
11748,
12972,
6018,
13,
1845,
21108,
355,
279,
80,
198,
11748,
19798,
292,
355,
279,
67,
198,
11748,
33918,
198,
6738,
19720,
1330,
7343,
11,
4889,
540,
11,
40806,
1352,
11,
4479,
11,
32233,
198,
6738,
5701,
7890,
4399,
13,
11250,
133... | 2.55107 | 1,635 |
import json
import socket
# UDP IP address and port
UDP_IP = "127.0.0.1"
UDP_PORT = 5005
# Press the green button in the gutter to run the script.
if __name__ == '__main__':
# Import functions
from mycode import abc, double_int, say_hello, rpc_test, doggo_test, favorite_number, half_float, bye_professor
# Wrap all functions
wrapped_abc = RPCClient(abc)
wrapped_double = RPCClient(double_int)
wrapped_hello = RPCClient(say_hello)
wrapped_rpc_test = RPCClient(rpc_test)
wrapped_doggo_test = RPCClient(doggo_test)
wrapped_favorite_number = RPCClient(favorite_number)
wrapped_half_float = RPCClient(half_float)
wrapped_bye_professor = RPCClient(bye_professor)
# Run functions that have been wrapped
print(wrapped_abc(5, 'AAA'))
print(wrapped_double(5.0))
print(wrapped_hello())
print(wrapped_doggo_test('WOOF!'))
print(wrapped_favorite_number(11))
print(wrapped_favorite_number(713))
print(wrapped_rpc_test())
print(wrapped_half_float(13.0))
print(wrapped_bye_professor())
| [
11748,
33918,
198,
11748,
17802,
198,
198,
2,
36428,
6101,
2209,
290,
2493,
198,
52,
6322,
62,
4061,
796,
366,
16799,
13,
15,
13,
15,
13,
16,
1,
198,
52,
6322,
62,
15490,
796,
5323,
20,
628,
198,
198,
2,
4332,
262,
4077,
4936,
2... | 2.626238 | 404 |
import pytest
from prisma import Client
from prisma.errors import DataError
@pytest.mark.asyncio
async def test_filtering(client: Client) -> None:
"""Finding records by a a float value"""
async with client.batch_() as batcher:
for i in range(10):
batcher.types.create({'float_': i + 1})
total = await client.types.count(where={'float_': {'gte': 5}})
assert total == 6
found = await client.types.find_first(
where={
'float_': {
'equals': 2,
},
},
)
assert found is not None
assert found.float_ == 2
results = await client.types.find_many(
where={
'float_': {
'in': [1, 5, 7],
},
},
order={
'float_': 'asc',
},
)
assert len(results) == 3
assert results[0].float_ == 1
assert results[1].float_ == 5
assert results[2].float_ == 7
results = await client.types.find_many(
where={
'float_': {
'not_in': [1, 2, 3, 4, 6, 7, 8, 9],
},
},
order={
'float_': 'asc',
},
)
assert len(results) == 2
assert results[0].float_ == 5
assert results[1].float_ == 10
found = await client.types.find_first(
where={
'float_': {
'lt': 5,
},
},
order={
'float_': 'desc',
},
)
assert found is not None
assert found.float_ == 4
found = await client.types.find_first(
where={
'float_': {
'lte': 5,
},
},
order={
'float_': 'desc',
},
)
assert found is not None
assert found.float_ == 5
found = await client.types.find_first(
where={
'float_': {
'gt': 5,
},
},
order={
'float_': 'asc',
},
)
assert found is not None
assert found.float_ == 6
found = await client.types.find_first(
where={
'float_': {
'gte': 6,
},
},
order={
'float_': 'asc',
},
)
assert found is not None
assert found.float_ == 6
found = await client.types.find_first(
where={
'float_': {
'not': 1,
},
},
order={'float_': 'asc'},
)
assert found is not None
assert found.float_ == 2
@pytest.mark.asyncio
async def test_atomic_update(client: Client) -> None:
"""Atomically updating a float value"""
model = await client.types.create({'id': 1, 'float_': 1})
assert model.float_ == 1
updated = await client.types.update(
where={
'id': 1,
},
data={
'float_': {'increment': 5},
},
)
assert updated is not None
assert updated.float_ == 6
updated = await client.types.update(
where={
'id': 1,
},
data={
'float_': {
'set': 20,
},
},
)
assert updated is not None
assert updated.float_ == 20
updated = await client.types.update(
where={
'id': 1,
},
data={
'float_': {
'decrement': 5,
},
},
)
assert updated is not None
assert updated.float_ == 15
updated = await client.types.update(
where={
'id': 1,
},
data={
'float_': {
'multiply': 2,
},
},
)
assert updated is not None
assert updated.float_ == 30
updated = await client.types.update(
where={
'id': 1,
},
data={
'float_': {
'divide': 3,
},
},
)
assert updated is not None
assert updated.float_ == 10
@pytest.mark.asyncio
async def test_atomic_update_invalid_input(client: Client) -> None:
"""Float atomic update only allows one field to be passed"""
with pytest.raises(DataError) as exc:
await client.types.update(
where={
'id': 1,
},
data={ # pyright: reportGeneralTypeIssues=false
'float_': { # type: ignore
'divide': 1,
'multiply': 2,
},
},
)
message = exc.value.args[0]
assert isinstance(message, str)
assert 'Expected exactly one field to be present, got 2' in message
| [
11748,
12972,
9288,
198,
6738,
778,
38017,
1330,
20985,
198,
6738,
778,
38017,
13,
48277,
1330,
6060,
12331,
628,
198,
31,
9078,
9288,
13,
4102,
13,
292,
13361,
952,
198,
292,
13361,
825,
1332,
62,
10379,
20212,
7,
16366,
25,
20985,
8... | 1.896354 | 2,441 |
import os
import logging
import logging.config
import logger_formatter
import yaml
| [
11748,
28686,
198,
11748,
18931,
198,
11748,
18931,
13,
11250,
198,
11748,
49706,
62,
687,
1436,
198,
11748,
331,
43695,
628,
198
] | 3.863636 | 22 |
#!/usr/bin/env python
import rospy
from turtlesim.msg import Pose
if __name__ == '__main__':
rospy.init_node('subscriber', anonymous=True)
rospy.Subscriber("pose", Pose, detekcija)
rospy.spin()
| [
2,
48443,
14629,
14,
8800,
14,
24330,
21015,
198,
11748,
686,
2777,
88,
198,
6738,
36288,
320,
13,
19662,
1330,
37557,
198,
198,
361,
11593,
3672,
834,
6624,
705,
834,
12417,
834,
10354,
198,
220,
220,
220,
686,
2777,
88,
13,
15003,
... | 2.447059 | 85 |
import json
import unittest
from nanoservice import *
from nanoservice import config
if __name__ == '__main__':
unittest.main()
| [
11748,
33918,
198,
11748,
555,
715,
395,
198,
198,
6738,
15709,
418,
712,
501,
1330,
1635,
198,
6738,
15709,
418,
712,
501,
1330,
4566,
628,
198,
198,
361,
11593,
3672,
834,
6624,
705,
834,
12417,
834,
10354,
198,
220,
220,
220,
555,
... | 2.833333 | 48 |
# Note this requires an internet connection
import os
import urllib.request
import sys
thepipelines = set()
theplugins = set()
thepipelines.add(sys.argv[1]+"/config.txt")
while (len(thepipelines) != 0):
configfile = open(thepipelines.pop(), 'r')
for line in configfile:
contents = line.strip().split(" ")
if (contents[0] == "Pipeline"):
thepipelines.add("../"+contents[1])
elif (contents[0] == "Plugin"):
theplugins.add(contents[1])
#import urllib2
response = urllib.request.urlopen("http://biorg.cis.fiu.edu/pluma/plugins.html")
page_source = str(response.read())
if (len(sys.argv) > 2):
pluginpath = sys.argv[2]
else:
pluginpath = "../plugins"
# Plugin Table
while (page_source.find("</table>") != -1):
plugin_table = page_source[page_source.find("<table "):page_source.find("</table>")]
# Individual Plugins
plugins = plugin_table.split("<tr>")
for plugin in plugins:
while(plugin.find("</a>") != -1):
content = plugin[plugin.find("<a href="):plugin.find("</a>")]
content = content.replace('<a href=', '')
data = content.split('>')
if (len(data) == 2 and data[1] in theplugins):
if (os.path.exists(pluginpath+"/"+data[1])):
print("Plugin "+data[1]+" already installed.")
else:
repo = data[0][1:len(data[0])-1] # Remove quotes
os.system("git clone "+repo+" "+pluginpath+"/"+data[1])
plugin = plugin[plugin.find("</a>")+1:]
page_source = page_source[page_source.find("</table>")+1:]
| [
2,
5740,
428,
4433,
281,
5230,
4637,
198,
11748,
28686,
198,
11748,
2956,
297,
571,
13,
25927,
198,
11748,
25064,
198,
198,
1169,
79,
541,
20655,
796,
900,
3419,
198,
1169,
37390,
796,
900,
3419,
198,
1169,
79,
541,
20655,
13,
2860,
... | 2.460784 | 612 |
from authz.controller import apiv1 | [
6738,
6284,
89,
13,
36500,
1330,
2471,
452,
16
] | 3.777778 | 9 |
import shelve
blt = ["bacon", "lettuce", "tomato", "bread"]
beans_on_toast = ["beans", "bread"]
scrambled_eggs = ["eggs", "butter", "milk"]
soup = ["tin of soup"]
pasta = ["pasta", "cheese"]
with shelve.open("recipes") as recipes:
recipes["blt"] = blt
recipes["beans on toast"] = beans_on_toast
recipes["scrambled eggs"] = scrambled_eggs
recipes["soup"] = soup
recipes["pasta"] = pasta
for snack in recipes:
print(snack, recipes[snack])
print("========== Example 2 ==========")
books = {"recipes": {"blt": ["bacon", "lettuce", "tomato", "bread"],
"beans_on_toast": ["beans", "bread"],
"scrambled_eggs": ["tin of soup"],
"pasta": ["pasta", "cheese"]},
"maintenance": {"stuck": ["oil"],
"loose": ["gaffer tape"]}}
| [
11748,
7497,
303,
198,
198,
2436,
83,
796,
14631,
65,
7807,
1600,
366,
15503,
7234,
1600,
366,
39532,
5549,
1600,
366,
29573,
8973,
198,
44749,
62,
261,
62,
1462,
459,
796,
14631,
44749,
1600,
366,
29573,
8973,
198,
1416,
859,
9342,
6... | 2.203125 | 384 |
import unittest
from user import User
from info import Info
if __name__ == '__main__':
unittest.main() | [
11748,
555,
715,
395,
198,
6738,
2836,
1330,
11787,
198,
6738,
7508,
1330,
14151,
198,
220,
220,
220,
220,
220,
220,
220,
220,
198,
361,
11593,
3672,
834,
6624,
705,
834,
12417,
834,
10354,
198,
220,
220,
220,
555,
715,
395,
13,
124... | 2.613636 | 44 |
import platform
from includes import *
from common import waitForIndex, arch_int_bits
| [
11748,
3859,
198,
6738,
3407,
1330,
1635,
198,
6738,
2219,
1330,
4043,
1890,
15732,
11,
3934,
62,
600,
62,
9895,
628
] | 4.142857 | 21 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" Main entry. Setup the command line interface then run the main function."""
from logging import INFO, DEBUG
from sys import argv
import argparse
import botocore.exceptions
from . import __version__
import ez_repo.command as command
import ez_repo.error as error
import ez_repo.logger as logger
def build_cli_interface():
"""
Building command line interface and registering callback on (sub)commands
available which will be executed in the main.
:return: complete parser
"""
parser = argparse.ArgumentParser(
description="""Commandline client to send/get/search artefacts"""
""" as in a Maven repository using a custom storage"""
"""(for now S3 only).""")
parser.add_argument(
'--version',
action='store_true',
help='Display version'
)
parser.add_argument(
'-v',
action='store_true',
help='Augment verbosity'
)
parser.add_argument(
'-vv',
action='store_true',
help='Augment greatly verbosity'
)
parser.add_argument(
'-quiet',
action='store_true',
help='Activate silent mode'
)
subparsers = parser.add_subparsers()
for cmd in command.COMMANDS:
new_parser = subparsers.add_parser(name=cmd["name"], help=cmd["help"])
new_parser.set_defaults(func=cmd["func"])
for option in cmd["options"]:
new_parser.add_argument(*option["args"], **option["kwargs"])
return parser
def run(raw_args):
"""
Parse arguments in parameter. Then call the function registered in the
argument parser which matches them.
:param raw_args:
:return:
"""
if "--version" in raw_args:
print("version: ", __version__)
return error.ReturnCode.success.value
parser = build_cli_interface()
args = parser.parse_args()
if args.v:
logger.set_global_level(INFO)
if args.vv:
logger.set_global_level(DEBUG)
if args.quiet:
logger.disable_logs()
if "func" in args:
try:
args.func(args)
except error.ConfigError as e:
logger.LOGGER.error(e)
return error.ReturnCode.config_error.value
except error.ArtefactError as e:
logger.LOGGER.error(e)
return error.ReturnCode.artefact_error.value
except error.ExpressionError as e:
logger.LOGGER.error(e)
return error.ReturnCode.expression_error.value
except IOError as e:
logger.LOGGER.error(e)
return error.ReturnCode.artefact_error.value
except botocore.exceptions.ClientError as e:
logger.LOGGER.error("S3 error: %s" % e)
return error.ReturnCode.s3_error.value
except KeyboardInterrupt:
logger.LOGGER.info("Interrupted")
return error.ReturnCode.success.value
def main():
"""
Main function. Entry point.
:return:
"""
return run(argv)
# Useful for dev testing (without installation)
if __name__ == "__main__":
main()
| [
2,
48443,
14629,
14,
8800,
14,
24330,
21015,
198,
2,
532,
9,
12,
19617,
25,
3384,
69,
12,
23,
532,
9,
12,
198,
198,
37811,
8774,
5726,
13,
31122,
262,
3141,
1627,
7071,
788,
1057,
262,
1388,
2163,
526,
15931,
198,
198,
6738,
18931... | 2.4139 | 1,295 |
__author__ = "Qianli Wang and Nazar Sopiha"
__copyright__ = "Copyright (c) 2019 qiaw99"
# https://github.com/qiaw99/WS2019-20/blob/master/LICENSE
from matplotlib import pyplot as plt
if __name__ == '__main__':
main()
| [
834,
9800,
834,
796,
366,
48,
666,
4528,
15233,
290,
12819,
283,
35643,
72,
3099,
1,
198,
834,
22163,
4766,
834,
796,
366,
15269,
357,
66,
8,
13130,
10662,
544,
86,
2079,
1,
198,
2,
3740,
1378,
12567,
13,
785,
14,
80,
544,
86,
2... | 2.5 | 88 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2020 Tomaz Muraus
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import tempfile
import unittest
import yaml
from dcsm.secrets_writer import encrypt_and_write_to_file
from dcsm.secrets_writer import remove_secret_from_file
from dcsm.secrets_writer import decrypt_secret_from_file
from dcsm.decryption import decrypt_secret
from dcsm.utils import get_template_file_lock_path
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
FIXTURES_DIR = os.path.abspath(os.path.join(BASE_DIR, "../fixtures"))
PRIVATE_KEY_1_PATH = os.path.join(FIXTURES_DIR, "keys/private_key_1_no_password.pem")
PUBLIC_KEY_1_PATH = os.path.join(FIXTURES_DIR, "keys/public_key_1_no_password.pem")
SECRETS_1_PATH = os.path.join(FIXTURES_DIR, "secrets/secrets1.yaml")
__all__ = ["SecretsWriterTestCase"]
| [
2,
48443,
14629,
14,
8800,
14,
24330,
21015,
18,
198,
2,
532,
9,
12,
19617,
25,
3384,
69,
12,
23,
532,
9,
12,
198,
2,
15069,
12131,
4186,
1031,
337,
5330,
385,
198,
2,
198,
2,
49962,
739,
262,
24843,
13789,
11,
10628,
362,
13,
... | 2.969163 | 454 |
import unittest
import numpy as np
from keras.optimizers import Adam
from keras.utils import plot_model
from rl.policy import EpsGreedyQPolicy, LinearAnnealedPolicy, GreedyQPolicy
from rl.memory import SequentialMemory
import sys
sys.path.append('../src')
from iqn import IQNAgent
from network_architecture_distributional import NetworkMLPDistributional, NetworkCNNDistributional
from policy import DistributionalEpsGreedyPolicy
if __name__ == '__main__':
unittest.main()
| [
11748,
555,
715,
395,
198,
11748,
299,
32152,
355,
45941,
198,
6738,
41927,
292,
13,
40085,
11341,
1330,
7244,
198,
6738,
41927,
292,
13,
26791,
1330,
7110,
62,
19849,
198,
6738,
374,
75,
13,
30586,
1330,
43427,
43887,
4716,
48,
36727,
... | 3.356643 | 143 |
import base64
import unittest
import pytest
from tag_bot.main import UpdateImageTags, assert_images_info_input, split_str_to_list
from tag_bot.yaml_parser import YamlParser
yaml = YamlParser()
if __name__ == "__main__":
unittest.main()
| [
11748,
2779,
2414,
198,
11748,
555,
715,
395,
198,
198,
11748,
12972,
9288,
198,
198,
6738,
7621,
62,
13645,
13,
12417,
1330,
10133,
5159,
36142,
11,
6818,
62,
17566,
62,
10951,
62,
15414,
11,
6626,
62,
2536,
62,
1462,
62,
4868,
198,
... | 2.78022 | 91 |
TestFile = "hello.py"
import logging
from logging import debug, info, warning, basicConfig, INFO, DEBUG, WARNING
basicConfig(level = WARNING)
main(TestFile)
print("")
print("")
print("----------------")
print("Process complete")
print("----------------") | [
14402,
8979,
796,
366,
31373,
13,
9078,
1,
198,
11748,
18931,
198,
6738,
18931,
1330,
14257,
11,
7508,
11,
6509,
11,
4096,
16934,
11,
24890,
11,
16959,
11,
39410,
198,
35487,
16934,
7,
5715,
796,
39410,
8,
628,
628,
198,
12417,
7,
1... | 3.73913 | 69 |
# -*- coding: utf-8 -*-
import os.path
from docutils import nodes
from docutils.parsers.rst import Directive
from sphinx.directives.code import container_wrapper
from .loader import JsonSchemaLoader
| [
2,
532,
9,
12,
19617,
25,
3384,
69,
12,
23,
532,
9,
12,
628,
198,
11748,
28686,
13,
6978,
198,
198,
6738,
2205,
26791,
1330,
13760,
198,
6738,
2205,
26791,
13,
79,
945,
364,
13,
81,
301,
1330,
34736,
198,
6738,
599,
20079,
87,
1... | 3.138462 | 65 |
import numpy as np
import torch
import random
import os
from pathlib import Path
from sklearn.model_selection import KFold
import sys
sys.path.append('..')
from dataset import get_segmentation, random_crop, SegItemListCustom
from config import *
trainFolders = [
'ARMS',
'AisazuNihaIrarenai',
'AkkeraKanjinchou',
'Akuhamu',
'AosugiruHaru',
'AppareKappore',
'Arisa',
'BEMADER_P',
'BakuretsuKungFuGirl',
'Belmondo',
'BokuHaSitatakaKun',
'BurariTessenTorimonocho',
'ByebyeC-BOY',
'Count3DeKimeteAgeru',
'DollGun',
'Donburakokko',
'DualJustice',
'EienNoWith',
'EvaLady',
'EverydayOsakanaChan',
'GOOD_KISS_Ver2',
'GakuenNoise',
'GarakutayaManta',
'GinNoChimera',
'Hamlet',
'HanzaiKousyouninMinegishiEitarou',
'HaruichibanNoFukukoro',
'HarukaRefrain',
'HealingPlanet',
"UchiNoNyan'sDiary",
'UchuKigekiM774',
'UltraEleven',
'UnbalanceTokyo',
'WarewareHaOniDearu',
'YamatoNoHane',
'YasasiiAkuma',
'YouchienBoueigumi',
'YoumaKourin',
'YukiNoFuruMachi',
'YumeNoKayoiji',
'YumeiroCooking',
'TotteokiNoABC',
'ToutaMairimasu',
'TouyouKidan',
'TsubasaNoKioku'
]
assert(len(trainFolders) == len(set(trainFolders)))
for x in trainFolders:
assert(os.path.isdir(MASKS_PATH + '/' + x))
#gets Kfolded data in order to train the models, 4/5 goes to train and 1/5 to validation in each fold.
#returns single dataset to use by methods that were not trained with manga (icdar2013, total-text, synthetic)
#given prediction and ground truth, returns colorized tensor with true positives as green, false positives as red and false negative as white
#given an image index from a folder (like ARMS, 0) finds which dataset has it in validation and the index inside it
| [
11748,
299,
32152,
355,
45941,
198,
11748,
28034,
220,
198,
11748,
4738,
198,
11748,
28686,
198,
6738,
3108,
8019,
1330,
10644,
198,
6738,
1341,
35720,
13,
19849,
62,
49283,
1330,
509,
37,
727,
198,
198,
11748,
25064,
220,
198,
17597,
1... | 2.264741 | 831 |
from django.shortcuts import render, redirect, get_object_or_404, Http404
from django.utils.translation import gettext_lazy as _
from django.contrib import messages
from django.conf import settings
from django.contrib.sitemaps import Sitemap
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import DetailView, FormView, UpdateView
from froide.foirequest.models import FoiRequest
from froide.helper.cache import cache_anonymous_page
from froide.helper.search.views import BaseSearchView
from froide.helper.auth import can_moderate_object
from .models import PublicBody, FoiLaw, Jurisdiction
from .documents import PublicBodyDocument
from .forms import (
PublicBodyProposalForm,
PublicBodyChangeProposalForm,
PublicBodyAcceptProposalForm,
)
from .filters import PublicBodyFilterSet
import markdown
from .utils import LawExtension
FILTER_ORDER = ("jurisdiction", "category")
SUB_FILTERS = {"jurisdiction": ("category",)}
@cache_anonymous_page(15 * 60)
SITEMAP_PROTOCOL = "https" if settings.SITE_URL.startswith("https") else "http"
| [
6738,
42625,
14208,
13,
19509,
23779,
1330,
8543,
11,
18941,
11,
651,
62,
15252,
62,
273,
62,
26429,
11,
367,
29281,
26429,
198,
6738,
42625,
14208,
13,
26791,
13,
41519,
1330,
651,
5239,
62,
75,
12582,
355,
4808,
198,
6738,
42625,
14... | 3.198251 | 343 |
from flask import Flask, jsonify, request, send_from_directory
from tinydb import TinyDB, Query
from werkzeug.utils import secure_filename
import socketio
import eventlet
import os
UPLOADED_IMAGES = 'uploaded_images'
app = Flask(__name__)
sio = socketio.Server()
db = TinyDB('db.json')
items = db.table('items')
@app.route('/api/img/<string:filename>')
@app.route('/api/upload-image', methods=['POST'])
@app.route('/api/data.json')
@app.route('/api/items.json')
@app.route('/api/new-item', methods=['POST'])
@app.route('/api/item/<int:item_id>/update', methods=['POST'])
@app.route('/api/item/<int:item_id>.json')
# Any table api
@sio.on('connect')
@sio.on('disconnect')
@sio.on('listen')
@sio.on('new')
@sio.on('update')
@sio.on('get')
@sio.on('list')
if __name__ == '__main__':
app = socketio.Middleware(sio, app)
eventlet.wsgi.server(eventlet.listen(('', 5000)), app)
| [
6738,
42903,
1330,
46947,
11,
33918,
1958,
11,
2581,
11,
3758,
62,
6738,
62,
34945,
198,
6738,
7009,
9945,
1330,
20443,
11012,
11,
43301,
198,
6738,
266,
9587,
2736,
1018,
13,
26791,
1330,
5713,
62,
34345,
198,
11748,
17802,
952,
198,
... | 2.467914 | 374 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This app provides a basic stress test suite for the birdie app with locust.io library.
"""
__version__ = "0.1"
#from birdie-stress import xxx | [
2,
48443,
14629,
14,
8800,
14,
24330,
21015,
198,
2,
532,
9,
12,
19617,
25,
3384,
69,
12,
23,
532,
9,
12,
198,
220,
198,
37811,
198,
220,
220,
220,
770,
598,
3769,
257,
4096,
5503,
1332,
18389,
329,
262,
6512,
494,
598,
351,
117... | 2.54321 | 81 |
from io import StringIO
import ZConfig
import logging
import logging.handlers
import pkg_resources
import pytest
@pytest.fixture(autouse=True)
def logger(request):
"""Logger for tests."""
request.addfinalizer(reset_handler)
def load_config(config):
"""Help to load config."""
schema = ZConfig.loadSchemaFile(open(pkg_resources.resource_filename(
__name__, 'schema.xml')))
conf, handler = ZConfig.loadConfigFile(schema, StringIO(config))
return conf.loggers
def test_creates_watchedfilehandler():
"""It creates a watchedfilehandler at the path."""
loggers = load_config(u"""
%import zconfig_watchedfile
<logger>
name foo
<watchedfile>
path /dev/null
</watchedfile>
</logger>
""")
logger = loggers[0].create()
assert isinstance(logger.handlers[0], logging.handlers.WatchedFileHandler)
assert '/dev/null' == logger.handlers[0].baseFilename
def test_passes_parameters():
"""It passes the parameter from config to handler."""
loggers = load_config(u"""
%import zconfig_watchedfile
<logger>
name foo
<watchedfile>
path /dev/null
mode w
encoding utf-8
delay true
</watchedfile>
</logger>
""")
logger = loggers[0].create()
handler = logger.handlers[0]
assert 'w' == handler.mode
assert 'utf-8' == handler.encoding
assert handler.delay
| [
6738,
33245,
1330,
10903,
9399,
198,
11748,
1168,
16934,
198,
11748,
18931,
198,
11748,
18931,
13,
4993,
8116,
198,
11748,
279,
10025,
62,
37540,
198,
11748,
12972,
9288,
628,
198,
31,
9078,
9288,
13,
69,
9602,
7,
2306,
1076,
28,
17821,... | 2.72 | 500 |
#!/usr/bin/python
# ~/dev/py/xlreg_py/makeTestData
""" Make data for test scripts. """
import os
import subprocess
import sys
import time
from Crypto.Cipher import AES
from xlutil import DecimalVersion as dv
from xlReg import reg_cred
import rnglib
OPENSSL = '/usr/bin/openssl'
SSH_KEYGEN = '/usr/bin/ssh-keygen'
KEY_BITS = 1024
KEY_BYTES = KEY_BITS / 8
SHA1_BYTES = 20
TEST_DATA_DIR = "./testData"
# REG CRED TEST DATA ################################################
REG_CRED_DATA_DIR = os.path.join(TEST_DATA_DIR, 'reg_cred')
# HELLO AND REPLY TEST DATA #########################################
MAX_MSG = KEY_BYTES - 1 - 2 * SHA1_BYTES # one more than max value
AES_IV_LEN = 16
AES_KEY_LEN = 32
AES_BLOCK_LEN = 16
SALT_LEN = 8
VERSION_LEN = 4
HELLO_DATA_LEN = AES_IV_LEN + AES_KEY_LEN + SALT_LEN + VERSION_LEN
UNPADDED_REPLY_LEN = HELLO_DATA_LEN + SALT_LEN
PADDING_LEN = ((UNPADDED_REPLY_LEN + AES_BLOCK_LEN - 1) / AES_BLOCK_LEN) * \
AES_BLOCK_LEN - UNPADDED_REPLY_LEN
HELLO_REPLY_LEN = HELLO_DATA_LEN + SALT_LEN + PADDING_LEN
HR_TEST_DIR = os.path.join(TEST_DATA_DIR, 'helloAndReply')
HR_KEY_FILE = 'key-rsa'
HR_PUBKEY_FILE = 'key-rsa.pub'
HR_PEM_FILE = 'key-rsa.pem'
PATH_TO_HR_KEY = os.path.join(HR_TEST_DIR, HR_KEY_FILE)
PATH_TO_HR_PUBKEY = os.path.join(HR_TEST_DIR, HR_PUBKEY_FILE)
PATH_TO_HR_PEM = os.path.join(HR_TEST_DIR, HR_PEM_FILE)
PATH_TO_HELLO = os.path.join(HR_TEST_DIR, 'hello-data')
PATH_TO_REPLY = os.path.join(HR_TEST_DIR, 'reply-data')
PATH_TO_ENCRYPTED_REPLY = os.path.join(HR_TEST_DIR, 'reply-encrypted')
# REG CRED DATA #####################################################
# HELLO AND REPLY DATA ##############################################
def make_hello_reply_data(rng):
""" Make the data bytes for the hello-reply message. """
make_or_clear_test_dir(HR_TEST_DIR)
# A, B: generate an ssh2 key pair in HR_TEST_DIR -------------------
cmd = [SSH_KEYGEN, '-q', '-t', 'rsa', '-b', str(KEY_BITS),
'-N', '', # empty passphrase
'-f', PATH_TO_HR_KEY]
result = subprocess.check_call(cmd)
if result != 0:
print("ssh-keygen call failed (result: %d); aborting" % result)
system.exit()
# from id_rsa.pub generate the pem version of the public key
# C: generate 'pem' = PKCS8 version of public key ---------------
# this command writes to stdout
f = open(PATH_TO_HR_PEM, 'w')
cmd = [SSH_KEYGEN, '-e', '-m', 'PKCS8', '-f', PATH_TO_HR_PUBKEY, ]
result = subprocess.check_call(cmd, stdout=f)
if result != 0:
print("write to PEM file failed (result: %d); aborting" % result)
f.close()
system.exit()
f.close() # GEEP
# D: write version1.str -----------------------------------------
dv1 = dv.DecimalVersion(1, 2, 3, 4)
v1s = dv1.__str__()
with open(os.path.join(HR_TEST_DIR, 'version1.str'), 'w') as file:
file.write(v1s)
# generate low-quality random data ==============================
hello_data = bytearray(HELLO_DATA_LEN - VERSION_LEN)
rng.next_bytes(hello_data) # that many random bytes
# append version number -------------------------------
dv1 = dv.DecimalVersion(1, 2, 3, 4)
# NOTE silly but will do for now
# NOTE version is big-endian
hello_data.append(dv1.getA())
hello_data.append(dv1.getB())
hello_data.append(dv1.getC())
hello_data.append(dv1.getD())
# E: write hello_data -------------------------------------------
with open(PATH_TO_HELLO, 'w') as file:
file.write(hello_data)
# F: write iv1 --------------------------------------------------
iv1 = hello_data[0:AES_IV_LEN]
with open(os.path.join(HR_TEST_DIR, 'iv1'), 'w') as file:
file.write(iv1)
# G: write key1 -------------------------------------------------
key1 = hello_data[AES_IV_LEN:AES_IV_LEN + AES_KEY_LEN]
with open(os.path.join(HR_TEST_DIR, 'key1'), 'w') as file:
file.write(key1)
# H: write salt1 ------------------------------------------------
salt1 = hello_data[
AES_IV_LEN +
AES_KEY_LEN:AES_IV_LEN +
AES_KEY_LEN +
SALT_LEN]
with open(os.path.join(HR_TEST_DIR, 'salt1'), 'w') as file:
file.write(salt1) # GEEP
# I: write version1 ---------------------------------------------
version1 = hello_data[AES_IV_LEN + AES_KEY_LEN + SALT_LEN:]
with open(os.path.join(HR_TEST_DIR, 'version1'), 'w') as file:
file.write(version1)
# J: write hello-encrypted --------------------------------------
# openssl rsautl -in test_dir/data -inkey test_dir/key-rsa.pem -pubin
# -encrypt -out test_dir/hello-encrypted -oaep
cmd = [OPENSSL, 'rsautl', '-in', PATH_TO_HELLO,
'-inkey', PATH_TO_HR_PEM, '-pubin', '-encrypt',
'-oaep', '-out', os.path.join(HR_TEST_DIR, 'hello-encrypted')]
result = subprocess.check_call(cmd)
if result != 0:
print("OAEP encryption call failed (result: %d); aborting" % result)
system.exit()
# generate more low-quality random data =========================
replyData = bytearray(HELLO_DATA_LEN - VERSION_LEN)
rng.next_bytes(replyData) # that many random bytes
# append version number -------------------------------
dv2 = dv.DecimalVersion(5, 6, 7, 8)
replyData.append(dv2.getA())
replyData.append(dv2.getB())
replyData.append(dv2.getC())
replyData.append(dv2.getD())
# append salt1 ----------------------------------------
for ndx in range(8):
replyData.append(salt1[ndx])
# append PKCS7 padding --------------------------------
for ndx in range(PADDING_LEN):
replyData.append(PADDING_LEN)
# K: write reply_data -------------------------------------------
with open(PATH_TO_REPLY, 'w') as file:
file.write(replyData)
# L: write iv2 --------------------------------------------------
iv2 = replyData[0:AES_IV_LEN]
with open(os.path.join(HR_TEST_DIR, 'iv2'), 'w') as file:
file.write(iv2)
# M: write key2 -------------------------------------------------
key2 = replyData[AES_IV_LEN:AES_IV_LEN + AES_KEY_LEN]
with open(os.path.join(HR_TEST_DIR, 'key2'), 'w') as file:
file.write(key2)
# N: write salt2 ------------------------------------------------
salt2 = replyData[
AES_IV_LEN +
AES_KEY_LEN:AES_IV_LEN +
AES_KEY_LEN +
SALT_LEN]
with open(os.path.join(HR_TEST_DIR, 'salt2'), 'w') as file:
file.write(salt2)
# O: write version2.str -----------------------------------------
v2s = dv2.__str__()
with open(os.path.join(HR_TEST_DIR, 'version2.str'), 'w') as file:
file.write(v2s)
# P: write version2 as byte slice -------------------------------
v2 = bytearray(4)
v2[0] = dv2.getA()
v2[1] = dv2.getB()
v2[2] = dv2.getC()
v2[3] = dv2.getD()
with open(os.path.join(HR_TEST_DIR, 'version2'), 'w') as file:
file.write(v2)
# Q: write padding as byte slice --------------------------------
padding = bytearray(PADDING_LEN)
# the essence of PKCS7:
for i in range(PADDING_LEN):
padding[i] = PADDING_LEN
with open(os.path.join(HR_TEST_DIR, 'padding'), 'w') as file:
file.write(padding)
# R: AES-encrypt padded reply as replyEncrypted -----------------
keyBuff = buffer(key1)
ivBuff = buffer(iv1)
cipher1s = AES.new(keyBuff, AES.MODE_CBC, ivBuff)
outBuff = buffer(replyData)
replyEncrypted = cipher1s.encrypt(outBuff)
# S: write reply-encrypted --------------------------------------
with open(os.path.join(HR_TEST_DIR, 'reply-encrypted'), 'w') as file:
file.write(replyEncrypted) # GEEPGEEP
# MAIN ##############################################################
if __name__ == '__main__':
main()
| [
2,
48443,
14629,
14,
8800,
14,
29412,
198,
2,
47795,
7959,
14,
9078,
14,
87,
75,
2301,
62,
9078,
14,
15883,
14402,
6601,
198,
198,
37811,
6889,
1366,
329,
1332,
14750,
13,
37227,
198,
198,
11748,
28686,
198,
11748,
850,
14681,
198,
... | 2.38695 | 3,295 |
# stdlib
import webbrowser
from typing import Tuple
# 3rd party
import pytest
from coincidence.regressions import AdvancedFileRegressionFixture
from consolekit.testing import CliRunner, Result
from domdf_python_tools.iterative import permutations
from domdf_python_tools.paths import PathPlus
# this package
from football_badges import football_badge
from football_badges.__main__ import main
teams = [
"ARS", # Arsenal
"AV", # Aston Villa
"BRH", # Brighton & Hove Albion
"CHE", # Chelsea
"EVE", # Everton
"FUL", # Fulham
"LEI", # Leicester City
"MCI", # Manchester City
"SHU", # Sheffield United
"SOU", # Southampton
"TOT", # Tottenham Hotspur
"WBA", # West Bromwich Albion
"BRS", # Barnsley
"BRC", # Birmingham City
"NTG", # Nottingham Forest
"RDG", # Reading
"STK", # Stoke City
"WAT", # Watford
"WYC", # Wycombe Wanderers
]
scores = pytest.mark.parametrize(
"score",
[
pytest.param((9, 0), id="9_0"),
pytest.param((0, 9), id="0_9"),
pytest.param((5, 5), id="5_5"),
pytest.param((10, 4), id="10_4"),
pytest.param((5, 2), id="5_2"),
]
)
elapsed_times = pytest.mark.parametrize(
"elapsed_time", [
"0:05",
"0:55",
"4:30",
"8:15",
"12:00",
"32:12",
"45:00",
"56:09",
"74:39",
"90:00",
]
)
elapsed_extra_times = pytest.mark.parametrize(
"time",
[
pytest.param(("45:00", 5), id='a'),
pytest.param(("45:00", '5'), id='b'),
pytest.param(("45:00", '3'), id='c'),
pytest.param(("45:00", '3'), id='d'),
pytest.param(("45:00", "+3"), id='e'),
pytest.param(("48:10", '3'), id='f'),
pytest.param(("90:00", 5), id='g'),
pytest.param(("90:00", '5'), id='h'),
pytest.param(("90:00", '3'), id='i'),
pytest.param(("90:00", '3'), id='j'),
pytest.param(("93:10", '3'), id='k'),
pytest.param(("93:10", "+3"), id='l'),
pytest.param(("119:10", "30"), id='m'),
pytest.param(("119:10", "+30"), id='n'),
pytest.param(("119:10", 30), id='o'),
]
)
team_perms = pytest.mark.parametrize(
"teams", [pytest.param(t, id=str(idx)) for idx, t in enumerate(permutations(teams, 2)[::3])]
)
| [
2,
14367,
8019,
198,
11748,
3992,
40259,
198,
6738,
19720,
1330,
309,
29291,
198,
198,
2,
513,
4372,
2151,
198,
11748,
12972,
9288,
198,
6738,
21083,
13,
2301,
601,
507,
1330,
13435,
8979,
8081,
2234,
37,
9602,
198,
6738,
8624,
15813,
... | 2.114674 | 1,029 |
import unittest
from mock import MagicMock
from hazelcast.proxy.cp.atomic_long import AtomicLong
| [
11748,
555,
715,
395,
198,
198,
6738,
15290,
1330,
6139,
44,
735,
198,
198,
6738,
11595,
417,
2701,
13,
36436,
13,
13155,
13,
47116,
62,
6511,
1330,
28976,
14617,
628
] | 3.333333 | 30 |
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import pandas_datareader as web
import datetime as dt
from sklearn.preprocessing import MinMaxScaler
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout, LSTM
#loading data
company = 'FB'
start = dt.datetime(2012,1,1)
end = dt.datetime(2021,1,11)
data = web.DataReader(company, 'yahoo', start, end)
#preparing the data
scaler = MinMaxScaler(feature_range=(0,1))
scaled_data = scaler.fit_transform(data['Close'].values.reshape(-1,1))
prediction_days = 60
x_train = []
y_train = []
for x in range(prediction_days, len(scaled_data)):
x_train.append(scaled_data[x-prediction_days:x, 0])
y_train.append(scaled_data[x, 0])
x_train, y_train = np.array(x_train), np.array(y_train)
x_train = np.reshape(x_train, (x_train.shape[0], x_train.shape[1], 1))
#Creating the Neural Network Model
model = Sequential()
model.add(LSTM(units=50, return_sequences=True, input_shape=(x_train.shape[1], 1)))
model.add(Dropout(0.2))
model.add(LSTM(units=50, return_sequences=True))
model.add(Dropout(0.2))
model.add(LSTM(units=50))
model.add(Dropout(0.2))
model.add(Dense(units=1))
model.compile(optimizer='harry', loss='mean_squared_error')
model.fit(x_train, y_train, epochs=25, batch_size=32)
test_start = dt.datetime(2021,1,11)
test_end = dt.datetime.now()
test_data = web.DataReader(company, 'yahoo', test_start, test_end)
actual_prices = test_data['Close'].values
total_dataset = pd.concat((data['Close'], test_data['Close']), axis=0)
model_input = total_dataset[len(total_dataset) - len(test_data) - prediction_days:].values
model_inputs = model_input.reshape(-1, 1)
model_inputs = scaler.transform(model_inputs)
#Making the predictions for the stocks
x_test = []
for x in range(prediction_days, len(model_inputs)):
x_test.append(model_inputs[x-prediction_days:x, 0])
x_test = np.array(x_test)
x_test = np.reshape(x_test, (x_test.shape[0], x_test.shape[1], 1))
predicted_prices = model.predict(x_test)
predicted_prices = scaler.inverse_transform(predicted_prices)
#Ploting the prices for the test predictions
plt.plot(actual_prices, color="black", label=f"Actual {company} Price")
plt.plot(predicted_prices, color='green', label=f"Predicted {company} Price")
plt.title(f'{company} Share Price')
plt.xlabel('Time')
plt.ylabel(f'{company} Share Price')
plt.legend()
plt.show()
#Prediction for the next day
real_data = [model_inputs[len(model_inputs) + 1 - prediction_days:len(model_inputs+1), 0]]
real_data = np.array(real_data)
real_data = np.reshape(real_data, (real_data.shape[0], real_data.shape[1],1))
prediction = model.predict(real_data)
prediction = scaler.inverse_transform(prediction)
print(f"Prediction: {prediction}") | [
11748,
299,
32152,
355,
45941,
220,
201,
198,
11748,
2603,
29487,
8019,
13,
9078,
29487,
355,
458,
83,
220,
201,
198,
11748,
19798,
292,
355,
279,
67,
220,
201,
198,
11748,
19798,
292,
62,
19608,
533,
5067,
355,
3992,
220,
201,
198,
... | 2.417369 | 1,186 |
from sklearn.preprocessing import LabelEncoder, MinMaxScaler
from utils.util import ensure_dir
from base import BaseDataLoader
import pandas as pd
import numpy as np
import torch
import time
import os
| [
6738,
1341,
35720,
13,
3866,
36948,
1330,
36052,
27195,
12342,
11,
1855,
11518,
3351,
36213,
198,
6738,
3384,
4487,
13,
22602,
1330,
4155,
62,
15908,
198,
6738,
2779,
1330,
7308,
6601,
17401,
198,
198,
11748,
19798,
292,
355,
279,
67,
1... | 3.625 | 56 |
#OVERVIEW OF ALL QUESTION IDS
"id": "Xa2T0bcZ5VnY",
"title": "Do you identify as a:",
"id": "QUtA6k0gcrZf",
"title": "How old are you? ",
"id": "ZNZyNVwMtwID",
"title": "How would you identify your ethnicity"
"id": "azlKRkvdcc7O",
"title": "Who are you in lockdown with"
"id": "Vrzj2uv0i29C",
"title": "Where are you based during lockdown"
"id": "Xh2W1d6FhXyK",
"title": "Are you feeling safe at home"
"id": "t9EaTsONnJfR",
"title": "How has your feeling of safety at home changed"
"id": "OaujoVSY6NaS",
"title": "Why do you think this is"
"id": "ASolp4v3adZK",
"title": "Are you doing okay during lockdown - mental helath"
"id": "erHBE6gKxycf",
"title": "Have you experienced any of these negative experiences"
"id": "ASQmq4h3vxRt",
"title": "Have you had any of these positive"
"id": "KEGztC8iYfyy",
"title": "Are you currently working?"
"id": "kWb7LUjdJyhb",
"title": "How has COVID-19 made you feel about your ifnancial situation"
"id": "g9goY6hIxmC9",
"title": "How much of the housework do you do"
"id": "jG2wzvAmOWxq",
"title": "Has your time spent on caring changed"
"id": "HNqA7BK7ZDFl",
"title": "Is there anything else you would like to share about your experience "
"id": "hXM65Xe75JCt",
"title": "EMAIL"
#OVERVIEW OF ALL COLNAMES
colnames = ["id",
"gender",
"age",
"ethnicity",
"live_alone",
"live_friends",
"live_partner",
"live_parents",
"live_siblings",
"live_otherfamily",
"live_children",
"live_other",
"location",
"safety_scale",
"safety_change",
"safety_why",
"mental_scale",
"mental_problems_repetitive",
"mental_problems_lonely",
"mental_problems_stressed",
"mental_problems_anxious",
"mental_problems_worriedhealth",
"mental_problems_scaredfuture",
"mental_problems_relationship",
"mental_problems_other",
"mental_problems_none",
"positive_impact_support_housework",
"positive_impact_support_childcare",
"positive_impact_connect",
"positive_impact_leisure",
"positive_impact_wfh",
"positive_impact_other",
"positive_impact_none",
"work_situation",
"work_situation_other",
"financial_situation",
"housework_amount",
"housework_change",
"testimonial",
"start_date",
"submit_date",
"n_id"
] | [
2,
41983,
28206,
3963,
11096,
43658,
2849,
4522,
50,
220,
198,
198,
1,
312,
1298,
366,
55,
64,
17,
51,
15,
15630,
57,
20,
53,
77,
56,
1600,
198,
1,
7839,
1298,
366,
5211,
345,
5911,
355,
257,
25,
1600,
198,
198,
1,
312,
1298,
... | 2.353484 | 976 |
"""Create the input data pipeline using `tf.data`"""
import tensorflow as tf
import tensorflow.contrib as tc
import os
from collections import namedtuple
BatchInput = namedtuple('BatchInput',
['iterator', 'word_ids', 'label_ids', 'sentence_lengths'])
| [
37811,
16447,
262,
5128,
1366,
11523,
1262,
4600,
27110,
13,
7890,
63,
37811,
198,
198,
11748,
11192,
273,
11125,
355,
48700,
198,
11748,
11192,
273,
11125,
13,
3642,
822,
355,
37096,
198,
11748,
28686,
198,
6738,
17268,
1330,
3706,
83,
... | 2.745098 | 102 |
from rest_framework import status
from rest_framework.response import Response
def success_response(data=None, status=status.HTTP_200_OK):
"""Returns a response with `status` (200 default) and `data` if provided."""
if data is None:
return Response(status=status)
return Response(data, status=status)
def failure_response(message=None, status=status.HTTP_404_NOT_FOUND):
"""Returns a response with `status` (404 default) and `message` if provided."""
if message is None:
return Response(status=status)
return Response({"error": message}, status=status)
def update(model, attr_name, attr_value):
"""Update attribute attr_name with attr_value if attr_value isn't None and different from current value."""
if (
attr_value is not None
and attr_value != "null"
and attr_value != getattr(model, attr_name)
):
setattr(model, attr_name, attr_value)
| [
6738,
1334,
62,
30604,
1330,
3722,
198,
6738,
1334,
62,
30604,
13,
26209,
1330,
18261,
628,
198,
4299,
1943,
62,
26209,
7,
7890,
28,
14202,
11,
3722,
28,
13376,
13,
40717,
62,
2167,
62,
11380,
2599,
198,
220,
220,
220,
37227,
35561,
... | 2.873457 | 324 |
times = 10
with open('src-train-aug-err-old.txt') as f:
srcs = f.readlines()
with open('tgt-train-aug-err-old.txt') as f:
tgts = f.readlines()
with open('src-train-aug-err.txt', 'w') as f:
for t in range(times):
f.writelines(srcs)
with open('tgt-train-aug-err.txt', 'w') as f:
for t in range(times):
f.writelines(tgts)
| [
198,
22355,
796,
838,
198,
198,
4480,
1280,
10786,
10677,
12,
27432,
12,
7493,
12,
8056,
12,
727,
13,
14116,
11537,
355,
277,
25,
198,
197,
10677,
82,
796,
277,
13,
961,
6615,
3419,
198,
198,
4480,
1280,
10786,
83,
13655,
12,
27432,... | 2.234899 | 149 |
# 9.2.2 多次元ガウス分布のEMアルゴリズム
#%%
# 9.2.2項で利用するライブラリ
import numpy as np
from scipy.stats import multivariate_normal # 多次元ガウス分布
import matplotlib.pyplot as plt
#%%
## 真の分布の設定
# 次元数を設定:(固定)
D = 2
# クラスタ数を指定
K = 3
# K個の真の平均を指定
mu_truth_kd = np.array(
[[5.0, 35.0],
[-20.0, -10.0],
[30.0, -20.0]]
)
# K個の真の共分散行列を指定
sigma2_truth_kdd = np.array(
[[[250.0, 65.0], [65.0, 270.0]],
[[125.0, -45.0], [-45.0, 175.0]],
[[210.0, -15.0], [-15.0, 250.0]]]
)
# 真の混合係数を指定
pi_truth_k = np.array([0.45, 0.25, 0.3])
#%%
# 作図用のx軸のxの値を作成
x_1_line = np.linspace(
np.min(mu_truth_kd[:, 0] - 3 * np.sqrt(sigma2_truth_kdd[:, 0, 0])),
np.max(mu_truth_kd[:, 0] + 3 * np.sqrt(sigma2_truth_kdd[:, 0, 0])),
num=300
)
# 作図用のy軸のxの値を作成
x_2_line = np.linspace(
np.min(mu_truth_kd[:, 1] - 3 * np.sqrt(sigma2_truth_kdd[:, 1, 1])),
np.max(mu_truth_kd[:, 1] + 3 * np.sqrt(sigma2_truth_kdd[:, 1, 1])),
num=300
)
# 作図用の格子状の点を作成
x_1_grid, x_2_grid = np.meshgrid(x_1_line, x_2_line)
# 作図用のxの点を作成
x_point_arr = np.stack([x_1_grid.flatten(), x_2_grid.flatten()], axis=1)
# 作図用に各次元の要素数を保存
x_dim = x_1_grid.shape
print(x_dim)
# 真の分布を計算
model_dens = 0
for k in range(K):
# クラスタkの分布の確率密度を計算
tmp_dens = multivariate_normal.pdf(
x=x_point_arr, mean=mu_truth_kd[k], cov=sigma2_truth_kdd[k]
)
# K個の分布を線形結合
model_dens += pi_truth_k[k] * tmp_dens
#%%
# 真の分布を作図
plt.figure(figsize=(12, 9))
plt.contour(x_1_grid, x_2_grid, model_dens.reshape(x_dim)) # 真の分布
plt.suptitle('Mixture of Gaussians', fontsize=20)
plt.title('K=' + str(K), loc='left')
plt.xlabel('$x_1$')
plt.ylabel('$x_2$')
plt.colorbar() # 等高線の色
plt.show()
#%%
# (観測)データ数を指定
N = 250
# 潜在変数を生成
z_truth_nk = np.random.multinomial(n=1, pvals=pi_truth_k, size=N)
# クラスタ番号を抽出
_, z_truth_n = np.where(z_truth_nk == 1)
# (観測)データを生成
x_nd = np.array([
np.random.multivariate_normal(
mean=mu_truth_kd[k], cov=sigma2_truth_kdd[k], size=1
).flatten() for k in z_truth_n
])
#%%
# 観測データの散布図を作成
plt.figure(figsize=(12, 9))
for k in range(K):
k_idx, = np.where(z_truth_n == k) # クラスタkのデータのインデック
plt.scatter(x=x_nd[k_idx, 0], y=x_nd[k_idx, 1], label='cluster:' + str(k + 1)) # 観測データ
plt.contour(x_1_grid, x_2_grid, model_dens.reshape(x_dim), linestyles='--') # 真の分布
plt.suptitle('Mixture of Gaussians', fontsize=20)
plt.title('$N=' + str(N) + ', K=' + str(K) +
', \pi=(' + ', '.join([str(pi) for pi in pi_truth_k]) + ')$', loc='left')
plt.xlabel('$x_1$')
plt.ylabel('$x_2$')
plt.colorbar() # 等高線の色
plt.show()
#%%
## 初期値の設定
# 平均パラメータの初期値を生成
mu_kd = np.array([
np.random.uniform(
low=np.min(x_nd[:, d]), high=np.max(x_nd[:, d]), size=K
) for d in range(D)
]).T
# 共分散行列の初期値を指定
sigma2_kdd = np.array([np.identity(D) * 1000 for _ in range(K)])
# 混合係数の初期値を生成
pi_k = np.random.rand(3)
pi_k /= np.sum(pi_k) # 正規化
# 初期値による対数尤度を計算:式(9.14)
term_dens_nk = np.array(
[multivariate_normal.pdf(x=x_nd, mean=mu_kd[k], cov=sigma2_kdd[k]) for k in range(K)]
).T
L = np.sum(np.log(np.sum(term_dens_nk, axis=1)))
#%%
# 初期値による混合分布を計算
init_dens = 0
for k in range(K):
# クラスタkの分布の確率密度を計算
tmp_dens = multivariate_normal.pdf(
x=x_point_arr, mean=mu_kd[k], cov=sigma2_kdd[k]
)
# K個の分布線形結合
init_dens += pi_k[k] * tmp_dens
# 初期値による分布を作図
plt.figure(figsize=(12, 9))
plt.contour(x_1_grid, x_2_grid, model_dens.reshape(x_dim),
alpha=0.5, linestyles='dashed') # 真の分布
#plt.contour(x_1_grid, x_2_grid, init_dens.reshape(x_dim)) # 推定値による分布:(等高線)
plt.contourf(x_1_grid, x_2_grid, init_dens.reshape(x_dim), alpha=0.6) # 推定値による分布:(塗りつぶし)
plt.suptitle('Mixture of Gaussians', fontsize=20)
plt.title('iter:' + str(0) + ', K=' + str(K), loc='left')
plt.xlabel('$x_1$')
plt.ylabel('$x_2$')
plt.colorbar() # 等高線の色
plt.show()
#%%
## 推論処理
# 試行回数を指定
MaxIter = 100
# 推移の確認用の受け皿を作成
trace_L_i = [L]
trace_gamma_ink = [np.tile(np.nan, reps=(N, K))]
trace_mu_ikd = [mu_kd.copy()]
trace_sigma2_ikdd = [sigma2_kdd.copy()]
trace_pi_ik = [pi_k.copy()]
# 最尤推定
for i in range(MaxIter):
# 負担率を計算:式(9.13)
gamma_nk = np.array(
[multivariate_normal.pdf(x=x_nd, mean=mu_kd[k], cov=sigma2_kdd[k]) for k in range(K)]
).T
gamma_nk /= np.sum(gamma_nk, axis=1, keepdims=True) # 正規化
# 各クラスタとなるデータ数の期待値を計算:式(9.18)
N_k = np.sum(gamma_nk, axis=0)
for k in range(K):
# 平均パラメータの最尤解を計算:式(9.17)
mu_kd[k] = np.dot(gamma_nk[:, k], x_nd) / N_k[k]
# 共分散行列の最尤解を計算:式(9.19)
term_x_nd = x_nd - mu_kd[k]
sigma2_kdd[k] = np.dot(gamma_nk[:, k] * term_x_nd.T, term_x_nd) / N_k[k]
# 混合係数の最尤解を計算:式(9.22)
pi_k = N_k / N
# 対数尤度を計算:式(9.14)
tmp_dens_nk = np.array(
[multivariate_normal.pdf(x=x_nd, mean=mu_kd[k], cov=sigma2_kdd[k]) for k in range(K)]
).T
L = np.sum(np.log(np.sum(tmp_dens_nk, axis=1)))
# i回目の結果を記録
trace_L_i.append(L)
trace_gamma_ink.append(gamma_nk.copy())
trace_mu_ikd.append(mu_kd.copy())
trace_sigma2_ikdd.append(sigma2_kdd.copy())
trace_pi_ik.append(pi_k.copy())
# 動作確認
print(str(i + 1) + ' (' + str(np.round((i + 1) / MaxIter * 100, 1)) + '%)')
#%%
## 推論結果の確認
# K個のカラーマップを指定
colormap_list = ['Blues', 'Oranges', 'Greens']
# 負担率が最大のクラスタ番号を抽出
z_n = np.argmax(gamma_nk, axis=1)
# 割り当てられたクラスタとなる負担率(確率)を抽出
prob_z_n = gamma_nk[np.arange(N), z_n]
# 最後の更新値による混合分布を計算
res_dens = 0
for k in range(K):
# クラスタkの分布の確率密度を計算
tmp_dens = multivariate_normal.pdf(
x=x_point_arr, mean=mu_kd[k], cov=sigma2_kdd[k]
)
# K個の分布を線形結合
res_dens += pi_k[k] * tmp_dens
# 最後の更新値による分布を作図
plt.figure(figsize=(12, 9))
plt.contour(x_1_grid, x_2_grid, model_dens.reshape(x_dim),
alpha=0.5, linestyles='dashed') # 真の分布
plt.scatter(x=mu_truth_kd[:, 0], y=mu_truth_kd[:, 1],
color='red', s=100, marker='x') # 真の平均
plt.contourf(x_1_grid, x_2_grid, res_dens.reshape(x_dim), alpha=0.5) # 推定値による分布:(塗りつぶし)
for k in range(K):
k_idx, = np.where(z_n == k) # クラスタkのデータのインデックス
cm = plt.get_cmap(colormap_list[k]) # クラスタkのカラーマップを設定
plt.scatter(x=x_nd[k_idx, 0], y=x_nd[k_idx, 1],
c=[cm(p) for p in prob_z_n[k_idx]], label='cluster:' + str(k + 1)) # 負担率によるクラスタ
#plt.contour(x_1_grid, x_2_grid, res_dens.reshape(x_dim)) # 推定値による分布:(等高線)
#plt.colorbar() # 等高線の値:(等高線用)
plt.suptitle('Mixture of Gaussians:Maximum Likelihood', fontsize=20)
plt.title('$iter:' + str(MaxIter) +
', L=' + str(np.round(L, 1)) +
', N=' + str(N) +
', \pi=[' + ', '.join([str(pi) for pi in np.round(pi_k, 3)]) + ']$',
loc='left')
plt.xlabel('$x_1$')
plt.ylabel('$x_2$')
plt.legend()
plt.show()
#%%
## 対数尤度の推移を作図
plt.figure(figsize=(12, 9))
plt.plot(np.arange(MaxIter + 1), np.array(trace_L_i))
plt.xlabel('iteration')
plt.ylabel('value')
plt.suptitle('Maximum Likelihood', fontsize=20)
plt.title('Log Likelihood', loc='left')
plt.grid() # グリッド線
plt.show()
#%%
## パラメータの更新値の推移の確認
# muの推移を作図
plt.figure(figsize=(12, 9))
plt.hlines(y=mu_truth_kd, xmin=0, xmax=MaxIter + 1, label='true val',
color='red', linestyles='--') # 真の値
for k in range(K):
for d in range(D):
plt.plot(np.arange(MaxIter+1), np.array(trace_mu_ikd)[:, k, d],
label='k=' + str(k + 1) + ', d=' + str(d + 1))
plt.xlabel('iteration')
plt.ylabel('value')
plt.suptitle('Maximum Likelihood', fontsize=20)
plt.title('$\mu$', loc='left')
plt.legend() # 凡例
plt.grid() # グリッド線
plt.show()
#%%
# lambdaの推移を作図
plt.figure(figsize=(12, 9))
plt.hlines(y=sigma2_truth_kdd, xmin=0, xmax=MaxIter + 1, label='true val',
color='red', linestyles='--') # 真の値
for k in range(K):
for d1 in range(D):
for d2 in range(D):
plt.plot(np.arange(MaxIter + 1), np.array(trace_sigma2_ikdd)[:, k, d1, d2],
alpha=0.5, label='k=' + str(k + 1) + ', d=' + str(d1 + 1) + ', d''=' + str(d2 + 1))
plt.xlabel('iteration')
plt.ylabel('value')
plt.suptitle('Maximum Likelihood', fontsize=20)
plt.title('$\Sigma$', loc='left')
plt.legend() # 凡例
plt.grid() # グリッド線
plt.show()
#%%
# piの推移を作図
plt.figure(figsize=(12, 9))
plt.hlines(y=pi_truth_k, xmin=0, xmax=MaxIter + 1, label='true val',
color='red', linestyles='--') # 真の値
for k in range(K):
plt.plot(np.arange(MaxIter + 1), np.array(trace_pi_ik)[:, k], label='k=' + str(k + 1))
plt.xlabel('iteration')
plt.ylabel('value')
plt.suptitle('Maximum Likelihood', fontsize=20)
plt.title('$\pi$', loc='left')
plt.legend() # 凡例
plt.grid() # グリッド線
plt.show()
#%%
## アニメーションによる確認
# 追加ライブラリ
import matplotlib.animation as animation
#%%
## 分布の推移の確認
# K個のカラーマップを指定
colormap_list = ['Blues', 'Oranges', 'Greens']
# 画像サイズを指定
fig = plt.figure(figsize=(9, 9))
# 作図処理を関数として定義
# gif画像を作成
model_anime = animation.FuncAnimation(fig, update_model, frames=MaxIter + 1, interval=100)
model_anime.save("ch9_2_2_Model.gif")
#%%
print('end')
| [
2,
860,
13,
17,
13,
17,
36469,
248,
162,
105,
94,
17739,
225,
23728,
34103,
26344,
228,
30585,
225,
5641,
3620,
47794,
17933,
12675,
37426,
25795,
198,
198,
2,
16626,
198,
198,
2,
860,
13,
17,
13,
17,
165,
254,
227,
30640,
26344,
... | 1.523403 | 5,854 |
import requests
TAG_LIST_ENDPOINT = 'http://127.0.0.1:8000/api/recipe/tags/'
TOKEN_ENDPOINT = 'http://127.0.0.1:8000/api/user/token/'
def authenticate_user(payload):
"""First authenticate user"""
res = requests.post(TOKEN_ENDPOINT, payload)
return res.json()['token']
def create_tag(data, headers):
"""Create tags"""
res = requests.post(TAG_LIST_ENDPOINT, data=data, headers=headers)
return res.json()
def list_tags(headers):
"""list created tags"""
res = requests.get(TAG_LIST_ENDPOINT, headers=headers)
return res.json()
payload = {'email': 'mynew@email.com',
'password': 'mynewpass'
}
token = authenticate_user(payload)
print(token)
headers = {}
headers['Authorization'] = 'Token ' + token
data = {'name': 'Breakfasts'}
print(create_tag(data, headers))
print(list_tags(headers))
| [
11748,
7007,
198,
198,
42197,
62,
45849,
62,
1677,
6322,
46,
12394,
796,
705,
4023,
1378,
16799,
13,
15,
13,
15,
13,
16,
25,
33942,
14,
15042,
14,
29102,
431,
14,
31499,
14,
6,
198,
10468,
43959,
62,
1677,
6322,
46,
12394,
796,
70... | 2.516224 | 339 |
from data.base import DataLoaderExt
from data.chen_example import ChenDataset
from data.silverbox import create_silverbox_datasets
from data.f16gvt import create_f16gvt_datasets
| [
6738,
1366,
13,
8692,
1330,
6060,
17401,
11627,
198,
6738,
1366,
13,
6607,
62,
20688,
1330,
12555,
27354,
292,
316,
198,
6738,
1366,
13,
40503,
3524,
1330,
2251,
62,
40503,
3524,
62,
19608,
292,
1039,
198,
6738,
1366,
13,
69,
1433,
70... | 3.254545 | 55 |
########################################################
# Copyright (c) 2015-2017 by European Commission. #
# All Rights Reserved. #
########################################################
"""
This view shows, for each energy, a pie chart of the different supply types in the context, with their proportions.
"""
from com.artelys.platform.config import Constantes
execfile(Constantes.REP_SCRIPTS+'/results\kpis\imports\BaseKPI.py')
IndicatorLabel = "Supply pie chart (Wh)"
IndicatorUnit = "Wh"
IndicatorDeltaUnit = "Wh"
IndicatorDescription = "Total supply attached to a technology or a contract type"
# IndicatorParameters = []
# IndicatorIcon = "./gfx/energies/co2.png"
# IndicatorCategory = "Results>Technical>Production"
# IndicatorTags = "" | [
29113,
14468,
7804,
198,
2,
15069,
357,
66,
8,
1853,
12,
5539,
416,
3427,
4513,
13,
220,
220,
220,
220,
220,
1303,
198,
2,
1439,
6923,
33876,
13,
220,
220,
220,
220,
220,
220,
220,
220,
220,
220,
220,
220,
220,
220,
220,
220,
22... | 3.34322 | 236 |
from flask import render_template, url_for, redirect, flash, request, abort, Blueprint
from flask_login import current_user, login_required
from blogapp import db
from blogapp.models import Post
from blogapp.posts.forms import PostForm
posts = Blueprint ('posts', __name__)
@posts.route ("/post/new", methods = ['GET', 'POST'])
@login_required
@posts.route ("/post/<int:post_id>")
@posts.route ("/post/<int:post_id>/update", methods = ['GET', 'POST'])
@login_required
@posts.route ("/post/<int:post_id>/delete", methods = ['POST'])
@login_required | [
6738,
42903,
1330,
8543,
62,
28243,
11,
19016,
62,
1640,
11,
18941,
11,
7644,
11,
2581,
11,
15614,
11,
39932,
198,
6738,
42903,
62,
38235,
1330,
1459,
62,
7220,
11,
17594,
62,
35827,
198,
6738,
4130,
1324,
1330,
20613,
198,
6738,
4130... | 3.083799 | 179 |
import torch
from .abstract import TargetNetwork
| [
11748,
28034,
198,
6738,
764,
397,
8709,
1330,
12744,
26245,
198
] | 4.454545 | 11 |
import os, sys
parentPath = os.path.abspath("..")
if parentPath not in sys.path:
sys.path.insert(0, parentPath)
import string
from collections import Counter, defaultdict
from itertools import chain, groupby, product
from config.dictionary import supportWords
import nltk
from enum import Enum
from nltk.tokenize import wordpunct_tokenize
import nltk.data
import codecs
import re
METRIC_DEGREE_DIV_FREQUENCY = 0 # d / f
METRIC_DEGREE = 1 # d
METRIC_FREQUENCY = 2 # f
#txt = ""
#with open('53out.txt', encoding='utf-8') as f:
# for line in f:
# txt += line
#
#txt = """
#Set within a year after the events of Batman Begins, Batman, Lieutenant James Gordon, and new district attorney Harvey Dent successfully begin to round up the criminals that plague Gotham City until a mysterious and sadistic criminal mastermind known only as the Joker appears in Gotham, creating a new wave of chaos. Batman's struggle against the Joker becomes deeply personal, forcing him to "confront everything he believes" and improve his technology to stop him. A love triangle develops between Bruce Wayne, Dent and Rachel Dawes. Written by Leon Lombardi
#"""
#stopwords = []
#with open('data\stopwords\en', encoding='utf-8') as f:
# for line in f:
# stopwords.append(line[:len(line)-1])
#punctuations = '!@#$%^&*()_+=?/.,;:°–'
#
#ke = KeywordExtractor(stopwords = stopwords, punctuations=punctuations)
#ke.extractKeyWords(txt)
#ans = ke.getRankedPhrases()
#
#ofile = codecs.open("outkw.txt", "w", "utf-8")
#for w in ans:
# _w = re.search(w, txt, re.IGNORECASE)
# if _w:
# ofile.write(_w.group(0)+'\n---------------\n')
# ofile.write(w+'\n---------------\n')
#ofile.close()
| [
11748,
28686,
11,
25064,
198,
8000,
15235,
796,
28686,
13,
6978,
13,
397,
2777,
776,
7203,
492,
4943,
198,
361,
2560,
15235,
407,
287,
25064,
13,
6978,
25,
198,
197,
17597,
13,
6978,
13,
28463,
7,
15,
11,
2560,
15235,
8,
198,
198,
... | 2.939341 | 577 |
#!/usr/bin/env python
# encoding: utf-8
from .serializers import UserSerializer
| [
2,
48443,
14629,
14,
8800,
14,
24330,
21015,
198,
2,
21004,
25,
3384,
69,
12,
23,
198,
198,
6738,
764,
46911,
11341,
1330,
11787,
32634,
7509,
628
] | 3.037037 | 27 |
import tkinter as tk
import tkinter.ttk as ttk
from .util import * | [
11748,
256,
74,
3849,
355,
256,
74,
198,
11748,
256,
74,
3849,
13,
926,
74,
355,
256,
30488,
198,
198,
6738,
764,
22602,
1330,
1635
] | 2.68 | 25 |
from dotenv import load_dotenv
load_dotenv()
if __name__ == "__main__":
pass | [
6738,
16605,
24330,
1330,
3440,
62,
26518,
24330,
198,
2220,
62,
26518,
24330,
3419,
198,
198,
361,
11593,
3672,
834,
6624,
366,
834,
12417,
834,
1298,
198,
220,
220,
220,
1208
] | 2.612903 | 31 |
import sys
def retrieve_file(filename):
"""
Opens a file and returns its contents as a string after
encoding to UTF-8
:param filename:
:return:
"""
with open(filename, 'rb') as f:
original_contents = f.read()
decoded_contents = original_contents.decode('utf-8-sig').encode('utf-8')
return decoded_contents
def retrieve_file_lines(filename):
"""
Opens a file and returns its contents as an List of lines
after encoding to UTF-8
:param filename:
:return:
"""
decoded_contents = retrieve_file(filename)
return decoded_contents.splitlines()
| [
11748,
25064,
628,
198,
4299,
19818,
62,
7753,
7,
34345,
2599,
198,
220,
220,
220,
37227,
198,
220,
220,
220,
8670,
641,
257,
2393,
290,
5860,
663,
10154,
355,
257,
4731,
706,
198,
220,
220,
220,
21004,
284,
41002,
12,
23,
198,
220,... | 2.703057 | 229 |
import numpy as np
import torch
import torch.nn as nn
__all__ = [ 'Linear' ]
class Linear(nn.Linear):
'''
Fully connected linear layer class::
line0 = Linear([n], num_neurons, init, bias)
creates a fully connected linear layer with 'n' input neurons and
'num_neurons' output neurons. The weight matrix is initialized
according to 'init' which must be one of the initialization methods described in
pyTorch.
The output of a layer with m neurons is computed as
.. math::
Y = W X^T + b
where the input is given as an mbs x n matrix X with the flattened n-dimensional
inputs as rows and the mini batch size mbs, the output as an mbs x m matrix Y with
neuron outputs in a row, the m x n weight matrix W and the m x 1 bias vector b.
The layer accepts only flat input tensors of size [mbs,n] and produces flat output tensors
of size [mbs,n]. If the input is in unflattened format, a Flatten node has to be
included as input layer. If the argument 'bias' is set to False the bias vector is
ignored.
Attributes:
* w: weight matrix
* b: bias vector
'''
# return printable representation
# Get the input block of a given output block
def get_input_block(self, outp):
'''
Returns the input block that feeds into the specified output block. Since this is
a fully connected layer, the entire input layer is returned as a block.
'''
return [0, 0, 0, 0, 0, self.in_features - 1]
# get weights
@property
# set weights
@w.setter
# get bias
@property
# set bias
@b.setter
| [
11748,
299,
32152,
355,
45941,
198,
11748,
28034,
198,
11748,
28034,
13,
20471,
355,
299,
77,
628,
198,
834,
439,
834,
796,
685,
705,
14993,
451,
6,
2361,
628,
198,
4871,
44800,
7,
20471,
13,
14993,
451,
2599,
198,
220,
220,
220,
70... | 2.596726 | 672 |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file '/mnt/c/Documents and Settings/icheberiak/Sources/Python/lan-map/viewgui/gui_windows/gui_form_new_device.ui'
#
# Created by: PyQt5 UI code generator 5.15.4
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 import QtCore, QtGui, QtWidgets
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
FormNewDevice = QtWidgets.QWidget()
ui = Ui_FormNewDevice()
ui.setupUi(FormNewDevice)
FormNewDevice.show()
sys.exit(app.exec_())
| [
2,
532,
9,
12,
19617,
25,
3384,
69,
12,
23,
532,
9,
12,
198,
198,
2,
5178,
7822,
7560,
422,
3555,
334,
72,
2393,
31051,
76,
429,
14,
66,
14,
38354,
290,
16163,
14,
14234,
527,
32994,
14,
21188,
14,
37906,
14,
9620,
12,
8899,
1... | 2.674699 | 249 |
# AWS IoT EduKit Pre-Provisioned MCU Device Registration Helper
# v1.1.0
#
# Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software without restriction, including without limitation the rights to
# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
# the Software, and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import sys
import argparse
import subprocess
import os
# os.environ["CRYPTOAUTHLIB_NOUSB"] = "1"
subprocess.check_call([sys.executable, '-m', 'pip', 'install', '-r',
'requirements.txt'])
from pyasn1_modules import pem
from cryptography import x509
from cryptography.x509.oid import NameOID
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.backends import default_backend
from datetime import datetime, timedelta
import fileinput
import re
import binascii
import json
from botocore.exceptions import ClientError
import boto3
import esptool
# Import the Espressif CryptoAuthLib Utility libraries
sys.path.append(os.path.abspath(os.path.join(os.path.dirname( __file__ ), "..", "..", "components", "esp-cryptoauthlib", "esp_cryptoauth_utility")))
import helper_scripts as esp_hs
# Import the Microchip Trust Platform Design Suite libraries
trustplatform_path = os.path.join(os.path.dirname( __file__ ), "..", "trustplatform", "assets", "python")
sys.path.append(trustplatform_path)
import certs_handler
import trustplatform
from requirements_helper import requirements_installer
import manifest_helper
# Import the Microchip Trust Platform Design Suite AWS and manifest helper libraries
trustplatform_aws_path = os.path.join(os.path.dirname( __file__ ), "..", "trustplatform", "TrustnGO")
sys.path.append(trustplatform_aws_path)
from helper_aws import *
from Microchip_manifest_handler import *
atecc608_i2c_sda_pin = 21
atecc608_i2c_scl_pin = 22
policy_name = 'EduKit_Policy'
iot = boto3.client('iot')
def check_environment():
"""Checks to ensure environment is set per AWS IoT EduKit instructions.
Verifies Python 3.6.x+ is installed and is being used to execute this script.
Verifies that the AWS CLI is installed and configured. Prints
AWS IoT endpoint address.
"""
if sys.version_info[0] != 3 or sys.version_info[1] < 6:
print(f"Python version {sys.version}")
print("Incorrect version of Python detected. Must use Python version 3.6.x+. Please check your Python installation and that you're using the PlatformIO CLI terminal in VS Code'.")
exit(0)
print(f"Python {sys.version} detected...")
try:
aws_iot_endpoint = iot.describe_endpoint(endpointType='iot:Data-ATS')
except ClientError:
print(ClientError.response['Error']['Code'])
print("Error with AWS CLI! Follow the configurtion docs at 'https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2.html'")
print(f"AWS CLI configured for IoT endpoint: {aws_iot_endpoint['endpointAddress']}")
replace_file_text( os.path.join( os.path.dirname( __file__ ), '..', '..', 'sdkconfig.defaults' ), "CONFIG_AWS_IOT_MQTT_HOST=\n", f"CONFIG_AWS_IOT_MQTT_HOST={aws_iot_endpoint['endpointAddress']}\n" )
replace_file_text( os.path.join( os.path.dirname( __file__ ), '..', '..', '..', 'Smart-Thermostat', 'sdkconfig.defaults' ), "CONFIG_AWS_IOT_MQTT_HOST=\n", f"CONFIG_AWS_IOT_MQTT_HOST={aws_iot_endpoint['endpointAddress']}\n" )
def generate_signer_certificate():
"""Generates a x.509 certificate signed by ECDSA key
This signer certificate is used to generate the device manifest file and helps
ensure the validity/ownership of the manifest contents. This signer certificate's
Distinguished Name (DN) includes the AWS IoT registration code (FDQN)as the
common name and can be helpful for fleet provisioning.
Signer certificate and key is saved in ./output_files/
Certificate is set to expire in 1 year.
"""
print("Generating ECDSA 256-bit prime field key...")
signer_key = ec.generate_private_key(
curve = ec.SECP256R1(),
backend = default_backend()
)
signer_key_pem = signer_key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.TraditionalOpenSSL,
encryption_algorithm=serialization.NoEncryption(),
)
with open(os.path.join(os.path.dirname( __file__ ), "output_files", "signer_key.pem"), "wb") as signer_key_file:
signer_key_file.write(signer_key_pem)
print("Generating self-signed x.509 certificate...")
try:
aws_iot_reg_code = iot.get_registration_code()
except ClientError:
print(ClientError.response['Error']['Code'])
print("Error with the AWS CLI when running the command 'aws iot get-registration-code'.")
exit(0)
signer_public_key = signer_key.public_key()
time_now = datetime.utcnow()
days_to_expire = 365
x509_cert = (
x509.CertificateBuilder()
.issuer_name(x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, aws_iot_reg_code['registrationCode']),]))
.subject_name(x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, aws_iot_reg_code['registrationCode']),]))
.serial_number(x509.random_serial_number())
.public_key(signer_public_key)
.not_valid_before(time_now)
.not_valid_after(time_now + timedelta(days=days_to_expire))
.add_extension(x509.SubjectKeyIdentifier.from_public_key(signer_public_key), False)
.add_extension(x509.AuthorityKeyIdentifier.from_issuer_public_key(signer_public_key), False)
.add_extension(x509.BasicConstraints(ca=True, path_length=None), True)
.sign(signer_key, hashes.SHA256(), default_backend())
)
signer_cert_pem = x509_cert.public_bytes(encoding=serialization.Encoding.PEM)
with open(os.path.join(os.path.dirname( __file__ ), "output_files","signer_cert.crt"), "wb") as signer_cert_file:
signer_cert_file.write(signer_cert_pem)
print(f"Successfully created x.509 certificate with expiration in {days_to_expire} days...")
def upload_manifest():
"""Uses Microchip TrustPlatform to register an AWS IoT thing
Parses through the generated manifest file, creates an AWS IoT thing
with a thing name that is the ATECC608 secure element serial number,
applies the device certificate (public key) that is stored in the manifest
file, and attaches a default policy.
"""
check_and_install_policy('EduKit_Policy')
for file in os.listdir("output_files"):
if re.match("\w+(\_manifest.json)", file):
manifest_file = open(os.path.join(os.path.dirname( __file__ ), "output_files", file), "r")
manifest_data = json.loads(manifest_file.read())
signer_cert = open(os.path.join(os.path.dirname( __file__ ), "output_files","signer_cert.crt"), "r").read()
signer_cert_bytes = str.encode(signer_cert)
invoke_import_manifest('EduKit_Policy', manifest_data, signer_cert_bytes)
invoke_validate_manifest_import(manifest_data, signer_cert_bytes)
def main():
"""AWS IoT EduKit MCU hardware device registration script
Checkes environment is set correctly, generates ECDSA certificates,
ensures all required python libraries are included, retrieves on-board
device certificate using the esp-cryptoauth library and utility, creates
an AWS IoT thing using the AWS CLI and Microchip Trust Platform Design Suite.
"""
app_binary = 'sample_bins/secure_cert_mfg.bin'
parser = argparse.ArgumentParser(description='''Provision the Core2 for AWS IoT EduKit with
device_certificate and signer_certificate required for TLS authentication''')
parser.add_argument(
"--port", '-p',
dest='port',
metavar='[port]',
required=True,
help='Serial comm port of the Core2 for AWS IoT EduKit device')
args = parser.parse_args()
args.signer_cert = "output_files/signer_cert.crt"
args.signer_privkey = "output_files/signer_key.pem"
args.print_atecc608_type = False
check_environment()
generate_signer_certificate()
esp = esptool.ESP32ROM(args.port,baud=115200)
esp_hs.serial.load_app_stub(app_binary, esp)
init_mfg = esp_hs.serial.cmd_interpreter()
retval = init_mfg.wait_for_init(esp._port)
if retval is not True:
print("CMD prompt timed out.")
exit(0)
retval = init_mfg.exec_cmd(esp._port, "init {0} {1}".format(atecc608_i2c_sda_pin, atecc608_i2c_scl_pin))
esp_hs.serial.esp_cmd_check_ok(retval, "init {0} {1}".format(atecc608_i2c_sda_pin, atecc608_i2c_scl_pin))
esp_hs.generate_manifest_file(esp, args, init_mfg)
upload_manifest()
if __name__ == "__main__":
main() | [
2,
30865,
38488,
40766,
20827,
3771,
12,
2964,
10178,
276,
13122,
52,
16232,
24610,
5053,
525,
198,
2,
410,
16,
13,
16,
13,
15,
198,
2,
198,
2,
15069,
357,
34,
8,
12131,
6186,
13,
785,
11,
3457,
13,
393,
663,
29116,
13,
220,
143... | 2.779564 | 3,484 |
# -*- coding: utf-8 -*-
"""
bouncerapi
This file was automatically generated by APIMATIC v2.0 ( https://apimatic.io ).
"""
from bouncerapi.decorators import lazy_property
from bouncerapi.configuration import Configuration
from bouncerapi.controllers.blacklist_controller import BlacklistController
from bouncerapi.controllers.users_login_registration_controller import UsersLoginRegistrationController
from bouncerapi.controllers.whitelist_geo_locations_controller import WhitelistGeoLocationsController
from bouncerapi.controllers.blacklist_geo_locations_controller import BlacklistGeoLocationsController
from bouncerapi.controllers.check_ip_addresses_controller import CheckIPAddressesController
from bouncerapi.controllers.blacklist_ip_addresses_controller import BlacklistIPAddressesController
from bouncerapi.controllers.whitelist_ip_addresses_controller import WhitelistIPAddressesController
from bouncerapi.controllers.whitelist_controller import WhitelistController
| [
2,
532,
9,
12,
19617,
25,
3384,
69,
12,
23,
532,
9,
12,
198,
198,
37811,
198,
220,
220,
220,
31283,
2189,
15042,
628,
220,
220,
220,
770,
2393,
373,
6338,
7560,
416,
3486,
3955,
1404,
2149,
410,
17,
13,
15,
357,
3740,
1378,
499,... | 3.742424 | 264 |
import numpy as np
from .. import units
| [
11748,
299,
32152,
355,
45941,
198,
6738,
11485,
1330,
4991,
628
] | 3.727273 | 11 |
# ********************************************************************************
#
# Convert 18016.def to compileable code
#
# ********************************************************************************
import os,re
target = "../emulator/generated/".replace("/",os.sep) # output directory.
#
# Load source
#
src = open("18016.def").readlines() # read in source
src = [x if x.find("//") < 0 else x[:x.find("//")] for x in src] # strip comments
src = [x.replace("\t"," ").strip() for x in src if x.strip() != ""] # tabs,spaces
#
# Create C file with 18016 functions
#
h = open(target+"18016_code.h","w") # output code lines
h.write("\n".join([x[1:] for x in src if x.startswith(":")]))
h.close()
src = [x for x in src if not x.startswith(":")] # remove them.
#
# Create default port includes
#
h = open(target+"18016_ports.h","w")
for port in range(1,7+1):
h.write("#ifndef INPUT{0}\n#define INPUT{0}() (0)\n#endif\n".format(port))
h.write("#ifndef OUTPUT{0}\n#define OUTPUT{0}(n) {{}}\n#endif\n".format(port))
for flag in range(1,4+1):
h.write("#ifndef EFLAG{0}\n#define EFLAG{0}() (0)\n#endif\n".format(flag))
h.close()
#
# Create switch handler
#
mnemonics = [ None ] * 256
code = [ None ] * 256
for l in src:
m = re.match('^([0-9A-Fa-f\\-]+)\\s*\\"(.*)\\"\\s*(.*)$',l) # Analyse
assert m is not None,l
opc = m.group(1) if len(m.group(1)) == 5 else m.group(1)+"-"+m.group(1)
for opcode in range(int(opc[:2],16),int(opc[3:],16)+1):
assert mnemonics[opcode] is None,"Duplicated {0:02x}".format(opcode)
mnemonics[opcode] = process(m.group(2),opcode).lower()
code[opcode] = process(m.group(3),opcode)+";break;"
# print("{0:02x} {1:6} {2}".format(opcode,mnemonics[opcode],code[opcode]))
#
# Output Mnemonics
#
for i in range(0,256):
if mnemonics[i] is None:
mnemonics[i] = "byte {0:02x}".format(i)
h = open(target+"18016_mnemonics.h","w")
m = ",".join(['"'+x+'"' for x in mnemonics])
h.write("static const char *_mnemonics[256] = {{ {0} }};\n".format(m))
h.close()
#
# Output switch code
#
h = open(target+"18016_switch.h","w")
for i in range(0,256):
if code[i] is not None:
h.write("case 0x{0:02x}: // *** ${0:02x} {1} ***\n\t{2}\n".format(i,mnemonics[i],code[i]))
h.close()
#
print("Generated C 18016 CPU.") | [
2,
41906,
17174,
8412,
198,
2,
198,
2,
197,
197,
197,
197,
197,
197,
3103,
1851,
1248,
27037,
13,
4299,
284,
17632,
540,
2438,
198,
2,
198,
2,
41906,
17174,
8412,
198,
198,
11748,
28686,
11,
260,
198,
198,
16793,
796,
366,
40720,
... | 2.281343 | 1,013 |
from .JSONConfiguration import JSONConfiguration
from .ConfigurationSchemeV1 import ConfigurationSchemeV1
| [
6738,
764,
40386,
38149,
1330,
19449,
38149,
198,
6738,
764,
38149,
27054,
1326,
53,
16,
1330,
28373,
27054,
1326,
53,
16,
198
] | 4.818182 | 22 |
from flask import Blueprint
bp = Blueprint("scoring", __name__)
from app.scoring import routes
| [
6738,
42903,
1330,
39932,
198,
198,
46583,
796,
39932,
7203,
46536,
1600,
11593,
3672,
834,
8,
198,
198,
6738,
598,
13,
46536,
1330,
11926,
198
] | 3.88 | 25 |
from petisco import use_case_handler, UseCase, Petisco
from meiga import Result, Error, Success
from petisco.event.bus.domain.interface_event_bus import IEventBus
from taskmanager.src.modules.tasks.domain.description import Description
from taskmanager.src.modules.tasks.domain.title import Title
from taskmanager.src.modules.tasks.domain.interface_task_repository import (
ITaskRepository,
)
from taskmanager.src.modules.tasks.domain.task import Task
from taskmanager.src.modules.tasks.domain.task_id import TaskId
@use_case_handler(logging_parameters_whitelist=["task_id", "title", "description"])
| [
6738,
4273,
4861,
1330,
779,
62,
7442,
62,
30281,
11,
5765,
20448,
11,
4767,
4861,
198,
198,
6738,
502,
13827,
1330,
25414,
11,
13047,
11,
16282,
198,
6738,
4273,
4861,
13,
15596,
13,
10885,
13,
27830,
13,
39994,
62,
15596,
62,
10885,... | 3.291892 | 185 |