index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
987,500 | 89d1d5eb04b4ea9c053ab62307fddeefaefb140b | #
# PySNMP MIB module ALCATEL-IND1-DOT1Q-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ALCATEL-IND1-DOT1Q-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:17:20 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)
#
softentIND1Dot1Q, = mibBuilder.importSymbols("ALCATEL-IND1-BASE", "softentIND1Dot1Q")
ObjectIdentifier, Integer, OctetString = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "Integer", "OctetString")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ValueRangeConstraint, ValueSizeConstraint, SingleValueConstraint, ConstraintsUnion, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "ValueSizeConstraint", "SingleValueConstraint", "ConstraintsUnion", "ConstraintsIntersection")
NotificationGroup, ModuleCompliance, ObjectGroup = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance", "ObjectGroup")
enterprises, TimeTicks, Unsigned32, MibScalar, MibTable, MibTableRow, MibTableColumn, Bits, MibIdentifier, NotificationType, iso, Counter32, ModuleIdentity, Gauge32, IpAddress, Counter64, Integer32, ObjectIdentity = mibBuilder.importSymbols("SNMPv2-SMI", "enterprises", "TimeTicks", "Unsigned32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Bits", "MibIdentifier", "NotificationType", "iso", "Counter32", "ModuleIdentity", "Gauge32", "IpAddress", "Counter64", "Integer32", "ObjectIdentity")
RowStatus, TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "RowStatus", "TextualConvention", "DisplayString")
alcatelIND1Dot1QMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 6486, 801, 1, 2, 1, 21, 1))
alcatelIND1Dot1QMIB.setRevisions(('2007-04-03 00:00',))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
if mibBuilder.loadTexts: alcatelIND1Dot1QMIB.setRevisionsDescriptions(('Addressing discrepancies with Alcatel Standard.',))
if mibBuilder.loadTexts: alcatelIND1Dot1QMIB.setLastUpdated('200704030000Z')
if mibBuilder.loadTexts: alcatelIND1Dot1QMIB.setOrganization('Alcatel-Lucent')
if mibBuilder.loadTexts: alcatelIND1Dot1QMIB.setContactInfo('Please consult with Customer Service to ensure the most appropriate version of this document is used with the products in question: Alcatel-Lucent, Enterprise Solutions Division (Formerly Alcatel Internetworking, Incorporated) 26801 West Agoura Road Agoura Hills, CA 91301-5122 United States Of America Telephone: North America +1 800 995 2696 Latin America +1 877 919 9526 Europe +31 23 556 0100 Asia +65 394 7933 All Other +1 818 878 4507 Electronic Mail: support@ind.alcatel.com World Wide Web: http://alcatel-lucent.com/wps/portal/enterprise File Transfer Protocol: ftp://ftp.ind.alcatel.com/pub/products/mibs')
if mibBuilder.loadTexts: alcatelIND1Dot1QMIB.setDescription('This module describes an authoritative enterprise-specific Simple Network Management Protocol (SNMP) Management Information Base (MIB): For the Birds Of Prey Product Line 802.1q for vlan assignment to slot/port and aggregates The right to make changes in specification and other information contained in this document without prior notice is reserved. No liability shall be assumed for any incidental, indirect, special, or consequential damages whatsoever arising from or related to this document or the information contained herein. Vendors, end-users, and other interested parties are granted non-exclusive license to use this specification in connection with management of the products for which it is intended to be used. Copyright (C) 1995-2007 Alcatel-Lucent ALL RIGHTS RESERVED WORLDWIDE')
alcatelIND1Dot1QMIBObjects = ObjectIdentity((1, 3, 6, 1, 4, 1, 6486, 801, 1, 2, 1, 21, 1, 1))
if mibBuilder.loadTexts: alcatelIND1Dot1QMIBObjects.setStatus('current')
if mibBuilder.loadTexts: alcatelIND1Dot1QMIBObjects.setDescription('Branch For 802.1Q Subsystem Managed Objects.')
alcatelIND1Dot1QMIBConformance = ObjectIdentity((1, 3, 6, 1, 4, 1, 6486, 801, 1, 2, 1, 21, 1, 2))
if mibBuilder.loadTexts: alcatelIND1Dot1QMIBConformance.setStatus('current')
if mibBuilder.loadTexts: alcatelIND1Dot1QMIBConformance.setDescription('Branch For 802.1Q Subsystem Conformance Information.')
alcatelIND1Dot1QMIBGroups = ObjectIdentity((1, 3, 6, 1, 4, 1, 6486, 801, 1, 2, 1, 21, 1, 2, 1))
if mibBuilder.loadTexts: alcatelIND1Dot1QMIBGroups.setStatus('current')
if mibBuilder.loadTexts: alcatelIND1Dot1QMIBGroups.setDescription('Branch For 802.1Q Subsystem Units Of Conformance.')
alcatelIND1Dot1QMIBCompliances = ObjectIdentity((1, 3, 6, 1, 4, 1, 6486, 801, 1, 2, 1, 21, 1, 2, 2))
if mibBuilder.loadTexts: alcatelIND1Dot1QMIBCompliances.setStatus('current')
if mibBuilder.loadTexts: alcatelIND1Dot1QMIBCompliances.setDescription('Branch For 802.1Q Subsystem Compliance Statements.')
v8021Q = MibIdentifier((1, 3, 6, 1, 4, 1, 6486, 801, 1, 2, 1, 21, 1, 1, 1))
qPortVlanTable = MibTable((1, 3, 6, 1, 4, 1, 6486, 801, 1, 2, 1, 21, 1, 1, 1, 1), )
if mibBuilder.loadTexts: qPortVlanTable.setStatus('current')
if mibBuilder.loadTexts: qPortVlanTable.setDescription('This table lists the 802.1q vlans on a port.')
qPortVlanEntry = MibTableRow((1, 3, 6, 1, 4, 1, 6486, 801, 1, 2, 1, 21, 1, 1, 1, 1, 1), ).setIndexNames((0, "ALCATEL-IND1-DOT1Q-MIB", "qPortVlanSlot"), (0, "ALCATEL-IND1-DOT1Q-MIB", "qPortVlanPort"), (0, "ALCATEL-IND1-DOT1Q-MIB", "qPortVlanTagValue"))
if mibBuilder.loadTexts: qPortVlanEntry.setStatus('current')
if mibBuilder.loadTexts: qPortVlanEntry.setDescription('An entry in 802.1q port vlan table.')
qPortVlanSlot = MibTableColumn((1, 3, 6, 1, 4, 1, 6486, 801, 1, 2, 1, 21, 1, 1, 1, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 16))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: qPortVlanSlot.setStatus('current')
if mibBuilder.loadTexts: qPortVlanSlot.setDescription('The slot id of the required port.')
qPortVlanPort = MibTableColumn((1, 3, 6, 1, 4, 1, 6486, 801, 1, 2, 1, 21, 1, 1, 1, 1, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 64))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: qPortVlanPort.setStatus('current')
if mibBuilder.loadTexts: qPortVlanPort.setDescription('The physical port number.')
qPortVlanTagValue = MibTableColumn((1, 3, 6, 1, 4, 1, 6486, 801, 1, 2, 1, 21, 1, 1, 1, 1, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 4094))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: qPortVlanTagValue.setStatus('current')
if mibBuilder.loadTexts: qPortVlanTagValue.setDescription('Tag for a particular port')
qPortVlanStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 6486, 801, 1, 2, 1, 21, 1, 1, 1, 1, 1, 4), RowStatus()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: qPortVlanStatus.setStatus('current')
if mibBuilder.loadTexts: qPortVlanStatus.setDescription('Row Status for creating/deleting rules')
qPortVlanDescription = MibTableColumn((1, 3, 6, 1, 4, 1, 6486, 801, 1, 2, 1, 21, 1, 1, 1, 1, 1, 5), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 31))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: qPortVlanDescription.setStatus('current')
if mibBuilder.loadTexts: qPortVlanDescription.setDescription('Textual description of vlan added to a port.')
qPortVlanForceTagInternal = MibTableColumn((1, 3, 6, 1, 4, 1, 6486, 801, 1, 2, 1, 21, 1, 1, 1, 1, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(2, 1, 0))).clone(namedValues=NamedValues(("na", 2), ("on", 1), ("off", 0))).clone('na')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: qPortVlanForceTagInternal.setStatus('current')
if mibBuilder.loadTexts: qPortVlanForceTagInternal.setDescription('0-ON, 1-OFF and 2-NA')
qAggregateVlanTable = MibTable((1, 3, 6, 1, 4, 1, 6486, 801, 1, 2, 1, 21, 1, 1, 1, 2), )
if mibBuilder.loadTexts: qAggregateVlanTable.setStatus('current')
if mibBuilder.loadTexts: qAggregateVlanTable.setDescription('This table lists the 802.1q vlans on a aggregate.')
qAggregateVlanEntry = MibTableRow((1, 3, 6, 1, 4, 1, 6486, 801, 1, 2, 1, 21, 1, 1, 1, 2, 1), ).setIndexNames((0, "ALCATEL-IND1-DOT1Q-MIB", "qAggregateVlanAggregateId"), (0, "ALCATEL-IND1-DOT1Q-MIB", "qAggregateVlanTagValue"))
if mibBuilder.loadTexts: qAggregateVlanEntry.setStatus('current')
if mibBuilder.loadTexts: qAggregateVlanEntry.setDescription('An entry in 802.1q aggregate vlan table.')
qAggregateVlanAggregateId = MibTableColumn((1, 3, 6, 1, 4, 1, 6486, 801, 1, 2, 1, 21, 1, 1, 1, 2, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 31))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: qAggregateVlanAggregateId.setStatus('current')
if mibBuilder.loadTexts: qAggregateVlanAggregateId.setDescription('The aggreagte id of the aggregate.')
qAggregateVlanTagValue = MibTableColumn((1, 3, 6, 1, 4, 1, 6486, 801, 1, 2, 1, 21, 1, 1, 1, 2, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 4094))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: qAggregateVlanTagValue.setStatus('current')
if mibBuilder.loadTexts: qAggregateVlanTagValue.setDescription('Tag Value on the particular aggregate.')
qAggregateVlanStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 6486, 801, 1, 2, 1, 21, 1, 1, 1, 2, 1, 3), RowStatus()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: qAggregateVlanStatus.setStatus('current')
if mibBuilder.loadTexts: qAggregateVlanStatus.setDescription('Row status for creating/deleting rules.')
qAggregateVlanDescription = MibTableColumn((1, 3, 6, 1, 4, 1, 6486, 801, 1, 2, 1, 21, 1, 1, 1, 2, 1, 4), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 31))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: qAggregateVlanDescription.setStatus('current')
if mibBuilder.loadTexts: qAggregateVlanDescription.setDescription('Textual description of vlan added to a aggregate.')
qAtmIfIndexVpiVciTable = MibTable((1, 3, 6, 1, 4, 1, 6486, 801, 1, 2, 1, 21, 1, 1, 1, 3), )
if mibBuilder.loadTexts: qAtmIfIndexVpiVciTable.setStatus('current')
if mibBuilder.loadTexts: qAtmIfIndexVpiVciTable.setDescription('This table lists the 802.1q vlans on an ATM port.')
qAtmIfIndexVpiVciEntry = MibTableRow((1, 3, 6, 1, 4, 1, 6486, 801, 1, 2, 1, 21, 1, 1, 1, 3, 1), ).setIndexNames((0, "ALCATEL-IND1-DOT1Q-MIB", "qAtmIfIndex"), (0, "ALCATEL-IND1-DOT1Q-MIB", "qAtmVpiValue"), (0, "ALCATEL-IND1-DOT1Q-MIB", "qAtmVciValue"), (0, "ALCATEL-IND1-DOT1Q-MIB", "qAtmIfIndexVpiVciVlanTagValue"))
if mibBuilder.loadTexts: qAtmIfIndexVpiVciEntry.setStatus('current')
if mibBuilder.loadTexts: qAtmIfIndexVpiVciEntry.setDescription('An entry in 802.1q IfIndex/VPI/VCI vlan table.')
qAtmIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 6486, 801, 1, 2, 1, 21, 1, 1, 1, 3, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(4259841, 2147483647))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: qAtmIfIndex.setStatus('current')
if mibBuilder.loadTexts: qAtmIfIndex.setDescription('The ATM Interface Index.')
qAtmVpiValue = MibTableColumn((1, 3, 6, 1, 4, 1, 6486, 801, 1, 2, 1, 21, 1, 1, 1, 3, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 4095))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: qAtmVpiValue.setStatus('current')
if mibBuilder.loadTexts: qAtmVpiValue.setDescription('.The Vpi value of the ATM VC..')
qAtmVciValue = MibTableColumn((1, 3, 6, 1, 4, 1, 6486, 801, 1, 2, 1, 21, 1, 1, 1, 3, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: qAtmVciValue.setStatus('current')
if mibBuilder.loadTexts: qAtmVciValue.setDescription('.The Vci value of the ATM VC..')
qAtmIfIndexVpiVciVlanTagValue = MibTableColumn((1, 3, 6, 1, 4, 1, 6486, 801, 1, 2, 1, 21, 1, 1, 1, 3, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 4094))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: qAtmIfIndexVpiVciVlanTagValue.setStatus('current')
if mibBuilder.loadTexts: qAtmIfIndexVpiVciVlanTagValue.setDescription('Tag for a particular ATM Interface Index')
qAtmIfIndexVpiVciVlanAction = MibTableColumn((1, 3, 6, 1, 4, 1, 6486, 801, 1, 2, 1, 21, 1, 1, 1, 3, 1, 5), RowStatus()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: qAtmIfIndexVpiVciVlanAction.setStatus('current')
if mibBuilder.loadTexts: qAtmIfIndexVpiVciVlanAction.setDescription('Row Status for creating/deleting services.')
qAtmIfIndexVpiVciVlanDescription = MibTableColumn((1, 3, 6, 1, 4, 1, 6486, 801, 1, 2, 1, 21, 1, 1, 1, 3, 1, 6), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 31))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: qAtmIfIndexVpiVciVlanDescription.setStatus('current')
if mibBuilder.loadTexts: qAtmIfIndexVpiVciVlanDescription.setDescription('Textual description of vlan added to an Interface Index.')
qAtmIfIndexVpiVciAcceptableFrameTypes = MibTableColumn((1, 3, 6, 1, 4, 1, 6486, 801, 1, 2, 1, 21, 1, 1, 1, 3, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("admitAll", 1), ("admitOnlyVlanTagged", 2))).clone('admitAll')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: qAtmIfIndexVpiVciAcceptableFrameTypes.setStatus('current')
if mibBuilder.loadTexts: qAtmIfIndexVpiVciAcceptableFrameTypes.setDescription('When this is admitOnlyVlanTagged(2) the device will discard untagged frames or Priority-Tagged frames received on this port. When admitAll(1), untagged frames or Priority-Tagged frames received on this port will be accepted and assigned to the PVID for this port. This control does not affect VLAN independent BPDU frames, such as GVRP and STP. It does affect VLAN dependent BPDU frames, such as GMRP.')
qAtmIfIndexVpiVciForceTagInternal = MibTableColumn((1, 3, 6, 1, 4, 1, 6486, 801, 1, 2, 1, 21, 1, 1, 1, 3, 1, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(2, 1, 0))).clone(namedValues=NamedValues(("na", 2), ("on", 1), ("off", 0))).clone('na')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: qAtmIfIndexVpiVciForceTagInternal.setStatus('current')
if mibBuilder.loadTexts: qAtmIfIndexVpiVciForceTagInternal.setDescription('0-ON, 1-OFF and 2-NA')
alcatelIND1Dot1QMIBCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 6486, 801, 1, 2, 1, 21, 1, 2, 2, 1)).setObjects(("ALCATEL-IND1-DOT1Q-MIB", "dot1qPortGroup"), ("ALCATEL-IND1-DOT1Q-MIB", "dot1qAggregateGroup"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
alcatelIND1Dot1QMIBCompliance = alcatelIND1Dot1QMIBCompliance.setStatus('current')
if mibBuilder.loadTexts: alcatelIND1Dot1QMIBCompliance.setDescription('Compliance statement for 802.1q.')
dot1qPortGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 6486, 801, 1, 2, 1, 21, 1, 2, 1, 1)).setObjects(("ALCATEL-IND1-DOT1Q-MIB", "qPortVlanSlot"), ("ALCATEL-IND1-DOT1Q-MIB", "qPortVlanPort"), ("ALCATEL-IND1-DOT1Q-MIB", "qPortVlanTagValue"), ("ALCATEL-IND1-DOT1Q-MIB", "qPortVlanStatus"), ("ALCATEL-IND1-DOT1Q-MIB", "qPortVlanDescription"), ("ALCATEL-IND1-DOT1Q-MIB", "qPortVlanForceTagInternal"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
dot1qPortGroup = dot1qPortGroup.setStatus('current')
if mibBuilder.loadTexts: dot1qPortGroup.setDescription('Collection of objects for management of 802.1q on the ports.')
dot1qAggregateGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 6486, 801, 1, 2, 1, 21, 1, 2, 1, 2)).setObjects(("ALCATEL-IND1-DOT1Q-MIB", "qAggregateVlanAggregateId"), ("ALCATEL-IND1-DOT1Q-MIB", "qAggregateVlanTagValue"), ("ALCATEL-IND1-DOT1Q-MIB", "qAggregateVlanStatus"), ("ALCATEL-IND1-DOT1Q-MIB", "qAggregateVlanDescription"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
dot1qAggregateGroup = dot1qAggregateGroup.setStatus('current')
if mibBuilder.loadTexts: dot1qAggregateGroup.setDescription('Collection of objects for management of 802.1q on the aggregate.')
mibBuilder.exportSymbols("ALCATEL-IND1-DOT1Q-MIB", qAggregateVlanTagValue=qAggregateVlanTagValue, qAtmIfIndexVpiVciEntry=qAtmIfIndexVpiVciEntry, qAggregateVlanStatus=qAggregateVlanStatus, qPortVlanTagValue=qPortVlanTagValue, qAtmIfIndexVpiVciForceTagInternal=qAtmIfIndexVpiVciForceTagInternal, alcatelIND1Dot1QMIB=alcatelIND1Dot1QMIB, v8021Q=v8021Q, qPortVlanTable=qPortVlanTable, dot1qPortGroup=dot1qPortGroup, PYSNMP_MODULE_ID=alcatelIND1Dot1QMIB, qAtmVciValue=qAtmVciValue, alcatelIND1Dot1QMIBObjects=alcatelIND1Dot1QMIBObjects, qAtmIfIndex=qAtmIfIndex, alcatelIND1Dot1QMIBGroups=alcatelIND1Dot1QMIBGroups, qAtmVpiValue=qAtmVpiValue, qAtmIfIndexVpiVciTable=qAtmIfIndexVpiVciTable, alcatelIND1Dot1QMIBCompliances=alcatelIND1Dot1QMIBCompliances, qPortVlanDescription=qPortVlanDescription, qPortVlanForceTagInternal=qPortVlanForceTagInternal, qAggregateVlanDescription=qAggregateVlanDescription, alcatelIND1Dot1QMIBConformance=alcatelIND1Dot1QMIBConformance, alcatelIND1Dot1QMIBCompliance=alcatelIND1Dot1QMIBCompliance, qAtmIfIndexVpiVciAcceptableFrameTypes=qAtmIfIndexVpiVciAcceptableFrameTypes, qAggregateVlanTable=qAggregateVlanTable, qAggregateVlanEntry=qAggregateVlanEntry, qAtmIfIndexVpiVciVlanTagValue=qAtmIfIndexVpiVciVlanTagValue, qAtmIfIndexVpiVciVlanDescription=qAtmIfIndexVpiVciVlanDescription, dot1qAggregateGroup=dot1qAggregateGroup, qAggregateVlanAggregateId=qAggregateVlanAggregateId, qAtmIfIndexVpiVciVlanAction=qAtmIfIndexVpiVciVlanAction, qPortVlanPort=qPortVlanPort, qPortVlanSlot=qPortVlanSlot, qPortVlanStatus=qPortVlanStatus, qPortVlanEntry=qPortVlanEntry)
|
987,501 | c04a7d9c9a4b9405630423b43b3f19c380e7829b | import redis
from django.conf import settings
from django.core.management.base import BaseCommand
from pin.search_indexes import PostIndex
from pin.models import Post
class Command(BaseCommand):
def handle(self, *args, **options):
r_server = redis.Redis(settings.REDIS_DB, db=settings.REDIS_DB_NUMBER)
s = r_server.smembers("ChangedPostsV1")
for cp in s:
try:
print "post:", cp
pi = PostIndex()
pi.update_object(Post.objects.get(id=cp))
r_server.srem("ChangedPostsV1", cp)
except Exception, e:
print str(e)
|
987,502 | a927a8cc5be4e0f82ce4d8c54ef8341b14da80fe | #!/usr/bin/env python
# -*- coding: utf-8 -*-s
from time import sleep
from Prototipo.intManager import Irq
class Cpu:
def __init__(self, mmu, intManager):
self._pc = (-1)
self._ir = None
self._mmu = mmu
self._intManager = intManager
#Proposito:Hace un tick al cpu
#Precondicion:-
def tick(self, log):
if (self._pc == -1):
return
log.setPidEjecutado() # para imprimir el pid ejecutado
self._fetch(log)
self._decode()
self._execute(log)
#Proposito:fechea una intruccion de la memoria y actualiza el pc.
#Precondicion:debe existir dicha posicion que fechea.
def _fetch(self, log):
self._ir = self._mmu.fetch(self._pc, log)
self._pc += 1
#Proposito:Levanta una interrupcion dependiendo la si la intruccion es un exit o un io, en caso q no sea
# ninguna de estas no hace nada.
#Precondicion:-
def _decode(self):
if self._ir.isExit():
self._intManager.handle(Irq.KILL, None)
elif self._ir.isIO():
self._intManager.handle(Irq.IO_IN, self._ir)
#Proposito:imprime por consola la intruccion y el pc de la proxima intruccion.
#Precondicion:-
def _execute(self, log):
log.printExecuteCPU(self._ir, self._pc)
sleep(0.25)
#Proposito:setea el pc<pc>
#Precondicion:-
def set_pc(self, pc):
self._pc = pc
#Proposito:retorna el pc
#Precondicion:-
def get_pc(self):
return self._pc
#Proposito:Retorna el ir
#Precondicion:-
def get_ir(self):
return self._ir
def __repr__(self):
return "CPU(PC={pc})".format(pc=self._pc)
|
987,503 | 60773bad2ce85530b5075dd54e0e20d2253f1523 | import os
import cupy as cp
BLOCKSIZE = 1024
module = cp.RawModule(path = os.path.dirname(__file__) + '/kernels.cubin', backend = 'nvcc')
ker_cubic = module.get_function('cubic')
def cubic(b, c, d):
x = cp.empty_like(b)
ker_cubic(((x.size- 1) // BLOCKSIZE + 1, ), \
(BLOCKSIZE, ), \
(b, c, d, x.size, x))
return x
|
987,504 | 8b8d7c43daa4ea5512a7c0d606d37c8906ddb20e | """
@BY: Reem Alghamdi
@DATE: 17-09-2020
"""
def de_bruijn_graph_fromkmer(kmers):
"""
:param kmers: array of kmers
:return adjacency list of prefix/suffix
"""
adj_list = {}
for edge in kmers:
from_prefix = edge[:-1]
to_suffix = edge[1:]
if adj_list.get(from_prefix):
adj_list[from_prefix].append(to_suffix)
else:
adj_list[from_prefix] = [to_suffix]
return adj_list
if __name__ == "__main__":
with open("../data/de_bruijn_graph_fromkmer") as file:
kmers = file.read().splitlines()
adj_list = de_bruijn_graph_fromkmer(kmers)
print(adj_list)
for node, lists in adj_list.items():
print(node, " -> ", ', '.join(lists))
# with open("../data/dataset_369270_8.txt") as file:
# with open("../data/output/ch3_05.txt", "a") as output:
# kmers = file.read().splitlines()
# adj_list = de_bruijn_graph_fromkmer(kmers)
# for node, lists in adj_list.items():
# output.write(node + " -> " + ', '.join(lists) + "\n")
|
987,505 | c8686756af6800082abf2d933bfbbc9932ea1f98 | import os
import random
import networkx as nx
import pandas as pd
delimiter = '\t'
def generate_graph(graph_func, params):
# set seed
seed = 93
# generate graph based on passed function and params
graph = graph_func(**params, seed=seed)
return graph
def load_dataset_to_graph(dataset_dir, node_limit=600):
prepared_edge_list = os.path.join(dataset_dir, 'edge_list.csv')
# LOAD EDGES
# Weights are auto loaded {'weight': 1.0}
graph = nx.read_edgelist(prepared_edge_list, create_using=nx.DiGraph(), nodetype=int)
# should still work after removing nodes
# because real attributes mapping is based on node id
# remove nodes if more than node_limit
overlimit_nodes = graph.number_of_nodes() - node_limit
if overlimit_nodes > 0:
print('Cutting nodes up to {}'.format(node_limit))
random.seed(93)
nodes_to_remove = random.sample(graph.nodes(), overlimit_nodes)
graph.remove_nodes_from(nodes_to_remove)
return graph
def attach_graph_attributes(graph):
# get list of attributes for each node id
degree_centralities = nx.degree_centrality(graph)
betweenness_centralities = nx.betweenness_centrality(graph)
closeness_centralities = nx.closeness_centrality(graph)
pageranks = nx.pagerank(graph)
# attach appropriate attributes to each node
for node_id in graph.nodes:
node_attributes = {
'degree_centrality': degree_centralities[node_id],
'betweenness_centrality': betweenness_centralities[node_id],
'closeness_centrality': closeness_centralities[node_id],
'pagerank': pageranks[node_id]
}
graph.node[node_id].update(node_attributes)
def attach_real_attributes(graph, dataset_dir):
prepared_node_attributes = os.path.join(dataset_dir, 'node_attributes.csv')
# LOAD ATTRIBUTES
attributes_data = pd.read_csv(prepared_node_attributes, delimiter=delimiter)
# list of node attributes without node_id
attributes_columns = list(attributes_data.columns)
attributes_columns.remove('node_id')
for node_id in graph.nodes:
attrs = attributes_data.loc[attributes_data['node_id'] == node_id]
node_attributes = {
colname: attrs[colname].values[0]
for colname in attributes_columns
}
graph.node[node_id].update(node_attributes)
return graph
|
987,506 | a03188760fce49616ef4603e97cd20b0d6437f2e | #!/usr/bin/env python3
# An example of how to use a custom message in a publisher.
#
# custom_publisher.py
#
# Bill Smart
#
# This shows how to use a custom message type with more than one data field.
import rospy
import sys
# Import the message definition
from rob599_basic.msg import Rectangle
from random import randint
if __name__ == '__main__':
# Initialize the node.
rospy.init_node('rectangler', argv=sys.argv)
# Set up the publisher.
publisher = rospy.Publisher('rectangles', Rectangle, queue_size=10)
# Manage the rate.
rate = rospy.Rate(1)
while not rospy.is_shutdown():
# Create the message and fill in the fields.
message = Rectangle()
message.height = randint(1, 10)
message.width = randint(1, 10)
# We could also construct the message like this. The data gets filled in according to the
# message definition. Don't use this, though, since it's not as clear to the reader as the
# other ways to do it.
#message = Rectangle(randint(1, 10), randint(1, 10))
# This is a better way to do it in the constructor, with named arguments.
#message = Rectangle(height=randint(1, 10), width=randint(1, 10))
publisher.publish(message)
rate.sleep()
|
987,507 | 0639cb0ddc7cf942325972da1278caebea22aa40 | class Solution:
def maximumWealth(self, a: List[List[int]]) -> int:
sumi = 0
for i in a:
sumi = max(sumi, sum(i))
return sumi
|
987,508 | 264525d93a310d19f9dc1e36625abd7e03014851 | # -*- coding: utf-8 -*-
# PlatoonTools plugin for BigBrotherBot(B3)
# Copyright (c) 2014 Harry Gabriel <rootdesign@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import b3
from b3.plugin import Plugin
from b3.clients import Client, Group
import b3.events
from threading import Thread
import json
from urllib2 import Request, urlopen, URLError
from ConfigParser import NoOptionError
import datetime
__version__ = '0.0.1'
__author__ = 'ozon'
class PlatoontoolsPlugin(Plugin):
_admin_plugin = None
platoons = {}
default_platoon_settings = {
'member_group': 'mod',
'leader_group': 'mod',
'admin_group': 'admin',
'min_member_days': 3,
}
def onLoadConfig(self):
# setup platoons and load settings
for section in self.config.sections():
if section != 'settings':
self.platoons.update({
section: {
'data': None,
'settings': self.default_platoon_settings
}
})
try:
self.platoons[section]['settings']['member_group'] = self.config.get(section, 'member_group')
except NoOptionError:
self.warning('could not find [platoon_id]/member_group for platoon id %s in config file, '
'using default: %s' % (section, self.default_platoon_settings['member_group']))
try:
self.platoons[section]['settings']['leader_group'] = self.config.get(section, 'leader_group')
except NoOptionError:
self.warning('could not find [platoon_id]/leader_group for platoon id %s in config file, '
'using default: %s' % (section, self.default_platoon_settings['leader_group']))
try:
self.platoons[section]['settings']['admin_group'] = self.config.get(section, 'admin_group')
except NoOptionError:
self.warning('could not find [platoon_id]/admin_group for platoon id %s in config file, '
'using default: %s' % (section, self.default_platoon_settings['admin_group']))
try:
self.platoons[section]['settings']['min_member_time'] = self.config.getint(section,
'min_member_days')
except NoOptionError:
self.warning('could not find [platoon_id]/min_member_time for platoon id %s in config file, '
'using default: %s' % (section, self.default_platoon_settings['min_member_time']))
# first platoon update
self.do_platoon_update()
def onStartup(self):
# load the admin plugin
self._admin_plugin = self.console.getPlugin('admin')
# check game parser
if self.console.game.gameName != 'bf4':
self.error('This plugin needs a BF4 game server.')
raise SystemExit(220)
# register event "Client Connect"
self.registerEvent(b3.events.EVT_CLIENT_AUTH)
def onEvent(self, event):
if event.type == b3.events.EVT_CLIENT_AUTH:
self._update_client_group(event.client)
def _get_platoon_member(self, client):
for p_id, platoon in self.platoons.items():
if client.name in platoon['data']['members']:
return platoon['data']['members'][client.name]
def _update_client_group(self, client):
"""Update the group for the given client"""
platoon_member = self._get_platoon_member(client)
if platoon_member:
# check join date
join_date = datetime.datetime.fromtimestamp(platoon_member['joined']).date()
min_member_days = self.platoons[platoon_member['platoon_id']]['settings']['min_member_days']
if join_date >= datetime.date.today()-datetime.timedelta(days=min_member_days):
self.info('%s does not reach the required member time.' % client.name)
return
# get b3 group keyword for the platoon member
group = Group(keyword=self.platoons[platoon_member['platoon_id']]['settings']['member_group'])
if platoon_member['is_admin']:
group = Group(keyword=self.platoons[platoon_member['platoon_id']]['settings']['admin_group'])
elif platoon_member['is_leader']:
group = Group(keyword=self.platoons[platoon_member['platoon_id']]['settings']['leader_group'])
#elif platoon_member['is_founder']:
# group = Group(keyword=self.platoons[platoon_member['platoon_id']]['settings']['founder_group'])
# get group from storage
group = self.console.storage.getGroup(group)
# put client in group
if not client.inGroup(group) and not client.maxLevel >= group.level:
self.debug('Put %s in group %s' % (client.name, group.name))
client.setGroup(group)
client.save()
def callback_platoon_update(self, platoon_id, data):
raw_data = data.get('globalContext').get('club')
if raw_data:
self.info('Update platoon [%s] - %s' % (raw_data.get('tag'), raw_data.get('name')))
if raw_data.get('status') == 'applyinvite':
self.warning('Everyone can join the platoon "%s" without invitation! '
'For safe use, new members should join by invitation only.' % raw_data.get('name'))
platoon_members = raw_data.get('founders') + raw_data.get('leaders') + raw_data.get('members')
admin_ids = raw_data.get('adminIds')
founder_ids = [f.get('userId') for f in raw_data.get('founders')]
leader_ids = [f.get('userId') for f in raw_data.get('leaders')]
members = dict()
for member in platoon_members:
members[member.get('user').get('username')] = dict(
name=member.get('user').get('username'),
user_id=member.get('user').get('userId'),
level=member.get('level'),
joined=member.get('joinedDate'),
is_admin=True if member.get('user').get('userId') in admin_ids else False,
is_founder=True if member.get('user').get('userId') in founder_ids else False,
is_leader=True if member.get('user').get('userId') in leader_ids else False,
platoon_id=member.get('clubId')
)
self.platoons[platoon_id]['data'] = {
'name': raw_data.get('name'),
'tag': raw_data.get('tag'),
'admin_ids': admin_ids,
'members': members,
'status': raw_data.get('status')
}
# update connected clients
[self._update_client_group(client) for client in self.console.clients.getList()]
def do_platoon_update(self):
for p_id in self.platoons.keys():
self.debug('Fetch data from battlelog for platoon id: %s' % p_id)
BattlelogQuery(platoon_id=p_id, callback=self.callback_platoon_update, callback_args=(p_id,)).start()
class BattlelogQuery(Thread):
def __init__(self, name=None, platoon_id=None, callback=None, callback_args=()):
Thread.__init__(self, name=name, )
self.__platoon_id = platoon_id
self.__callback = callback
self.__callback_args = callback_args
def run(self):
platoon_raw_data = self.fetch_data()
if self.__callback:
self.__callback(*self.__callback_args, data=platoon_raw_data)
def fetch_data(self):
url = 'http://battlelog.battlefield.com/bf4/en/platoons/members/%s/' % self.__platoon_id
headers = {'X-Requested-With': 'XMLHttpRequest', 'X-AjaxNavigation': '1'}
req = Request(url, '', headers)
try:
response = urlopen(req)
except URLError as e:
print e.reason
else:
return json.load(response)
if __name__ == '__main__':
from b3.fake import fakeConsole, superadmin, joe, simon, fakeAdminPlugin
import time
myplugin = PlatoontoolsPlugin(fakeConsole, 'extplugins/conf/plugin_platoontools.ini')
myplugin.console.game.gameName = 'bf4'
myplugin.onStartup()
myplugin.onLoadConfig()
time.sleep(2)
myplugin.console.game.gameType = 'Domination0'
myplugin.console.game._mapName = 'XP2_Skybar'
superadmin.connects(cid=0)
# make joe connect to the fake game server on slot 1
joe.connects(cid=1)
# make joe connect to the fake game server on slot 2
simon.connects(cid=2)
# superadmin put joe in group user
#superadmin.says('!putgroup joe user')
superadmin.says('!putgroup simon user')
joe.name = 'O2ON'
superadmin.connects(cid=0) |
987,509 | 3fea1c84129f7ef3ae6f6ef9f76054e6e27e871e | # The number 3797 has an interesting property. Being prime itself, it is
# possible to continuously remove digits from left to right, and remain prime
# at each stage: 3797, 797, 97, and 7. Similarly we can work from right to
# left: 3797, 379, 37, and 3.
#
# Find the sum of the only eleven primes that are both truncatable from left
# to right and right to left.
#
# NOTE: 2, 3, 5, and 7 are not considered to be truncatable primes.
from p032 import render_to_number
from itertools import ifilter, product, count, chain
from math import sqrt
def truncations(number):
digits = str(number)
for i in xrange(1,len(digits)):
yield int(digits[:-i])
yield int(digits[i:])
def is_truncatable(number):
if not is_prime(number):
return False
if any( not is_prime(trunc) for trunc in truncations(number) ):
return False
return True
mod30_set = set([1,7,11,13,17,19,23,29])
def is_potential_prime(n):
if n % 30 in mod30_set:
return True
return False
def potential_primes(limit=None):
def candidates(start=1):
for i in count(start):
n = 6 * i
yield n - 1
yield n + 1
for n in chain([2,3,5],ifilter(is_potential_prime,candidates())):
if limit and n > limit:
break
yield n
raise StopIteration()
def is_prime(n):
for pprime in potential_primes(sqrt(n)):
if n % pprime == 0:
return False
return True
def potential_truncatable_primes():
begin_digits = (2,3,4,5,7)
middle_digits = (1,3,7,9)
end_digits = (3,7)
for i in count():
for num in [ render_to_number(seq) for seq in
[ (beg,) + mid + (end,)
for beg in begin_digits
for mid in product(middle_digits, repeat=i)
for end in end_digits
] ]:
yield num
def truncatable_primes():
prime_count = 0
for prime in ifilter(is_truncatable,
potential_truncatable_primes()):
yield prime
prime_count += 1
if prime_count >= 11: break
raise StopIteration()
if __name__ == "__main__":
trunc_primes = list(truncatable_primes())
assert( 3797 in trunc_primes )
assert( len(trunc_primes) == 11 )
print 'Truncatable Primes:', trunc_primes
print 'Sum:', sum(trunc_primes)
|
987,510 | 4b06c73d51fb662691580f1d27c621647b947b15 | # from django.db.models.signals import post_save,pre_save,post_delete,pre_delete
# from django.dispatch import receiver
# from .models import Book,ISBN,User
# @receiver(post_save, sender = Book)
# def after_book_addition(sender,instance,created,*args, **kwargs):
# if created:
# isbn_instance = ISBN.objects.create(author_title=instance.user.username,
# book_name=instance.book_name
# )
# instance.isbn = isbn_instance
# instance.save() |
987,511 | adc9447ea0444bcf0ff6e0e01c7f988456a18af6 | from random import randint
from sqlalchemy.exc import IntegrityError
from faker import Faker
from . import db
from .models import User, Post
def users(count=100):
faker = Faker()
i = 0
while i < count:
u = User(email=faker.email(), username=faker.user_name(),
password='password',
name=faker.name(), location=faker.city(),
about_me=faker.text(), member_since=faker.past_date())
db.session.add(u)
try:
db.session.commit()
i += 1
# 防止faker生成重复的用户名和电子邮件,如果重复则抛出异常
except IntegrityError:
db.session.rollback()
def posts(count=100):
faker = Faker()
user_count = User.query.count()
for i in range(count):
u = User.query.offset(randint(0, user_count-1)).first()
p = Post(body=faker.text(), timestamp=faker.past_date(), author=u)
db.session.add(p)
db.session.commit() |
987,512 | d206f286ef133efef45bd57a7ccb54928f2a2ea8 | '''
-Medium-
Given a binary tree, imagine yourself standing on the right side of it, return the values of
the nodes you can see ordered from top to bottom.
Example:
Input: [1,2,3,null,5,null,4]
Output: [1, 3, 4]
Explanation:
1 <---
/ \
2 3 <---
\ \
5 4 <---
'''
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
from collections import deque
class Solution(object):
def rightSideView(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
res = []
if not root: return res
queue = deque([root])
while queue:
newq = deque()
while len(queue) > 1:
node = queue.popleft()
if node.left:
newq.append(node.left)
if node.right:
newq.append(node.right)
node = queue.popleft()
res.append(node.val)
if node.left:
newq.append(node.left)
if node.right:
newq.append(node.right)
queue = newq
return res
|
987,513 | 61cd2b418bdc2fbe93b3c97dfe99b9938f3ce8c7 | #使用while-else和列表实现1~9的平方
list1=[1,2,3,4,5,6,7,8,9]
total=len(list1)
i=0
print("计算1-9的平方:")
while i<total:
square=list1[i] * list1[i]
print(i+1,"的平方是:",square)
i+=1
else:
print("循环正常结束!")
'''
#while-else有break练习
i=0
while i<5:
print("第%d次循环"%i)
if i==3:
break
i+=1
else:
print("循环正常结束!")
print("开始执行循环后语句...")
'''
#for-else练习
for i in range(1,5,1):
print(i)
if i==4:
break
else:
print("循环正常结束!")
|
987,514 | 758bfadb9493f24596827c70c9f0bce4d0e0fcf4 | import programs.schema.table_building.tablebuilder as tablebuilder
from programs.schema.schemas.schemamaker import SchemaMaker
from constants import CC
import numpy as np
import pandas as pd
import das_utils
import programs.cenrace as cenrace
def getTableDict():
tabledict = {
################################################
# Hierarchical age category tables
################################################
# Prefix Query
"prefixquery": ['prefix_agecats', 'age'],
# Range Query
"rangequery": ['range_agecats', 'age'],
# Prefix Query
"binarysplitquery": ['binarysplit_agecats', 'age'],
################################################
# SF1 Proposed Tables for 2020 (Person-focused)
################################################
# Table P1 - Total Population
# Universe: Total Population
"P1": ["total"],
# Table P3 - Race
# Universe: Total Population
"P3": ["total", "majorRaces"],
# Table P4 - Hispanic or Latino
# Universe: Total Population
"P4": ["total", "hispanic"],
# Table P5 - Hispanic or Latino by Race
# Universe: Total Population
"P5": ["total", "hispanic", "hispanic * majorRaces"],
# Table P6 - Race (Total Races Tallied)
# Universe: Total Races Tallied ???
# What does the total races tallied query mean??? Do we use "total" or some
# recode that totals the racecomb query answers?
"P6": [# "racecombTotal",
# "total",
"racecomb"],
# Table P7 - Hispanic or Latino by Race (Total Races Tallied)
# Universe: Total Races Tallied ???
# What does the total races tallied query mean??? Do we use "total" or some
# recode that totals the racecomb query answers?
"P7": [# "racecombTotal",
# "total",
# "hispanic * racecombTotal",
# "hispanic",
"racecomb", "hispanic * racecomb"],
# Table P12 - Sex by Age
# Universe: Total Population
"P12": ["total", "sex", "sex * agecat"],
# Table P13 - Median age by Sex (1 Expressed Decimal)
# Table P14 - Sex by Age for the Population Under 20 Years
# Universe: Population Under 20 Years
"P14": ["under20yearsTotal", "under20yearsTotal * sex", "under20years * sex"],
# Table P16 - Population in households by age
"P16": ["hhTotal", "hhTotal * votingage"],
# Table P43 - GQ Population by Sex by Age by Major GQ Type
# Universe: Population in GQs
"P43": ["gqTotal", "gqTotal * sex", "gqTotal * sex * agecat43", "sex * agecat43 * institutionalized",
"sex * agecat43 * majorGQs"],
# Table P12A - Sex by Age (White alone)
# Universe: People who are White alone
"P12A": [
"whiteAlone", "whiteAlone * sex", "whiteAlone * sex * agecat",
],
# Table P12B - Sex by Age (Black or African American alone)
# Universe: People who are Black or African American alone
"P12B": [
"blackAlone", "blackAlone * sex", "blackAlone * sex * agecat"
],
# Table P12C - Sex by Age (American Indian and Alaska Native alone)
# Universe: People who are American Indian and Alaska Native alone
"P12C": [
"aianAlone", "aianAlone * sex", "aianAlone * sex * agecat"
],
# Table P12D - Sex by Age (Asian alone)
# Universe: People who are Asian alone
"P12D": [
"asianAlone", "asianAlone * sex", "asianAlone * sex * agecat"
],
# Table P12E - Sex by Age (Native Hawaiian and Other Pacific Islander alone)
# Universe: People who are Native Hawaiian and Other Pacific Islander alone)
"P12E": [
"nhopiAlone", "nhopiAlone * sex", "nhopiAlone * sex * agecat"
],
# Table P12F - Sex by Age (Some Other Race alone)
# Universe: People who are Some Other Race alone
"P12F": [
"sorAlone", "sorAlone * sex", "sorAlone * sex * agecat"
],
# Table P12G - Sex by Age (Two or more races)
# Universe: People who are two or more races
"P12G": [
"tomr", "tomr * sex", "tomr * sex * agecat"
],
# Table P12H - Sex by Age (Hispanic or Latino)
# Universe: People who are Hispanic or Latino
"P12H": [
"hispTotal", "hispTotal * sex", "hispTotal * sex * agecat"
],
# Table P12I - Sex by Age (White alone, not Hispanic or Latino)
"P12I": [
"whiteAlone * notHispTotal", "whiteAlone * notHispTotal * sex", "whiteAlone * notHispTotal * sex * agecat"
],
# Tables P13A-I Median age by sex
# PCO1 - Group Quarters Population by Sex by Age
# Universe: Population in group quarters
"PCO1": ["gqTotal", "gqTotal * sex", "gqTotal * sex * agecatPCO1"],
# PCO2 - Group Quarters Population in Institutional Facilities by Sex by Age
# Universe: Institutionalized Population
"PCO2": ["instTotal", "instTotal * sex", "instTotal * sex * agecatPCO1"],
# PCO3 - GQ Pop in Correctional Facilities for Adults by Sex by Age
# Universe: Pop in correctional facilities for adults
"PCO3": ["gqCorrectionalTotal", "gqCorrectionalTotal * sex", "gqCorrectionalTotal * sex * agecatPCO3"],
# PCO4 - GQ Pop in Juvenile Facilities by Sex by Age
# Universe: Pop in juvenile facilities
"PCO4": ["gqJuvenileTotal", "gqJuvenileTotal * sex", "gqJuvenileTotal * sex * agecatPCO4"],
# PCO5 - GQ Pop in Nursing Facilities / Skilled-Nursing Facilities by Sex by Age
# Universe: Pop in nursing facilities/skilled-nursing facilities
"PCO5": ["gqNursingTotal", "gqNursingTotal * sex", "gqNursingTotal * sex * agecatPCO5"],
# PCO6 - GQ Pop in Other Institutional Facilities by Sex by Age
# Universe: Pop in other institutional facilities
"PCO6": ["gqOtherInstTotal", "gqOtherInstTotal * sex", "gqOtherInstTotal * sex * agecatPCO1"],
# PCO7 - GQ Pop in Noninstitutional Facilities by Sex by Age
# Universe: Pop in noninstitutional facilities
"PCO7": ["noninstTotal", "noninstTotal * sex", "noninstTotal * sex * agecatPCO7"],
# PCO8 - GQ Pop in College/University Student Housing by Sex by Age
# Universe: Pop in college/university student housing
"PCO8": ["gqCollegeTotal", "gqCollegeTotal * sex", "gqCollegeTotal * sex * agecatPCO8"],
# PCO9 - GQ Pop in Military Quarters by Sex by Age
# Universe: Pop in military quarters
"PCO9": ["gqMilitaryTotal", "gqMilitaryTotal * sex", "gqMilitaryTotal * sex * agecatPCO8"],
# PCO10 - GQ Pop in Other Noninstitutional Facilities by Sex by Age
# Universe: Pop in other noninstitutional facilities
"PCO10": ["gqOtherNoninstTotal", "gqOtherNoninstTotal * sex", "gqOtherNoninstTotal * sex * agecatPCO7"],
# PCO43A - GQ Pop by Sex by Age by Major GQ Type (White alone)
# Universe: Pop in group quarters
"PCO43A": [
"whiteAlone * gqTotal",
"whiteAlone * gqTotal * sex",
"whiteAlone * gqTotal * sex * agecat43",
"whiteAlone * institutionalized * sex * agecat43",
"whiteAlone * majorGQs * sex * agecat43"
],
# PCO43B - GQ Pop by Sex by Age by Major GQ Type (Black or African American alone)
# Universe: Pop in group quarters
"PCO43B": [
"blackAlone * gqTotal",
"blackAlone * gqTotal * sex",
"blackAlone * gqTotal * sex * agecat43",
"blackAlone * institutionalized * sex * agecat43",
"blackAlone * majorGQs * sex * agecat43"
],
# PCO43C - GQ Pop by Sex by Age by Major GQ Type (American Indian or Alaska Native alone)
# Universe: Pop in group quarters
"PCO43C": [
"aianAlone * gqTotal",
"aianAlone * gqTotal * sex",
"aianAlone * gqTotal * sex * agecat43",
"aianAlone * institutionalized * sex * agecat43",
"aianAlone * majorGQs * sex * agecat43"
],
# PCO43D - GQ Pop by Sex by Age by Major GQ Type (Asian alone)
# Universe: Pop in group quarters
"PCO43D": [
"asianAlone * gqTotal",
"asianAlone * gqTotal * sex",
"asianAlone * gqTotal * sex * agecat43",
"asianAlone * institutionalized * sex * agecat43",
"asianAlone * majorGQs * sex * agecat43"
],
# PCO43E - GQ Pop by Sex by Age by Major GQ Type (Native Hawaiian or Other Pacific Islander alone)
# Universe: Pop in group quarters
"PCO43E": [
"nhopiAlone * gqTotal",
"nhopiAlone * gqTotal * sex",
"nhopiAlone * gqTotal * sex * agecat43",
"nhopiAlone * institutionalized * sex * agecat43",
"nhopiAlone * majorGQs * sex * agecat43"
],
# PCO43F - GQ Pop by Sex by Age by Major GQ Type (Some Other Race alone)
# Universe: Pop in group quarters
"PCO43F": [
"sorAlone * gqTotal",
"sorAlone * gqTotal * sex",
"sorAlone * gqTotal * sex * agecat43",
"sorAlone * institutionalized * sex * agecat43",
"sorAlone * majorGQs * sex * agecat43"
],
# PCO43G - GQ Pop by Sex by Age by Major GQ Type (Two or More Races Alone)
# Universe: Pop in group quarters
"PCO43G": [
"tomr * gqTotal",
"tomr * gqTotal * sex",
"tomr * gqTotal * sex * agecat43",
"tomr * institutionalized * sex * agecat43",
"tomr * majorGQs * sex * agecat43"
],
# PCO43H - GQ Pop by Sex by Age by Major GQ Type (Hispanic or Latino)
# Universe: Pop in group quarters
"PCO43H": [
"hispTotal * gqTotal",
"hispTotal * gqTotal * sex",
"hispTotal * gqTotal * sex * agecat43",
"hispTotal * institutionalized * sex * agecat43",
"hispTotal * majorGQs * sex * agecat43"
],
# PCO43I - GQ Pop by Sex by Age by Major GQ Type (White Alone, Not Hispanic or Latino)
# Universe: Pop in group quarters
### The [complement/partition of each race * not hispanic] of the universe might be useful ####
"PCO43I": [
"whiteAlone * notHispTotal * gqTotal",
"whiteAlone * notHispTotal * gqTotal * sex",
"whiteAlone * notHispTotal * gqTotal * sex * agecat43",
"whiteAlone * notHispTotal * institutionalized * sex * agecat43",
"whiteAlone * notHispTotal * majorGQs * sex * agecat43"
],
# PCT12 - Sex by Age
# Universe: Total Population
"PCT12": ["total", "sex", "sex * agecatPCT12"],
# PCT13
# Universe: Population in households
"PCT13": ["hhTotal", "hhTotal * sex", "hhTotal * sex * agecat"],
# PCT22 - GQ Pop by Sex by Major GQ Type for Pop 18 Years and Over
# Universe: Pop 18 years and over in group quarters
"PCT22": ["over17yearsTotal * gqTotal", "over17yearsTotal * gqTotal * sex", "over17yearsTotal * sex * institutionalized",
"over17yearsTotal * sex * majorGQs"],
# PCT13A
# Universe: Population of White alone in households
"PCT13A": [
"whiteAlone * hhTotal", "whiteAlone * hhTotal * sex", "whiteAlone * hhTotal * sex * agecat",
],
# PCT13B
# Universe: Population of Black alone in households
"PCT13B": ["blackAlone * hhTotal", "blackAlone * hhTotal * sex", "blackAlone * hhTotal * sex * agecat",
],
# PCT13C
# Universe: Population of AIAN alone in households
"PCT13C": ["aianAlone * hhTotal", "aianAlone * hhTotal * sex", "aianAlone * hhTotal * sex * agecat",
],
# PCT13D
# Universe: Population of Asian alone in households
"PCT13D": ["asianAlone * hhTotal", "asianAlone * hhTotal * sex", "asianAlone * hhTotal * sex * agecat",
],
# PCT13E
# Universe: Population of Hawaiian/Pacific Islander alone in households
"PCT13E": ["nhopiAlone * hhTotal", "nhopiAlone * hhTotal * sex", "nhopiAlone * hhTotal * sex * agecat",
],
# PCT13F
# Universe: Population of Some other race alone in households
"PCT13F": ["sorAlone * hhTotal", "sorAlone * hhTotal * sex", "sorAlone * hhTotal * sex * agecat",
],
# PCT13G
# Universe: Population of Two or more races in households
"PCT13G": ["tomr * hhTotal", "tomr * hhTotal * sex", "tomr * hhTotal * sex * agecat",
],
# PCT13H
# Universe: Population of Hispanic or latino in households
"PCT13H": ["hispTotal * hhTotal", "hispTotal * hhTotal * sex", "hispTotal * hhTotal * sex * agecat",
],
# PCT13I
# Universe: Population of White alone, non-hispanic in households
"PCT13I": ["whiteAlone * notHispTotal * hhTotal", "whiteAlone * notHispTotal * hhTotal * sex",
"whiteAlone * notHispTotal * hhTotal * sex * agecat"
],
}
return tabledict
def getTableBuilder(testtables=None):
"""
:param testtables: Will run the testTableDefs function to ensure recodes
from the same dimension aren't crossed in a table. This is useful if you
get the error because it identifies the table and the cell of the list where
the error occurs.
:return:
"""
schema = SchemaMaker.fromName(CC.SCHEMA_REDUCED_DHCP_HHGQ)
tabledict = getTableDict()
if testtables==True:
tablebuilder.testTableDefs(schema, tabledict)
else:
schema = SchemaMaker.fromName(CC.SCHEMA_REDUCED_DHCP_HHGQ)
tabledict = getTableDict()
builder = tablebuilder.TableBuilder(schema, tabledict)
return builder
############################################################
## Consolidated tables
############################################################
'''
# Tables P12A-I
# Combines individual P12A-I tables
"P12A-I": [# P12A-G
"total", "majorRaces", "majorRaces * sex", "majorRaces * sex * agecat",
# P12H
"hispTotal", "hispTotal * sex", "hispTotal * sex * agecat",
# P12I
"whiteAlone * notHispTotal", "whiteAlone * notHispTotal * sex", "whiteAlone * notHispTotal * sex * agecat"],
# Tables PCO43A-I
# Combines individual PCO43A-I tables
"PCO43A-I": [
# PCO43A-G
"majorRaces * gqTotal", "majorRaces * gqTotal * sex", "majorRaces * gqTotal * sex * agecat43",
"majorRaces * sex * agecat43 * institutionalized", "majorRaces * sex * agecat43 * majorGQs",
# PCO43H
"hispTotal * gqTotal", "hispTotal * gqTotal * sex", "hispTotal * gqTotal * sex * agecat43",
"hispTotal * sex * agecat43 * institutionalized", "hispTotal * sex * agecat43 * majorGQs",
# PCO43I
"whiteAlone * notHispTotal * gqTotal", "hispTotal * gqTotal * sex", "whiteAlone * notHispTotal * gqTotal * sex * agecat43",
"whiteAlone * notHispTotal * sex * agecat43 * institutionalized", "whiteAlone * notHispTotal * sex * agecat43 * majorGQs"
],
# PCT13A-I
#Combines individual tables PCT13A-PCT13I
#Universe: Population in households for major race group, hispanic, or white along/non-hispanic
"PCT13A-I": [
# PCT13A-G
"majorRaces * hhTotal", "majorRaces * hhTotal * sex", "majorRaces * hhTotal * sex * agecat",
# PCT13H
"hispTotal * hhTotal", "hispTotal * hhTotal * sex", "hispTotal * hhTotal * sex * agecat",
#PCT13I
"whiteAlone * notHispTotal * hhTotal", "whiteAlone * notHispTotal * hhTotal * sex", "whiteAlone * notHispTotal * hhTotal * sex * agecat"
],
''' |
987,515 | c1c4b75a7c2b6c46fbdf4402a50a4d5a3b68bbba | from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.decorators import api_view
from rest_framework import status
from .models import Team, Game
from .serializers import *
from datetime import datetime
import json
@api_view(['GET'])
def teams(request):
data = Team.objects.all().order_by('-playoff_points', '-diff')
serializer = TeamSerializer(data, context={'request': request}, many=True)
return Response(serializer.data)
@api_view(['GET'])
def teams_ordered(request):
data = Team.objects.all().order_by('pk')
serializer = TeamSerializer(data, context={'request': request}, many=True)
return Response(serializer.data)
@api_view(['GET'])
def teams_by_region(request, region):
data = Team.objects.filter(region=region).order_by('-playoff_points', '-diff')
serializer = TeamSerializer(data, context={'request': request}, many=True)
return Response(serializer.data)
@api_view(['GET'])
def week(request):
current_week = (int(datetime.now().strftime("%W"))-14)%52
games = Game.objects.filter(week=current_week)
if len(games) != 0:
current_tournament = games[0].tournament
else:
current_tournament = ""
return_dict = {"week": current_week, "tournament": current_tournament}
return Response(json.dumps(return_dict))
@api_view(['GET'])
def games(request, week):
try:
games = Game.objects.filter(week=week)
except:
return Response(status=status.HTTP_404_NOT_FOUND)
else:
serializer = GameSerializer(games, context={'request': request}, many=True)
return Response(serializer.data)
@api_view(['GET'])
def games_by_tournament(request):
current_week = (int(datetime.now().strftime("%W"))-14)%52
games = Game.objects.filter(week=current_week)
if len(games) != 0:
current_tournament = games[0].tournament
else:
current_tournament = ""
games = Game.objects.filter(tournament=current_tournament, has_occurred=False).order_by('date_time')
serializer = GameSerializer(games, context={'request': request}, many=True)
return Response(serializer.data)
#@api_view(['GET'])
#def head_to_head(request, team1, team2, tournament):
# games = Game.objects.filter(tournament=tournament, has_occurred=True)
# for game in games:
# teams = game.teams.all()
# t1 = Team.objects.get(name=team1)
# t2 = Team.objects.get(name=team2)
# if t1 in teams and t2 in teams:
# if
# return Response(json.dumps({"headtohead": True}))
#
# return Response(json.dumps({"headtohead": 0})) |
987,516 | 5dccd30c116e98893cc36fc2df0a62843fac21c2 | from pathlib import Path
import logging
import torch
from torch.autograd import Variable
from gammago.model import BaseModel, TorchModel
from gammago.commands import argument
# Arguments can be added using the "argument" annotation
# whose parameters follow the argpase.ArgumentParser.add_argument
@argument("--hidden", type=int, default=0)
class Model(TorchModel):
"""
A simple model with one or two layers
Torch models must implement four methods:
- construct: construct the module
- train: train with a batch and output the cost
- cost: compute the cost of a batch
- predict:
"""
def construct(self):
"""Called when the model has been configured to construct the network"""
self.input_size = self.numplanes * self.boardsize**2
if self.hidden:
layers = [
torch.nn.Linear(self.input_size, self.hidden),
torch.nn.ReLU(),
torch.nn.Linear(self.hidden, self.boardsize**2)
]
else:
layers = [torch.nn.Linear(self.input_size, self.boardsize**2)]
self.layers = torch.nn.ModuleList(layers)
self.optimizer = torch.optim.Adam(self.parameters(), lr=1e-5)
logging.info("Model initialized: %s", self)
def _predict(self, boards, volatile=True):
_boards = Variable(torch.Tensor(boards), volatile=volatile)
y = _boards.view(-1, self.input_size)
for layer in self.layers:
y = layer(y)
return y
def _cost(self, boards, labels, volatile=True):
_labels = Variable(torch.LongTensor(labels), volatile=volatile)
y = self._predict(boards, volatile=volatile)
return torch.nn.functional.cross_entropy(y, _labels)
def predict(self, boards):
"""Predict a move
:param boards: a numpy tensor of dimension (batch size, num planes, board size, board size)
:returns: A probability distribution over moves
"""
y = self._predict(boards)
return torch.nn.functional.softmax(y).data.numpy()
def train(self, boards, labels):
"""Train the model on the batch and returns the current cost
:param boards: a numpy real tensor of dimension (batch size, num planes, board size, board size)
:param labels: a numpy integer tensor of dimension (batch size, output size)
"""
cost = self._cost(boards, labels, volatile=False)
cost.backward()
self.optimizer.step()
self.epoch += 1
return cost.data.numpy()
def cost(self, boards, labels):
"""Return the batch cost
:param boards: a numpy real tensor of dimension (batch size, num planes, board size, board size)
:param labels: a numpy integer tensor of dimension (batch size, output size)
"""
return self._cost(boards, labels, volatile=True).data.numpy()
|
987,517 | 9d6de4ef6d93ba53e72b2acdb4b751171b47e6b2 | from translate import Translator
translator = Translator(to_lang="ja")
try:
with open('./test.txt', mode='r') as my_file:
text = my_file.read()
translation = translator.translate(text)
with open('./test=py.txt', mode="w") as my_file_ja:
my_file_ja.write(translation)
except FileNotFoundError as err:
print(f'file not found: {err}')
|
987,518 | 525564c2b98178c0021db13c1621b37de88910cb | n=int (input())
a,b=(input().split())
a,b= [int(a),int(b)]
if((n>a)and(n<b)):
print('yes')
else:
print('no')
|
987,519 | 417560f6e78ada58f1ca5b26fbce6fec22546c06 | from datetime import datetime
class Patient(object):
num_pat = 0
def __init__(self,pat_name, pat_allergies,):
self.id = Patient.num_pat
self.pat_name = pat_name
self.pat_allergies = pat_allergies
self.pat_bed = 0
Patient.num_pat += 1
def display(self):
print self.id
print self.pat_name
print self.pat_allergies
print self.pat_bed
return self
class Hospital(object):
def __init__(self, name, cap):
self.patients = []
self.name = name
self.capacity = cap
self.beds = self.initialize_beds()
def initialize_beds(self):
beds = []
for i in range (1, self.capacity+1):
beds.append({
"bed_id": i,
"Available": True
})
return beds
def admit(self,new_pat):
print "Patients:", len(self.patients)
print "Beds: ", len(self.beds)
print "admitting: ", new_pat.pat_name
if len(self.patients) >= len(self.beds):
print "All beds full"
else:
for q in range (0, len(self.beds)):
if self.beds[q]["Available"] == True:
new_pat.pat_bed = self.beds[q]["bed_id"]
self.beds[q]["Available"] = False
print "Patient in bed: ", self.beds[q]["bed_id"]
self.patients.append(new_pat)
break
def discharge(self,dis_pat):
#remove a patent add bed back jsut liek add but work off patient"ID" to figure out what bed to free up
print self.name
def info(self):
print self.name
print "-------------------------------------"
for patient in self.patients:
print patient.pat_name, " | Room: ", patient.pat_bed
c1 = Patient('Jeff Whitton', "food")
c2 = Patient('Jerry Herd', "drugs")
c3 = Patient('Harry Hood', "drugs")
c4 = Patient('Mary Nerd', "drugs")
c5 = Patient('Dairy Herd', "drugs")
c6 = Patient('Hon Doe', "drugs")
c7 = Patient('Mancy', "drugs")
c8 = Patient('Lichtenstein Mcdaverd', "drugs")
c1.display()
ER = Hospital('The Emergency Room', 5)
ER.admit(c1)
ER.admit(c2)
ER.admit(c3)
ER.admit(c4)
ER.admit(c5)
ER.admit(c6)
ER.admit(c7)
ER.admit(c8)
ER.info()
|
987,520 | fcb1bce973b60c6ac64674a510718ffe058f2374 | # Generated by the protocol buffer compiler. DO NOT EDIT!
# source: protocol/Proto/Platform.proto
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import descriptor_pb2
# @@protoc_insertion_point(imports)
DESCRIPTOR = _descriptor.FileDescriptor(
name='protocol/Proto/Platform.proto',
package='protocol.platform',
serialized_pb='\n\x1dprotocol/Proto/Platform.proto\x12\x11protocol.platform\"\xba\x01\n\x0fQQGameLoginData\x12\x0e\n\x06openID\x18\x01 \x01(\t\x12\x0f\n\x07openKey\x18\x02 \x01(\t\x12\r\n\x05pfKey\x18\x03 \x01(\t\x12\x11\n\tisBlueVip\x18\x04 \x01(\x08\x12\x15\n\risBlueYearVip\x18\x05 \x01(\x08\x12\x14\n\x0c\x62lueVipLevel\x18\x06 \x01(\r\x12\x10\n\x08nickName\x18\x07 \x01(\t\x12\x0e\n\x06gender\x18\x08 \x01(\t\x12\x15\n\risHighBlueVip\x18\t \x01(\x08\"\xc1\x01\n\x10LoginSessionData\x12\x10\n\x08\x63lientID\x18\x01 \x02(\r\x12\x13\n\x0b\x61\x63\x63ountName\x18\x02 \x02(\t\x12\x0f\n\x07isAdult\x18\x03 \x02(\x08\x12\x11\n\tchannelID\x18\x04 \x02(\r\x12\x0f\n\x07netType\x18\x05 \x02(\r\x12\x14\n\x0cplatformType\x18\x06 \x02(\r\x12;\n\x0fqqGameLoginData\x18\x07 \x01(\x0b\x32\".protocol.platform.QQGameLoginData\"4\n\rLoginFailData\x12\x10\n\x08\x63lientID\x18\x01 \x02(\r\x12\x11\n\terrorCode\x18\x02 \x02(\r\"^\n\rLoginSuccData\x12\x10\n\x08\x63lientID\x18\x01 \x02(\r\x12\x13\n\x0b\x61\x63\x63ountName\x18\x02 \x02(\t\x12\x11\n\tgatewayIP\x18\x03 \x02(\t\x12\x13\n\x0bgatewayPort\x18\x04 \x02(\r\"\x1e\n\tZoneState\x12\x11\n\tonlineNum\x18\x01 \x02(\r')
_QQGAMELOGINDATA = _descriptor.Descriptor(
name='QQGameLoginData',
full_name='protocol.platform.QQGameLoginData',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='openID', full_name='protocol.platform.QQGameLoginData.openID', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=unicode("", "utf-8"),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='openKey', full_name='protocol.platform.QQGameLoginData.openKey', index=1,
number=2, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=unicode("", "utf-8"),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='pfKey', full_name='protocol.platform.QQGameLoginData.pfKey', index=2,
number=3, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=unicode("", "utf-8"),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='isBlueVip', full_name='protocol.platform.QQGameLoginData.isBlueVip', index=3,
number=4, type=8, cpp_type=7, label=1,
has_default_value=False, default_value=False,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='isBlueYearVip', full_name='protocol.platform.QQGameLoginData.isBlueYearVip', index=4,
number=5, type=8, cpp_type=7, label=1,
has_default_value=False, default_value=False,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='blueVipLevel', full_name='protocol.platform.QQGameLoginData.blueVipLevel', index=5,
number=6, type=13, cpp_type=3, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='nickName', full_name='protocol.platform.QQGameLoginData.nickName', index=6,
number=7, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=unicode("", "utf-8"),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='gender', full_name='protocol.platform.QQGameLoginData.gender', index=7,
number=8, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=unicode("", "utf-8"),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='isHighBlueVip', full_name='protocol.platform.QQGameLoginData.isHighBlueVip', index=8,
number=9, type=8, cpp_type=7, label=1,
has_default_value=False, default_value=False,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
extension_ranges=[],
serialized_start=53,
serialized_end=239,
)
_LOGINSESSIONDATA = _descriptor.Descriptor(
name='LoginSessionData',
full_name='protocol.platform.LoginSessionData',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='clientID', full_name='protocol.platform.LoginSessionData.clientID', index=0,
number=1, type=13, cpp_type=3, label=2,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='accountName', full_name='protocol.platform.LoginSessionData.accountName', index=1,
number=2, type=9, cpp_type=9, label=2,
has_default_value=False, default_value=unicode("", "utf-8"),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='isAdult', full_name='protocol.platform.LoginSessionData.isAdult', index=2,
number=3, type=8, cpp_type=7, label=2,
has_default_value=False, default_value=False,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='channelID', full_name='protocol.platform.LoginSessionData.channelID', index=3,
number=4, type=13, cpp_type=3, label=2,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='netType', full_name='protocol.platform.LoginSessionData.netType', index=4,
number=5, type=13, cpp_type=3, label=2,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='platformType', full_name='protocol.platform.LoginSessionData.platformType', index=5,
number=6, type=13, cpp_type=3, label=2,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='qqGameLoginData', full_name='protocol.platform.LoginSessionData.qqGameLoginData', index=6,
number=7, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
extension_ranges=[],
serialized_start=242,
serialized_end=435,
)
_LOGINFAILDATA = _descriptor.Descriptor(
name='LoginFailData',
full_name='protocol.platform.LoginFailData',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='clientID', full_name='protocol.platform.LoginFailData.clientID', index=0,
number=1, type=13, cpp_type=3, label=2,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='errorCode', full_name='protocol.platform.LoginFailData.errorCode', index=1,
number=2, type=13, cpp_type=3, label=2,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
extension_ranges=[],
serialized_start=437,
serialized_end=489,
)
_LOGINSUCCDATA = _descriptor.Descriptor(
name='LoginSuccData',
full_name='protocol.platform.LoginSuccData',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='clientID', full_name='protocol.platform.LoginSuccData.clientID', index=0,
number=1, type=13, cpp_type=3, label=2,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='accountName', full_name='protocol.platform.LoginSuccData.accountName', index=1,
number=2, type=9, cpp_type=9, label=2,
has_default_value=False, default_value=unicode("", "utf-8"),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='gatewayIP', full_name='protocol.platform.LoginSuccData.gatewayIP', index=2,
number=3, type=9, cpp_type=9, label=2,
has_default_value=False, default_value=unicode("", "utf-8"),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='gatewayPort', full_name='protocol.platform.LoginSuccData.gatewayPort', index=3,
number=4, type=13, cpp_type=3, label=2,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
extension_ranges=[],
serialized_start=491,
serialized_end=585,
)
_ZONESTATE = _descriptor.Descriptor(
name='ZoneState',
full_name='protocol.platform.ZoneState',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='onlineNum', full_name='protocol.platform.ZoneState.onlineNum', index=0,
number=1, type=13, cpp_type=3, label=2,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
extension_ranges=[],
serialized_start=587,
serialized_end=617,
)
_LOGINSESSIONDATA.fields_by_name['qqGameLoginData'].message_type = _QQGAMELOGINDATA
DESCRIPTOR.message_types_by_name['QQGameLoginData'] = _QQGAMELOGINDATA
DESCRIPTOR.message_types_by_name['LoginSessionData'] = _LOGINSESSIONDATA
DESCRIPTOR.message_types_by_name['LoginFailData'] = _LOGINFAILDATA
DESCRIPTOR.message_types_by_name['LoginSuccData'] = _LOGINSUCCDATA
DESCRIPTOR.message_types_by_name['ZoneState'] = _ZONESTATE
class QQGameLoginData(_message.Message):
__metaclass__ = _reflection.GeneratedProtocolMessageType
DESCRIPTOR = _QQGAMELOGINDATA
# @@protoc_insertion_point(class_scope:protocol.platform.QQGameLoginData)
class LoginSessionData(_message.Message):
__metaclass__ = _reflection.GeneratedProtocolMessageType
DESCRIPTOR = _LOGINSESSIONDATA
# @@protoc_insertion_point(class_scope:protocol.platform.LoginSessionData)
class LoginFailData(_message.Message):
__metaclass__ = _reflection.GeneratedProtocolMessageType
DESCRIPTOR = _LOGINFAILDATA
# @@protoc_insertion_point(class_scope:protocol.platform.LoginFailData)
class LoginSuccData(_message.Message):
__metaclass__ = _reflection.GeneratedProtocolMessageType
DESCRIPTOR = _LOGINSUCCDATA
# @@protoc_insertion_point(class_scope:protocol.platform.LoginSuccData)
class ZoneState(_message.Message):
__metaclass__ = _reflection.GeneratedProtocolMessageType
DESCRIPTOR = _ZONESTATE
# @@protoc_insertion_point(class_scope:protocol.platform.ZoneState)
# @@protoc_insertion_point(module_scope)
|
987,521 | c4f26820ff3d3a279a53e0e8be94dc8b40f591fe |
# 银行操作
# 开户,查询,存款,取款,转账,改密,锁卡,解锁,补卡,销户
from cards import Card
from users import User
import random
import pickle
import os
class Bank:
def __init__(self):
pass
self.users = [] # 当前银行系统的所有用户
self.file_path = 'users.txt' # 本地文件路径
# 启动银行系统后,立刻获取user.txt文件中保存的所有用户
self.__get_user()
print('=> 原来的所有用户:', self.users)
# 保存用户到文件中
def __save_users(self):
# 写入文件
fp = open(self.file_path, 'wb')
pickle.dump(self.users,fp)
fp.close()
print('当前所有用户:', self.users)
# 每次运行项目后都要重新获取user.txt文件中的所有数据
def __get_user(self):
# 读取文件
if os.path.exists(self.file_path):
fp = open(self.file_path,'rb')
self.users = pickle.load(fp)
fp.close()
# ------------------------------华丽的分割线----------------------------------
# 开户
def create_user(self):
pass
# 1.创建卡
# 卡号
cardid = self.__create_cardid()
print('=>成功创建卡号:',cardid)
# 卡密码
passwd = self.__set_password()
if not passwd:
return
# 卡余额
money= float(input('请输入预存金额:'))
# 创建卡对象
card = Card(cardid, passwd, money)
print('=>创建卡成功:',card)
# 2.创建用户
name = input('请输入您的真实姓名:')
idcard = input('请输入您的身份证号码:')
phone = input('请输入您的手机号码:')
# 创建用户
user = User(name, phone, idcard, card)
print('=> 创建用户成功:', user)
# 3.将新用户存储
# 将新用户加到银行系统中
self.users.append(user)
# 存储
self.__save_users()
# 创建随机,唯一卡号
def __create_cardid(self):
while True:
# 生成随机卡号
cardid = '8888'
for i in range(4):
cardid += str(random.randint(0, 9))
# 如果有一个用户的卡号和cardid相同,则break继续执行while,否则返回cardid
for user in self.users:
if user.card.cardid == cardid:
break
else:
return cardid
# 设置密码
def __set_password(self):
# 允许输错3 次
for i in range(3):
passwd = input('请您输入密码:')
passwd2 = input('请确认密码:')
# 验证两次密码是否一致
if passwd == passwd2:
return passwd
print('=>您两次密码不一致,请重新输入...')
else:
print('=>您输入了3次错误密码.')
return False
# ------------------------------华丽的分割线----------------------------------
# 查询
def search_money(self):
pass
# 1.输入卡号
user = self.__input_cardid()
if not user:
print('=> 卡号不存在.')
return
# 2.输入密码:考虑允许输错3次,否则锁卡
count = 0
while True:
count += 1
passwd = input('请输入银行卡密码:')
if passwd != user.card.password:
print('=>密码错误')
if count >= 3:
user.card.islock = True
self.__save_users()
return
else:
break
# 3.显示余额
print('当前余额:', user.card.money)
# 输入卡号
def __input_cardid(self):
cardid = input('请输入的银行卡号:')
# 如果卡号存在则返回所在的用户对象,否则默认返回None
for user in self.users:
if user.card.cardid == cardid:
return user
# ------------------------------华丽的分割线----------------------------------
# 存款
def save_money(self):
pass
# 1. 输入卡号
user = self.__input_cardid()
if not user:
print('=> 卡号不存在.')
return
# 2. 输入密码
passwd = input('请输入银行卡密码:')
if passwd != user.card.password:
print('=>密码错误')
return
# 3. 输入存款金额,并将user.money+=100
money1 = float(input('请输入存款金额:'))
user.card.money += money1
# 4.self.__save_users()
print('=>存款成功!')
self.__save_users()
# ------------------------------华丽的分割线----------------------------------
# 取款
def get_money(self):
pass
# 1.输入卡号
user = self.__input_cardid()
if not user:
print('=> 卡号不存在.')
return
# 2.输入密码
passwd = input('请输入银行卡密码:')
if passwd != user.card.password:
print('=>密码错误')
return
if user.card.islock:
print('=>卡已锁住')
return
# 3.输入取款金额,并将user.money-=100
while True:
money2 = float(input('请输入取款金额:'))
if user.card.money < money2:
print('=>余额不足')
continue
user.card.money -= money2
break
# 4.self.__save_users()
print('=>取款成功!')
self.__save_users()
# ------------------------------华丽的分割线----------------------------------
# 转账
def transform_money(self):
pass
# 1.输入转出卡号
print('=>转出')
user = self.__input_cardid()
if not user:
print('=> 卡号不存在.')
return
# 2.输入转出密码
passwd = input('请输入银行卡密码:')
if passwd != user.card.password:
print('=>密码错误')
return
if user.card.islock:
print('=>卡已锁住')
return
# 输入对方的卡号
print('=>转入')
user1 = self.__input_cardid()
if not user1:
print('=> 卡号不存在.')
return
# 3.输入转账金额,并将自己user.money-=100
# 输入转账金额,并将对方user.money+=100
while True:
money3 = float(input('请输入转账金额:'))
if user.card.money < money3:
print('=>余额不足')
continue
user.card.money -= money3
user1.card.money += money3
# 4.self.__save_users()
print('=>转出成功!')
self.__save_users()
# 改密
def modify_password(self):
pass
# 1.输入卡号
user = self.__input_cardid()
if not user:
print('=> 卡号不存在.')
return
# 2.输入身份证
while True:
idcard = input('请输入身份证号码:')
if user.idcard != idcard:
print('=>身份证验证失败!')
continue
break
# 3.输入旧密码,再输入新密码
# 输入旧密码
while True:
old_passwd = input('请输入旧密码:')
if user.card.password != old_passwd:
print('=>旧密码输入错误')
continue
break
# 输入新密码
new_passwd = input('请输入新密码:')
user.card.password = new_passwd
# 4.self.__save_users()
self.__save_users()
# 锁卡
def lock_card(self):
pass
# 1.输入卡号
user = self.__input_cardid()
if not user:
print('=> 卡号不存在.')
return
# 2.输入密码
passwd = input('请输入银行卡密码:')
if passwd != user.card.password:
print('=>密码错误')
return
# 3.锁卡user.card.islock = True
user.card.islock = True
# 4.self.__save_users()
self.__save_users()
# 解锁
def unlock_card(self):
pass
# 1.输入卡号
user = self.__input_cardid()
if not user:
print('=> 卡号不存在.')
return
# 2.输入密码
passwd = input('请输入银行卡密码:')
if passwd != user.card.password:
print('=>密码错误')
return
# 3.卡user.card.islock = False
user.card.islock = False
# 4.self.__save_users()
self.__save_users()
# 补卡
def makeup_card(self):
pass
# 1.输入身份证
idcard = input('请输入身号码份证:')
myuser = None
for user in self.users:
if user.idcard == idcard:
myuser = user
if not myuser:
print('=>身份证不存在')
return
# 2.创建新卡,并替换卡: user.card = card
cardid = self.__create_cardid()
# 设置密码
passwd = self.__set_password()
# 获取旧卡的money
money = myuser.card.money
# 创建新卡
new_card = Card(cardid, passwd, money)
# 替换旧卡
myuser.card = new_card
# 3.self.__save_user()
self.__save_users()
# 销户
def delete_user(self):
pass
idcard = input('请输入身号码份证:')
myuser = None
for user in self.users:
if user.idcard == idcard:
myuser = user
if not myuser:
print('=>身份证不存在')
return
# 1.输入身份证
# 2. 删除用户
money = myuser.card.money
print(f'=> 当前余额:{money}')
confirm = input('确认销户吗? (y/n):')
if confirm == 'y' or confirm == 'yes':
self.users.remove(myuser)
# 3.self.__save_user()
self.__save_users()
else:
print('=>取消销户') |
987,522 | ae0ecdaad6f3f9cf9701aa14dd39cdf162d49465 | import urllib
from time import sleep
from ConnectMongoDB import MyMongoDB
from ConnectToElasticSearch import ConnectToElasticSearch
import requests
from bs4 import BeautifulSoup
class BaiduSpider(object):
def __init__(self, keyword):
self.keyword = keyword
self.connection = ConnectToElasticSearch()
self.headers = {
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
'Accept-Encoding': 'deflate, br',
'Accept-Language': 'en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7',
'Connection': 'keep-alive',
'Cookie': 'BIDUPSID=EEE9FED806AEBDF27D8BD1F68FDE2758; PSTM=1572065115; BAIDUID=EEE9FED806AEBDF24ED0F7EBBC77417E:FG=1; BD_UPN=12314753; BDUSS=k4dEVuN3NLdmZ2V3loeElNR000WjRyVUpuVWR2T2hJYW50YXNOYkpVSnFiSkZlRVFBQUFBJCQAAAAAAAAAAAEAAAC2538~U2lsdmVyx7OzwQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGrfaV5q32leZm; H_PS_PSSID=; BDORZ=FFFB88E999055A3F8A630C64834BD6D0; ZD_ENTRY=empty; delPer=0; BD_CK_SAM=1; PSINO=7; BDRCVFR[VXHUG3ZuJnT]=mk3SLVN4HKm; sug=3; sugstore=0; ORIGIN=2; bdime=0; H_PS_645EC=476a2vjcYBLh9uWLj%2B%2BSkgD1TGPVaJZvs42JeM76S0jjojq7r9AKzi5FB6952%2BGkAlq36NfhRyZK; BDSVRTM=95',
'Host': 'www.baidu.com',
'Sec-Fetch-Dest': 'document',
'Sec-Fetch-Mode': 'navigate',
'Sec-Fetch-Site': 'none',
'Sec-Fetch-User': '?1',
'Upgrade-Insecure-Requests': '1',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36'
}
self.sitelist = [
['知乎', 'zhihu.com'],
# ['新华网', 'xinhuanet.com'],
['人民网', 'people.com.cn'],
['搜狐网', 'sohu.com'],
['凤凰网', 'ifeng.com'],
['新浪网', 'sina.com'],
['腾讯网', 'qq.com'],
# ['中国人大网','npc.gov.cn'],
['北京人大网','bjrd.gov.cn']
]
def parse(self, response, keyword, site):
# page = response.read().decode('utf-8')
page = response.text
soup = BeautifulSoup(page)
# print(soup)
# print(page)
divs = soup.find_all('div', attrs={"class": 'result c-container'})
# print(divs)
reslist = []
for div in divs:
try:
contentdiv = div.find('div')
abstract = contentdiv.text
time = div.find('span').text
h3 = div.find('h3')
taga = h3.find('a')
href = taga.get('href')
title = taga.text
baidu_url = requests.get(url=href, headers= self.headers, allow_redirects=False)
real_url = baidu_url.headers['Location'] # 得到网页原始地址
if real_url.startswith('http'):
res = {}
res['title'] = title
res['time'] = time.replace('-', '').replace(' ', '')
res['real_url'] = real_url
res['abstract'] = abstract
res['keyword'] = keyword
res['site'] = site[0]
# 放进数据库
self.connection.insert(res)
reslist.append(res)
except:
continue
return reslist
def getContent(self, keyword, pageIndex, site):
url = 'https://www.baidu.com/s?wd=' + urllib.parse.quote(keyword + ' ') + 'site:' + site[1] + '&pn=' + str(
(pageIndex - 1) * 10)
# url2 = 'https://www.baidu.com/s?wd=疫情%20site%3Axinhuanet.com&pn=30'
response = requests.get(url = url, headers = self.headers)
if response.status_code == 200:
return self.parse(response, keyword, site)
else:
return ''
def run(self):
# print("run begin!")
for i in range(len(self.sitelist)):
site = self.sitelist[i]
for j in range(3):
sleep(1)
res = self.getContent(self.keyword, j + 1, site)
# print(res)
|
987,523 | b7aa5bb093eecd4115575b3c1cb600cca620fd02 | # -*- coding: utf-8 -*-
"""Hate Speech Detection Task - BERTweet.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1njB3qP4fB79EDY9QUajmbfPlAcPCkIAF
# Fine-Tuning BERTweet on the Hate Speech Detection Task
## Loading Libraries and Dataset
Installing and importing the required libraries.
"""
!pip install simpletransformers
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
from tqdm.notebook import tqdm
tqdm.pandas()
import csv
import torch
import logging
import itertools
# Import the ClassificationModel module as we need to do multi-class text classification
from simpletransformers.classification import ClassificationModel
import sklearn
from sklearn.metrics import f1_score, accuracy_score
!pip install emoji
from nltk.tokenize import TweetTokenizer
from emoji import demojize
import re
"""Loading the dataset"""
hate_train_df = pd.read_csv("https://raw.githubusercontent.com/cardiffnlp/tweeteval/main/datasets/hate/train_text.txt", sep="\n", skip_blank_lines=False, header=None, quoting=csv.QUOTE_NONE,)
hate_train_df.columns= ["tweet"]
hate_train_labels = pd.read_csv("https://raw.githubusercontent.com/cardiffnlp/tweeteval/main/datasets/hate/train_labels.txt", sep="\n", header=None)
hate_train_labels.columns= ["label"]
hate_val_df = pd.read_csv("https://raw.githubusercontent.com/cardiffnlp/tweeteval/main/datasets/hate/val_text.txt", sep="\n", skip_blank_lines=False, quoting=csv.QUOTE_NONE, header=None)
hate_val_df.columns= ["tweet"]
hate_val_labels = pd.read_csv("https://raw.githubusercontent.com/cardiffnlp/tweeteval/main/datasets/hate/val_labels.txt", sep="\n", header=None)
hate_val_labels.columns= ["label"]
hate_test_df = pd.read_csv("https://raw.githubusercontent.com/cardiffnlp/tweeteval/main/datasets/hate/test_text.txt", sep="\n", quoting=csv.QUOTE_NONE, skip_blank_lines=False, header=None)
hate_test_df.columns= ["tweet"]
hate_test_labels = pd.read_csv("https://raw.githubusercontent.com/cardiffnlp/tweeteval/main/datasets/hate/test_labels.txt", sep="\n", header=None)
hate_test_labels.columns= ["label"]
hate_train_df
"""Making sure that the data is loaded correctly by checking the dimensions of the data frames for the training, validation, and testing datasets to match the dimensions of their corresponding labels dataframes."""
# Checking whether the data is loaded correctly by checking the dimensions of the data frames for the training, validation, and testing datasets matches the dimensions of their corresponding labels datasets.
print(hate_train_df.shape, hate_train_labels.shape)
print(hate_val_df.shape, hate_val_labels.shape)
print(hate_test_df.shape, hate_test_labels.shape)
"""## Exploratory Data Analysis"""
# Pie chart showing how data is split
labels = ['Training Set', 'Validation Set', 'Test Set']
sizes = [len(hate_train_labels), len(hate_val_labels), len(hate_test_labels)]
explode = (0, 0, 0.1)
fig1, ax1 = plt.subplots()
ax1.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%', startangle=90)
ax1.axis('equal')
plt.tight_layout()
plt.title("How the data is split")
plt.show()
# Checking the labels
hate_labels = pd.read_csv("https://raw.githubusercontent.com/cardiffnlp/tweeteval/main/datasets/hate/mapping.txt", sep="\t", header=None)
hate_labels
"""Data statitics:"""
print("Training Data Statistics: ")
print("Total number of tweets:", hate_train_labels.shape[0])
print("Number of Not Hateful tweets:", int(hate_train_labels.value_counts()[0]))
print("Number of Hateful tweets:", int(hate_train_labels.value_counts()[1]), "\n")
print("Validation Data Statistics: ")
print("Total number of tweets:", hate_val_labels.shape[0])
print("Number of Not Hateful tweets:", int(hate_val_labels.value_counts()[0]))
print("Number of Hateful tweets:", int(hate_val_labels.value_counts()[1]), "\n")
print("Testing Data Statistics: ")
print("Total number of tweets:", hate_test_labels.shape[0])
print("Number of Not Hateful tweets:", int(hate_test_labels.value_counts()[0]))
print("Number of Hateful tweets:", int(hate_test_labels.value_counts()[1]))
""""""
data = hate_train_labels.groupby("label").sum()
data
# Pie chart shwoing percentages of classes
not_hateful_count = hate_train_labels[hate_train_labels.label == 0].shape[0]
hateful_count = hate_train_labels[hate_train_labels.label == 1].shape[0]
labels = ['Not Hateful Tweets', ' Hateful Tweets']
sizes = [not_hateful_count, hateful_count]
fig1, ax1 = plt.subplots()
explode = (0.02, 0.02)
ax1.pie(sizes, explode= explode, labels=labels, autopct='%1.1f%%', startangle=90)
ax1.axis('equal')
plt.tight_layout()
plt.title("Percentages of Hateful and Not Hateful Tweets")
plt.show()
# Count Plots shwoing Distribution of Hateful and Not Hateful Tweets in All Datasets
fig, axes = plt.subplots(1, 3, figsize=(15, 5), sharey=False)
fig.suptitle('Distribution of Hateful and Not Hateful Tweets in All Datasets')
sns.countplot(ax=axes[0], x=hate_train_labels.label)
axes[0].set_title('Training Data')
axes[0].set_xticklabels(labels)
sns.countplot(ax=axes[1], x=hate_val_labels.label)
axes[1].set_title('Validation Data')
axes[1].set_xticklabels(labels)
sns.countplot(ax=axes[2], x=hate_test_labels.label)
axes[2].set_title('Test Data')
axes[2].set_xticklabels(labels)
"""## Exploring the tokenization and attention mask process"""
from transformers import BertTokenizer
tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
"""Emojis are not recognized by the tokenizer so they are tokenized as [UNK].
"""
hate_train_df.iloc[30,0]
# tokenizing and removing white spaces while keepng punctuation
tweet_sample = hate_train_df.iloc[30,0]
token_sample = tokenizer.tokenize(tweet_sample)
print(token_sample)
"""Converting the corpus into tokens and then converting each token to its ID, which is a unique integer representing the index of that token in the vocabulary of the model.
"""
token_id_sample = tokenizer.convert_tokens_to_ids(token_sample)
print(token_id_sample)
"""We have to provide sequences of equal length therefore we'll add some padding, then pass "attention mask" where each term has a value of 1 and each padding token has a value of 0.
Special tokens are needed for separating betwen sentences, that's how BERT initially trained on squence classification.
Exploring types of tokens when encoding them into IDs:
"""
print("Types of tokens and their IDs:", tokenizer.special_tokens_map)
print(tokenizer.pad_token, tokenizer.pad_token_id)
print(tokenizer.unk_token, tokenizer.unk_token_id)
print(tokenizer.cls_token, tokenizer.cls_token_id) # CLS is sequence/text classification task
print(tokenizer.sep_token, tokenizer.sep_token_id)
print(tokenizer.mask_token, tokenizer.mask_token_id)
"""Exploring the encoding process"""
encoding = tokenizer.encode_plus( # why plus?
text = tweet_sample,
add_special_tokens=True, # Add '[CLS]' and '[SEP]'
return_token_type_ids=False,
# pad_to_max_length=True,
truncation=True,
max_length=60, # number of tokens
padding='max_length',
return_attention_mask = True,
return_tensors='pt', # Return PyTorch tensors, and tf can be used for TensorFlow as well
)
encoding.keys()
"""The Attention Mask giving the values of 1 to all tokens, except the padding tokens in which it gives them the value of 0."""
encoded_seq = encoding['input_ids'][0]
print("Encoded sequence (IDs):\n", encoded_seq)
print("Attention Mask:\n", encoding['attention_mask'])
"""## Pre-Processing Steps"""
# Checking for null values
print("Number of NULL values in the hate training set: ", hate_train_df['tweet'].isnull().values.sum())
print("Number of NULL values in the hate validation set: ", hate_val_df['tweet'].isnull().values.sum())
print("Number of NULL values in the hate testing set: ", hate_test_df['tweet'].isnull().values.sum(), '\n')
print(hate_train_df.shape)
print(hate_train_labels.shape)
hate_train_df
hate_train_labels
df = pd.concat([hate_train_df, hate_train_labels], axis=1)
df
df.dropna(inplace=True)
df.reset_index(drop=True, inplace=True)
hate_train_df = df[['tweet']]
hate_train_labels = df[['label']]
hate_train_df
hate_train_labels
print("Number of NULL values in the hate training set: ", hate_train_df['tweet'].isnull().values.sum())
print(hate_train_df.shape)
print(hate_train_labels.shape)
# dropping
print("Number of NULL values in the hate validation set: ", hate_val_df['tweet'].isnull().values.sum())
hate_val_df
hate_val_labels
df = pd.concat([hate_val_df, hate_val_labels], axis=1)
df
df.dropna(inplace=True)
df.reset_index(drop=True, inplace=True)
df.shape
hate_val_df = df[['tweet']]
hate_val_labels = df[['label']]
print(hate_val_df.shape)
print(hate_val_labels.shape)
print("Number of NULL values in the hate training set: ", hate_train_df['tweet'].isnull().values.sum())
print("Number of NULL values in the hate validation set: ", hate_val_df['tweet'].isnull().values.sum())
print("Number of NULL values in the hate testing set: ", hate_test_df['tweet'].isnull().values.sum(), '\n')
"""Choosing the right size of sequence (or number of tokens) for our dataset is necessary because the larger the sequence length the slower is the process of training the model since there is a corelation between the two."""
token_lens = []
for each_tweet in hate_train_df.tweet:
tokens = tokenizer.encode(each_tweet, max_length=512) # max length by the model
token_lens.append(len(tokens))
sns.histplot(token_lens)
plt.xlim([0, 100]);
plt.xlabel('Number of Tokens per Tweet');
hate_train = pd.concat([hate_train_df, hate_train_labels], axis=1)
hate_val = pd.concat([hate_val_df, hate_val_labels], axis=1)
hate_test = pd.concat([hate_test_df, hate_test_labels], axis=1)
for i in hate_train["tweet"][:20]:
print(i)
tokenizer = TweetTokenizer()
def normalizeToken(token):
lowercased_token = token.lower()
if token.startswith("@"):
return "@USER"
elif lowercased_token.startswith("http") or lowercased_token.startswith("www"):
return "HTTPURL"
elif len(token) == 1:
return demojize(token)
else:
if token == "’":
return "'"
elif token == "…":
return "..."
else:
return token
def normalizeTweet(tweet):
tokens = tokenizer.tokenize(tweet.replace("’", "'").replace("…", "..."))
normTweet = " ".join([normalizeToken(token) for token in tokens])
normTweet = normTweet.replace("cannot ", "can not ").replace("n't ", " n't ").replace("n 't ", " n't ").replace("ca n't", "can't").replace("ai n't", "ain't")
normTweet = normTweet.replace("'m ", " 'm ").replace("'re ", " 're ").replace("'s ", " 's ").replace("'ll ", " 'll ").replace("'d ", " 'd ").replace("'ve ", " 've ")
normTweet = normTweet.replace(" p . m .", " p.m.") .replace(" p . m ", " p.m ").replace(" a . m .", " a.m.").replace(" a . m ", " a.m ")
normTweet = re.sub(r",([0-9]{2,4}) , ([0-9]{2,4})", r",\1,\2", normTweet)
normTweet = re.sub(r"([0-9]{1,3}) / ([0-9]{2,4})", r"\1/\2", normTweet)
normTweet = re.sub(r"([0-9]{1,3})- ([0-9]{2,4})", r"\1-\2", normTweet)
normTweet = normTweet.replace('@USER', '')
normTweet = normTweet.replace('HTTPURL', '')
return " ".join(normTweet.split())
# Testing the pre-processing functions
print(normalizeTweet("SC has first two presumptive cases of coronavirus, DHEC confirms https://postandcourier.com/health/covid19/ … via @postandcourier"))
print(normalizeTweet("So. Many. Plot twists. 😩😭😭😭😭 #Westworld #WestworldFinale "))
print(normalizeTweet("@user @user @user Tamra would F her up if she swung on Tamra\nKelly is a piece of 💩 #needstobeadmitted #bully"))
print(normalizeTweet("in my dream....They were trying to steal my kidney!!! #blackmarket #whydidiwatchthat "))
!pip install ekphrasis
from ekphrasis.classes.preprocessor import TextPreProcessor
from ekphrasis.classes.tokenizer import SocialTokenizer
from ekphrasis.dicts.emoticons import emoticons
text_processor = TextPreProcessor(
# terms that will be normalized
normalize=['url', 'email', 'percent', 'money', 'phone', 'user',
'time', 'date', 'number'],
# terms that will be annotated
#annotate={"hashtag", "allcaps", "elongated", "repeated",
# 'emphasis', 'censored'},
fix_html=True, # fix HTML tokens
# corpus from which the word statistics are going to be used
# for word segmentation
segmenter="twitter",
# corpus from which the word statistics are going to be used
# for spell correction
corrector="twitter",
unpack_hashtags=True, # perform word segmentation on hashtags
unpack_contractions=True, # Unpack contractions (can't -> can not)
spell_correct_elong=True, # spell correction for elongated words
# select a tokenizer. You can use SocialTokenizer, or pass your own
# the tokenizer, should take as input a string and return a list of tokens
tokenizer=SocialTokenizer(lowercase=True).tokenize,
# list of dictionaries, for replacing tokens extracted from the text,
# with other expressions. You can pass more than one dictionaries.
dicts=[emoticons]
)
def preprocess_tweets(s):
s = " ".join(text_processor.pre_process_doc(s))
s = ' '.join(k for k, _ in itertools.groupby(s.split()))
s = s.replace("' ", "'").replace(" '", "'")
s = " ".join(s.split())
s = s.strip()
s = s.replace('“', "")
# s = s.replace("<user>", '')
# s = demojize(s)
return s
# Test Sentences
sentences = [
"CANT WAIT for the new season of #TwinPeaks \(^o^)/!!! #davidlynch #tvseries :)))",
"I saw the new #johndoe movie and it suuuuucks!!! WAISTED $10... #badmovies :/",
"@SentimentSymp: can't wait for the Nov 9 #Sentiment talks! YAAAAAAY !!! :-D http://sentimentsymposium.com/.",
"'You have a #problem? Yes! Can you do #something about it? No! Than why '",
"on the bright side , my music theory teacher just pocket dabbed and said ,'i know what's hip .'and walked away "
]
for i in sentences:
print(preprocess_tweets(i))
hate_train['tweet'] = hate_train['tweet'].apply(lambda x: preprocess_tweets(x))
hate_val['tweet'] = hate_val['tweet'].apply(lambda x: preprocess_tweets(x))
hate_test['tweet'] = hate_test['tweet'].apply(lambda x: preprocess_tweets(x))
del hate_train_df, hate_train_labels, hate_val_df, hate_val_labels, hate_test_df, hate_test_labels
hate_train.head()
hate_train.label.value_counts()
# pre-processed/clean input
for i in hate_train["tweet"][:20]:
print(i)
"""## Fine-Tuning and Evaluating the Model"""
import wandb
logging.basicConfig(level=logging.INFO)
transformers_logger = logging.getLogger("transformers")
transformers_logger.setLevel(logging.WARNING)
cuda_available = torch.cuda.is_available()
print(cuda_available)
train_args = {
'manual_seed':41,
'save_steps' : 2000,
'save_model_every_epoch' : True,
'save_eval_checkpoints' : True, # s false
"warmup_steps": 100, # s 100
'use_early_stopping' : True, # False
'early_stopping_delta' : 0.01, # s 0.01
'early_stopping_metric' : "eval_loss", # s mcc
'early_stopping_metric_minimize' : True, #True
'early_stopping_patience' : 5, # s 5
'evaluate_during_training_steps' : 125, # 2000
'no_cache' : True, # False
'num_train_epochs':3,
'train_batch_size':32, # 8
'eval_batch_size': 32,
'max_seq_length':100, # 128
'learning_rate':4e-5,
'optimizer': "AdamW",
'use_tensorboard': True,
'evaluate_during_training': True,
'overwrite_output_dir': True,
"use_multiprocessing": False, # False
"use_multiprocessing_for_evaluation" : False,
"use_multiprocessed_decoding" : False,
'wandb_project': "CE888"}
trained_model = ClassificationModel(model_type = 'bertweet',
model_name = 'vinai/bertweet-base',
tokenizer_name = "vinai/bertweet-base",
num_labels=2,
use_cuda=True,
#cuda_device=0,
args=train_args)
trained_model.train_model(hate_train, eval_df=hate_val)
from sklearn.metrics import f1_score, accuracy_score
def f1_multiclass(labels, preds):
return f1_score(labels, preds, average='macro')
from sklearn.metrics import recall_score
def macro_recall(labels, preds):
return recall_score(labels, preds, average='macro')
result, model_outputs, wrong_predictions = trained_model.eval_model(hate_test, mavg_f1=f1_multiclass, acc=accuracy_score, mavg_recall = macro_recall)
"""Graphs showing the training process as imported from the Weights and Biases platform (wandb.ai).

The confustion matrix showing that the second class "hateful" is correctly classified most of the time, while the first class "not hateful" is widely missclassified.

"""
result
"""### Macro-Averaged F1 Score"""
print("Macro-Averaged F1 Score: ", result['mavg_f1']*100)
# Plays an audio message as a notification when the training process is done.
import IPython.display as display
display.Audio(url="https://static.sfdict.com/audio/C07/C0702600.mp3", autoplay=True)
"""## Saving the best model"""
# Transforming the model folder into a single compressed file.
!zip -r /content/outputs/best_model_file.zip /content/outputs/best_model
# Downloading the model locally.
from google.colab import files
files.download("/content/outputs/best_model_file.zip")
"""## Loading the saved model"""
# If you don't want to retrain the model, you can load the best saved model directly by running the code below.
logging.basicConfig(level=logging.INFO)
transformers_logger = logging.getLogger("transformers")
transformers_logger.setLevel(logging.WARNING)
cuda_available = torch.cuda.is_available()
print(cuda_available)
import wandb
trained_model = ClassificationModel(
"deperta", "outputs/best_model"
# "bertweet", "outputs/checkpoint-612-epoch-6"
) |
987,524 | 0d2d258e74f2c6dce63cffcf897ec46e178e0dc0 | Product Id : 45660022
Max Video Resolution : 3840x2160 resolution
Image Sensor : 8 megapixels
Video Modes : 4k, 1080p, 720p
Video Features : Auto Track and Zoom, HDR, H.264 and H.265 Encoding
Lens Field of View : 180 degree diagonal
Sensor Size : 1/2"
Spotlight : 6500K, 42Lux @1M
Motion Detection : Dual Motion Detectors, 150 degree horizontal
Night Vision : high powered Infrared LEDs (850nm) with IR Cut Filter
AC Adapter Output : 5V 2A
AC Adapter Input : 100-240V AC, 50/60Hz
Indoor/Outdoor : Both - outdoor UV and weather-resistant
Digital Zoom : 12x
Microphone : Dual Microphone Array with noise and wind cancellation
Audio : Full Duplex 2 way Audio
Status Lights : 2x LEDs (blue and amber)
Networking : 802.11 b/g/n/ac, Bluetooth Low Energy 4.2
Compliant Standards : 128-bit SSL, AES-128, TSL, 2 factor authentication
Battery Life : 3-6 months
Operating Temperature : -20 to 60 degree Celsius
Connectivity : Wi-Fi Connection. Working broadband connection with at least 2Mbps upload speed
Min home upload speed : 2-4Mbps; optimized for 2 simultaneous 4k streams
|
987,525 | 8db06ee4a310879971de2a802b73db993297b816 | from . import g2p |
987,526 | 456374e87a0b790a8b0323e2e595a5a8999685c5 | import socket
from time import time
sock = socket.socket()
sock.connect(('localhost',8080))
t0 = time()
for _ in range(1000):
sock.send(bytes('test msg',encoding='utf-8'))
sock.recv(99)
print('time cost',time()-t0)
sock.close() |
987,527 | 33856452dba93b24a208e3d3677795915ba661c8 | '''
4.
다중상속을 이용하여 카드사의 클래스를 만들고
영화카드는 20% 할인
마트카드는 10% 할인
교통은 10%할인을 받는 카드 class를 구현하시오
테스트코드
<입력>
multi_card=Multi_card()
multi_card.charge(20000)
multi_card.consume(5000,'마트')
multi_card.consume(10000,'영화관')
multi_card.consume(2000,'교통')
multi_card.print()
<출력>
카드가 발급 되었습니다.
20000이 충전되었습니다.
마트에서 4500.0원을 사용했습니다.
영화관에서 8000.0원을 사용했습니다.
교통에서 1800.0원을 사용했습니다.
잔액이 5700.0원 입니다
'''
class MovieCard():
def __init__(self):
self.balance = 0
def consume(self, payment, location):
if location == "영화관":
discount = payment*0.8
if self.balance - discount <0:
print("잔액이 부족합니다.")
else:
self.balance-=discount
print("{}에서 {}원을 사용했습니다.".format(location, discount))
else:
self.balance-=payment
print("{}에서 {}원을 사용했습니다.".format(location, payment))
class MartCard():
def __init__(self):
self.balance = 0
def consume(self, payment, location):
if location == "마트":
discount = payment * 0.9
if self.balance - discount < 0:
print("잔액이 부족합니다.")
else:
self.balance -= discount
print("{}에서 {}원을 사용했습니다.".format(location, discount))
else:
self.balance -= payment
print("{}에서 {}원을 사용했습니다.".format(location, payment))
class TransCard():
def __init__(self):
self.balance = 0
def consume(self, payment, location):
if location == "교통":
discount = payment * 0.9
if self.balance - discount < 0:
print("잔액이 부족합니다.")
else:
self.balance -= discount
print("{}에서 {}원을 사용했습니다.".format(location, discount))
else:
self.balance -= payment
print("{}에서 {}원을 사용했습니다.".format(location, payment))
class Multi_card(MovieCard,MartCard,TransCard):
def __init__(self):
self.balance = 0
print('카드가 발급 되었습니다.')
def consume(self, payment, location):
if location == '영화관':
MovieCard.consume(self, payment, location)
elif location == '마트':
MartCard.consume(self, payment, location)
elif location == '교통':
TransCard.consume(self,payment,location)
else:
super().consume(self, payment, location)
def charge(self, deposit):
self.balance+=deposit
print('{}이 충전되었습니다.'.format(deposit))
def print(self):
print('잔액이 {}원입니다.'.format(self.balance))
multi_card = Multi_card()
multi_card.charge(20000)
multi_card.consume(5000, '마트')
multi_card.consume(10000, '영화관')
multi_card.consume(2000, '교통')
multi_card.print() |
987,528 | e760c40c14b8ab3a3581249c81592d4d146bffd1 | # __slots__
# class Student:
# __slots__ = ('name', 'age')
# st = Student()
# st.name = 'mzw'
# print(st.name) # mzw
# st.age = 21
# print(st.age) # 21
# st.score = 100 # 'Student' object has no attribute 'score'
# print(st.score)
# @property
# class Student:
# def __init__(self):
# self._name = 'no name'
# @property
# def name(self):
# return self._name
# # @name.setter
# # def name(self, val):
# # if not isinstance(val, str):
# # print('name must be str type')
# # return
# # self._name = val
# st = Student()
# # st.name = 1 # name must be str type
# st.name = 'mzw' # AttributeError: can't set attribute
# print(st.name) # mzw
# # 多重继承
# class Animal:
# pass
# class RunnaleMixIn:
# pass
# class CarnivorousMixIn:
# pass
# class Tigger(Animal, RunnaleMixIn, CarnivorousMixIn):
# pass
# 定制类
# __str__
# class Student:
# def __init__(self, name):
# self.name = name
# def __str__(self):
# return 'Student object (name: %s)' % self.name
# __repr__ = __str__
# print(Student('mzw')) # Student object (name: mzw)
# __iter__实现斐波那契数列
# class Fib:
# def __init__(self):
# self.a, self.b = 0, 1
# def __iter__(self):
# return self
# def __next__(self):
# self.a, self.b = self.b, self.a + self.b
# if self.a > 10000:
# raise StopIteration()
# return self.a
# for n in Fib():
# if (n > 100):
# break
# print(n)
# # 1
# # 1
# # 2
# # 3
# # 5
# # 8
# # 13
# # 21
# # 34
# # 55
# # 89
# __getitem__
# class FibList():
# def __getitem__(self, n):
# a, b = 1, 1
# for x in range(n):
# a, b = b, a + b
# return a
# fib = FibList()
# print(fib[0]) # 0
# print(fib[5]) # 8
# getattr
# class Student:
# def __getattr__(self, attr):
# if attr == 'score':
# return 0
# st = Student()
# print(st.score)
# st.score = 100
# print(st.score)
# __call__
# class Student:
# def __init__(self, name):
# self.name = name
# def __call__(self):
# print('My name is %s' % self.name)
# class Test:
# pass
# st = Student('mzw')
# st() # My name is mzw
# test = Test()
# print(callable(st)) # True
# print(callable(test)) # False
# print(callable(abs)) # True
# print(callable(int)) # True
# print(callable(123)) # False
# print(callable('123')) # False
# print(callable([1, 2, 3])) # False
# from enum import Enum
# Day = Enum('Day', ('Mon', 'Tue', 'Wes', 'Thu', 'Fri', 'Sat', 'Sun'))
# print(Day.Mon) # Day.Mon
# print(Day.Tue.value) # 2
# print(Day(2)) # Day.Tue
# for name, member in Day.__members__.items():
# print('name:', name, 'member:', member, 'value:', member.value)
# # name: Mon member: Day.Mon value: 1
# # name: Tue member: Day.Tue value: 2
# # name: Wes member: Day.Wes value: 3
# # name: Thu member: Day.Thu value: 4
# # name: Fri member: Day.Fri value: 5
# # name: Sat member: Day.Sat value: 6
# # name: Sun member: Day.Sun value: 7
from enum import Enum, unique
@unique
class WeekDay(Enum):
Mon = 1
Tue = 2
# Tue = 3
Wes = 3
Thu = 4
print(WeekDay.Mon) # WeekDay.Mon
print(WeekDay(1)) # WeekDay.Mon
print(WeekDay.Mon.value) # 1 |
987,529 | 3535433ed53d1bc79a7f050c2b28557e101ae6b2 |
# can be used by all
cellLines = ["BT20", "MCF7", "UACC812", "BT549"]
ligands = ["EGF", "HGF", "FGF1", "IGF1", "Insulin", "NRG1", "PBS", "Serum"]
metadata = {
'sc1a': {"true_synapse_id": "syn1971278"},
'sc1b': {},
'sc2a': {},
'sc2b': {},
}
import commons
import scoring
from scoring import *
import hpn
from hpn import *
import submissions
import os
from dreamtools import dreampath
d8c1path = os.sep.join([dreampath, 'dream8', 'D8C1'])
# download data if not found
# syn1920412
|
987,530 | 593cdd52ae28a40521065df7d014d8e55ef86f55 | import sys
import string
def wordcount():
#file = open("pg600.txt")
# Try to open the file.
file = open(str(sys.argv[1]))
total_number_of_words = 0
words_dict = {}
for line in file:
wordlist = line.split()
for word in wordlist:
clean_word = word.translate(None, string.punctuation).lower()
total_number_of_words += 1
if clean_word not in words_dict:
words_dict[clean_word] = 1
else:
words_dict[clean_word] += 1
top_words = []
words_dict['*default*'] = 0
for x in range(0, len(words_dict)):
current = '*default*' # only used once
for entry in words_dict:
if words_dict[entry] > words_dict[current]:
current = entry
if current == '*default*':
pass
else:
top_words.append(current)
top_words.append(words_dict[current])
words_dict.pop(current)
for x in range(0, len(top_words), 2):
print top_words[x], top_words[x+1]
print '\n\tFile: ', sys.argv[1]
print '\tNumber of individual words: ', len(top_words)/2
print '\tTotal number of words: ', total_number_of_words, '\n'
try:
wordcount()
except (IndexError, IOError, TypeError):
print '\n\tUsage: Please provide the name of a text file as an argument.\n' |
987,531 | 4c532ff793842f347f7959dd6078a41465f7bd1d | # 두개의 수를 입력받아 사칙 연산 출력하는 함수
def calc():
a, b = input().split(' ')
a = float(a)
b = float(b)
print(int(a+b))
print(int(a-b))
print(int(a*b))
print(int(a//b))
print(int(a % b))
print(round(a/b, 2))
calc()
|
987,532 | 3b3a71133deba892fb5ef205c6f5be6e8504f5eb | # coding: utf-8
import sys
import time
try:
x = input('Input :')
print(float(x))
except:
print("Error! This application has stopped.")
sys.exit()
y = input('keep calcurating → 0 , exit → 1:')
while y == 0:
try:
x = input('Input :')
print(float(x))
except:
print("Error! This application has stopped.")
sys.exit()
y = input('keep calcurating → 0 , exit → 1:')
if y == 1:
print("Good bye")
sys.exit()
else:
print("Error! This application has stopped.")
sys.exit()
|
987,533 | 68a7390daa3a3d5858ac052b567f9c8e035f75d8 | # -*- coding: utf-8 -*-
'''
Author: Andre Pacheco
E-mail: pacheco.comp@gmail.com
This class implements the Kernel Extreme Learning Machine (ELM) according to:
[1] Huang, Guang-Bin, et al. "Extreme learning machine for regression and multiclass
classification." IEEE Transactions on Systems, Man, and Cybernetics,
Part B (Cybernetics) 42.2 (2012): 513-529.
All the code is very commented to ease the undertanding.
If you find some bug, please e-mail me =)
'''
import numpy as np
import sys
from sklearn.metrics.pairwise import rbf_kernel, polynomial_kernel, sigmoid_kernel
# Function to transform the data to one hot enconding
def one_hot_encoding(ind, N=None):
ind = np.asarray(ind)
if ind is None:
return None
if N is None:
N = ind.max() + 1
return (np.arange(N) == ind[:,None]).astype(int)
# Function to cont the errors
def contError (vreal, vclass):
# Getting the matrix binarized
vclass = one_hot_encoding (vclass)
[m,n] = vreal.shape
#dif = vreal - vclass
err = abs(vreal - vclass).sum()
return int(err/2)
# Function to compute the sigmoid
def sigmoid (v):
return 1/(1+np.exp(-v))
class KELM:
inTrain = None
outTrain = None
kernelType = None
# The constructor method. If you intend to train de ELM, you must fill all parameters.
# If you already have the weights and wanna only execute the net, just fill W and beta.
def __init__ (self, inTrain=None, outTrain=None, kernelType = 'rbf'):
if kernelType != 'rbf' and kernelType != 'pol' and kernelType != 'sig':
print 'ERROR: This kernelType does not exist'
raise Exception('ELM initialize error')
else:
self.kernelType = kernelType
if inTrain is not None and outTrain is not None:
self.inTrain = inTrain
self.outTrain = outTrain
else:
print 'ERROR: you need to set inTrain and outTrain'
raise Exception('ELM initialize error')
# This method trains and tests the ELM. If you wanna check the training error, set aval=True
def train_and_test (self, dataTest, realOutput=None, aval=False, reg=0.01, deg=3, gamm=None, coef=1):
if self.kernelType == 'rbf':
K = rbf_kernel(self.inTrain, self.inTrain, gamm)
Ktest = rbf_kernel(dataTest, self.inTrain, gamm)
elif self.kernelType == 'pol':
K = polynomial_kernel(self.inTrain, self.inTrain, deg, gamm, coef)
Ktest = polynomial_kernel(dataTest, self.inTrain, deg, gamm, coef)
elif self.kernelType == 'sig':
K = sigmoid_kernel(self.inTrain, self.inTrain, gamm, coef)
Ktest = sigmoid_kernel(dataTest, self.inTrain, gamm, coef)
I = np.eye(self.inTrain.shape[0])
outNet = np.dot (np.dot(Ktest, np.linalg.inv(K + reg*I)), self.outTrain)
if aval:
miss = float(cont_error (realOutput, outNet))
si = float(outNet.shape[0])
acc = (1-miss/si)*100
print 'Miss classification on the test: ', miss, ' of ', si, ' - Accuracy: ',acc , '%'
return outNet, acc
return outNet, None |
987,534 | 0721bf78e960e16d455b14f0b715f12a320ca003 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from n0ted0wn.Block.Parser.Base import Base
from n0ted0wn.Block.Parser.StdEnv import StdEnv
class UnorderedList(Base):
"""
Implements parsing for the following block format.
* Item 1
* Item 2
* Item 3
"""
def __init__(self, raw, parsed_blocks_list, style_cls):
super(UnorderedList, self).__init__(raw, style_cls)
self.parsed_blocks_list = parsed_blocks_list
@classmethod
def parse(cls, raw, style_cls):
lines = raw.strip().split('\n')
items = []
for l in lines:
if l.startswith('* '):
items.append(l[2:])
elif l.startswith(' '):
if not items:
return None
else:
items[-1] += '\n' + l[2:]
else:
return None
from n0ted0wn.Block.Parser import Parser
return cls(raw, \
[Parser(style_cls, 0).parse(item) for item in items], style_cls)
class UnorderedListStdEnv(StdEnv):
"""
Implements parsing for the following block format.
{ul}
* Item 1
* Item 2
with new lines
* Item 3
with blocks
{ul}
"""
_block_type = 'ul'
def __init__(self, raw, params, content, style_cls):
super(UnorderedListStdEnv, self).__init__(raw, params, content, style_cls)
self.parsed_blocks_list = []
def _transform_args(self):
item_marker_index = self.content.find('* ')
if item_marker_index == -1:
return None
lines = self.content.split('\n')
grouped_lines = []
for l in lines:
if l.startswith(' ') or not l.strip():
if not grouped_lines:
return None
grouped_lines[-1].append(l)
else:
counter_marker = '* '
if not l.startswith(counter_marker):
return None
grouped_lines.append([' ' * len(counter_marker) + \
l[len(counter_marker):]])
from n0ted0wn.Block.Parser import Parser
for lines in grouped_lines:
self.parsed_blocks_list.append(
Parser(self.style_cls, 2).parse('\n'.join(lines)))
return self
|
987,535 | 25f2022ee7f617b26b566c34b608bb9e8c41bc04 | import pandas as pd
from tqdm.auto import tqdm
zipcode_interconnector = pd.read_csv('zipcode_interconnector_connection.csv' , header = 0, index_col = 0, sep = ',')
zipcode_coordinates = pd.read_csv('filtered_storageSystems_mapped.csv', header = 0 ,index_col = None, sep = ',')
interconnector_coordinates = pd.read_csv('updated_geocoded_50hztl.csv', header = 0 , index_col = None, sep = ',')
zipcode_coordinates = zipcode_coordinates.loc[:,['zipcode','lat', 'lon']]
zipcode_coordinates = zipcode_coordinates.drop_duplicates(subset = ['zipcode'])
zipcode_coordinates.set_index("zipcode", inplace = True)
interconnector_coordinates = interconnector_coordinates.loc[:,['Ende','end_lat','end_lon']]
interconnector_coordinates = interconnector_coordinates.drop_duplicates(subset = ['Ende'])
interconnector_coordinates.set_index('Ende', inplace = True)
'''
def getZipcodeCoordinates(zipcode):
for i in zipcode_coordinates.index:
if i == zipcode:
print('found match')
#print('coordinates are ' + str(zipcode_coordinates.loc[i,'lat']) + ','+ str(zipcode_coordinates.loc[i,'lon']))
return (zipcode_coordinates.loc[i,'lat'],zipcode_coordinates.loc[i,'lon'])
'''
#print(str(zipcode_coordinates.loc[19348,'lat']) + ','+ str(zipcode_coordinates.loc[19348,'lon']))
#zipcode_interconnector.loc[19348,'latitude of zipcode'],zipcode_interconnector.loc[19348,'longitude of zipcode'] = zipcode_coordinates.loc[19348,'lat'],zipcode_coordinates.loc[19348,'lon']
#zipcode_interconnector.loc[19348,'latitude of zipcode'] = zipcode_coordinates.loc[19348,'lat']
#print(zipcode_interconnector)
print('updating the geo-coordinates of zipcodes ')
for i in tqdm(zipcode_interconnector.index):
try:
temp = float(i)
zipcode_interconnector.loc[i,'latitude of zipcode'],zipcode_interconnector.loc[i,'longitude of zipcode'] = zipcode_coordinates.loc[temp,'lat'],zipcode_coordinates.loc[temp,'lon']
except ValueError:
print(i)
print('updated the geo-coordinates of zipcodes ')
def getInterconnectorCoordinates(interconnector):
for i in interconnector_coordinates.index:
if i == interconnector:
return interconnector_coordinates.loc[i,'end_lat'], interconnector_coordinates.loc[i,'end_lon']
return 0,0
column = list(zipcode_interconnector.columns)
df1 = pd.DataFrame(columns = column).reindex(['latitude of interconnector'])
zipcode_interconnector = zipcode_interconnector.append(df1)
df2 = pd.DataFrame(columns = column).reindex(['longitude of interconnector'])
zipcode_interconnector = zipcode_interconnector.append(df2)
print('updating the interconnector geo-coordinates')
for i in tqdm(column):
zipcode_interconnector.loc['latitude of interconnector',i],zipcode_interconnector.loc['longitude of interconnector',i] = getInterconnectorCoordinates(i)
#print(i + ' interconnector has latitude ' + str(lat) + " and longitude "+ str(lon))
#print(i + " interconnector has latitude " + str(zipcode_interconnector[index1,i]) + " and longitude " + str(zipcode_interconnector[index2,i]))
print('updated the interconnector geo-coordinates')
zipcode_interconnector.fillna(0,inplace = True)
zipcode_interconnector.to_csv('zipcode_interconnector_withlatlon.csv')
|
987,536 | 046af17d428a6e09ddc9851ba3e4a420046b2557 | expr = exp(pi*I*2*(x+y))
assumption = Q.integer(x) & Q.integer(y)
expr = refine(expr, assumption) |
987,537 | 13ea20f101be689345bf7f8a3d4d2061b2a4f737 | import uvicorn
from app.main import app
if __name__ == "__main__":
uvicorn.run(app, host="127.0.0.1", port=8000)
|
987,538 | ba5d7cdbe5c106ec7cf739f2c0de624e5864a382 | #!/usr/bin/env python
'''
temperature from planck's equation to RGB values
'''
from math import log, e
import matplotlib.pyplot as plt
from scipy.constants import c,h, k
def planck(wavelenght, T):
wvl=wavelenght*1e-9
B=2*h*(c**2)/((wvl**5)*(e**(h*c/(wvl*k*T))-1))
return B #if B*1e-12 units kW·str-1·m-2·nm-1 else W·str-1·m-3
def clamp(x, smallest, largest):
if x< smallest:
return smallest
if x> largest:
return largest
return x
def planck2RGB(wavelenghts, T):
answer=[]
for wvl in wavelenghts:
value=log(planck(wvl, T))
if value<0:
value=0
answer.append(value)
return answer
if __name__ == "__main__":
show = 2
if show == 0:
for temperature in range(3000, 7000, 1000):
x=[]
y=[]
for i in range(150, 1500):
x.append(i)
y.append(planck(i, temperature)*1e-12)
linelable="temperature: "+str(temperature)
plt.plot(x, y, label=linelable)
plt.legend()
plt.show()
if show ==1:
wavelenghts=[420, 530, 680]
for wvl in wavelenghts:
y=[]
x=[]
for temperature in range(600, 6000, 10):
x.append(temperature)
y.append(log(planck(wvl, temperature)))
lnlabel=str(wvl)+' nm'
plt.plot(x, y, label=lnlabel)
plt.legend()
plt.show()
if show==2:
wavelenghts=[420, 530, 680]
x=[]
r=[]
g=[]
b=[]
for temperature in range(600, 6000, 10):
x.append(temperature)
tmpr, tmpg, tmpb=planck2RGB(wavelenghts, temperature)
r.append(tmpr)
g.append(tmpg)
b.append(tmpb)
plt.plot(x, r, color='r')
plt.plot(x, g, color='g')
plt.plot(x, b, color='b')
plt.show()
|
987,539 | ebe5e264b5721a7d49758ff109378b2e8e16b95e | #! /usr/local/bin/python3.4
f = open("report 69069-29232.txt",'r')
#cont = f.read()
#print cont
c = 0
for lines in f:
if c == 0 or c==1:
c = c+1
continue
else:
#print lines
cnt = lines.split()
print cnt
print cnt[0]
print cnt[1]
print cnt[2]
print cnt[3]
print cnt[4].split('$')[1]
|
987,540 | 44c0c352058fd901d42b802a6287108de5922257 | import pygame
import os
from pygame import *
import pyganim
import blocks
import player
WIN_WIDTH = 1280
WIN_HEIGHT = 720
DISPLAY = (WIN_WIDTH, WIN_HEIGHT)
BACKGROUND_COLOR = "#00a693"
PLATFORM_WIDTH = 64
PLATFORM_HEIGHT = 64
COIN1 = COIN2 = COIN3 = COIN4 = COIN5 = COIN6 = COIN7 = COIN8 = COIN9 = None
COINS = 0
BUTTON_VERIFY = False
PLAY_TIMES = 0
LEVEL = 0
START_X = 200
START_Y = 1000
def load_image(name, color_key=None):
fullname = os.path.join('Image', name)
try:
image = pygame.image.load(fullname)
except pygame.error as message:
print('Cannot load image:', name)
raise SystemExit(message)
image = image.convert_alpha()
if color_key is not None:
if color_key == -1:
color_key = image.get_at((0, 0))
image.set_colorkey(color_key)
return image
class Camera(object):
def __init__(self, camera_func, width, height):
self.camera_func = camera_func
self.state = Rect(0, 0, width, height)
def apply(self, target):
return target.rect.move(self.state.topleft)
def update(self, target):
self.state = self.camera_func(self.state, target.rect)
def camera_configure(camera, target_rect):
l, t, _, _ = target_rect
_, _, w, h = camera
l, t = -l+WIN_WIDTH / 2, -t+WIN_HEIGHT / 2
l = min(0, l)
l = max(-(camera.width-WIN_WIDTH), l)
t = max(-(camera.height-WIN_HEIGHT), t)
t = min(0, t)
return Rect(l, t, w, h)
def finish(screen):
global BUTTON_VERIFY
BUTTON_VERIFY = 2
screen.fill((0, 0, 0))
font = pygame.font.Font('C:\\WINDOWS\\Fonts\\impact.ttf', 100)
text = font.render("YOU WON!", True, (255, 255, 255))
screen.blit(text, [440, 75])
c_x, c_y, c_wight, c_hight = (490, 420, 300, 90)
font = pygame.font.Font('C:\\WINDOWS\\Fonts\\impact.ttf', 75)
text = font.render("Continue", True, (255, 255, 255))
screen.blit(text, [500, 420])
pygame.draw.rect(screen, (255, 255, 255), (490, 420, 300, 90), 1)
font = pygame.font.Font('C:\\WINDOWS\\Fonts\\impact.ttf', 100)
text = font.render("Thanks for playing!", True, (255, 255, 255))
screen.blit(text, [240, 175])
pygame.display.flip()
return c_x, c_y, c_wight + c_x, c_hight + c_y
def menu(screen):
global BUTTON_VERIFY
BUTTON_VERIFY = 0
screen.fill((0, 0, 0))
play_x, play_y, play_wight, play_hight = (560, 270, 160, 90)
font = pygame.font.Font('C:\\WINDOWS\\Fonts\\impact.ttf', 75)
text = font.render("PLAY", True, (255, 255, 255))
screen.blit(text, [570, 270])
pygame.draw.rect(screen, (255, 255, 255), (560, 270, 160, 90), 1)
ex_x, ex_y, ex_wight, ex_hight = (560, 420, 160, 90)
font = pygame.font.Font('C:\\WINDOWS\\Fonts\\impact.ttf', 75)
text = font.render("EXIT", True, (255, 255, 255))
screen.blit(text, [580, 420])
pygame.draw.rect(screen, (255, 255, 255), (560, 420, 160, 90), 1)
font = pygame.font.Font('C:\\WINDOWS\\Fonts\\impact.ttf', 100)
text = font.render("DANGEROUS ADVENTURE", True, (255, 255, 255))
screen.blit(text, [145, 75])
pygame.display.flip()
return play_x, play_y, play_wight + play_x, play_hight + play_y, ex_x, ex_y, ex_wight + ex_x, ex_hight + ex_y
def level_update(screen):
global BUTTON_VERIFY, LEVEL, COINS
BUTTON_VERIFY = 3
screen.fill((0, 0, 0))
font = pygame.font.Font('C:\\WINDOWS\\Fonts\\impact.ttf', 100)
text = font.render("LEVEL {} COMPLITE!".format(LEVEL + 1), True, (255, 255, 255))
screen.blit(text, [300, 75])
c_x, c_y, c_wight, c_hight = (490, 420, 300, 90)
font = pygame.font.Font('C:\\WINDOWS\\Fonts\\impact.ttf', 75)
text = font.render("Continue", True, (255, 255, 255))
screen.blit(text, [500, 420])
pygame.draw.rect(screen, (255, 255, 255), (490, 420, 300, 90), 1)
font = pygame.font.Font('C:\\WINDOWS\\Fonts\\impact.ttf', 100)
text = font.render("Coins: {} / 3".format(COINS), True, (255, 255, 255))
screen.blit(text, [420, 175])
pygame.display.flip()
return c_x, c_y, c_wight + c_x, c_hight + c_y
def gameover(screen):
global BUTTON_VERIFY
BUTTON_VERIFY = 4
screen.fill((0, 0, 0))
font = pygame.font.Font('C:\\WINDOWS\\Fonts\\impact.ttf', 100)
text = font.render("GAMEOVER", True, (255, 255, 255))
screen.blit(text, [440, 75])
c_x, c_y, c_wight, c_hight = (520, 420, 275, 90)
font = pygame.font.Font('C:\\WINDOWS\\Fonts\\impact.ttf', 75)
text = font.render("RESTART", True, (255, 255, 255))
screen.blit(text, [530, 420])
pygame.draw.rect(screen, (255, 255, 255), (520, 420, 275, 90), 1)
pygame.display.flip()
return c_x, c_y, c_wight + c_x, c_hight + c_y
def levels(level_score, entities, platforms):
global COIN1, COIN2, COIN3, COIN4, COIN5, COIN6, COIN7, COIN8, COIN9
level = ['']
level1 = [
"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"x x",
"x s k x",
"x * c --- --- x",
"x s---- s--- --- s x",
"x s --- --- x",
"x s x",
"x --- x",
"x s ---s s x",
"x --- --- x",
"x f x",
"x --- s * s---- --- ------x",
"x --- ----- s x",
"x --- x",
"x --- * x",
"x * s s--- --- x",
"x --- --- n --- x",
"x --- - --- - x",
"x * - * - - * - * - * x",
"111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111"]
level2 = [
"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"x g j x",
"x --- s --- s x",
"x x",
"x --- --- --- --- --- x",
"x m x",
"x s--- s ---s x",
"x x",
"x --- --- --- --- --- x",
"x s--- x",
"x s x",
"x x",
"x x",
"x s s--- x",
"x --- --- s x",
"x x",
"x h x",
"x - - - - - --- - - - x",
"x **************************************************************************************************x",
"111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111"]
level3 = [
"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"x x",
"x u x",
"x --- --- x",
"x --- --- x",
"x -b --- --- z x",
"x --- --- --- x",
"x --- --- x",
"x --- --- s x",
"x x",
"x x",
"x x",
"x x",
"x --- --- x",
"x --- --- x",
"x s --- --- x",
"x --- --- x",
"x --- --- x",
"x - * - * v *x",
"111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111"]
level_time = [level1, level2, level3, level]
for i in range(len(level_time)):
if i == level_score:
level = level_time[i]
total_level_width = len(level[0]) * PLATFORM_WIDTH
total_level_height = len(level) * PLATFORM_HEIGHT
camera = Camera(camera_configure, total_level_width, total_level_height)
y = 0
x = -64
for row in level:
for col in row:
if col == "-":
pf = blocks.Platform(x, y)
entities.add(pf)
platforms.append(pf)
if col == "*":
bd = blocks.BlockDie(x, y)
entities.add(bd)
platforms.append(bd)
if col == "1":
pf = blocks.Dirt1(x, y)
entities.add(pf)
platforms.append(pf)
if col == "x":
pf = blocks.Barrier(x, y - 64)
entities.add(pf)
platforms.append(pf)
if col == "s":
pf = blocks.Stairs(x, y)
entities.add(pf)
platforms.append(pf)
if col == "c":
COIN1 = blocks.Coin1(x, y)
entities.add(COIN1)
platforms.append(COIN1)
if col == "n":
COIN2 = blocks.Coin2(x, y)
entities.add(COIN2)
platforms.append(COIN2)
if col == "k":
COIN3 = blocks.Coin3(x, y)
entities.add(COIN3)
platforms.append(COIN3)
if col == "m":
COIN4 = blocks.Coin4(x, y)
entities.add(COIN4)
platforms.append(COIN4)
if col == "h":
COIN5 = blocks.Coin5(x, y)
entities.add(COIN5)
platforms.append(COIN5)
if col == "j":
COIN6 = blocks.Coin6(x, y)
entities.add(COIN6)
platforms.append(COIN6)
if col == "b":
COIN7 = blocks.Coin7(x, y)
entities.add(COIN7)
platforms.append(COIN7)
if col == "v":
COIN8 = blocks.Coin8(x, y)
entities.add(COIN8)
platforms.append(COIN8)
if col == "z":
COIN9 = blocks.Coin9(x, y)
entities.add(COIN9)
platforms.append(COIN9)
if col == "f":
a = blocks.Flag(x, y)
entities.add(a)
platforms.append(a)
if col == "g":
a = blocks.Flag2(x, y)
entities.add(a)
platforms.append(a)
if col == "u":
a = blocks.Flag3(x, y)
entities.add(a)
platforms.append(a)
x += PLATFORM_WIDTH
y += PLATFORM_HEIGHT
x = -64
return level, camera
def main():
global BUTTON_VERIFY, PLAY_TIMES, LEVEL, START_X, START_Y, COIN1, COIN2, COIN3, COIN4, COIN5, COIN6, COINS
pygame.init()
screen = pygame.display.set_mode(DISPLAY)
pygame.display.set_caption("Game")
pygame.display.set_icon(pygame.image.load("Image\Ico\caesar.png"))
timer = pygame.time.Clock()
hero = None
camera = None
fon = pygame.transform.scale(load_image('Ico\cyberpunk-street.png'), (WIN_WIDTH + 300, WIN_HEIGHT))
play_x, play_y, play_wight_x, play_hight_y, exit_x, exit_y, exit_wight_x, exit_hight_y = menu(screen)
left = right = up = w_up = s_down = False
c_x = c_y = c_wight_x = c_hight_y = None
animatedEntities = pygame.sprite.Group()
entities = pygame.sprite.Group()
platforms = []
tr1 = True
tr2 = True
running = True
while running:
timer.tick(60)
for e in pygame.event.get():
if e.type == QUIT:
running = False
if e.type == pygame.MOUSEBUTTONDOWN:
if e.button == 1:
x_button, y_button = e.pos
if exit_wight_x > x_button > exit_x and exit_hight_y > y_button > exit_y and BUTTON_VERIFY == 0:
running = False
if play_wight_x > x_button > play_x and play_hight_y > y_button > play_y and BUTTON_VERIFY == 0:
BUTTON_VERIFY = 1
screen.fill((0, 0, 0))
if PLAY_TIMES == 0:
animatedEntities = pygame.sprite.Group()
entities = pygame.sprite.Group()
platforms = []
hero = player.Player(START_X, START_Y, screen, LEVEL)
level, camera = levels(LEVEL, entities, platforms)
entities.add(hero)
PLAY_TIMES = 1
if BUTTON_VERIFY == 2 and c_wight_x > x_button > c_x and c_hight_y > y_button > c_y:
menu(screen)
PLAY_TIMES = 0
BUTTON_VERIFY = 0
LEVEL = 0
if BUTTON_VERIFY == 3 and c_wight_x > x_button > c_x and c_hight_y > y_button > c_y:
BUTTON_VERIFY = 1
if BUTTON_VERIFY == 4 and c_wight_x > x_button > c_x and c_hight_y > y_button > c_y:
menu(screen)
PLAY_TIMES = 0
BUTTON_VERIFY = 0
LEVEL = 0
if e.type == pygame.MOUSEMOTION:
x_button, y_button = e.pos
if exit_wight_x > x_button > exit_x and exit_hight_y > y_button > exit_y and BUTTON_VERIFY == 0 and tr1:
menu(screen)
pygame.draw.polygon(screen, (255, 255, 255), [(530, 490), (530, 440), (555, 465)], 0)
tr1 = False
tr2 = True
if play_wight_x > x_button > play_x and play_hight_y > y_button > play_y and BUTTON_VERIFY == 0 and tr2:
menu(screen)
pygame.draw.polygon(screen, (255, 255, 255), [(530, 340), (530, 290), (555, 315)], 0)
tr1 = True
tr2 = False
if e.type == pygame.KEYDOWN and e.key == 27 and BUTTON_VERIFY == 1:
pygame.mouse.set_visible(True)
levels(-1, entities, platforms)
menu(screen)
if e.type == KEYDOWN and e.key == 119:
w_up = True
if e.type == KEYDOWN and e.key == 115:
s_down = True
if e.type == KEYUP and e.key == 119:
w_up = False
if e.type == KEYUP and e.key == 115:
s_down = False
if e.type == KEYDOWN and e.key == 97:
left = True
if e.type == KEYDOWN and e.key == 100:
right = True
if e.type == KEYUP and e.key == 100:
right = False
if e.type == KEYUP and e.key == 97:
left = False
if e.type == KEYDOWN and e.key == 32:
up = True
if e.type == KEYUP and e.key == 32:
up = False
if BUTTON_VERIFY == 1:
pygame.mouse.set_visible(False)
screen.blit(fon, (-100, 0))
camera.update(hero)
animatedEntities.update()
for e in entities:
screen.blit(e.image, camera.apply(e))
coins, c1, c2, c3, c4, c5, c6, c7, c8, c9, lev, live = hero.update(left, right, up, w_up, s_down, platforms)
COINS = coins
if live == 0:
pygame.mouse.set_visible(True)
c_x, c_y, c_wight_x, c_hight_y = gameover(screen)
if lev != LEVEL:
if lev == 3:
pygame.mouse.set_visible(True)
c_x, c_y, c_wight_x, c_hight_y = finish(screen)
else:
pygame.mouse.set_visible(True)
c_x, c_y, c_wight_x, c_hight_y = level_update(screen)
LEVEL = lev
levels(-1, entities, platforms)
animatedEntities = pygame.sprite.Group()
entities = pygame.sprite.Group()
platforms = []
hero = player.Player(START_X, START_Y, screen, LEVEL)
entities.add(hero)
level, camera = levels(LEVEL, entities, platforms)
if c1:
COIN1.kill()
if c2:
COIN2.kill()
if c3:
COIN3.kill()
if c4:
COIN4.kill()
if c5:
COIN5.kill()
if c6:
COIN6.kill()
if c7:
COIN7.kill()
if c8:
COIN8.kill()
if c9:
COIN9.kill()
pygame.display.update()
main()
|
987,541 | 71beb5c923039915964c8fea2ed360ebf445aedd | from calculator import add
def test_add():
# BDD
# Given
a = 5
b = 6
# When
result = add(a, b)
# Then
assert result == 11
def test_add_simple():
assert add(5, 6) == 11
|
987,542 | 643f3ab701e1566d10d6893dcf90b87ba7b3fc5e | from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^interim_intentions$', views.InterimIntentionsView.as_view(), name='interim_intentions'),
url(r'^interim_intentions_admin$', views.InterimIntentionsAdminView.as_view(), name='interim_intentions_admin'),
url(r'^ta_view$', views.InterimIntentionsTAView.as_view(), name='interim_intentions_ta_view'),
url(r'^calendar_view$', views.InterimIntentionsCalendarView.as_view(), name='interim_intentions_calendar_view'),
]
|
987,543 | a7435ee9133286a20f49302de7e02ed887396a25 | from django.urls import path
from .views import UrlList, UrlCreate, UrlRedirect
from scripts.remove_urls import remove_url
urlpatterns = [
path("url/", UrlList.as_view(), name="list"),
path("url/create/", UrlCreate.as_view(), name="create"),
path("url/<name>/", UrlRedirect.as_view(), name="retrive"),
]
remove_url()
|
987,544 | 1a4c018b1360b051be3544827cc7f01984d0ec61 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from collections import namedtuple
INITIAL_START_TIME = '0001-01-01T00:00:00Z'
STATE_ABSENT = 'absent' # Does not exist.
STATE_PRESENT = 'present' # Exists but is not running.
STATE_RUNNING = 'running' # Exists and is running.
STATE_FLAG_INITIAL = 1 # Container is present but has never been started.
STATE_FLAG_RESTARTING = 1 << 1 # Container is not running, but in the process of restarting.
STATE_FLAG_NONRECOVERABLE = 1 << 10 # Container is stopped with an error that cannot be solved through restarting.
STATE_FLAG_OUTDATED = 1 << 11 # Container in any base state does not correspond with current config.
ContainerConfigStates = namedtuple('ContainerConfigState', ['client', 'map', 'config', 'flags', 'instances',
'attached'])
ContainerInstanceState = namedtuple('ContainerInstanceState', ['instance', 'base_state', 'flags', 'extra_data'])
|
987,545 | b7bb2a579af72cb19047e53cb83e580c5fba03cb | class Connection:
"""Contains the details required to connect to a RMQ broker: the amqp uri and the exchange"""
def __init__(self, amqp_uri: str, exchange: str, exchange_type: str = "direct", is_durable: bool = False, connect_timeout: int = 30, heartbeat: int = 30) -> None:
self._amqp_uri = amqp_uri
self._exchange = exchange
self._exchange_type = exchange_type
self._is_durable = is_durable
self._connect_timeout = connect_timeout
self._heartbeat = heartbeat
@property
def amqp_uri(self) -> str:
return self._amqp_uri
@amqp_uri.setter
def amqp_uri(self, value: str):
self._amqp_uri = value
@property
def exchange(self) -> str:
return self._exchange
@exchange.setter
def exchange(self, value: str):
self._exchange = value
@property
def exchange_type(self) -> str:
return self._exchange_type
@exchange_type.setter
def exchange_type(self, value: str):
self._exchange_type = value
@property
def is_durable(self):
return self._is_durable
@is_durable.setter
def is_durable(self, value):
self._is_durable = value
@property
def connect_timeout(self) -> int:
return self._connect_timeout
@connect_timeout.setter
def connect_timeout(self, value:int):
self._connect_timeout = value
@property
def heartbeat(self) -> int:
return self._heartbeat
@heartbeat.setter
def heartbeat(self, value:int):
self._heartbeat = value |
987,546 | 7077dca18599aad7cc4beb3cec2e57a6c0dc5f5e | __author__ = 'PyBeaner'
from random import sample
coefficients = sample(range(10), 2)
# O(n)
def horner_rule(x):
y = 0
for i in range(len(coefficients) - 1):
y = coefficients[i + 1] * x + coefficients[i]
return y
# O(n^2)
def normal(x):
y = 0
for i in range(len(coefficients)):
y += coefficients[i] * x ** i
return y
if __name__ == '__main__':
print(coefficients)
y = horner_rule(10)
print(y)
y = normal(10)
print(y)
|
987,547 | 52e9a15f60f9db70970bfa7a24e13f8b48502869 | # -*- coding: utf-8 -*-
"""
Created on Tue Mar 15 21:54:13 2016
@author: Rohan Koodli
"""
def encoding_test(sequence):
encoded = []
for i in sequence: #turns base pairs into numbers
if i == 'A':
encoded.append('1')
if i == 'T':
encoded.append('2')
if i == 'G':
encoded.append('3')
if i == 'C':
encoded.append('4')
#print encoded prints fine
seq = []
for i in range(len(encoded)):
if i%3 == 0:
a = encoded[i:i+3]
a = ''.join(a)
a = float(a)
seq.append(a)
return seq
import math
from collections import Counter
def entropy(labels):
num_labels = len(labels)
probability = [count / num_labels for count in Counter(labels).values()]
if num_labels <= 1:
return 0
return sum(-probability * math.log(probability,2)) #this is the formula
def encode_bases(sequence):#Bio.seq.seq type is iterable
encoded = []
for i in sequence:
if i == 'A':
encoded.append('1')
if i == 'T':
encoded.append('2')
if i == 'G':
encoded.append('3')
if i == 'C':
encoded.append('4')
encoded = encoded[:20] + ['.'] + encoded[20:]
encoded = ''.join(encoded)
encoded = float(encoded)
encoded1 = []
encoded1.append(encoded)
return encoded1
def encode_bases_2(sequence):#Bio.seq.seq type is iterable
encoded = []
for i in sequence:
if i == 'A':
encoded.append('1')
if i == 'T':
encoded.append('2')
if i == 'G':
encoded.append('3')
if i == 'C':
encoded.append('4')
encoded = encoded[:20] + ['.'] + encoded[20:]
encoded = ''.join(encoded)
encoded = float(encoded)
#print encoded
return encoded
def decrypt(array):#result is numpy.ndarray
results = []
results.append(array[0][0])
if array[0][1] == 0.0:
results.append('male')
elif array[0][1] == 1.0:
results.append('female')
else:
results.append('error')
results.append(array[0][2])
if array[0][3] == 0.0:
results.append('resistant to adamantanes')
elif array[0][3] == 1.0:
results.append('sensitive to adamantanes')
else:
results.append('error')
if array[0][4] == 0.0:
results.append('resistant to oseltamvir')
elif array[0][4] == 1.0:
results.append('sensitive to oseltamvir')
else:
results.append('error')
if array[0][5] == 0.0:
results.append('resistant to zanamvir')
elif array[0][5] == 1.0:
results.append('sensitive to zanamvir')
else:
results.append('error')
return results
def encode_bases_3(sequence):
encoded = []
for i in sequence:
if i == 'A':
encoded.append('1')
if i == 'T':
encoded.append('2')
if i == 'G':
encoded.append('3')
if i == 'C':
encoded.append('4')
e1 = encoded[0:20]
print (e1)
print len(e1)
print e1[0]
e1 = ''.join(e1)
print e1
e1 = float(e1)
final = []
final.append(e1)
return final
oooo = []
for i in range(len(encoded)):
if i%20 == 0:
a = ''.join(encoded[i],encoded[i+20])
def encode_bases_4(sequence):
encoded = []
for i in sequence:
if i == 'A':
encoded.append('1')
if i == 'T':
encoded.append('2')
if i == 'G':
encoded.append('3')
if i == 'C':
encoded.append('4')
oooo = []
for i in range(len(encoded)):
#print i
if i%20 == 0:
#print i
#i = int(i)
a = encoded[i:i+20]
a = ''.join(a)
a = float(a)
oooo.append(a)
o1 = []
o1.append(oooo)
return o1
def encode_bases_5(sequence):
encoded = []
for i in sequence:
if i == 'A':
encoded.append('1')
if i == 'T':
encoded.append('2')
if i == 'G':
encoded.append('3')
if i == 'C':
encoded.append('4')
oooo = []
for i in range(len(encoded)):
#print i
if i%20 == 0:
#print i
#i = int(i)
a = encoded[i:i+20]
a = ''.join(a)
a = float(a)
oooo.append(a)
o1 = []
o1.append(oooo)
return oooo
def encode_bases_np(sequence):
import numpy as np
encoded = []
for i in sequence:
if i == 'A':
encoded.append('1')
if i == 'T':
encoded.append('2')
if i == 'G':
encoded.append('3')
if i == 'C':
encoded.append('4')
oooo = []
for i in range(len(encoded)):
#print i
if i%20 == 0:
#print i
#i = int(i)
a = encoded[i:i+20]
a = ''.join(a)
a = float(a)
oooo.append(a)
o1 = []
o1.append(oooo)
o2 = np.array(o1)
return o2
def encode_bases_6(sequence):
encoded = []
for i in sequence:
if i == 'A':
encoded.append('1')
if i == 'T':
encoded.append('2')
if i == 'G':
encoded.append('3')
if i == 'C':
encoded.append('4')
oooo = []
for i in range(len(encoded)):
#print i
if i%20 == 0:
#print i
#i = int(i)
a = encoded[i:i+20]
a = ''.join(a)
a = float(a)
oooo.append(a)
o1 = []
o1.append(oooo)
return oooo
def encoding(sequence):
encoded = []
for i in sequence:
if i == 'A':
encoded.append('1')
if i == 'T':
encoded.append('2')
if i == 'G':
encoded.append('3')
if i == 'C':
encoded.append('4')
#print encoded prints fine
number = []
for i in range(len(encoded)):
if i%15 == 0:
a = encoded[i:i+15]
a = ''.join(a)
a = float(a)
number.append(a)
return number
'''
a = list(SeqIO.parse('/Users/rohankoodli/Desktop/Data-Files/Test-multiple-fasta.fasta','fasta'))
#print a[0]
b = encode_bases_4(a[0].seq)
#print 'aaaaa ',b
ab = []
ab.append(b)
#print ('%.20f' % b[0])
'''
|
987,548 | b4c62150a57967ffcfcf362cfccd757236f153c9 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
import tensorflow as tf
tf.compat.v1.enable_eager_execution()
import numpy as np
from ray.rllib.examples.env.rock_paper_scissors import RockPaperScissors
from ray.rllib.agents.ppo import PPOTrainer
from ray.tune.logger import pretty_print
from ray.rllib.agents.ppo.ppo_tf_policy import PPOTFPolicy
import ray
from ray import tune
from ray.tune import track
def ray_init():
ray.shutdown()
return ray.init(ignore_reinit_error=True, include_webui=True,
temp_dir='/scratch/sergei/tmp') # Skip or set to ignore if already called
ray_init()
env_config = {}
env_cls = RockPaperScissors
def build_trainer_config(restore_state=None, train_policies=None, config=None):
"""Build configuration for 1 run."""
obs_space = env_cls(env_config).observation_space
act_space = env_cls(env_config).action_space
agent_config = (PPOTFPolicy, obs_space, act_space, {
"model": {
"use_lstm": True,
"fcnet_hiddens": [config['fc_units'], config['fc_units']],
"lstm_cell_size": config['lstm_units'],
},
"framework": "tfe",
})
# N_POLICIES = 2
policies_keys = ['victim', 'adversary']
#policies = {policy_template % i: agent_config for i in range(N_POLICIES)}
policies = {name: agent_config for name in policies_keys}
def select_policy(agent_id):
assert agent_id in ["player1", "player2"]
agent_ids = ["player1", "player2"]
# selecting the corresponding policy (only for 2 policies)
return policies_keys[agent_ids.index(agent_id)]
# randomly choosing an opponent
# return np.random.choice(list(policies.keys()))
if train_policies is None:
train_policies = list(policies.keys())
for k in train_policies:
assert k in policies.keys()
config = {
"env": env_cls,
# "gamma": 0.9,
"num_workers": 0,
# "num_envs_per_worker": 10,
# "rollout_fragment_length": 10,
"train_batch_size": config['train_batch_size'],
"multiagent": {
"policies_to_train": train_policies,
"policies": policies,
"policy_mapping_fn": select_policy,
},
"framework": "tfe",
#"train_batch_size": 512
#"num_cpus_per_worker": 2
}
return config
def build_trainer(restore_state=None, train_policies=None, config=None):
"""Create a RPS trainer for 2 agents, restore state, and only train specific policies."""
print("Using config")
print(config)
cls = PPOTrainer
trainer = cls(config=config)
env = trainer.workers.local_worker().env
if restore_state is not None:
trainer.restore_from_object(restore_state)
return trainer
def train(trainer, stop_iters, do_track=True):
"""Train the agents and return the state of the trainer."""
for _ in range(stop_iters):
results = trainer.train()
print(pretty_print(results))
if do_track:
track.log(**results)
o = trainer.save_to_object()
return o
def train_one(config, restore_state=None, do_track=True):
"""Train with one config."""
def train_call(policies, state, iters):
rl_config = build_trainer_config(restore_state=state,
train_policies=policies,
config=config)
trainer = build_trainer(restore_state=state, config=rl_config)
state = train(trainer, iters, do_track=do_track)
return state
pretrain_time = config['train_steps']
evaluation_time = config['train_steps']
burst_size = config['burst_size']
n_bursts = pretrain_time // (2 * burst_size)
print("Pretrain time: %d" % pretrain_time)
print("Evaluation time: %d" % evaluation_time)
print("Burst size", burst_size)
print("Number of bursts", n_bursts)
print("Total iterations (true)", n_bursts * burst_size * 2 + evaluation_time)
state = None
if burst_size == 0:
state = train_call(['victim', 'adversary'], state, pretrain_time)
else:
for i in range(n_bursts):
state = train_call(['victim'], state, burst_size)
state = train_call(['adversary'], state, burst_size)
state = train_call(['adversary'], state, evaluation_time)
return state
burst_sizes = list(np.arange(35))
# best hypers from rps_rllib_tune.py and rps_rllib-analysis.ipynb
config = {
'fc_units': 100,
'lstm_units': 22,
'num_workers': 10,
'train_batch_size': 4096,
'train_steps': 40,
}
config['burst_size'] = tune.grid_search(burst_sizes)
print(config)
if __name__ == "__main__":
ray_init()
analysis = tune.run(
train_one,
config=config,
verbose=1,
#num_samples=100,
name="bursts",
num_samples=10,
) |
987,549 | de49c24276c353da0830d407113ade79ddc251db | # MongoDB Writer module
from pymongo import MongoClient
from bson.objectid import ObjectId
from nltk_ext.pipelines.pipeline_module import PipelineModule
# Item pipeline to write the item to a MongoDB store
class MongoWriter(PipelineModule):
"""
Initialize a MongoWriter object for a pipeline
If the operation is of type insert, you can specify the keys to update
in the constructor.
"""
def __init__(self, db="spout_test", collection="documents",
operation="insert", keys=[]):
self.mongodb_client = MongoClient()
self.db = self.mongodb_client[db]
self.collection = self.db[collection]
self.operation = operation
self.keys = keys
def process(self, documents, keys=None):
if (keys == None) and (self.keys != None):
keys = self.keys
for d in documents:
doc_id = d.doc_id
if self.operation == "insert":
self.collection.insert(d.document)
elif self.operation == "update":
if keys == None:
self.collection.update({ '_id': ObjectId(doc_id) }, d.document)
else:
filtered_dict = {key: d.document[key] for key in keys}
self.collection.update({ "_id": ObjectId(doc_id) },
{ "$set": filtered_dict})
#doc = self.collection.find_one({'_id': ObjectId(doc_id)})
yield d
|
987,550 | 1e4ba614cfcf2f28d554fec5f642de81f1552a7c | from django.shortcuts import render
from django.shortcuts import redirect
from django.shortcuts import HttpResponse
from app01 import models
# Create your views here.
from django.views import View
from day04 import settings
import os,sys
import zipfile
DOWN=os.path.join(settings.BASE_DIR,"down")
file_name=os.path.join(DOWN,"users.zip")
# 查看班级
def grade(request):
# 取出所有班级对象
class_obj=models.Grade.objects.all()
#返回班级grade.HTML网页文件,并将班级对象传入给网页
return render(request,"grade.html",{"grade_list":class_obj})
#添加班级
def add_grade(request):
if request.method=="POST":
# 取出post请求中的新班级名
add_classname=request.POST.get("add_classname")
#操作数据库表,向其中添加该数据
models.Grade.objects.create(classname=add_classname)
#返回一个查看班级的URl
return redirect("/grade/")
else:
#返回一个添加班级的页面
return render(request,"add_grade.html")
#删除班级
def del_grade(request):
# 取出URL后拼接的id值
class_id=request.GET.get("id")
# 从数据库表中取出对应的对象
class_obj=models.Grade.objects.get(id=class_id)
# 删除该对象
class_obj.delete()
# 返回查询班级的URL
return redirect("/grade/")
#修改班级
def change_grade(request):
if request.method=="POST":
#从拼接的URL中取出修改班级的id值
class_id = request.GET.get("id")
#从POST请求中取出新的班级名称
new_classname=request.POST.get("new_classname")
#从数据库中根据班级id取出班级对象
class_obj = models.Grade.objects.get(id=class_id)
# 修改班级对象的名称
class_obj.classname=new_classname
#保存班级对象
class_obj.save()
# 返回查询班级的URL
return redirect("/grade/")
else:
#取出拼接URL中修改班级的id值
class_id=request.GET.get("id")
# 从数据库中取出修改的班级对象
class_obj=models.Grade.objects.get(id=class_id)
#返回一个修改页面文件,并将要修改的班级对象传如网页
return render(request,"change_grade.html",{"class_list":class_obj})
# 查看学生
def student(request):
# 取出所有学生对象
student_obj=models.Student.objects.all()
#返回一个学生页面文件,并将所有学生对象传入该文件
return render(request,"student.html",{"student_obj_list":student_obj})
# 添加学生
def add_student(request):
if request.method=="POST":
#取出post请求中的添加的学生姓名
add_student_name=request.POST.get("add_student_name")
# 取出post请求中添加学生的班级id
class_id=request.POST.get("student_class")
#操作数据库表创建该学生
models.Student.objects.create(student_name=add_student_name,grade_id=class_id)
#返回查询学生的URL
return redirect("/student/")
else:
# 取出所有班级对象
all_grade=models.Grade.objects.all()
#返回一个添加学生的页面,并将多有班级对象传入该文件
return render(request,"add_student.html",{"grade_list":all_grade})
# 删除学生
def del_student(request):
#取得拼接URL中的要删除的学生id
student_id=request.GET.get("id")
#根据学生id在数据库中查出该学生对象
student_obj=models.Student.objects.get(id=student_id)
#删除该学生对象
student_obj.delete()
# 返回查询学生的URL
return redirect("/student/")
# 修改学生
def change_student(request):
if request.method=="POST":
#取得拼接URL中要修改的学生id
student_id=request.GET.get("id")
#根据学生id查询出要修改的学生的对象
student_obj=models.Student.objects.get(id=student_id)
#取出POST请求中的新的学生姓名
new_student_name=request.POST.get("new_student_name")
#取出POST请求中新的班级id
student_class_id=request.POST.get("student_class_id")
#修改学生姓名
student_obj.student_name=new_student_name
#修改学生班级id
student_obj.grade_id=student_class_id
#保存修改
student_obj.save()
# 返回查询学生的URL
return redirect("/student/")
else:
#取得拼接URL中要修改的学生id
student_id=request.GET.get("id")
#根据学生id查询出要修改的学生的对象
sutdent_obj=models.Student.objects.get(id=student_id)
#查询出所有班级对象
grade_all=models.Grade.objects.all()
#返回一个修改网页,将所有的班级对象和要修改的学生对象传入网页中
return render(request,"change_student.html",{"sutdent":sutdent_obj,"grade_list":grade_all})
#查看老师
def teacher(request):
#查询所有老师对象
teacher_obj=models.Teacher.objects.all()
#返回一个页面,并将所有老师对象传入该文件
return render(request,"teacher.html",{"teacher_list":teacher_obj})
#添加老师
def add_teacher(request):
if request.method=="POST":
# 取得POST请求中的添加的老师名
add_teacher_name=request.POST.get("add_teacher_name")
# 操作数据库表添加该老师
models.Teacher.objects.create(teacher_name=add_teacher_name)
#返回一条查询老师信息的URL
return redirect("/teacher/")
else:
#查询出所有班级对象,传入添加老师的页面
all_grade=models.Grade.objects.all()
return render(request,"add_teacher.html",{"grade_list":all_grade})
#删除老师
def del_teacher(request):
#接受拼接URL中的要删除的老师id
teacher_id=request.GET.get("id")
#根据id从数据库中取出该老师对象
teacher_obj=models.Teacher.objects.get(id=teacher_id)
#删除该对象
teacher_obj.delete()
#返回一个老师查询URL
return redirect("/teacher/")
#修改老师
def change_teacher(request):
if request.method=="POST":
##接受拼接URL中的要修改的老师id
teacher_id = request.GET.get("id")
# 根据id从数据库中取出该老师对象
teacher_obj = models.Teacher.objects.get(id=teacher_id)
#取出POST请求中老师选择教授的班级id
grades_list=request.POST.getlist("teacher_class_id")
#取出POST请求中新的老师名
teacher_new_name=request.POST.get("new_teacher_name")
#修改数据库中老师的名称
teacher_obj.teacher_name=teacher_new_name
#保存修改
teacher_obj.save()
#修改老师教授的班级
teacher_obj.grades.set(grades_list)
return redirect("/teacher/")
else:
##接受拼接URL中的要修改的老师id
teacher_id=request.GET.get("id")
# 根据id从数据库中取出该老师对象
teacher_obj = models.Teacher.objects.get(id=teacher_id)
#查询出所有的班级对象
grade_all=models.Grade.objects.all()
#返回一个修改老师的页面文件,将所有班级对象和要修改的老师对象传入该页面
return render(request,"change_teacher.html",{"teacher":teacher_obj,"grade_list":grade_all})
def index(request):
return render(request,"index.html")
#传入一个目录,拿出目录下所有文件的路径
def allfile(dirs,li=[]):
file_list=os.listdir(dirs)
for i in file_list:
neic=os.path.join(dirs,i)
if os.path.isdir(neic):
allfile(neic)
else:
li.append(neic)
return li
#传入一个文件路径列表,返回所有文件的代码行数
def num_all(li):
num = 0
size=0
for i in li:
with open(i, "r", encoding="utf8") as f:
for line in f:
if line.strip() == "":
pass
elif line.strip().startswith("#"):
pass
else:
num += 1
size+=os.path.getsize(i)
return num,size
#响应url的函数
def Addfile(request):
if request.method=="GET":
return render(request,"addfile.html")
else:
file_obj=request.FILES.get("filename")
file_name=os.path.join(DOWN,file_obj.name)
file_dir=os.path.join(file_name.split(".")[0])
with open(file_name,"wb") as f:
for i in file_obj:
f.write(i)
file_size=os.path.getsize(file_name)
#解压文件
z = zipfile.ZipFile(file_name)
z.extractall(path=file_dir)
z.close()
#获取加压目录中的文件和子文件
b=allfile(file_dir,[])
print(b)
num=num_all(b)
file={
"name":file_obj.name,
"num":num[0],
"size":num[1],
"ysq":file_size,
}
return render(request,"file.html",{"file_a":file})
|
987,551 | 6f965100bdad157a90cb98f16e86d0dc460048e4 | #!/usr/bin/env python
"""
fusion_report_referrals.py
Author: Seemu Ali
Created: 10.06.2020
Version: 0.0.2
"""
import numpy as np
import pandas as pd
import sys
import os
sample_dir=sys.argv[1]
panel_dir=sys.argv[2]
sampleId=sys.argv[3]
tool_output =[ "StarFusion", "Arriba", "ArribaDiscarded", ]
referrals = ["Lymphoma", "AML", "CML", "MPN", "ALL", "Myeloma", ]
# *Referrals*
referral_df=pd.read_csv(panel_dir+'/HaemReferrals.csv', sep=",", index_col=False)
lymphoma = referral_df['Lymphoma'].to_list()
AML = referral_df['AML'].to_list()
CML = referral_df['CML'].tolist()
MPN = referral_df['MPN'].tolist()
ALL = referral_df['ALL'].tolist()
myeloma = referral_df['Myeloma'].tolist()
# *Format Starfusion Report*
fusion_report=pd.read_csv(sample_dir+"/STAR-Fusion/fusionReport/"+sampleId+"_fusionReport.txt", sep="\t", index_col=False)
if (fusion_report.shape[0]!=0):
genes=fusion_report["Fusion_Name"].str.split("--", expand=True)
fusion_report["gene1"]=genes[0]
fusion_report["gene2"]=genes[1]
fusion_report=pd.DataFrame(fusion_report)
elif (fusion_report.shape[0]==0):
fusion_report["gene1"]=""
fusion_report["gene2"]=""
fusion_report=pd.DataFrame(fusion_report)
# *Format Arriba Report*
arriba_report=pd.read_csv(sample_dir+"/Arriba/"+sampleId+"_arriba_fusions.tsv", sep="\t")
arriba_report=arriba_report.rename(columns={'#gene1': 'gene1'})
arriba_discarded=pd.read_csv(sample_dir+"/Arriba/"+sampleId+"_fusions_arriba_discarded.tsv", sep="\t")
arriba_discarded=arriba_discarded.rename(columns={'#gene1': 'gene1'})
# *Report Generator*
def report_maker(tool, sampleId, referral, genes, results):
referral_dict = { i : referral for i in genes}
results["gene1_mark"] = results["gene1"].map(referral_dict)
results["gene2_mark"] = results["gene2"].map(referral_dict)
final_report = results
final_report["1-hit"] = np.where((final_report["gene1_mark"] == referral) | (final_report["gene2_mark"] == referral), 1, 0)
final_report["2-hit"] = np.where((final_report["gene1_mark"] == referral) & (final_report["gene2_mark"] == referral), 1, 0)
full_report = final_report.loc[final_report["1-hit"] == 1 ]
twohit_report = final_report.loc[final_report["2-hit"] == 1 ]
twohit_report.to_csv(f"./Results/{referral}/{sampleId}_{referral}_{tool}_2Hit_Report.csv", sep=',')
if (full_report.shape[0]!=0):
full_report.to_csv(f"./Results/{referral}/Full_Reports/{sampleId}_{referral}_{tool}_Full_Report.csv", sep=',')
if (twohit_report.shape[0] == 0):
os.remove(f"./Results/{referral}/{sampleId}_{referral}_{tool}_2Hit_Report.csv")
if (full_report.shape[0] == 0):
with open(f"./Results/{referral}/Full_Reports/Nofusions.txt", 'a+') as file:
file.seek(0)
data = file.read(100)
if len(data) > 0 :
file.write("\n")
file.write( f' \n *{tool}: {referral} fusions not detected*')
file.close()
for referral in referrals:
genes = referral_df[referral].to_list()
for tool in tool_output:
if tool == "StarFusion":
results = fusion_report
report_maker(tool, sampleId, referral, genes, results)
elif tool == "Arriba":
results = arriba_report
report_maker(tool, sampleId, referral, genes, results)
elif tool == "ArribaDiscarded":
results = arriba_discarded
report_maker(tool, sampleId, referral, genes, results)
|
987,552 | 63d353d98a8ebba0b80ef2a93f2c00bd6b3b4489 | from django.contrib import admin
from . import models
@admin.register(models.Post)
class AuthorAdmin(admin.ModelAdmin):
list_display = ('place', 'id', 'author')
@admin.register(models.Review)
class AuthorAdmin(admin.ModelAdmin):
list_display = ('guide', 'id', 'author')
admin.site.register(models.Contact)
|
987,553 | 0902c76ca45e34f22d5db3a4b38bc2caf08f74cd | """__init__.py
Localizer package initializer
"""
from .ekf_slam import EKF_SLAM
from .ekf_slam import * |
987,554 | 1176c7ab66f080302bb7aa8225fa56c7ea8f568e | from tkinter import *
from os import walk
window = Tk()
window.geometry("875x500")
class ItemClass:
def __init__(self, name, cost):
self.name = name
self.cost = int(float(cost))
self.quantity = Entry(window)
self.quantity.place(x=X_loc + 550, y=Y_loc + 35)
def printItem(self):
print(' name: {} , cost {} '.format(self.name, self.cost))
def getName(self):
return str(self.name)
def getCost(self):
return str(self.cost)
def getQuantity(self):
if self.quantity.get() == "":
return 0;
return self.quantity.get()
def resetQuantity(self):
self.quantity.delete(0, "end")
class MenuCard:
obj = []
def __init__(self, heading):
self.heading = heading
self.itemDetails = {}
self.X_loc = 50
self.Y_loc = 110
self.quantity = 0
self.myBillpath = "BILLS"
self.label_head = Label(window, text=self.heading, font="Times 32 bold")
self.label_head.place(x=420, y=30, anchor="center")
self.subMenu = Label(window, text="MENU", font="Times 28 bold")
self.subMenu.place(x=50, y=60)
self.BillNo = 1000
def getLastBillNo(self):
for i in walk(self.myBillpath):
for file in i[2]:
if file.split("_")[0] == "BILL":
if int(float(file.split("_")[1].strip(".txt"))) > int(self.BillNo):
self.BillNo = int(float(file.split("_")[1].strip(".txt")))
return self.BillNo;
def getNextBillNo(self):
return self.getLastBillNo() + 1
def getNextBillName(self):
return '{}\\BILL_{}.txt'.format(self.myBillpath, self.getNextBillNo())
def UpdateLocation(self, x, y):
self.X_loc = x
self.Y_loc = y
def getLocation(self):
return self.X_loc, self.Y_loc
def addItems(self, ItemClass):
MenuCard.obj.append(ItemClass)
text2fill = '{:.<30}'.format(ItemClass.getName()) + "Rs." + '{:5}'.format(ItemClass.getCost())
label = Label(window, text=text2fill, font="Courier 18 ")
label.place(x=self.X_loc, y=self.Y_loc + 30)
self.UpdateLocation(self.X_loc, self.Y_loc + 30)
def resetItemQuantity(self):
for item in MenuCard.obj:
item.resetQuantity()
self.clearSummary()
obj = []
def clearSummary(self):
xxx = 550
yyy = 300
for clear_loc in range(yyy, 500, 10):
label = Label(window, text=" ", font="Courier 12 ")
label.place(x=xxx, y=clear_loc)
def Summary(self):
xxx = 550
yyy = 300
label = Label(window, text='Bill NO: {}'.format(self.getNextBillNo()), font="Courier 12 ")
label.place(x=xxx, y=yyy)
yyy = yyy + 30
sumof_each = []
for i in MenuCard.obj:
sumof_each.append(int(i.getQuantity()) * int(i.getCost()))
text2fillAgain = '{} {} x Rs.{} = Rs.{} '.format(str(i.getName()), int(i.getQuantity()), int(i.getCost()),
int(i.getQuantity()) * int(i.getCost()))
label = Label(window, text=text2fillAgain, font="Courier 12 ")
label.place(x=xxx, y=yyy)
yyy = yyy + 20
label = Label(window, text="---------------------", font="Courier 12 ")
label.place(x=xxx, y=yyy)
yyy = yyy + 20
label = Label(window, text='Total Rs.{}'.format(str(sum(sumof_each))), font="Courier 12 ")
label.place(x=xxx, y=yyy)
yyy = yyy + 20
label = Label(window, text="---------------------", font="Courier 12 ")
label.place(x=xxx, y=yyy)
# ==========================
##=== main starts here=====
# ==========================
print("Starting..")
listofitems = []
# heading
a = MenuCard("MY BILLING TOOL")
# --------------------
# reading file
# --------------------
val = []
filename = "CONFIG/config.csv"
# open the file for reading
filehandle = open(filename, 'r')
while True:
# read a single line
line = filehandle.readline()
if not line:
break
a1, b1 = line.split(",")
# val.append(str(a1))
# val.append(b1.rstrip())
val.append([a1, b1.strip()])
# close the pointer to that file
filehandle.close()
# --------------------
# --------------------
# creating objects in Menu
# --------------------
for i in val:
print(i[0])
X_loc, Y_loc = a.getLocation()
listofitems.append(ItemClass(i[0].strip('"'), i[1].strip('"')))
a.addItems(ItemClass(i[0].strip('"'), i[1].strip('"')))
# --------------------
print(MenuCard.obj)
for i in listofitems:
i.printItem()
def cleanExit():
window.destroy()
def createBill():
sumofEach = []
q_in_list=sum([int(i.getQuantity()) for i in MenuCard.obj])
if q_in_list>0:
curr_file = a.getNextBillName()
with open(curr_file, "x") as writer:
writer.write("BILL NO:" + str(a.getNextBillNo() - 1) + "\n");
for i in MenuCard.obj:
sumofEach.append(int(i.getQuantity()) * int(i.getCost()));
text2fillAgain = '{} {} x Rs.{} = Rs.{} {}'.format(str(i.getName()), int(i.getQuantity()),
int(i.getCost()),
int(i.getQuantity()) * int(i.getCost()), "\n");
writer.write(text2fillAgain);
writer.write("---------------------\n");
text = 'Total {} {}'.format(str(sum(sumofEach)), "\n");
writer.write(text);
writer.write("---------------------\n");
print("Bill written {}".format(curr_file));
a.resetItemQuantity();
else:
print("Nothing to Bill")
b1 = Button(window, text="biil", width=20, command=createBill)
b1.place(x=100, y=350)
b2 = Button(window, text="Summary", width=20, command=a.Summary)
b2.place(x=100, y=400)
b3 = Button(window, text="Exit", width=20, command=cleanExit)
b3.place(x=100, y=450)
window.mainloop()
|
987,555 | f4597c8a34543f96eb5140b0605383c25b472fb5 | import turtle
mario = turtle.Turtle()
luigi = turtle.Turtle()
koopa = turtle.Turtle()
khide = koopa.color("snow4")
def spire(i):
for i in range (i):
mario.forward(i)
mario.right(270)
mario.forward(i+50)
mario.right(270)
mario.forward(i)
mario.right(270)
mario.forward(i+50)
mario.right(270)
mario.forward(i)
def roadlines(i):
for i in range (i):
koopa.color("gold")
koopa.forward(i+1)
koopa.color("snow4")
koopa.forward(i+1)
koopa.color("gold")
koopa.pensize(i+1)
turtle.bgcolor("midnight blue")
luigi.color("midnight blue")
luigi.right(90)
luigi.forward(45)
luigi.color("green")
luigi.begin_fill()
luigi.right(270)
luigi.forward(1000)
luigi.right(90)
luigi.forward(1000)
luigi.right(90)
luigi.forward(2000)
luigi.right(90)
luigi.forward(1000)
luigi.right(90)
luigi.forward(1000)
luigi.end_fill()
luigi.color("snow4")
luigi.begin_fill()
luigi.right(45)
luigi.forward(750)
luigi.right(135)
luigi.forward(1100)
luigi.right(135)
luigi.forward(750)
luigi.right(45)
luigi.forward(50)
luigi.end_fill()
koopa.color("midnight blue")
koopa.right(90)
koopa.forward(45)
koopa.right(90)
koopa.color("snow4")
koopa.forward(25)
koopa.right(270)
koopa.speed(900)
roadlines(20)
mario.right(90)
mario.color("midnight blue")
mario.forward(45)
mario.right(90)
mario.color("snow4")
mario.forward(45)
mario.color("green")
mario.forward(300)
mario.color("black")
mario.fillcolor("dim grey")
mario.right(180)
mario.begin_fill()
mario.forward(50)
mario.right(270)
mario.forward(150)
mario.right(270)
mario.forward(100)
mario.right(270)
mario.forward(150)
mario.right(270)
mario.forward(50)
mario.end_fill()
mario.forward(100)
mario.fillcolor("light grey")
mario.begin_fill()
mario.forward(50)
mario.right(270)
mario.forward(200)
mario.right(315)
mario.forward(100)
mario.right(45)
mario.right(180)
mario.forward(270)
mario.right(270)
mario.forward(50)
mario.end_fill()
mario.forward(125)
mario.fillcolor("light steel blue")
mario.begin_fill()
mario.forward(75)
mario.right(270)
mario.forward(76)
mario.right(270)
mario.forward(150)
mario.right(270)
mario.forward(76)
mario.right(270)
mario.forward(75)
mario.end_fill()
mario.forward(100)
mario.fillcolor("grey")
mario.begin_fill()
mario.speed(10)
spire(14)
mario.end_fill()
turtle.exitonclick()
|
987,556 | 5a2ca57d8b5fa48a5c28349fec53b41a095e809d | # coding:utf-8
from __future__ import absolute_import, unicode_literals
from celery import Celery
from django.conf import settings
import os
# 获取当前文件夹名,即为该Django的项目名
project_name = os.path.split(os.path.abspath('.'))[-1]
project_settings = '%s.settings' % project_name
# 设置环境变量
os.environ.setdefault('DJANGO_SETTINGS_MODULE', project_settings)
# 实例化Celery
app = Celery('tasksss', broker='redis://:qqcqqc@47.102.138.171:6379/3')
# 使用django的settings文件配置celery
app.config_from_object('django.conf:settings')
# Celery加载所有注册的应用
app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)
"""
命令启动 同manage.py文件目录下:
执行任务:celery -A test_obj worker --pool=solo -l info --pidfile=
发布任务:elery -A test_obj beat
发布和执行一起: celery -B -A test_obj worker
指定队列启动:celery -A test_obj worker -n dj_two -Q dj_two --pool=solo -l info
flower 启动: flower worker -A test_obj --port=8004
supervisorctl 命令
supervisorctl restart test-django:* 重启
supervisorctl stop test-django:* 停止
supervisorctl start test-django:* 开启
"""
|
987,557 | 5353efb6ce3889645bc8d8bdc69e3d371b2656ad | '''Дані про температуру води на Чорноморському узбережжі за декаду
вересня зберігаються в масиві. Визначити, скільки за цей час було днів, придатних для
купання.
Bиконал Пахомов Олександр 122-А'''
import numpy as np
a=np.zeros(10, dtype= int)
c=0
for i in range(10):
a[i]= int(input('temperatura:'))
if a[i]>15:
c+=1
print(c)
|
987,558 | 6be69fa0234ab46aac1077846de11650d97ac683 | a=1000
print("hello")
print("dfsdf")
b=2000
print(a+b)
|
987,559 | b469c3f77e20ac19a61914de18c84fe08dde5646 | # Generated by Django 2.2.6 on 2019-10-28 18:23
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('company_service', '0041_availability_state'),
]
operations = [
migrations.RemoveField(
model_name='productionline',
name='turn',
),
migrations.RemoveField(
model_name='productionline',
name='turn_scheme',
),
]
|
987,560 | ace90aedfa398eb4c5f261d1e775461cdab3fa69 | #!/usr/bin/env python
''' The Census Transform
Scan an 8 bit greyscale image with a 3x3 window
At each scan position create an 8 bit number by comparing the value
of the centre pixel in the 3x3 window with that of its 8 neighbours.
The bit is set to 1 if the outer pixel >= the centre pixel
See http://stackoverflow.com/questions/38265364/census-transform-in-python-opencv
Written by PM 2Ring 2016.07.09
'''
import numpy as np
from PIL import Image
import time
import cv2
def censusTransformSingleChannel(src_bytes):
h,w = src_bytes.shape
#Initialize output array
census = np.zeros((h-2, w-2), dtype='uint8')
#census1 = np.zeros((h, w), dtype='uint8')
#centre pixels, which are offset by (1, 1)
cp = src_bytes[1:h-1, 1:w-1]
#offsets of non-central pixels
offsets = [(u, v) for v in range(3) for u in range(3) if not u == 1 == v]
#Do the pixel comparisons
for u,v in offsets:
census = (census << 1) | (src_bytes[v:v+h-2, u:u+w-2] >= cp)
return census
def censusTransform( src_bytes ):
# chk num of channels. if 1 call as is, if 3 call it with each channel
if len(src_bytes.shape) == 2: #single channel
census = censusTransformSingleChannel( np.lib.pad( src_bytes, 1, 'constant', constant_values=0 ) )
if len( src_bytes.shape ) == 3 and src_bytes.shape[2] == 3 :
census_a = censusTransformSingleChannel( np.lib.pad( src_bytes[:,:,0], 1, 'constant', constant_values=0 ) )
census_b = censusTransformSingleChannel( np.lib.pad( src_bytes[:,:,1], 1, 'constant', constant_values=0 ) )
census_c = censusTransformSingleChannel( np.lib.pad( src_bytes[:,:,2], 1, 'constant', constant_values=0 ) )
census = np.dstack( (census_a,census_b,census_c) )
return census
##iname = 'Glasses0S.png'
#iname = 'lena.bmp'
#
#im = cv2.imread( iname, cv2.IMREAD_COLOR )
#print 'im.shape : ', im.shape, im.dtype
#
#startTime = time.time()
#census = censusTransform( im)
#print 'Elapsed time : ', time.time() - startTime
#print 'census.shape : ', census.shape, census.dtype
#
#cv2.imshow( 'org', im )
#cv2.imshow( 'census', census )
#
#cv2.waitKey(0)
##Get the source image
#src_img = Image.open(iname)
#src_img.show()
#
#w, h = src_img.size
#print('image size: %d x %d = %d' % (w, h, w * h))
#print('image mode:', src_img.mode)
#
##Convert image to Numpy array
#src_bytes = np.asarray(src_img)
#
#startTime = time.time()
#census = censusTransform(src_bytes)
#print 'time taken : ', time.time() - startTime
#
#
##Convert transformed data to image
#out_img = Image.fromarray(census)
#out_img.show()
#out_img.save(oname)
|
987,561 | aa166dfc3ff65b4bc10fe385e0e33d40a28a6f78 | import ast
import pandas as pd
import requests
import json
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import ObjectDoesNotExist
from . models import NerSample
def create_ner_samples_from_csv(file, text_col='text', ent_col='entities'):
df = pd.read_csv(file)
df['dict'] = df[ent_col].map(ast.literal_eval)
for i, row in df.iterrows():
try:
textlenght = len(row[text_col])
except TypeError:
textlenght = None
if textlenght is None:
pass
else:
ner, _ = NerSample.objects.get_or_create(
text=row[text_col], entity_json=row['dict']
)
def create_ner_samples_from_list(ner_list, limit=10):
for row in ner_list:
if len(row[0]) > limit:
ner = NerSample.objects.get_or_create(
text=row[0], entity_json=row[1]
)
def create_ner_sample_from_qs(app_label, model_label, textfield, endpoint, start=0, limit=None):
url = endpoint
try:
ct = ContentType.objects.get(app_label=app_label, model=model_label).model_class()
except ObjectDoesNotExist:
ct = None
if ct:
qs = ct.objects.all()
if qs:
try:
limit = int(limit)
except TypeError:
limit = qs.count()
for x in qs[start:limit]:
obj_text = getattr(x, textfield, 'None')
if obj_text:
text = "{}".format(obj_text).strip()
else:
text = None
if text:
payload = {}
payload['longtext'] = text
payload['dont_split'] = True
headers = {'content-type': "application/json; charset=utf-8"}
response = requests.request(
"POST", url, headers=headers,
data=json.dumps(payload)
)
resp_dict = json.loads(response.text)
if resp_dict:
for y in resp_dict:
ner, _ = NerSample.objects.get_or_create(
text=y[0]
)
ner.entity_json = y[1]
ner.content_object = x
ner.save()
yield ner
|
987,562 | cba8573373a316245d6daf9f26f44418ef7bd056 | __author__ = 'magic'
from model.contact import Contact
import random
import string, re
import os.path
import jsonpickle
import getopt, sys
try:
opts, args = getopt.getopt(sys.argv[1:], "n:f:", ["number of contacts", "file"])
except getopt.GetoptError as err:
getopt.usage()
sys.exit(2)
n = 5
f = "data/contacts.json"
for o, a in opts:
if o == "-n":
n = int(a)
elif o == "-f":
f = a
def random_string(maxlen):
symbols = string.ascii_letters + string.digits
s = "".join([random.choice(symbols) for i in range(random.randrange(maxlen))])
return re.sub("\s\s+", " ", s)
testdata = [Contact(firstname="", lastname="", email="")] + [
Contact(firstname=random_string(10), lastname=random_string(20), email=random_string(20))
for i in range(n)
]
file = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", f)
with open(file, "w") as output:
jsonpickle.set_encoder_options("json", indent=2)
output.write(jsonpickle.encode(testdata)) |
987,563 | 1afc875fc7b6b976cb484b33fbb0b5db8644631f | import pickle
import matplotlib.pyplot as plt
import numpy as np
import os
import cv2
import keras
from PIL import Image
from keras.models import load_model
def get_label_dict():
f = open('./b_label', 'rb')
label_dict = pickle.load(f)
f.close()
return label_dict
lang_chars = get_label_dict()
words_label = []
for (char, value) in lang_chars.items():
words_label.append(char)
class Prediction(object):
def __init__(self, ModelFile, words_label, Width=25, Height=30):
self.modelfile = ModelFile
self.Width = Width
self.Height = Height
self.words_label = words_label
def get_words_list(self, path_):
list_name = []
files = os.listdir(path_)
files.sort() # 对列表排序
for word in files:
word_path = os.path.join(path_, word)
list_name.append(word_path)
return list_name
def Predict(self):
keras.backend.clear_session()
model = load_model(self.modelfile)
image_set = []
word_path = []
word_path = self.get_words_list(path_='./image_temp/')
# print(word_path)
for image in word_path:
new_img = Image.open(image).convert('L')
new_img = new_img.resize((self.Width, self.Height), Image.ANTIALIAS)
new_img.save(image)
new_img = np.asarray(new_img)
new_img = new_img.reshape([-1, 30, 25, 1])
image_set.append(new_img)
word_list = []
for image_predict in image_set:
prediction = model.predict(image_predict)
Final_prediction = [result.argmax() for result in prediction][0]
count = 0
max_subscript = 0
max_acc = 0.0
for i in prediction[0]:
if (max_acc < i):
max_acc = i
max_subscript = count
count += 1
# percentage1 = '%.2f%%' % (i * 100)
# print (self.words_label[count-1],'概率:' ,percentage1)
percentage = '%.2f%%' % (max_acc * 100)
if (max_acc * 100) < 70.0:
word_list.append(' ')
else:
word_list.append(self.words_label[max_subscript])
sentence = "".join(word_list)
print(sentence)
# print (self.words_label[max_subscript],'概率:' ,percentage)
def remove_(self):
word_path = []
word_path = self.get_words_list(path_='./image_temp/')
for image in word_path:
os.remove(image)
word_path = self.get_words_list(path_='./row_cut/')
for image in word_path:
os.remove(image)
Pred = Prediction(ModelFile='words_recognize.h5',
words_label=words_label,
)
Pred.Predict()
#Pred.remove_() |
987,564 | 6b7cc4f22bf1a013d85e4768dc9e7437cf03bdfc | from tkinter import *
import networkx as nwx, matplotlib.pyplot as plt
import Create_matrix
def created_graph(event):
graf1 = nwx.Graph()
edges = []
for i in Create_matrix.value:
edges.append(i[:2])
for i in edges:
graf1.add_nodes_from(i)
for i in edges:
graf1.add_edges_from(edges)
nwx.draw(graf1, pos=nwx.shell_layout(graf1), alpha=0.6, edge_color='b', font_size=20,
node_size=700, arrows=True, with_labels=True)
plt.show()
|
987,565 | ea410523bae8e3750b0cbbcbebd7f2f4589bfed9 |
def cara_coroa(resultado):
john = 0
mary = 0
for e in resultado:
if e == '1':
john += 1
elif e == '0':
mary += 1
return "Mary won %d times and John won %d times" %(mary,john)
while True:
jogadas = int(raw_input())
if jogadas == 0:
break
resultado = raw_input().split()
print cara_coroa(resultado)
|
987,566 | d77bd82db1dc7984117c90310398c089420da274 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
##Librerias necesarias para usar PyQt
from PyQt5.QtWidgets import QWidget, QFileDialog,QFileDialog,QMessageBox,QMainWindow, QApplication, QWidget, QAction, QTableWidget,QTableWidgetItem,QVBoxLayout, QPushButton,QHBoxLayout,QDialog
from PyQt5 import uic
from PyQt5.QtGui import QIcon
from PyQt5.QtGui import QFont
from PyQt5.QtCore import QDate
from PyQt5.QtCore import pyqtSlot
from PyQt5 import QtGui, QtCore
import numpy as np
#import matplotlib.pyplot as plt
import pandas as pd
import time
import shutil
import csv, operator
import pdfkit
import sys
import os
##Funcion que devuelve una lista de productos actualizada
def actualizarListaProductos():
productos=[]
with open('productos/productos.csv') as csvarchivo:
entrada = csv.DictReader(csvarchivo)
for reg in entrada:
productos.append(reg)
return productos
##Abecedario usado para encriptar
abc='ABCDEFGHIJKLMNÑOPQRSTUVWXYZabcdefghijklmnñopqrstuvwxyz123456789'
def posABC(letra): ##Funcion que devuelve la posicion de una letra en el abecedario
for i in range(len(abc)):
if(letra==abc[i]):
return i
def cifrar(contra): ##Algoritmo de cifrado Cesar
clave=3
contraC=''
for i in range(len(contra)):
contraC=contraC+(abc[(posABC(contra[i])+clave)%len(abc)])
return contraC
def descifrar(contra): ##Descifrado cesar
clave=3
contraC=''
for i in range(len(contra)):
contraC=contraC+(abc[(posABC(contra[i])-clave)%len(abc)])
return contraC
def comprobar(clave,claveC): ##Comprobacion de cifrado
if(cifrar(clave)==claveC):
return True
else:
return False
def txtToArray(texto):
cadena=[]
j=0
for i in range(len(texto)):
if(texto[i]==',' or i+1==len(texto)):
sub=texto[j:i]
j=i+1
cadena.append(sub)
return cadena
|
987,567 | 3839390505f7ce50f55db0066b798ba3f6007f35 | """
Auto-generated File
Create Time: 2019-12-27 02:33:27
"""
from .ROMEnum_Autogen import *
from renix_py_api.renix_common_api import *
from renix_py_api import rom_manager
from .ROMObject_Autogen import ROMObject
@rom_manager.rom
class HttpResponse(ROMObject):
def __init__(self, Code=None, Reason=None, Mime=None, TimeZone=None, DateType=None, DateTime=None, DateIncr=None, DateIncrSec=None, DateIncrPage=None, ModifyType=None, ModifyTime=None, ModifyIncr=None, ModifyIncrSec=None, ModifyIncrPage=None, ExpireType=None, ExpireTime=None, ExpireIncr=None, ExpireIncrSec=None, ExpireIncrPage=None, **kwargs):
self._Code = Code # Code
self._Reason = Reason # Reason
self._Mime = Mime # MIME Type
self._TimeZone = TimeZone # Time Zone
self._DateType = DateType # Date Type
self._DateTime = DateTime # Date Date/Time
self._DateIncr = DateIncr # Increment
self._DateIncrSec = DateIncrSec # Date Incr By (sec)
self._DateIncrPage = DateIncrPage # Date Incr For(Page Ref.)
self._ModifyType = ModifyType # Modify Type
self._ModifyTime = ModifyTime # Modify Date/Time
self._ModifyIncr = ModifyIncr # Modify Increment
self._ModifyIncrSec = ModifyIncrSec # Modify Incr By (sec)
self._ModifyIncrPage = ModifyIncrPage # Modify Incr For(Page Ref.)
self._ExpireType = ExpireType # Expire Type
self._ExpireTime = ExpireTime # Expire Date/Time
self._ExpireIncr = ExpireIncr # Expire Increment
self._ExpireIncrSec = ExpireIncrSec # Expire Incr By (sec)
self._ExpireIncrPage = ExpireIncrPage # Expire Incr For(Page Ref.)
properties = kwargs.copy()
if Code is not None:
properties['Code'] = Code
if Reason is not None:
properties['Reason'] = Reason
if Mime is not None:
properties['Mime'] = Mime
if TimeZone is not None:
properties['TimeZone'] = TimeZone
if DateType is not None:
properties['DateType'] = DateType
if DateTime is not None:
properties['DateTime'] = DateTime
if DateIncr is not None:
properties['DateIncr'] = DateIncr
if DateIncrSec is not None:
properties['DateIncrSec'] = DateIncrSec
if DateIncrPage is not None:
properties['DateIncrPage'] = DateIncrPage
if ModifyType is not None:
properties['ModifyType'] = ModifyType
if ModifyTime is not None:
properties['ModifyTime'] = ModifyTime
if ModifyIncr is not None:
properties['ModifyIncr'] = ModifyIncr
if ModifyIncrSec is not None:
properties['ModifyIncrSec'] = ModifyIncrSec
if ModifyIncrPage is not None:
properties['ModifyIncrPage'] = ModifyIncrPage
if ExpireType is not None:
properties['ExpireType'] = ExpireType
if ExpireTime is not None:
properties['ExpireTime'] = ExpireTime
if ExpireIncr is not None:
properties['ExpireIncr'] = ExpireIncr
if ExpireIncrSec is not None:
properties['ExpireIncrSec'] = ExpireIncrSec
if ExpireIncrPage is not None:
properties['ExpireIncrPage'] = ExpireIncrPage
# call base class function, and it will send message to renix server to create a class.
super(HttpResponse, self).__init__(**properties)
def delete(self):
"""
call to delete itself
"""
return self._finalize()
def edit(self, Code=None, Reason=None, Mime=None, TimeZone=None, DateType=None, DateTime=None, DateIncr=None, DateIncrSec=None, DateIncrPage=None, ModifyType=None, ModifyTime=None, ModifyIncr=None, ModifyIncrSec=None, ModifyIncrPage=None, ExpireType=None, ExpireTime=None, ExpireIncr=None, ExpireIncrSec=None, ExpireIncrPage=None, **kwargs):
properties = kwargs.copy()
if Code is not None:
self._Code = Code
properties['Code'] = Code
if Reason is not None:
self._Reason = Reason
properties['Reason'] = Reason
if Mime is not None:
self._Mime = Mime
properties['Mime'] = Mime
if TimeZone is not None:
self._TimeZone = TimeZone
properties['TimeZone'] = TimeZone
if DateType is not None:
self._DateType = DateType
properties['DateType'] = DateType
if DateTime is not None:
self._DateTime = DateTime
properties['DateTime'] = DateTime
if DateIncr is not None:
self._DateIncr = DateIncr
properties['DateIncr'] = DateIncr
if DateIncrSec is not None:
self._DateIncrSec = DateIncrSec
properties['DateIncrSec'] = DateIncrSec
if DateIncrPage is not None:
self._DateIncrPage = DateIncrPage
properties['DateIncrPage'] = DateIncrPage
if ModifyType is not None:
self._ModifyType = ModifyType
properties['ModifyType'] = ModifyType
if ModifyTime is not None:
self._ModifyTime = ModifyTime
properties['ModifyTime'] = ModifyTime
if ModifyIncr is not None:
self._ModifyIncr = ModifyIncr
properties['ModifyIncr'] = ModifyIncr
if ModifyIncrSec is not None:
self._ModifyIncrSec = ModifyIncrSec
properties['ModifyIncrSec'] = ModifyIncrSec
if ModifyIncrPage is not None:
self._ModifyIncrPage = ModifyIncrPage
properties['ModifyIncrPage'] = ModifyIncrPage
if ExpireType is not None:
self._ExpireType = ExpireType
properties['ExpireType'] = ExpireType
if ExpireTime is not None:
self._ExpireTime = ExpireTime
properties['ExpireTime'] = ExpireTime
if ExpireIncr is not None:
self._ExpireIncr = ExpireIncr
properties['ExpireIncr'] = ExpireIncr
if ExpireIncrSec is not None:
self._ExpireIncrSec = ExpireIncrSec
properties['ExpireIncrSec'] = ExpireIncrSec
if ExpireIncrPage is not None:
self._ExpireIncrPage = ExpireIncrPage
properties['ExpireIncrPage'] = ExpireIncrPage
super(HttpResponse, self).edit(**properties)
@property
def Code(self):
"""
get the value of property _Code
"""
if self.force_auto_sync:
self.get('Code')
return self._Code
@property
def Reason(self):
"""
get the value of property _Reason
"""
if self.force_auto_sync:
self.get('Reason')
return self._Reason
@property
def Mime(self):
"""
get the value of property _Mime
"""
if self.force_auto_sync:
self.get('Mime')
return self._Mime
@property
def TimeZone(self):
"""
get the value of property _TimeZone
"""
if self.force_auto_sync:
self.get('TimeZone')
return self._TimeZone
@property
def DateType(self):
"""
get the value of property _DateType
"""
if self.force_auto_sync:
self.get('DateType')
return self._DateType
@property
def DateTime(self):
"""
get the value of property _DateTime
"""
if self.force_auto_sync:
self.get('DateTime')
return self._DateTime
@property
def DateIncr(self):
"""
get the value of property _DateIncr
"""
if self.force_auto_sync:
self.get('DateIncr')
return self._DateIncr
@property
def DateIncrSec(self):
"""
get the value of property _DateIncrSec
"""
if self.force_auto_sync:
self.get('DateIncrSec')
return self._DateIncrSec
@property
def DateIncrPage(self):
"""
get the value of property _DateIncrPage
"""
if self.force_auto_sync:
self.get('DateIncrPage')
return self._DateIncrPage
@property
def ModifyType(self):
"""
get the value of property _ModifyType
"""
if self.force_auto_sync:
self.get('ModifyType')
return self._ModifyType
@property
def ModifyTime(self):
"""
get the value of property _ModifyTime
"""
if self.force_auto_sync:
self.get('ModifyTime')
return self._ModifyTime
@property
def ModifyIncr(self):
"""
get the value of property _ModifyIncr
"""
if self.force_auto_sync:
self.get('ModifyIncr')
return self._ModifyIncr
@property
def ModifyIncrSec(self):
"""
get the value of property _ModifyIncrSec
"""
if self.force_auto_sync:
self.get('ModifyIncrSec')
return self._ModifyIncrSec
@property
def ModifyIncrPage(self):
"""
get the value of property _ModifyIncrPage
"""
if self.force_auto_sync:
self.get('ModifyIncrPage')
return self._ModifyIncrPage
@property
def ExpireType(self):
"""
get the value of property _ExpireType
"""
if self.force_auto_sync:
self.get('ExpireType')
return self._ExpireType
@property
def ExpireTime(self):
"""
get the value of property _ExpireTime
"""
if self.force_auto_sync:
self.get('ExpireTime')
return self._ExpireTime
@property
def ExpireIncr(self):
"""
get the value of property _ExpireIncr
"""
if self.force_auto_sync:
self.get('ExpireIncr')
return self._ExpireIncr
@property
def ExpireIncrSec(self):
"""
get the value of property _ExpireIncrSec
"""
if self.force_auto_sync:
self.get('ExpireIncrSec')
return self._ExpireIncrSec
@property
def ExpireIncrPage(self):
"""
get the value of property _ExpireIncrPage
"""
if self.force_auto_sync:
self.get('ExpireIncrPage')
return self._ExpireIncrPage
@Code.setter
def Code(self, value):
self._Code = value
self.edit(Code=value)
@Reason.setter
def Reason(self, value):
self._Reason = value
self.edit(Reason=value)
@Mime.setter
def Mime(self, value):
self._Mime = value
self.edit(Mime=value)
@TimeZone.setter
def TimeZone(self, value):
self._TimeZone = value
self.edit(TimeZone=value)
@DateType.setter
def DateType(self, value):
self._DateType = value
self.edit(DateType=value)
@DateTime.setter
def DateTime(self, value):
self._DateTime = value
self.edit(DateTime=value)
@DateIncr.setter
def DateIncr(self, value):
self._DateIncr = value
self.edit(DateIncr=value)
@DateIncrSec.setter
def DateIncrSec(self, value):
self._DateIncrSec = value
self.edit(DateIncrSec=value)
@DateIncrPage.setter
def DateIncrPage(self, value):
self._DateIncrPage = value
self.edit(DateIncrPage=value)
@ModifyType.setter
def ModifyType(self, value):
self._ModifyType = value
self.edit(ModifyType=value)
@ModifyTime.setter
def ModifyTime(self, value):
self._ModifyTime = value
self.edit(ModifyTime=value)
@ModifyIncr.setter
def ModifyIncr(self, value):
self._ModifyIncr = value
self.edit(ModifyIncr=value)
@ModifyIncrSec.setter
def ModifyIncrSec(self, value):
self._ModifyIncrSec = value
self.edit(ModifyIncrSec=value)
@ModifyIncrPage.setter
def ModifyIncrPage(self, value):
self._ModifyIncrPage = value
self.edit(ModifyIncrPage=value)
@ExpireType.setter
def ExpireType(self, value):
self._ExpireType = value
self.edit(ExpireType=value)
@ExpireTime.setter
def ExpireTime(self, value):
self._ExpireTime = value
self.edit(ExpireTime=value)
@ExpireIncr.setter
def ExpireIncr(self, value):
self._ExpireIncr = value
self.edit(ExpireIncr=value)
@ExpireIncrSec.setter
def ExpireIncrSec(self, value):
self._ExpireIncrSec = value
self.edit(ExpireIncrSec=value)
@ExpireIncrPage.setter
def ExpireIncrPage(self, value):
self._ExpireIncrPage = value
self.edit(ExpireIncrPage=value)
def _set_code_with_str(self, value):
self._Code = value
def _set_reason_with_str(self, value):
self._Reason = value
def _set_mime_with_str(self, value):
self._Mime = value
def _set_timezone_with_str(self, value):
self._TimeZone = value
def _set_datetype_with_str(self, value):
seperate = value.find(':')
exec('self._DateType = EnumDateType.%s' % value[:seperate])
def _set_datetime_with_str(self, value):
self._DateTime = value
def _set_dateincr_with_str(self, value):
self._DateIncr = (value == 'True')
def _set_dateincrsec_with_str(self, value):
try:
self._DateIncrSec = int(value)
except ValueError:
self._DateIncrSec = hex(int(value, 16))
def _set_dateincrpage_with_str(self, value):
try:
self._DateIncrPage = int(value)
except ValueError:
self._DateIncrPage = hex(int(value, 16))
def _set_modifytype_with_str(self, value):
seperate = value.find(':')
exec('self._ModifyType = EnumModifyType.%s' % value[:seperate])
def _set_modifytime_with_str(self, value):
self._ModifyTime = value
def _set_modifyincr_with_str(self, value):
self._ModifyIncr = (value == 'True')
def _set_modifyincrsec_with_str(self, value):
try:
self._ModifyIncrSec = int(value)
except ValueError:
self._ModifyIncrSec = hex(int(value, 16))
def _set_modifyincrpage_with_str(self, value):
try:
self._ModifyIncrPage = int(value)
except ValueError:
self._ModifyIncrPage = hex(int(value, 16))
def _set_expiretype_with_str(self, value):
seperate = value.find(':')
exec('self._ExpireType = EnumExpireType.%s' % value[:seperate])
def _set_expiretime_with_str(self, value):
self._ExpireTime = value
def _set_expireincr_with_str(self, value):
self._ExpireIncr = (value == 'True')
def _set_expireincrsec_with_str(self, value):
try:
self._ExpireIncrSec = int(value)
except ValueError:
self._ExpireIncrSec = hex(int(value, 16))
def _set_expireincrpage_with_str(self, value):
try:
self._ExpireIncrPage = int(value)
except ValueError:
self._ExpireIncrPage = hex(int(value, 16))
|
987,568 | 8558e45bb0beebbc56463f07060cf6c229a8cd8b | def rotate_left(s, n):
return s[n:] + s[:n]
def rotate_right(s, n):
return s[-n:] + s[:-n]
if __name__ == '__main__':
assert rotate_left(['a', 'b', 'c', 'd'], 2) == ['c', 'd', 'a', 'b']
assert rotate_left(['a', 'b', 'c', 'd'], 3) == ['d', 'a', 'b', 'c'] |
987,569 | a78f1d9bbaa2393f009ea0741391f52ba9f68a6d | # coding: utf-8
from django.shortcuts import render
from django.http import HttpResponse
from .forms import AddForm
# Create your views here.
def index(request):
if request.method == 'POST':
form = AddForm(request.POST)
if form.is_valid():
a = form.cleaned_data['a']
b = form.cleaned_data['b']
return HttpResponse(str(int(a) + int(b)))
else:
form = AddForm()
return render(request, 'index.html', {'form': form})
def home(request):
TutorialList = ["HTML", "CSS", "jQuery", "Python", "Django"]
return render(request, 'home.html', {'TutorialList': TutorialList})
def add(request):
a = request.GET.get('a', 0)
b = request.GET.get('b', 0)
a = int(a)
b = int(b)
c = a + b
return HttpResponse(str(c))
|
987,570 | 47be75b5cbd9b3131f6a1816ba8cef0c4b8946ea | import os
from rest_framework import serializers
from gestion.models.category import Category
from gestion.serializers.subCategorySerializer import SubCategorySerializer
class CategorySerializer(serializers.ModelSerializer):
subCategories = SubCategorySerializer(many=True, required=False)
class Meta:
model = Category
fields = ("__all__")
def create(self, validated_data):
cat = Category.objects.create(**validated_data)
return cat
def update(self, instance, validated_data):
image = validated_data.get("image", None)
if not image:
if instance.image:
os.remove(instance.image.path)
instance.image = None
return super().update(instance, validated_data)
class CategorySerializerSimplified(serializers.ModelSerializer):
class Meta:
model = Category
fields = (
"id",
"title",
"image",
) |
987,571 | 541f17d1fc1be63a45b756156a93be43c1190f83 | from datetime import date
corrente = date.today().year
nascimento = int(input('Ano de nascimento: '))
idade = corrente - nascimento
print('Quem nasceu em {} tem {} anos em {}.'.format(nascimento, idade, corrente))
if idade > 18:
saldo = idade - 18
print('Você já deveria ter se alistado há {} anos, pois seu alistamento foi em {}.'
.format(saldo, corrente - saldo))
elif idade < 18:
saldo = 18 - idade
print('Ainda faltam {} anos para o alistamento, que será em {}.'
.format(saldo, corrente + saldo))
else:
print('Você deve se alistar IMEDIATAMENTE.')
|
987,572 | d918b70397a31c5defe1f758e47b79737218c679 | # -*- coding: utf-8 -*-
"""
Created on Tue Mar 27 19:23:41 2018
@author: alber
"""
import os
import glob
import pandas as pd
import re
import numpy as np
import pickle
from nltk.corpus import stopwords
from nltk.stem import SnowballStemmer
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
from sklearn.utils import shuffle
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import confusion_matrix, precision_score, accuracy_score, recall_score
from sklearn import preprocessing
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM
from keras.layers.convolutional import Conv1D
from keras.layers.convolutional import MaxPooling1D
from keras.layers.embeddings import Embedding
from keras.preprocessing import sequence
from keras.models import load_model
from keras.utils.np_utils import to_categorical
from data_preprocessing import word_vector, corpus_generation, obtain_train_corpus, word2idx_creation, word2idx_conversion
from other_preprocessing import word_tf_idf
global stemmer
stemmer = SnowballStemmer("english")
def rf_topic_train(df, dominio):
df_final = obtain_train_corpus()
# Puedo separarlo en distintos df segun el dominio
df_domain_total = [{category:df_domain} for category, df_domain in df_final.groupby('category')]
if dominio == "entidad":
# Tambien puedo separar a nivel de dominio y entity
df_domain_total_entity = {}
for df in df_domain_total:
category = list(df.keys())[0]
df = list(df.values())[0]
df_entities = [{entity:df_entity} for entity, df_entity in df.groupby('entity_name')]
df_domain_total_entity.update({category:df_entities})
vocabulario = corpus_generation(df_domain_total_entity, "entidad")
entidades = list(vocabulario.keys())
categorias = list(df_domain_total_entity.keys())
i = 1
total = len(entidades)
for categoria in categorias:
for df in df_domain_total_entity[categoria]:
print("Entrendando modelo " + str(i) + "/" + str(total))
entidad = list(df.keys())[0]
df = list(df.values())[0]
corpus = vocabulario[entidad][0]
print("Entidad: ", entidad)
X = list(df['text'])
y = list(df['topic'])
# Encoding a numerico
labelencoder_X = LabelEncoder()
y=labelencoder_X.fit_transform(y) # Codifico en valores numericos las clases que hay
y_original = y
if max(y_original) != 1:
# Encoding a one-hot
y = y.reshape(-1, 1)
onehotencoder = OneHotEncoder()
y = onehotencoder.fit_transform(y).toarray()
# Remove dummy variable trap
y = y[:, 1:] # Elimino una de las columnas por ser linearmente dependiente de las demas
# Encoding numerico de las palabras de los vectores de entrada segun el vocabulario
Xt = word_vector(X, corpus)
X = Xt
# Train/validation split
X_train, X_val, y_train, y_val = train_test_split(X, y, test_size = 0.1, random_state = 0)
# Por ser un RF no hace falta hacer feature scaling
"""from sklearn.preprocessing import StandardScaler
sc_X = StandardScaler()
X_train = sc_X.fit_transform(X_train)
X_test = sc_X.transform(X_test)
sc_y = StandardScaler()
y_train = sc_y.fit_transform(y_train)"""
# Fitting Random Forest Classificator to the Training set
classifier = RandomForestClassifier(n_estimators = 200, criterion = 'entropy', random_state = 0)
classifier.fit(X_train, y_train)
print("Entrenamiento terminado")
# Predicting the Test set results
y_pred = classifier.predict(X_val)
if max(y_original) != 1:
# Formatting results
y_val_original = np.asarray(y_val)
y_val = pd.DataFrame(y_val)
y_pred = pd.DataFrame(y_pred)
y_val = [np.argmax(np.asarray(x)) for x in y_val.values.tolist()]
y_pred = [np.argmax(np.asarray(x)) for x in y_pred.values.tolist()]
# Making the Confusion Matrix
cm = confusion_matrix(y_val, y_pred)
# Accuracy
accuracy = accuracy_score(y_val, y_pred)
# Precision
average_precision = precision_score(y_val, y_pred, average = "macro")
# Recall
recall = recall_score(y_val, y_pred, average='macro')
print("Modelo "+str(i)+" resultados")
print("accuracy ", accuracy, " precision ", average_precision, " recall ", recall) # Se ve que los resultados son muy malos
# Eliminio los backslashes de las palabras que los tengan
if '/' in entidad:
entidad= entidad.replace('/', '_')
# Persistencia del modelo entrenado
with open(os.path.abspath('') + r'/generated_data/model_rf_topic_detection_'+str(entidad)+'.p', 'wb') as handle:
pickle.dump(vocabulario, handle)
print("Modelo "+ str(i)+" entrenado y guardado")
i += 1
def rf_tf_idf_train(df, dominio):
"""
Comparo el MAE del tf-idf de mis clases y el de los datos a clasificar y asigno la
clase que mas se acerque.
Este modelo como tal no necesita entrenamiento; no alamcena nada mas de lo que ya hay almacenado en memoria
"""
df_final = obtain_train_corpus()
# Puedo separarlo en distintos df segun el dominio
df_domain_total = [{category:df_domain} for category, df_domain in df_final.groupby('category')]
if dominio == "entidad":
# Tambien puedo separar a nivel de dominio y entity
df_domain_total_entity = {}
for df in df_domain_total:
category = list(df.keys())[0]
df = list(df.values())[0]
df_entities = [{entity:df_entity} for entity, df_entity in df.groupby('entity_name')]
df_domain_total_entity.update({category:df_entities})
vocabulario = corpus_generation(df_domain_total_entity, "entidad")
entidades = list(vocabulario.keys())
categorias = list(df_domain_total_entity.keys())
i = 1
total = len(entidades)
for categoria in categorias:
for df in df_domain_total_entity[categoria]:
print("Entrendando modelo " + str(i) + "/" + str(total))
entidad = list(df.keys())[0]
df = list(df.values())[0]
df = df.reset_index()
X = list(df['text'])
print("Entidad: ", entidad)
words, words_tot, median, df_pattern, df_suma = word_tf_idf(X)
df_classificacion = df_suma.join(df, how="outer") # Join por los index
X_tf_idf = list(df_classificacion['tf-idf'])
y_tf_idf = list(df_classificacion['topic'])
# Encoding a numerico
labelencoder_X = LabelEncoder()
y_tf_idf=labelencoder_X.fit_transform(y_tf_idf) # Codifico en valores numericos las clases que hay
# Train/validation split
X_train, X_val, y_train, y_val = train_test_split(X_tf_idf, y_tf_idf,
test_size = 0.1, random_state = 0)
# Menor distancia cuadratica de TF
y_pred = []
for x_ref in X_val:
ref = 999
i = 0
for x in X_train:
diff = (x_ref - x)**2
diff = np.sqrt(diff)
print(diff)
if diff < ref:
i = X_train.index(x)
ref = diff
y_pred.append(y_train[i]) # Identifico con la clase de menor distancia cuadratica TF-IDF
# Making the Confusion Matrix
cm = confusion_matrix(y_val, y_pred)
# Accuracy
accuracy = accuracy_score(y_val, y_pred)
# Precision
average_precision = precision_score(y_val, y_pred, average = "macro")
# Recall
recall = recall_score(y_val, y_pred, average='macro')
print("Modelo "+str(i)+" resultados")
print("accuracy ", accuracy, " precision ", average_precision, " recall ", recall) # Se ve que los resultados son muy malos
|
987,573 | 06a900a0d910c4a30645f94f7b87c74cd2869b2d | class Vehicle:
def __init__(self, make, model, year, color):
self.make = make
self.model = model
self.year = year
self.color = color
def __str__(self):
return "Make: %s, Model: %s, Year: %d, Color: %s" % (self.make, self.model, self.year, self.color)
def wheels(self, wheels):
return "Wheels: %s" % wheels
# Make Model, Year
# Instantiate the class
honda = Vehicle("Honda", "Civic", 1998, "Silver")
print(honda)
print(honda.wheels(4))
|
987,574 | abc2221e62410c0a319dace738e08150202c5bfd | from keras.models import Sequential
from keras.layers import Dense, Dropout
from sklearn.feature_extraction import DictVectorizer
import numpy
import pandas as pd
from pandas import DataFrame
from sklearn.utils import shuffle
import numpy as np
from functools import *
from itertools import chain
from keras import optimizers
# fix random seed for reproducibility
numpy.random.seed(0)
from sklearn import preprocessing
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
from keras import optimizers
from keras.callbacks import EarlyStopping, ReduceLROnPlateau
from sklearn.metrics import roc_auc_score, confusion_matrix, roc_curve, recall_score, auc
earlystop = EarlyStopping(monitor='val_acc',
mode='auto'
, patience=5
)
reduce_lr = ReduceLROnPlateau(monitor='val_loss', factor=0.2,
patience=5, min_lr=0.001)
callbacks_list = [
earlystop
# ,
# reduce_lr
]
scaler = None
def make_prediction(df, model):
try:
loaded_model = model
print('inside make prediction')
### now predict label for the data ###
X_test = df.value
X_test_s = scaler.transform(X_test)
p = loaded_model.predict(X_test_s)
return p
except:
print('Error in making prediction')
return None
def make_model(df):
key = 'is_female'
df[key] = df[key].astype(str)
y = df['is_female']
df = df.drop('is_female', axis = 1)
# create model
model = Sequential()
model.add(Dense(500, input_dim=df.shape[1], activation='relu'))
model.add(Dense(200, activation='relu'))
model.add(Dropout(0.1))
model.add(Dense(200, activation='relu'))
model.add(Dropout(0.2))
model.add(Dense(200, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(200, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(100, activation='relu'))
model.add(Dropout(0.2))
model.add(Dense(100, activation='relu'))
model.add(Dropout(0.2))
model.add(Dense(80, activation='relu'))
model.add(Dense(1, activation='sigmoid'))
# Compile model
# opt = optimizers.Adam(lr=0.005, decay=0.2)
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
X_train = df.values
scaler = StandardScaler().fit(X_train)
X_train_s = scaler.transform(X_train)
X_train, X_test, y_train, y_test = train_test_split(X_train_s, y, test_size=0.15, random_state=0)
# model.fit(X_train, y_train, epochs=1)
model.fit(X_train, y_train, epochs=200,
batch_size=128*2,
validation_split=0.10,
verbose=2,
shuffle=True
)
scores = model.evaluate(X_test, y_test)
print("\n%s: %.2f%%" % (model.metrics_names[1], scores[1] * 100))
y_pred = model.predict(X_test)
print "PRED "
print y_pred[10:25]
# y_rounded = []
# for x in y_pred:
# val = x[0]
# if val <= 0.9:
# y_rounded.append('0')
# else:
# y_rounded.append('1')
#
# print "TEST "
# print y_test[10:25].values
#
# # y_rounded = [round(x[0]) for x in y_pred]
# # print "Rounded "
# # print y_rounded[10:25]
#
# print confusion_matrix(y_test, y_rounded)
# try:
# model_recall_score = recall_score(y_test, y_rounded, average='macro')
# auc_score = roc_auc_score(y_test, y_rounded)
# print("recall score", model_recall_score, " auc score ", auc_score)
# except:
# print("Error calculating recall score")
model.save('_select_25_02.h5')
return model
# _ big_4.csv is gold, keep it. do not replace/ rewrite
def get_data(name):
file = name + '_big_4.csv'
df = pd.read_csv(file)
print(name + ' file read ', df.shape)
df.fillna('NA', inplace=True)
# print('To delete = ',to_delete)
return df
if __name__ == "__main__":
df = get_data('train')
model = make_model(df)
print("df shape ", df.shape)
df_t = get_data('test')
label = make_prediction(df_t, model)
# print("label=", label.tolist())
scores = list(chain.from_iterable(label.tolist()))
print("df test shape ", df_t.shape)
output = []
for i in scores:
if i <= 0.5:
output.append(0)
else:
output.append(1)
index = range(0, len(output))
print(output[:20])
print(len(index))
df = DataFrame({'test_id': index, 'is_female': output})
print(df.head())
df.to_csv(path_or_buf='submission_4_keras_adam_save_it_feb_25.csv', index=False)
|
987,575 | a0675277abff7cd9b34878a07001a44832d884c0 | """
pyFF is a SAML metadata aggregator.
"""
import sys
import getopt
import pkg_resources
from pyff.mdrepo import MDRepository
from pyff.pipes import plumbing
import traceback
import logging
__version__ = pkg_resources.require("pyFF")[0].version
def main():
"""
The main entrypoint for the pyFF cmdline tool.
"""
try:
opts, args = getopt.getopt(sys.argv[1:], 'h', ['help', 'loglevel=', 'logfile=', 'version'])
except getopt.error, msg:
print msg
print 'for help use --help'
sys.exit(2)
md = MDRepository()
loglevel = logging.WARN
logfile = None
for o, a in opts:
if o in ('-h', '--help'):
print __doc__
sys.exit(0)
elif o in '--loglevel':
loglevel = getattr(logging, a.upper(), None)
if not isinstance(loglevel, int):
raise ValueError('Invalid log level: %s' % loglevel)
elif o in '--logfile':
logfile = a
elif o in '--version':
print "pyff version %s" % __version__
sys.exit(0)
else:
raise ValueError("Unknown option '%s'" % o)
log_args = {'level': loglevel}
if logfile is not None:
log_args['filename'] = logfile
logging.basicConfig(**log_args)
try:
for p in args:
plumbing(p).process(md, state={'batch': True, 'stats': {}})
sys.exit(0)
except Exception, ex:
if logging.getLogger().isEnabledFor(logging.DEBUG):
print "-" * 64
traceback.print_exc()
print "-" * 64
logging.error(ex)
sys.exit(-1)
if __name__ == "__main__":
main()
|
987,576 | c159cd27b6a49df4cbc0f11ab1e3d7507b37a19b | #!/usr/bin/python
import docker
import sys
def runContainerById2(name,ip):
client=docker.from_env()
print(str(client))
container=client.containers.run(name,detach=True)
# myNet=client.networks.get('8cc234f12ebe')
# myNet.connect(container.short_id,ipv4_address=ip)
# print('ceshi')
def restartContainerByid(container_id):
client=docker.from_env()
container=container=client.containers.get(container_id)
container.restart()
if __name__ == '__main__':
restartContainerByid('85f77e09d571')
|
987,577 | b8483392df4d0b1b24a71f5037160b2f5e6dedaa | import io
import os
import re
import sys
from setuptools import find_packages, setup
here = os.path.abspath(os.path.dirname(__file__))
def read(*parts):
with io.open(os.path.join(here, *parts), encoding="utf-8") as fp:
return fp.read()
def find_version(*file_paths):
version_file = read(*file_paths)
version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]", version_file, re.M)
if version_match:
return version_match.group(1)
raise RuntimeError("Unable to find version string.")
entry_point_name = "_pip_cli:main"
script_names = [
"pip",
"pip%s" % sys.version_info[:1],
"pip%s.%s" % sys.version_info[:2],
]
long_description = read("README.md")
setup(
name="pip-cli",
version=find_version("src", "_pip_cli.py"),
license="MIT",
url="https://github.com/pradyunsg/pip-cli",
author="Pradyun Gedam",
author_email="pradyunsg@gmail.com",
description="Command line wrappers for pip.",
long_description=long_description,
long_description_content_type="text/markdown",
keywords=["pip", "cli", "command-line"],
classifiers=[
"Development Status :: 5 - Production/Stable",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Topic :: Software Development :: Build Tools",
"Programming Language :: Python",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: Implementation :: CPython",
"Programming Language :: Python :: Implementation :: PyPy",
],
package_dir={"": "src"},
py_modules=["_pip_cli"],
entry_points={
"console_scripts": [
"{}={}".format(script, entry_point_name) for script in script_names
]
},
python_requires=">=2.7,!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*",
install_requires=["pip"],
)
|
987,578 | 5ae6d17993ff63b8514dbfa9e7a70b7ca1c0e642 | n= int(input('Enter the number you would like to know the factors for...'))
#n = int(input())
a=0
for z in range (0, n):
a=a+1
if n % a == 0:
c= int(n / a)
print(a, 'times', c, 'equals', n)
continue
else:
continue
# trying for prime factorization
x= a
y= c
while a % 2 == 0:
a= a/2
continue
if a != x:
print(a)
else:
print('no prime factors')
while c %2 == 0:
c= c/2
continue
if y != c:
print(c)
else:
print('no prime factors') |
987,579 | f69583d1c3fc06038aa1a3852fd7599e8c5597c7 | #!/usr/bin/env python3
#
# Author: Coleman Kane <ckane@colemankane.org>
# This module will run "exiftool" against an artifact and will
# write results into a file named exiftool_output.csv
#
import sqlite3
import os
from subprocess import Popen, DEVNULL, PIPE
from ztasks.base_zooqdb_task import base_zooqdb_task
class exifdata(base_zooqdb_task):
def __init__(self, objid, dir):
super(exifdata, self).__init__(objid, dir)
def dowork(self):
dbconn = sqlite3.connect('{dir}/samples.sqlite'.format(dir=self.dirname()))
cur = dbconn.cursor()
cur.execute('SELECT `mwpath` from `samples` WHERE `mwid`=?', (self.objid(),))
res = cur.fetchall()
dbconn.close()
if res:
mwpath = res[0][0]
mwdir = os.path.dirname(mwpath)
outfile = open(mwdir+'/exiftool.json', 'wb')
proc = Popen(['exiftool', '-j', mwpath],
stderr=DEVNULL, stdout=outfile, stdin=DEVNULL)
proc.wait()
|
987,580 | 7a0fbf68746211e6b1de51d01566a6cc44d058f5 | # Python Program for recursive binary search.
# Returns index of x in arr if present, else -1
def binarySearch(arr, l, r, x):
# Check base case
if r >= l:
mid = l + (r - l) // 2
# If element is present at the middle itself
if arr[mid] == x:
return mid
# If element is smaller than mid, then it
# can only be present in left subarray
elif arr[mid] > x:
return binarySearch(arr, l, mid - 1, x)
# Else the element can only be present
# in right subarray
else:
return binarySearch(arr, mid + 1, r, x)
else:
# Element is not present in the array
return -1
def bubblesort(A):
for i in range(len(A) - 1):
for j in range(0, len(A) - 1 - i):
if A[j] > A[j+1]:
A = swap(A[j], A[j+1], j, A)
return A
def swap(a, b, i, A):
A[i] = b
A[i+1] = a
return A
def mergeSort(alist):
print("Splitting ",alist)
if len(alist)>1:
mid = len(alist)//2
lefthalf = alist[:mid]
righthalf = alist[mid:]
mergeSort(lefthalf)
mergeSort(righthalf)
i=0
j=0
k=0
while i < len(lefthalf) and j < len(righthalf):
if lefthalf[i] < righthalf[j]:
alist[k]=lefthalf[i]
i=i+1
else:
alist[k]=righthalf[j]
j=j+1
k=k+1
while i < len(lefthalf):
alist[k]=lefthalf[i]
i=i+1
k=k+1
while j < len(righthalf):
alist[k]=righthalf[j]
j=j+1
k=k+1
print("Merging ",alist)
if __name__ == "__main__":
A = range(101)
search_val = 60
idx = binarySearch(A, 0, (len(A) - 1), search_val)
print(idx)
A = [5, 6]
A = bubblesort(A)
print(A)
alist = [54,26,93,17,77,31,44,55,20]
mergeSort(alist)
print(alist)
|
987,581 | 72856e26e8211d05c3a9ffd9eb80c469b8ec9eef | ,intensity,wavelength
0,1501.0,339.0737609863281
1,1501.0,339.52578573642876
2,1498.0,339.9778577243427
3,1501.0,340.42997693034937
4,1502.0,340.8821433347282
5,1503.0,341.3343569177587
6,1495.0,341.78661765972026
7,1499.0,342.2389255408923
8,1502.0,342.6912805415543
9,1500.0,343.14368264198566
10,1501.0,343.5961318224658
11,1496.0,344.0486280632742
12,1500.0,344.5011713446903
13,1498.0,344.9537616469935
14,1505.0,345.4063989504632
15,1501.0,345.85908323537893
16,1504.0,346.31181448202005
17,1499.0,346.76459267066605
18,1499.0,347.21741778159634
19,1504.0,347.67028979509035
20,1500.0,348.1232086914275
21,1498.0,348.5761744508873
22,1505.0,349.0291870537492
23,1503.0,349.4822464802925
24,1501.0,349.9353527107967
25,1497.0,350.3885057255412
26,1505.0,350.8417055048056
27,1504.0,351.29495202886915
28,1501.0,351.7482452780114
29,1498.0,352.20158523251166
30,1499.0,352.65497187264947
31,1499.0,353.1084051787043
32,1503.0,353.5618851309555
33,1502.0,354.0154117096825
34,1501.0,354.46898489516485
35,1501.0,354.92260466768187
36,1502.0,355.37627100751297
37,1504.0,355.82998389493775
38,1502.0,356.2837433102355
39,1503.0,356.7375492336857
40,1497.0,357.1914016455678
41,1498.0,357.64530052616124
42,1498.0,358.0992458557454
43,1500.0,358.55323761459977
44,1498.0,359.0072757830038
45,1501.0,359.46136034123685
46,1501.0,359.91549126957847
47,1496.0,360.36966854830797
48,1505.0,360.8238921577049
49,1503.0,361.27816207804864
50,1497.0,361.7324782896186
51,1495.0,362.18684077269427
52,1501.0,362.641249507555
53,1499.0,363.0957044744804
54,1500.0,363.55020565374974
55,1499.0,364.0047530256425
56,1500.0,364.45934657043813
57,1503.0,364.91398626841607
58,1503.0,365.36867209985576
59,1502.0,365.8234040450366
60,1499.0,366.2781820842381
61,1506.0,366.7330061977396
62,1502.0,367.18787636582056
63,1502.0,367.6427925687605
64,1499.0,368.0977547868388
65,1503.0,368.55276300033483
66,1502.0,369.00781718952817
67,1501.0,369.4629173346981
68,1506.0,369.91806341612414
69,1501.0,370.37325541408575
70,1500.0,370.82849330886233
71,1501.0,371.28377708073333
72,1502.0,371.73910670997816
73,1501.0,372.19448217687625
74,1501.0,372.6499034617071
75,1501.0,373.1053705447501
76,1499.0,373.5608834062847
77,1504.0,374.01644202659025
78,1503.0,374.4720463859463
79,1504.0,374.9276964646323
80,1500.0,375.3833922429276
81,1497.0,375.8391337011117
82,1501.0,376.2949208194639
83,1502.0,376.75075357826387
84,1502.0,377.2066319577908
85,1496.0,377.6625559383244
86,1501.0,378.11852550014385
87,1502.0,378.57454062352866
88,1503.0,379.03060128875836
89,1504.0,379.4867074761123
90,1500.0,379.94285916586995
91,1501.0,380.3990563383107
92,1500.0,380.85529897371407
93,1504.0,381.31158705235936
94,1498.0,381.76792055452614
95,1495.0,382.22429946049385
96,1501.0,382.6807237505418
97,1502.0,383.1371934049495
98,1497.0,383.59370840399646
99,1501.0,384.05026872796196
100,1501.0,384.5068743571255
101,1502.0,384.9635252717666
102,1498.0,385.42022145216464
103,1501.0,385.87696287859904
104,1503.0,386.3337495313492
105,1501.0,386.7905813906946
106,1498.0,387.2474584369147
107,1503.0,387.70438065028895
108,1498.0,388.1613480110967
109,1504.0,388.61836049961744
110,1503.0,389.0754180961306
111,1499.0,389.5325207809156
112,1503.0,389.9896685342519
113,1500.0,390.4468613364189
114,1502.0,390.90409916769613
115,1498.0,391.3613820083629
116,1499.0,391.81870983869874
117,1499.0,392.2760826389831
118,1499.0,392.7335003894953
119,1500.0,393.19096307051484
120,1503.0,393.6484706623212
121,1498.0,394.1060231451938
122,1498.0,394.56362049941197
123,1501.0,395.02126270525525
124,1499.0,395.4789497430031
125,1501.0,395.93668159293486
126,1504.0,396.39445823533003
127,1502.0,396.85227965046806
128,1502.0,397.31014581862837
129,1501.0,397.7680567200904
130,1495.0,398.22601233513353
131,1502.0,398.68401264403724
132,1502.0,399.14205762708093
133,1501.0,399.60014726454415
134,1499.0,400.0582815367062
135,1501.0,400.5164604238466
136,1500.0,400.97468390624476
137,1502.0,401.4329519641801
138,1499.0,401.8912645779321
139,1507.0,402.3496217277801
140,1499.0,402.8080233940037
141,1498.0,403.2664695568822
142,1505.0,403.72496019669506
143,1500.0,404.18349529372176
144,1499.0,404.6420748282417
145,1503.0,405.1006987805343
146,1502.0,405.559367130879
147,1497.0,406.0180798595553
148,1500.0,406.4768369468426
149,1499.0,406.9356383730203
150,1499.0,407.3944841183679
151,1500.0,407.8533741631648
152,1503.0,408.3123084876904
153,1502.0,408.7712870722242
154,1501.0,409.23030989704563
155,1497.0,409.6893769424341
156,1499.0,410.14848818866903
157,1501.0,410.60764361602986
158,1503.0,411.06684320479604
159,1502.0,411.52608693524706
160,1501.0,411.9853747876623
161,1500.0,412.44470674232116
162,1501.0,412.9040827795032
163,1500.0,413.3635028794877
164,1503.0,413.82296702255417
165,1501.0,414.2824751889821
166,1501.0,414.74202735905084
167,1500.0,415.20162351303986
168,1500.0,415.6612636312286
169,1501.0,416.12094769389654
170,1500.0,416.580675681323
171,1501.0,417.0404475737875
172,1498.0,417.5002633515695
173,1499.0,417.96012299494834
174,1504.0,418.42002648420356
175,1497.0,418.8799737996145
176,1500.0,419.3399649214607
177,1500.0,419.79999983002153
178,1506.0,420.2600785055764
179,1504.0,420.72020092840484
180,1502.0,421.18036707878616
181,1500.0,421.64057693699993
182,1501.0,422.1008304833255
183,1500.0,422.56112769804236
184,1502.0,423.02146856142986
185,1501.0,423.4818530537675
186,1504.0,423.94228115533474
187,1503.0,424.402752846411
188,1501.0,424.86326810727564
189,1500.0,425.32382691820817
190,1502.0,425.784429259488
191,1499.0,426.2450751113946
192,1500.0,426.7057644542074
193,1503.0,427.1664972682058
194,1500.0,427.62727353366927
195,1503.0,428.0880932308772
196,1498.0,428.54895634010904
197,1506.0,429.0098628416443
198,1501.0,429.47081271576235
199,1500.0,429.93180594274264
200,1500.0,430.3928425028646
201,1499.0,430.85392237640764
202,1497.0,431.31504554365125
203,1503.0,431.77621198487486
204,1500.0,432.2374216803579
205,1504.0,432.6986746103797
206,1499.0,433.1599707552199
207,1502.0,433.62131009515775
208,1498.0,434.0826926104728
209,1499.0,434.54411828144447
210,1501.0,435.0055870883521
211,1500.0,435.4670990114753
212,1496.0,435.9286540310933
213,1503.0,436.3902521274857
214,1499.0,436.8518932809319
215,1503.0,437.31357747171126
216,1498.0,437.7753046801033
217,1503.0,438.23707488638746
218,1499.0,438.6988880708431
219,1500.0,439.1607442137497
220,1502.0,439.62264329538675
221,1505.0,440.08458529603354
222,1501.0,440.54657019596965
223,1498.0,441.0085979754745
224,1499.0,441.47066861482745
225,1504.0,441.932782094308
226,1505.0,442.39493839419555
227,1500.0,442.8571374947695
228,1500.0,443.31937937630937
229,1499.0,443.7816640190946
230,1501.0,444.24399140340455
231,1499.0,444.70636150951873
232,1498.0,445.1687743177165
233,1500.0,445.63122980827734
234,1499.0,446.0937279614807
235,1503.0,446.556268757606
236,1498.0,447.0188521769327
237,1500.0,447.48147819974014
238,1501.0,447.94414680630786
239,1504.0,448.40685797691526
240,1499.0,448.8696116918418
241,1500.0,449.33240793136684
242,1502.0,449.79524667576993
243,1503.0,450.2581279053304
244,1503.0,450.72105160032777
245,1498.0,451.1840177410415
246,1501.0,451.6470263077509
247,1502.0,452.1100772807354
248,1500.0,452.5731706402746
249,1502.0,453.03630636664786
250,1502.0,453.49948444013455
251,1500.0,453.96270484101416
252,1503.0,454.42596754956617
253,1498.0,454.8892725460699
254,1504.0,455.35261981080487
255,1500.0,455.8160093240505
256,1501.0,456.2794410660863
257,1502.0,456.7429150171916
258,1499.0,457.20643115764585
259,1499.0,457.6699894677285
260,1497.0,458.13358992771896
261,1501.0,458.59723251789677
262,1500.0,459.06091721854125
263,1498.0,459.5246440099319
264,1499.0,459.98841287234814
265,1499.0,460.4522237860694
266,1504.0,460.9160767313751
267,1501.0,461.3799716885447
268,1506.0,461.8439086378577
269,1500.0,462.3078875595934
270,1500.0,462.7719084340313
271,1499.0,463.23597124145084
272,1502.0,463.70007596213145
273,1502.0,464.1642225763526
274,1499.0,464.6284110643937
275,1501.0,465.09264140653414
276,1502.0,465.5569135830534
277,1499.0,466.021227574231
278,1503.0,466.48558336034625
279,1501.0,466.9499809216786
280,1504.0,467.41442023850755
281,1497.0,467.87890129111247
282,1499.0,468.3434240597729
283,1499.0,468.8079885247681
284,1503.0,469.2725946663777
285,1502.0,469.737242464881
286,1503.0,470.20193190055744
287,1501.0,470.66666295368657
288,1500.0,471.13143560454773
289,1507.0,471.59624983342036
290,1502.0,472.061105620584
291,1500.0,472.52600294631793
292,1502.0,472.9909417909016
293,1501.0,473.45592213461464
294,1500.0,473.92094395773626
295,1498.0,474.386007240546
296,1499.0,474.8511119633233
297,1503.0,475.3162581063476
298,1497.0,475.7814456498983
299,1498.0,476.2466745742548
300,1503.0,476.7119448596967
301,1501.0,477.1772564865032
302,1498.0,477.64260943495395
303,1498.0,478.10800368532824
304,1498.0,478.5734392179056
305,1502.0,479.03891601296544
306,1498.0,479.50443405078715
307,1498.0,479.9699933116502
308,1498.0,480.43559377583404
309,1501.0,480.9012354236181
310,1501.0,481.36691823528184
311,1503.0,481.83264219110464
312,1502.0,482.29840727136593
313,1501.0,482.7642134563452
314,1506.0,483.2300607263219
315,1499.0,483.6959490615754
316,1501.0,484.16187844238516
317,1502.0,484.6278488490306
318,1501.0,485.0938602617912
319,1503.0,485.5599126609464
320,1500.0,486.0260060267756
321,1497.0,486.4921403395582
322,1504.0,486.95831557957376
323,1500.0,487.42453172710157
324,1501.0,487.89078876242115
325,1498.0,488.35708666581195
326,1499.0,488.8234254175534
327,1500.0,489.2898049979249
328,1500.0,489.75622538720586
329,1502.0,490.22268656567576
330,1503.0,490.68918851361406
331,1500.0,491.1557312113002
332,1498.0,491.62231463901355
333,1500.0,492.08893877703355
334,1499.0,492.5556036056397
335,1500.0,493.0223091051114
336,1500.0,493.4890552557281
337,1500.0,493.95584203776923
338,1503.0,494.4226694315142
339,1499.0,494.8895374172425
340,1501.0,495.35644597523344
341,1500.0,495.82339508576666
342,1500.0,496.29038472912146
343,1504.0,496.75741488557725
344,1504.0,497.2244855354136
345,1496.0,497.6915966589098
346,1503.0,498.1587482363454
347,1496.0,498.6259402479997
348,1504.0,499.09317267415236
349,1502.0,499.56044549508255
350,1500.0,500.0277586910699
351,1494.0,500.4951122423938
352,1501.0,500.96250612933363
353,1497.0,501.4299403321689
354,1499.0,501.897414831179
355,1503.0,502.36492960664333
356,1500.0,502.8324846388414
357,1500.0,503.3000799080526
358,1503.0,503.76771539455643
359,1496.0,504.2353910786323
360,1504.0,504.70310694055956
361,1495.0,505.17086296061774
362,1496.0,505.63865911908624
363,1498.0,506.10649539624455
364,1501.0,506.57437177237205
365,1497.0,507.04228822774814
366,1502.0,507.51024474265233
367,1499.0,507.97824129736404
368,1500.0,508.4462778721627
369,1503.0,508.9143544473277
370,1500.0,509.38247100313856
371,1499.0,509.85062751987465
372,1499.0,510.31882397781544
373,1501.0,510.7870603572404
374,1499.0,511.2553366384289
375,1502.0,511.72365280166036
376,1502.0,512.1920088272143
377,1499.0,512.6604046953701
378,1500.0,513.1288403864072
379,1503.0,513.597315880605
380,1504.0,514.0658311582431
381,1499.0,514.5343861996007
382,1498.0,515.0029809849574
383,1497.0,515.4716154945926
384,1504.0,515.9402897087857
385,1500.0,516.4090036078162
386,1501.0,516.8777571719635
387,1499.0,517.346550381507
388,1500.0,517.8153832167261
389,1501.0,518.2842556579004
390,1499.0,518.7531676853092
391,1499.0,519.2221192792321
392,1502.0,519.6911104199482
393,1497.0,520.1601410877373
394,1499.0,520.6292112628787
395,1499.0,521.0983209256517
396,1497.0,521.567470056336
397,1501.0,522.0366586352108
398,1501.0,522.5058866425557
399,1502.0,522.97515405865
400,1501.0,523.4444608637732
401,1504.0,523.9138070382048
402,1503.0,524.3831925622242
403,1500.0,524.8526174161107
404,1502.0,525.3220815801438
405,1501.0,525.7915850346031
406,1504.0,526.261127759768
407,1503.0,526.7307097359177
408,1500.0,527.2003309433319
409,1499.0,527.6699913622899
410,1498.0,528.1396909730711
411,1501.0,528.609429755955
412,1499.0,529.0792076912212
413,1499.0,529.5490247591488
414,1500.0,530.0188809400175
415,1500.0,530.4887762141067
416,1502.0,530.9587105616956
417,1502.0,531.4286839630639
418,1501.0,531.898696398491
419,1497.0,532.3687478482562
420,1495.0,532.8388382926391
421,1500.0,533.3089677119191
422,1499.0,533.7791360863756
423,1501.0,534.2493433962879
424,1500.0,534.7195896219357
425,1499.0,535.1898747435982
426,1502.0,535.6601987415551
427,1502.0,536.1305615960856
428,1499.0,536.6009632874692
429,1502.0,537.0714037959854
430,1498.0,537.5418831019134
431,1500.0,538.012401185533
432,1501.0,538.4829580271235
433,1501.0,538.9535536069642
434,1502.0,539.4241879053346
435,1501.0,539.8948609025142
436,1497.0,540.3655725787825
437,1506.0,540.8363229144188
438,1498.0,541.3071118897025
439,1501.0,541.7779394849132
440,1503.0,542.2488056803302
441,1502.0,542.719710456233
442,1495.0,543.190653792901
443,1503.0,543.6616356706137
444,1500.0,544.1326560696505
445,1500.0,544.6037149702908
446,1496.0,545.074812352814
447,1500.0,545.5459481974997
448,1503.0,546.0171224846272
449,1498.0,546.488335194476
450,1500.0,546.9595863073255
451,1498.0,547.4308758034551
452,1499.0,547.9022036631443
453,1501.0,548.3735698666726
454,1500.0,548.8449743943193
455,1499.0,549.3164172263638
456,1498.0,549.7878983430858
457,1504.0,550.2594177247645
458,1501.0,550.7309753516794
459,1499.0,551.2025712041099
460,1496.0,551.6742052623355
461,1506.0,552.1458775066355
462,1500.0,552.6175879172896
463,1503.0,553.0893364745771
464,1496.0,553.5611231587773
465,1500.0,554.0329479501697
466,1502.0,554.504810829034
467,1502.0,554.9767117756493
468,1502.0,555.4486507702951
469,1501.0,555.920627793251
470,1502.0,556.3926428247963
471,1501.0,556.8646958452105
472,1498.0,557.336786834773
473,1504.0,557.8089157737631
474,1498.0,558.2810826424605
475,1505.0,558.7532874211446
476,1498.0,559.2255300900947
477,1499.0,559.6978106295902
478,1504.0,560.1701290199107
479,1504.0,560.6424852413355
480,1496.0,561.1148792741442
481,1503.0,561.587311098616
482,1502.0,562.0597806950306
483,1504.0,562.5322880436672
484,1499.0,563.0048331248054
485,1504.0,563.4774159187245
486,1500.0,563.9500364057042
487,1496.0,564.4226945660236
488,1500.0,564.8953903799622
489,1501.0,565.3681238277996
490,1504.0,565.8408948898152
491,1503.0,566.3137035462884
492,1496.0,566.7865497774986
493,1500.0,567.2594335637252
494,1502.0,567.7323548852478
495,1503.0,568.2053137223457
496,1502.0,568.6783100552984
497,1501.0,569.1513438643854
498,1500.0,569.6244151298858
499,1506.0,570.0975238320794
500,1506.0,570.5706699512456
501,1501.0,571.0438534676637
502,1498.0,571.5170743616131
503,1500.0,571.9903326133735
504,1502.0,572.4636282032241
505,1502.0,572.9369611114444
506,1503.0,573.4103313183138
507,1499.0,573.8837388041118
508,1500.0,574.3571835491177
509,1503.0,574.8306655336112
510,1499.0,575.3041847378714
511,1504.0,575.7777411421781
512,1502.0,576.2513347268105
513,1498.0,576.724965472048
514,1499.0,577.1986333581702
515,1496.0,577.6723383654564
516,1504.0,578.1460804741862
517,1499.0,578.6198596646389
518,1501.0,579.093675917094
519,1498.0,579.5675292118308
520,1500.0,580.0414195291289
521,1499.0,580.5153468492676
522,1504.0,580.9893111525266
523,1498.0,581.4633124191851
524,1503.0,581.9373506295225
525,1502.0,582.4114257638183
526,1496.0,582.885537802352
527,1502.0,583.359686725403
528,1503.0,583.8338725132508
529,1501.0,584.3080951461747
530,1500.0,584.7823546044542
531,1503.0,585.2566508683688
532,1500.0,585.7309839181977
533,1501.0,586.2053537342207
534,1501.0,586.679760296717
535,1501.0,587.154203585966
536,1500.0,587.6286835822473
537,1504.0,588.1032002658402
538,1501.0,588.5777536170242
539,1498.0,589.0523436160788
540,1499.0,589.5269702432834
541,1501.0,590.0016334789173
542,1502.0,590.47633330326
543,1499.0,590.951069696591
544,1503.0,591.4258426391898
545,1505.0,591.9006521113357
546,1500.0,592.3754980933081
547,1501.0,592.8503805653867
548,1499.0,593.3252995078506
549,1499.0,593.8002549009794
550,1506.0,594.2752467250526
551,1502.0,594.7502749603495
552,1503.0,595.2253395871496
553,1498.0,595.7004405857324
554,1502.0,596.1755779363772
555,1501.0,596.6507516193635
556,1502.0,597.1259616149708
557,1501.0,597.6012079034784
558,1497.0,598.0764904651659
559,1500.0,598.5518092803127
560,1500.0,599.0271643291981
561,1504.0,599.5025555921015
562,1496.0,599.9779830493027
563,1501.0,600.4534466810808
564,1502.0,600.9289464677153
565,1503.0,601.4044823894857
566,1495.0,601.8800544266713
567,1500.0,602.3556625595518
568,1504.0,602.8313067684064
569,1504.0,603.3069870335147
570,1501.0,603.7827033351559
571,1500.0,604.2584556536096
572,1498.0,604.7342439691554
573,1504.0,605.2100682620724
574,1507.0,605.6859285126402
575,1499.0,606.1618247011382
576,1498.0,606.637756807846
577,1505.0,607.1137248130428
578,1502.0,607.5897286970082
579,1500.0,608.0657684400215
580,1500.0,608.5418440223623
581,1499.0,609.0179554243099
582,1503.0,609.4941026261438
583,1502.0,609.9702856081434
584,1502.0,610.4465043505882
585,1501.0,610.9227588337575
586,1500.0,611.3990490379309
587,1500.0,611.8753749433877
588,1503.0,612.3517365304075
589,1498.0,612.8281337792696
590,1496.0,613.3045666702534
591,1501.0,613.7810351836384
592,1501.0,614.2575392997041
593,1502.0,614.73407899873
594,1500.0,615.2106542609953
595,1497.0,615.6872650667794
596,1502.0,616.1639113963621
597,1500.0,616.6405932300225
598,1502.0,617.1173105480403
599,1500.0,617.5940633306948
600,1502.0,618.0708515582653
601,1495.0,618.5476752110314
602,1498.0,619.0245342692725
603,1500.0,619.5014287132682
604,1497.0,619.9783585232976
605,1500.0,620.4553236796404
606,1503.0,620.9323241625759
607,1500.0,621.4093599523836
608,1501.0,621.8864310293429
609,1503.0,622.3635373737333
610,1499.0,622.8406789658342
611,1500.0,623.3178557859251
612,1502.0,623.7950678142852
613,1501.0,624.2723150311942
614,1502.0,624.7495974169315
615,1498.0,625.2269149517763
616,1503.0,625.7042676160083
617,1499.0,626.181655389907
618,1501.0,626.6590782537514
619,1503.0,627.1365361878214
620,1504.0,627.6140291723963
621,1501.0,628.0915571877554
622,1504.0,628.5691202141782
623,1502.0,629.0467182319442
624,1499.0,629.5243512213328
625,1498.0,630.0020191626235
626,1503.0,630.4797220360956
627,1504.0,630.9574598220287
628,1497.0,631.435232500702
629,1504.0,631.9130400523952
630,1497.0,632.3908824573875
631,1502.0,632.8687596959586
632,1499.0,633.3466717483877
633,1497.0,633.8246185949544
634,1499.0,634.302600215938
635,1504.0,634.780616591618
636,1502.0,635.2586677022739
637,1500.0,635.736753528185
638,1500.0,636.2148740496308
639,1502.0,636.6930292468908
640,1503.0,637.1712191002443
641,1505.0,637.6494435899709
642,1499.0,638.12770269635
643,1498.0,638.6059963996609
644,1502.0,639.084324680183
645,1503.0,639.5626875181961
646,1499.0,640.0410848939792
647,1500.0,640.5195167878121
648,1498.0,640.997983179974
649,1503.0,641.4764840507444
650,1497.0,641.9550193804027
651,1502.0,642.4335891492284
652,1497.0,642.912193337501
653,1497.0,643.3908319254997
654,1499.0,643.8695048935042
655,1500.0,644.3482122217938
656,1501.0,644.8269538906479
657,1498.0,645.3057298803461
658,1501.0,645.7845401711677
659,1500.0,646.2633847433921
660,1498.0,646.7422635772988
661,1498.0,647.2211766531673
662,1491.0,647.700123951277
663,1504.0,648.1791054519072
664,1498.0,648.6581211353375
665,1499.0,649.1371709818474
666,1498.0,649.616254971716
667,1500.0,650.0953730852231
668,1499.0,650.574525302648
669,1499.0,651.05371160427
670,1500.0,651.5329319703688
671,1498.0,652.0121863812237
672,1497.0,652.4914748171141
673,1504.0,652.9707972583194
674,1495.0,653.4501536851192
675,1499.0,653.9295440777928
676,1500.0,654.4089684166197
677,1505.0,654.8884266818793
678,1498.0,655.3679188538512
679,1503.0,655.8474449128145
680,1502.0,656.3270048390489
681,1501.0,656.8065986128337
682,1496.0,657.2862262144484
683,1500.0,657.7658876241726
684,1505.0,658.2455828222854
685,1501.0,658.7253117890665
686,1506.0,659.2050745047951
687,1506.0,659.6848709497509
688,1502.0,660.1647011042132
689,1498.0,660.6445649484615
690,1502.0,661.1244624627751
691,1503.0,661.6043936274335
692,1505.0,662.0843584227163
693,1499.0,662.5643568289028
694,1500.0,663.0443888262722
695,1499.0,663.5244543951044
696,1501.0,664.0045535156785
697,1505.0,664.484686168274
698,1500.0,664.9648523331705
699,1500.0,665.4450519906472
700,1499.0,665.9252851209837
701,1500.0,666.4055517044594
702,1507.0,666.8858517213537
703,1500.0,667.3661851519461
704,1501.0,667.8465519765159
705,1499.0,668.3269521753427
706,1498.0,668.8073857287059
707,1505.0,669.2878526168848
708,1501.0,669.768352820159
709,1503.0,670.2488863188079
710,1506.0,670.7294530931108
711,1502.0,671.2100531233473
712,1506.0,671.6906863897968
713,1500.0,672.1713528727388
714,1497.0,672.6520525524526
715,1503.0,673.1327854092176
716,1498.0,673.6135514233134
717,1500.0,674.0943505750193
718,1499.0,674.5751828446149
719,1501.0,675.0560482123796
720,1504.0,675.5369466585926
721,1503.0,676.0178781635335
722,1503.0,676.4988427074819
723,1504.0,676.979840270717
724,1508.0,677.4608708335182
725,1504.0,677.9419343761652
726,1507.0,678.4230308789373
727,1506.0,678.9041603221139
728,1515.0,679.3853226859744
729,1529.0,679.8665179507983
730,1534.0,680.3477460968651
731,1535.0,680.8290071044541
732,1522.0,681.310300953845
733,1511.0,681.7916276253168
734,1505.0,682.2729870991493
735,1504.0,682.7543793556217
736,1499.0,683.2358043750137
737,1502.0,683.7172621376045
738,1501.0,684.1987526236736
739,1499.0,684.6802758135005
740,1505.0,685.1618316873646
741,1501.0,685.6434202255454
742,1503.0,686.1250414083222
743,1500.0,686.6066952159745
744,1501.0,687.0883816287817
745,1502.0,687.5701006270233
746,1493.0,688.0518521909787
747,1501.0,688.5336363009274
748,1505.0,689.0154529371488
749,1498.0,689.4973020799222
750,1503.0,689.9791837095272
751,1498.0,690.4610978062433
752,1501.0,690.9430443503497
753,1504.0,691.4250233221261
754,1503.0,691.9070347018517
755,1503.0,692.389078469806
756,1499.0,692.8711546062685
757,1502.0,693.3532630915187
758,1498.0,693.8354039058358
759,1497.0,694.3175770294996
760,1501.0,694.7997824427891
761,1504.0,695.2820201259841
762,1501.0,695.7642900593638
763,1496.0,696.2465922232078
764,1496.0,696.7289265977954
765,1502.0,697.2112931634061
766,1503.0,697.6936919003193
767,1501.0,698.1761227888146
768,1500.0,698.6585858091712
769,1502.0,699.1410809416686
770,1504.0,699.6236081665865
771,1500.0,700.1061674642038
772,1504.0,700.5887588148005
773,1502.0,701.0713821986557
774,1498.0,701.5540375960489
775,1500.0,702.0367249872596
776,1498.0,702.5194443525672
777,1497.0,703.0021956722511
778,1500.0,703.4849789265909
779,1501.0,703.9677940958658
780,1505.0,704.4506411603553
781,1502.0,704.9335201003389
782,1499.0,705.416430896096
783,1504.0,705.899373527906
784,1502.0,706.3823479760485
785,1500.0,706.8653542208028
786,1503.0,707.3483922424484
787,1499.0,707.8314620212647
788,1504.0,708.314563537531
789,1500.0,708.797696771527
790,1499.0,709.2808617035319
791,1495.0,709.7640583138252
792,1500.0,710.2472865826865
793,1506.0,710.730546490395
794,1502.0,711.2138380172303
795,1504.0,711.6971611434718
796,1498.0,712.180515849399
797,1500.0,712.6639021152911
798,1501.0,713.1473199214278
799,1498.0,713.6307692480883
800,1501.0,714.1142500755523
801,1504.0,714.597762384099
802,1498.0,715.081306154008
803,1498.0,715.5648813655587
804,1501.0,716.0484879990304
805,1502.0,716.5321260347027
806,1505.0,717.0157954528551
807,1499.0,717.4994962337668
808,1500.0,717.9832283577173
809,1502.0,718.4669918049862
810,1501.0,718.9507865558527
811,1497.0,719.4346125905964
812,1505.0,719.9184698894968
813,1503.0,720.4023584328331
814,1502.0,720.8862782008849
815,1501.0,721.3702291739318
816,1495.0,721.8542113322528
817,1504.0,722.3382246561276
818,1500.0,722.8222691258358
819,1503.0,723.3063447216565
820,1503.0,723.7904514238693
821,1500.0,724.2745892127537
822,1495.0,724.7587580685889
823,1499.0,725.2429579716546
824,1502.0,725.7271889022302
825,1499.0,726.211450840595
826,1499.0,726.6957437670285
827,1503.0,727.1800676618101
828,1499.0,727.6644225052194
829,1503.0,728.1488082775355
830,1500.0,728.6332249590382
831,1499.0,729.1176725300068
832,1502.0,729.6021509707207
833,1506.0,730.0866602614593
834,1501.0,730.5712003825022
835,1499.0,731.0557713141286
836,1502.0,731.5403730366181
837,1502.0,732.0250055302502
838,1500.0,732.5096687753041
839,1500.0,732.9943627520595
840,1499.0,733.4790874407956
841,1500.0,733.963842821792
842,1500.0,734.4486288753282
843,1500.0,734.9334455816833
844,1503.0,735.4182929211371
845,1499.0,735.9031708739689
846,1496.0,736.388079420458
847,1502.0,736.873018540884
848,1501.0,737.3579882155263
849,1502.0,737.8429884246644
850,1501.0,738.3280191485777
851,1504.0,738.8130803675455
852,1499.0,739.2981720618474
853,1499.0,739.7832942117627
854,1499.0,740.2684467975711
855,1498.0,740.7536297995517
856,1503.0,741.2388431979841
857,1497.0,741.7240869731478
858,1501.0,742.209361105322
859,1506.0,742.6946655747865
860,1499.0,743.1800003618205
861,1499.0,743.6653654467034
862,1501.0,744.1507608097147
863,1500.0,744.6361864311339
864,1501.0,745.1216422912403
865,1503.0,745.6071283703134
866,1499.0,746.0926446486327
867,1503.0,746.5781911064777
868,1500.0,747.0637677241275
869,1501.0,747.549374481862
870,1502.0,748.0350113599602
871,1499.0,748.5206783387017
872,1501.0,749.0063753983661
873,1498.0,749.4921025192327
874,1503.0,749.9778596815809
875,1500.0,750.4636468656902
876,1498.0,750.94946405184
877,1497.0,751.4353112203097
878,1502.0,751.9211883513788
879,1503.0,752.4070954253267
880,1504.0,752.893032422433
881,1497.0,753.3789993229768
882,1501.0,753.8649961072379
883,1503.0,754.3510227554955
884,1499.0,754.837079248029
885,1500.0,755.3231655651181
886,1501.0,755.8092816870419
887,1499.0,756.2954275940801
888,1499.0,756.7816032665121
889,1501.0,757.2678086846172
890,1500.0,757.754043828675
891,1504.0,758.2403086789648
892,1499.0,758.7266032157661
893,1501.0,759.2129274193583
894,1498.0,759.6992812700208
895,1501.0,760.1856647480332
896,1498.0,760.6720778336748
897,1499.0,761.1585205072251
898,1501.0,761.6449927489635
899,1500.0,762.1314945391695
900,1504.0,762.6180258581223
901,1502.0,763.1045866861017
902,1503.0,763.5911770033869
903,1503.0,764.0777967902574
904,1503.0,764.5644460269925
905,1499.0,765.0511246938719
906,1502.0,765.5378327711749
907,1498.0,766.0245702391808
908,1502.0,766.5113370781693
909,1497.0,766.9981332684196
910,1499.0,767.4849587902113
911,1498.0,767.9718136238238
912,1498.0,768.4586977495364
913,1505.0,768.9456111476288
914,1500.0,769.4325537983802
915,1500.0,769.9195256820701
916,1501.0,770.406526778978
917,1503.0,770.8935570693833
918,1502.0,771.3806165335654
919,1506.0,771.8677051518038
920,1501.0,772.3548229043779
921,1502.0,772.8419697715672
922,1501.0,773.3291457336509
923,1499.0,773.8163507709087
924,1504.0,774.30358486362
925,1499.0,774.7908479920641
926,1499.0,775.2781401365206
927,1500.0,775.7654612772689
928,1503.0,776.2528113945882
929,1499.0,776.7401904687582
930,1500.0,777.2275984800583
931,1499.0,777.7150354087679
932,1503.0,778.2025012351664
933,1504.0,778.6899959395333
934,1502.0,779.1775195021481
935,1501.0,779.66507190329
936,1503.0,780.1526531232387
937,1505.0,780.6402631422734
938,1499.0,781.1279019406737
939,1496.0,781.6155694987191
940,1494.0,782.1032657966888
941,1501.0,782.5909908148624
942,1501.0,783.0787445335192
943,1504.0,783.5665269329388
944,1499.0,784.0543379934006
945,1503.0,784.542177695184
946,1503.0,785.0300460185684
947,1504.0,785.5179429438333
948,1500.0,786.0058684512582
949,1501.0,786.4938225211224
950,1500.0,786.9818051337053
951,1501.0,787.4698162692865
952,1501.0,787.9578559081453
953,1501.0,788.4459240305613
954,1500.0,788.9340206168138
955,1503.0,789.4221456471822
956,1501.0,789.9102991019461
957,1498.0,790.3984809613847
958,1498.0,790.8866912057777
959,1505.0,791.3749298154044
960,1505.0,791.8631967705442
961,1501.0,792.3514920514766
962,1502.0,792.839815638481
963,1503.0,793.3281675118369
964,1501.0,793.8165476518236
965,1502.0,794.3049560387208
966,1503.0,794.7933926528076
967,1504.0,795.2818574743636
968,1499.0,795.7703504836684
969,1500.0,796.2588716610012
970,1497.0,796.7474209866415
971,1500.0,797.2359984408687
972,1501.0,797.7246040039623
973,1497.0,798.2132376562017
974,1499.0,798.7018993778664
975,1504.0,799.1905891492358
976,1503.0,799.6793069505893
977,1505.0,800.1680527622063
978,1498.0,800.6568265643665
979,1502.0,801.145628337349
980,1501.0,801.6344580614333
981,1501.0,802.123315716899
982,1497.0,802.6122012840254
983,1503.0,803.101114743092
984,1499.0,803.5900560743783
985,1502.0,804.0790252581635
986,1502.0,804.5680222747272
987,1499.0,805.057047104349
988,1501.0,805.546099727308
989,1498.0,806.0351801238838
990,1497.0,806.524288274356
991,1505.0,807.0134241590036
992,1501.0,807.5025877581065
993,1500.0,807.9917790519439
994,1504.0,808.4809980207953
995,1506.0,808.9702446449401
996,1499.0,809.4595189046577
997,1504.0,809.9488207802276
998,1503.0,810.4381502519293
999,1499.0,810.9275073000421
1000,1496.0,811.4168919048454
1001,1499.0,811.9063040466189
1002,1501.0,812.3957437056417
1003,1502.0,812.8852108621935
1004,1503.0,813.3747054965537
1005,1503.0,813.8642275890015
1006,1504.0,814.3537771198166
1007,1500.0,814.8433540692785
1008,1500.0,815.3329584176663
1009,1502.0,815.8225901452597
1010,1500.0,816.312249232338
1011,1500.0,816.8019356591807
1012,1501.0,817.2916494060672
1013,1505.0,817.781390453277
1014,1501.0,818.2711587810895
1015,1499.0,818.7609543697843
1016,1500.0,819.2507771996404
1017,1501.0,819.7406272509377
1018,1500.0,820.2305045039553
1019,1501.0,820.7204089389729
1020,1502.0,821.2103405362698
1021,1502.0,821.7002992761254
1022,1503.0,822.1902851388191
1023,1499.0,822.6802981046307
|
987,582 | 745075872567b5920841dc2c6a3da8b66f367988 | ### Boas Pucker ###
### bpucker@cebitec.uni-bielefeld.de ###
### v0.15 ###
### based on https://doi.org/10.1371/journal.pone.0164321 ###
__usage__ = """
python genome_wide_variants.py
--vcf <FULL_PATH_TO_INPUT_VCF>
--out <FULL_PATH_TO_OUTPUT_DIR>
optional:
--res <INT, RESOLUTION>[1000000]
bug reports and feature requests: bpucker@cebitec.uni-bielefeld.de
"""
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import sys, os
# --- end of imports --- #
def load_variants_from_vcf( vcf_file ):
"""! @brief loads the variant informaiton from a SnpEff output VCF file """
snps_per_chr = {}
indels_per_chr = {}
tri_counter = 0
with open( vcf_file, "r" ) as f:
line = f.readline()
while line:
if line[0] != '#':
parts = line.strip().split('\t')
if not "," in parts[4]: #only biallelic variants
if len( parts[3] ) == len( parts[4] ) and len( parts[3] ) == 1:
try:
snps_per_chr[ parts[0] ].append( parts[1] )
except KeyError:
snps_per_chr.update( { parts[0]: [ parts[1] ] } )
elif len( parts[3] ) != len( parts[4] ):
try:
indels_per_chr[ parts[0] ].append( parts[1] )
except KeyError:
indels_per_chr.update( { parts[0]: [ parts[1] ] } )
else: #count triallelic variants
tri_counter += 1
line = f.readline()
print "number of triallelic variants: " + str( tri_counter )
return snps_per_chr, indels_per_chr
def generate_binned_values( lower_lim, upper_lim, chr_length, snps_per_chr, indels_per_chr, resolution ):
"""! @brief group variants into bins """
snp_data = []
indel_data = []
while True:
if upper_lim >= chr_length:
break
else:
snp_tmp = []
indel_tmp = []
for SNP in snps_per_chr:
if SNP <= upper_lim and SNP > lower_lim:
snp_tmp.append( 'X' )
for indel in indels_per_chr:
if indel <= upper_lim and indel > lower_lim:
indel_tmp.append( 'X' )
snp_data.append( len( snp_tmp ) )
indel_data.append( len( indel_tmp ) )
upper_lim += resolution
lower_lim += resolution
return max( snp_data ), max( indel_data ), snp_data, indel_data
def construct_plot( snps_per_chr_in, indels_per_chr_in, result_file, result_table, resolution ):
"""! @brief construct variant over Col-0 genome distribution plot """
# --- conversion of data into lists of lists --- #
chr_lengths = []
chr_names = []
snps_per_chr = []
indels_per_chr = []
for key in sorted( snps_per_chr_in.keys() ):
snps = snps_per_chr_in[ key ]
indels = indels_per_chr_in[ key ]
snps_per_chr.append( snps )
indels_per_chr.append( indels )
chr_lengths.append( max( snps+indels ) )
chr_names.append( key )
max_x_value = max( [ x for chro in snps_per_chr for x in chro ] + [ x for chro in indels_per_chr for x in chro ] )
# --- generation of figure --- #
fig, ax = plt.subplots()
snp_scale = 1
indel_scale = 1
snp_data = []
indel_data = []
for idx, chr_length in enumerate( chr_lengths ):
max_snp, max_indel, snp_temp, indel_temp = generate_binned_values( 0, resolution+0, chr_length, snps_per_chr[ idx ], indels_per_chr[ idx ], resolution )
snp_data.append( snp_temp )
indel_data.append( indel_temp )
snp_scale = max( [ snp_scale, max_snp ] )
indel_scale = max( [ indel_scale, max_indel ] )
snp_scale = float( snp_scale )
indel_scale = float( indel_scale )
y_max = len( chr_lengths )
ax2 = ax.twinx()
with open( result_table, "w" ) as out:
for idx, chr_length in enumerate( chr_lengths ):
y = y_max-( idx*1.2 )
x = resolution / 1000000.0
ax.text( ( chr_length/ 1000000.0 ), y+0.3, chr_names[ idx ], ha="right" )
# --- plotting SNP and InDel distribution --- #
for i, snps in enumerate( snp_data[ idx ] ):
indels = indel_data[ idx ][ i ]
ax.plot( [ x*i+0.5*x, x*i+0.5*x ], [ y, y+ ( snps / snp_scale ) ], "-", color="lime" )
ax2.plot( [ x*i+0.5*x, x*i+0.5*x ], [ y, y+ ( indels / indel_scale ) ], "-", color="magenta" )
ax.plot( [ 0, 0 ], [ y, y+1 ], color="black" )
ax.text( 0, y+1, str( int( snp_scale ) ), ha="right", fontsize=5 )
ax.text( 0, y+0.5, str( int( snp_scale / 2 ) ), ha="right", fontsize=5 )
ax.text( 0, y, "0", ha="right", fontsize=5 )
ax.plot( [ max_x_value, max_x_value ], [ y, y+1 ], color="black" )
ax.text( max_x_value, y+1, str( int( indel_scale ) ), ha="right", fontsize=5 )
ax.text( max_x_value, y+0.5, str( int( indel_scale / 2 ) ), ha="right", fontsize=5 )
ax.text( max_x_value, y, "0", ha="right", fontsize=5 )
# --- writing data into output table --- #
out.write( 'Chr' + str( idx+1 ) + "SNVs:\t" + '\t'.join( map( str, snp_data ) ) + '\n' )
out.write( 'Chr' + str( idx+1 ) + "InDels:\t" + '\t'.join( map( str, indel_data ) ) + '\n' )
ax.set_xlabel( "genomic position [ Mbp ]" )
ax.set_ylabel( "number of SNVs per interval" )
ax2.set_ylabel( "number of InDels per interval" )
ax.set_xlim( 0, max( chr_lengths ) / 1000000.0 )
ax.legend( handles=[ mpatches.Patch(color='magenta', label='InDels'), mpatches.Patch(color='lime', label='SNVs') ], prop={'size':10} )
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['left'].set_visible(False)
ax.get_yaxis().set_ticks([])
ax2.get_yaxis().set_ticks([])
ax.yaxis.labelpad = 15
ax2.yaxis.labelpad = 15
plt.subplots_adjust( left=0.1, right=0.9, top=0.99, bottom=0.1 )
fig.savefig( result_file, dpi=600 )
plt.close('all')
def main( arguments ):
"""! @brief run everyting """
vcf_file = arguments[ arguments.index( '--vcf' )+1 ]
output_dir = arguments[ arguments.index( '--out' )+1 ]
if '--res' in arguments:
resolution = int( arguments[ arguments.index( '--res' )+1 ] )
else:
resolution = 1000000
if output_dir[ -1 ] != "/":
output_dir += "/"
if not os.path.exists( output_dir ):
os.makedirs( output_dir )
result_file = output_dir + "genome_wide_small_variants.png"
result_table = output_dir + "genome_wide_small_variants.txt"
snps_per_chr, indels_per_chr = load_variants_from_vcf( vcf_file )
print "number of SNVs: " + str( len( [ x for each in snps_per_chr.values() for x in each ] ) )
print "number of InDels: " + str( len( [ x for each in indels_per_chr.values() for x in each ]) )
construct_plot( snps_per_chr, indels_per_chr, result_file, result_table, resolution )
if '--vcf' in sys.argv and '--out' in sys.argv:
main( sys.argv )
else:
sys.exit( __usage__ )
|
987,583 | d95bfd14c65bda57d4bf74a18120f7e943dcb3c0 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-04-12 21:21
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('solicitudes', '0026_auto_20170412_1530'),
]
operations = [
migrations.RemoveField(
model_name='comprobante',
name='srf',
),
migrations.AddField(
model_name='solicitudrecursofinanciero',
name='comprobantes',
field=models.FileField(blank=True, null=True, upload_to='Comprobantes/%Y/%m/%d/'),
),
migrations.DeleteModel(
name='Comprobante',
),
]
|
987,584 | 2cd2febd4b9cf0ec993bf0b6e88940efefb5aca3 | from django.test import TestCase, Client
from models import CatModel
class CatModelTest(TestCase):
def setUp(self):
self.cat_a = CatModel(
name="A",
length=10,
width=20,
height=30
)
self.cat_a.save()
def test_get_volume(self):
"""
Compare cat_a volume with known value
"""
self.assertEqual(self.cat_a.volume(), 6000)
class CatApiTest(TestCase):
def setUp(self):
self.client = Client()
def test_create_and_get_cat(self):
response = self.client.post(
"/api/cat/",
data={
"name":"API cat",
"length": 10,
"width": 20,
"height": 30
})
self.assertEqual(response.status_code, 201)
response = self.client.get("/api/cat/1/")
self.assertEqual(
response.content,
"""{"name":"API cat","length":10,"height":30,"width":20,"volume":6000}"""
)
self.assertEqual(response.status_code, 200)
|
987,585 | 064ef4db62144b66246d4a0ce649152a182f4334 | """
Django settings for DjangoProject project.
Generated by 'django-admin startproject' using Django 1.8.3.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
from django.conf import global_settings
# TEMPLATE_CONTEXT_PROCESSORS = global_settings.TEMPLATE_CONTEXT_PROCESSORS + (
# 'setting.context_processors.lang_context_processor',
# )
SUIT_CONFIG = {
'ADMIN_NAME': 'NURAKSA TOUR',
# 'MENU': (
# {'label': 'Words', 'icon': 'fa fa-file-o', 'app': 'word'},
# {'label': 'Authorization', 'icon': 'fa fa-lock', 'app': 'auth'},
# ),
'ADMIN_BRAND_NAME': 'NURAKSATOUR',
'LIST_PER_PAGE': 18,
'SEARCH_URL': '',
'SHOW_REQUIRED_ASTERISK': True
}
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '*s4b!2sy0#6(ishr0)&&(^nls5hn8v9t^z58so&!cq@!#8(&&c'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
'suit',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admindocs',
'django.contrib.humanize',
'word',
'wysiwyg',
'mptt',
'filemedia',
'page',
'appearance',
'setting',
'contact',
'pront',
# 'prontand',
)
LOCALE_PATHS = (
os.path.join(os.path.dirname(__file__), "../locale"),
)
REDACTOR_OPTIONS = {}
REDACTOR_UPLOAD = 'image/'
# REDACTOR_UPLOAD_HANDLER = 'redactor.handlers.DateDirectoryUploader'
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
)
ROOT_URLCONF = 'DjangoProject.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'django.template.context_processors.i18n',
'setting.context_processors.general',
'setting.context_processors.admin',
],
},
},
]
WSGI_APPLICATION = 'DjangoProject.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'nuraksatour',
'USER': 'root',
'PASSWORD': 'admin',
'HOST': 'localhost', # Or an IP Address that your DB is hosted on
'PORT': '3306',
}
}
# DATABASES = {
# 'default': {
# 'ENGINE': 'django.db.backends.sqlite3',
# 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
# }
# }
# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/
LANGUAGE_CODE = 'id'
LANGUAGE = (
('id', 'Indonesia'),
)
TIME_ZONE = 'Asia/Makassar'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/
STATIC_ROOT = '/Users/antlink/PycharmProjects/DjangoProject/static/'
STATIC_URL = '/static/'
MEDIA_ROOT = '/Users/antlink/PycharmProjects/DjangoProject/media/'
MEDIA_URL = '/media/'
|
987,586 | ee82d336b3a006d273beded0782517483b0e2043 | from flax import linen as nn
from functools import partial
from survae.transforms.surjective import Surjective
from survae.distributions import *
from typing import Any
import jax.numpy as jnp
from jax import random
import numpy as np
class VariationalDequantization(nn.Module,Surjective):
"""
Note: it is very sensitive to the initialization. For instance, assume we have z ~ q(.|x) = N(\mu(x),\log_sigma(x)).
exp(\log_sigma(x)) may be too large for bad initalization. (e.g. exp(\log_sigma(x))=exp(100)=2.69e100)
"""
encoder: nn.Module = None
num_bits: int = 8
_dtype: Any = None
stochastic_forward: bool = True
@staticmethod
def _setup(encoder, num_bits=8):
return partial(VariationalDequantization, encoder=encoder, num_bits=num_bits)
def setup(self):
if self.encoder == None:
raise TypeError()
self._encoder = self.encoder()
return
@nn.compact
def __call__(self, x, rng, *args, **kwargs):
return self.forward(x=x, rng=rng)
def forward(self, x, rng, *args, **kwargs):
if self._dtype == None:
self._dtype = x.dtype
u, qu = self._encoder.sample_with_log_prob(rng=rng, context=x)
z = (x.astype(u.dtype) + u) / (2**self.num_bits)
ldj = self._ldj(z.shape) - qu
return z, ldj
def _ldj(self, shape):
batch_size = shape[0]
num_dims = jnp.array(shape[1:]).prod()
ldj = -jnp.log(2**self.num_bits) * num_dims
return ldj.repeat(batch_size)
def inverse(self, z, *args, **kwargs):
z = 2**self.num_bits * z
return jnp.clip(jnp.floor(z),a_min=0.,a_max=(2**self.num_bits-1)).astype(self._dtype)
|
987,587 | 92ff7b1b5634a778cda99f72e4cfdc7df32fe65d | from __future__ import print_function
from twitchstream.outputvideo import TwitchOutputStreamRepeater
from twitchstream.chat import TwitchChatStream
import argparse
import time
import numpy as np
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
required = parser.add_argument_group('required arguments')
required.add_argument('-u', '--username',
help='twitch username',
required=True)
required.add_argument('-o', '--oauth',
help='twitch oauth '
'(visit https://twitchapps.com/tmi/ '
'to create one for your account)',
required=False)
args = parser.parse_args()
if not args.oauth:
f = open("oauth.properties", "r")
auth = f.read()
# Launch a verbose (!) twitch stream
with TwitchChatStream(username=args.username,
oauth=auth,
verbose=True) as chatstream:
chatstream.join_channel('existentiallyyours')
# Send a message to this twitch stream
for x in range(10):
chatstream.send_chat_message("Oh Hello -"+ str(x) + "\r\n")
# Continuously check if messages are received (every ~10s)
# This is necessary, if not, the chat stream will close itself
# after a couple of minutes (due to ping messages from twitch)
while True:
received = chatstream.twitch_receive_messages()
if received:
print("received:", received)
time.sleep(1)
|
987,588 | 37ce2c4de619e64523a032d2ee76c82779fcd4a7 | import db
async def validate_form(conn, form):
name = form['name']
city = form['city']
age = form['age']
if not name:
return 'name is required'
if not city:
return 'city is required'
if not age:
return 'age is required'
else:
return None
return 'error' |
987,589 | 5bda98a4a3109dcf5c01777620616251309a36b0 | try:
rf = open(r'D:\Viknesh Ramm\Python Programs\Assignments\Day-6\readfile.txt','r')
wr = open(r'D:\Viknesh Ramm\Python Programs\Assignments\Day-6\writefile.txt','w')
wline = []
lno = 1
for line in rf:
li = str(lno)+":"+line.strip()+"\n"
print li
wr.write(li)
lno += 1
wr.close()
except IOError,var:
print str(var)
|
987,590 | 60aa8f2ca9cb24c42eeacb8d12c179e80dd32bc2 | import pandas as pandas
idlist = pd.read_excel("DataFile.xlsx", 'json_clean', index = False)
info = pd.read_excel("DataFile.xlsx", 'csv_clean', index = False)
all_data_st = pd.merge(idlist, info, how='left')
all_data_st.to_excel('DataFile.xlsx', sheet_name='processed', index = False)
print("Finished!")
|
987,591 | 032a962c414d0f41311dddf4f7d6aa095abf8d25 | import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from typing import List
sender = "ecinemaBookingWebsite@gmail.com"
password = "4050Project"
def send_email(email: str, sub: str, message: str):
receivers = email
subject = sub
msg = MIMEMultipart()
msg['From'] = sender
msg['To'] = email
msg['Subject'] = subject
msg.attach(MIMEText(message, 'plain'))
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.ehlo()
server.login(sender, password)
text = msg.as_string()
server.sendmail(sender, email, text)
server.quit()
|
987,592 | 7098055c33dff0b20d1694ec4bdc5713ba875a83 | from rest_framework import viewsets, generics
from django.contrib.auth.models import User
from .models import Comment
from django.shortcuts import get_object_or_404
from .serializers import CommentSerializer
class CommentList(generics.ListCreateAPIView):
queryset = Comment.objects.all()
serializer_class = CommentSerializer
class CommentDetails(generics.RetrieveUpdateDestroyAPIView):
queryset = Comment.objects.all()
serializer_class = CommentSerializer
def get_object(self):
return get_object_or_404(Comment, pk=self.kwargs.get('comment_id'))
|
987,593 | deb03fed74e27d3746319d369cb0149fd8706c10 | # -*- coding: utf-8 -*-
import inspect
import datetime
import time
from qgis.PyQt import QtCore
from PyQt5.QtWidgets import QTableView, QHeaderView, QApplication
from PyQt5.QtCore import Qt , QAbstractTableModel
from psCom.PsCom import log
from abc import abstractmethod
from PyQt5.Qt import QBrush
from psModel.PsCol import PsCol
from psCom.PsComWidget import PsComWidget
# ErpTableModel
class PsTableModel( QAbstractTableModel , PsComWidget ):
debug = True
__abstract__ = True
def __init__(self, parent, tableView ):
QAbstractTableModel.__init__(self, parent )
self.window = parent
self.order_by_idx = None
self.useSelector = False
self.useColumnAlignment = True
self.tableView = tableView
tableView.setSelectionBehavior( QTableView.SelectRows );
self.initModel()
pass
@abstractmethod
def initModel( self ):
self.tableHeader = None
self.psQuery = None
pass
# adjustColumnWidth
def adjustColumnWidth( self ):
tableView = self.tableView
# column width setting
header = tableView.horizontalHeader()
colCount = self.columnCount( tableView )
for idx in range( 0, colCount ) :
if colCount - 1 > idx :
header.setSectionResizeMode( idx, QHeaderView.ResizeToContents )
else :
header.setSectionResizeMode( idx, QHeaderView.Stretch )
pass
pass
# -- column width setting
pass
# -- adjustColumnWidth
# repaintTableView
def repaintTableView(self):
# set wait cursor
QApplication.setOverrideCursor(Qt.WaitCursor)
tableView = self.tableView
tableView.clearSelection()
self.dataChanged.emit(self.createIndex(0, 0), self.createIndex(self.rowCount(0), self.columnCount(0)))
self.layoutChanged.emit()
tableView.repaint()
tableView.update()
# restore cursor
QApplication.restoreOverrideCursor()
pass
# -- repaintTableView
# searchBtnClicked
def searchBtnClicked( self , window ):
self.doSearch( window, 1 )
pass
def doSearch(self, window, pageNo ):
if True :
# clear previous search result
window.status.setText( "검색중입니다. 잠시만 기다려 주세요." )
self.psQuery = None
self.repaintTableView()
pass
self.psQuery = self.getPsQuerySearchImpl( window, pageNo )
if not self.psQuery :
window.status.setText( "" )
elif self.psQuery :
rowCount = self.psQuery.rowCount
if 1 > rowCount :
window.status.setText( "검색 결과가 없습니다." )
if hasattr(window, "select" ) :
window.select.setEnabled( False )
pass
else :
window.status.setText( "총 검색 건수: %s" % ( "{:,d}".format( rowCount ) ) )
if hasattr(window, "select" ) :
window.select.setEnabled( True )
pass
pass
pass
self.repaintTableView()
pass
# -- searchBtnClicked
@abstractmethod
def getPsQuerySearchImpl(self, window, pageNo ):
pass
pass
# initSearchBtnClicked
def initSearchBtnClicked(self , window ):
self.initModel()
self.repaintTableView()
pass
# -- initSearchBtnClicked
# getTableHeader
def getTableHeader(self):
if hasattr(self, "table") :
return self.table.getTableHeader()
else :
return self.erpTable.getTableHeader()
pass
pass
# -- getTableHeader
# rowCount
def rowCount(self, parent):
debug = False
psQuery = self.psQuery
count = 0
if psQuery is None :
count = 0
else :
itemList = psQuery.itemList
if itemList is None :
count = 0
else :
count = len( itemList )
pass
pass
debug and log.use and log.info( "row count = %s" % count )
return count
pass
# -- rowCount
# columnCount
def columnCount(self, parent):
return 1 + len( self.getTableHeader() ) + 1
pass
# -- columnCount
# headerData
def headerData(self, col, orientation, role):
if orientation == Qt.Horizontal and role == Qt.DisplayRole:
if 0 == col :
return "No."
elif len( self.getTableHeader() ) >= col :
col = self.getTableHeader()[ col - 1 ]
if isinstance( col, PsCol ) :
return col.dispColName
else :
return col
pass
else :
return ""
pass
else :
return None
pass
pass
# -- headerData
# flags
def flags(self, index):
f = None
if index.isValid():
row = index.row()
col = index.column()
if 0 < row and 0 == col :
f = QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable
else :
f = QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable
pass
pass
f = super().flags(index) | f
return f
pass
# -- flags
# getBackgroundBrush
def getBackgroundBrush(self , index ):
row = index.row()
if row%2 :
return QBrush( Qt.lightGray )
else :
return None
pass
pass
# -- getBackgroundBrush
# getForegroundBrush
def getForegroundBrush(self , index ):
return None
pass
# -- getForegroundBrush
# getItemAt
def getItemAt(self, row) :
if self.psQuery and self.psQuery.itemList :
return self.psQuery.itemList[ row ]
else :
return None
pass
pass
# -- getItemAt
# getItemColumnValue
def getItemColumnValue(self, item , col ):
'''
debug = True
funName = self.getFunName( inspect.currentframe() )
debug and log.use and log.info( funName )
'''
return item.getColumnValue( col - 1 )
pass
# -- getItemColumnValue
# data
def data(self, index, role):
if not index.isValid():
return None
pass
if role == Qt.BackgroundRole :
return self.getBackgroundBrush( index )
elif role == Qt.ForegroundRole :
return self.getForegroundBrush( index )
elif role in ( Qt.EditRole, Qt.DisplayRole , Qt.CheckStateRole , Qt.TextAlignmentRole ) :
row = index.row()
col = index.column()
item = self.getItemAt( row )
if item is None :
value = None
else :
if Qt.CheckStateRole == role and 0 == col:
useSelector = self.useSelector
if useSelector :
value = ( Qt.Unchecked, Qt.Checked ) [ item.isChecked ]
else :
value = None
pass
elif Qt.CheckStateRole == role :
value = None
elif 0 == col :
psQuery = self.psQuery
value = ( psQuery.pageNo - 1 )*psQuery.pageRowCount + row + 1
else :
value = self.getItemColumnValue(item, col)
valueType = type( value )
# convert to its literal value
if value is None :
value = ""
elif valueType not in [ int , float, str ] :
value = "%s" % value
pass
pass
pass
# return cell alignment value
if Qt.TextAlignmentRole == role :
if type( value ) == int :
return Qt.AlignRight | QtCore.Qt.AlignVCenter
elif type( value ) == float :
return Qt.AlignRight | QtCore.Qt.AlignVCenter
elif isinstance( value, datetime.date) :
return Qt.AlignHCenter | QtCore.Qt.AlignVCenter
else :
if self.useColumnAlignment :
return self.getColumnAlignment(col)
else :
return Qt.AlignLeft | QtCore.Qt.AlignVCenter
pass
pass
pass
# -- return cell alignment value
return value
else :
return None
pass
pass
# -- data
# getColumnAlignment
def getColumnAlignment(self, col):
debug = False
funName = self.getFunName( inspect.currentframe() )
debug and log.use and log.info( funName )
alignment = Qt.AlignLeft | QtCore.Qt.AlignVCenter
psQuery = self.psQuery
if psQuery is None or psQuery.itemList is None :
alignment = Qt.AlignLeft | QtCore.Qt.AlignVCenter
else :
itemList = psQuery.itemList
if not hasattr( psQuery, "columnAlignments" ) :
psQuery.columnAlignments = { }
pass
columnAlignments = psQuery.columnAlignments
if col in columnAlignments :
alignment = columnAlignments[ col ]
else :
dataLen = None
alignment = Qt.AlignHCenter | QtCore.Qt.AlignVCenter
diffCount = 0
itemListLength = len( itemList )
for item in itemList :
data = self.getItemColumnValue(item, col)
if not data :
currDataLen = 0
else :
data = "%s" % data
data = data.strip()
currDataLen = len( data )
pass
debug and log.use and log.info( "data=%s, dataLen=%s" % (data, currDataLen ) )
if 0 == currDataLen :
pass
elif dataLen is None :
dataLen = currDataLen
elif dataLen != currDataLen :
diff = abs( dataLen - currDataLen )
if 3 < diff :
diffCount += 1
else :
dataLen = max( dataLen, currDataLen )
pass
if 0.1 < diffCount/itemListLength :
alignment = Qt.AlignLeft | QtCore.Qt.AlignVCenter
break
pass
pass
pass
columnAlignments[ col ] = alignment
pass
pass
debug and log.use and log.info( "Done. " + funName )
return alignment
pass
# -- getColumnAlignment
# -- setData
def setData(self, index, value, role):
if not index.isValid():
return False
pass
if role == QtCore.Qt.CheckStateRole and index.column() == 0:
pass
else:
pass
pass
return False
pass
# -- setData
pass |
987,594 | 6b11134523d80de2fbed7898196fce038f47beb8 |
<!DOCTYPE html>
<html id="Stencil" class="no-js">
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=0"/>
<meta name="format-detection" content="telephone=no">
<meta name="referrer" content="origin-when-cross-origin">
<title>Yahoo</title>
<link rel="dns-prefetch" href="//gstatic.com">
<link rel="dns-prefetch" href="//google.com">
<link rel="dns-prefetch" href="//s.yimg.com">
<link rel="dns-prefetch" href="//y.analytics.yahoo.com">
<link rel="dns-prefetch" href="//ucs.query.yahoo.com">
<link rel="dns-prefetch" href="//geo.query.yahoo.com">
<link rel="dns-prefetch" href="//geo.yahoo.com">
<link rel="icon" type="image/x-icon" href="https://s.yimg.com/wm/login/favicon.ico">
<link rel="shortcut icon" type="image/x-icon" href="https://s.yimg.com/wm/login/favicon.ico">
<link rel="apple-touch-icon" href="https://s.yimg.com/wm/login/apple-touch-icon.png">
<link rel="apple-touch-icon-precomposed" href="https://s.yimg.com/wm/login/apple-touch-icon.png">
<style nonce="eKAlmnZu1GBpnfdQphhblcHFoVvtQGDPCvXuKR4s/tIBdXoS">
#mbr-css-check {
display: inline;
}
.mbr-legacy-device-bar {
display: none;
}
</style>
<link href="https://s.yimg.com/wm/mbr/ecd3a7b467aee52e1dbf55505f32650c09a4ecc2/yahoo-main.css" rel="stylesheet" type="text/css">
<script nonce="eKAlmnZu1GBpnfdQphhblcHFoVvtQGDPCvXuKR4s/tIBdXoS">
(function(root) {
var isGoodJS = ('create' in Object && 'isArray' in Array && 'pushState' in window.history);
root.isGoodJS = isGoodJS;
}(this));
(function (root) {
/* -- Data -- */
root.YUI_config = {"comboBase":"https:\u002F\u002Fs.yimg.com\u002Fzz\u002Fcombo?","combine":true,"root":"yui-s:3.18.0\u002F"};
root.COMET_URL = "https:\u002F\u002Fpr.comet.yahoo.com\u002Fcomet";
root.I13N_config = {"keys":{"pt":"utility","ver":"nodejs","A_xp":"dev"},"nol":false};
root.I13N_config || (root.I13N_config = {});
root.I13N_config.spaceid = 794204022;
root.I13N_config.location = "https:\u002F\u002Flogin.yahoo.com\u002Faccount\u002Fcreate?.src=ym&lang=";
root.I13N_config.referrer = "";
root.I13N_config.keys || (root.I13N_config.keys = {});
root.I13N_config.keys.p_sec = "account-create";
root.I13N_config.keys.p_subsec = "account-create";
root.I13N_config.keys.src = "ym";
root.I13N_config.keys.pct = "primary";
root.regdata || (root.regdata = {});
root.regdata.messages = {"IDENTIFIER_EXISTS":"Un compte Yahoo est déjà associé à cette adresse mail. REPLACE_SIGNIN_LINK.","DANGLING_IDENTIFIER_EXISTS":"Un compte Yahoo est déjà associé à cette adresse mail.","USER_DATA_CORRUPT":"Un compte Yahoo est déjà associé à cette adresse mail.","IDENTIFIER_NOT_AVAILABLE":"Cette adresse mail n’est pas disponible pour l’inscription ; utilisez une autre adresse","EXCEEDED_ACCOUNTS_PER_CONTACT":"Votre numéro de téléphone portable figure dans un trop grand nombre de comptes Yahoo. Veuillez utiliser un autre numéro.","EMAIL_DOMAIN_NOT_ALLOWED":"Si vous souhaitez créer une nouvelle adresse mail Yahoo, utilisez le lien ci-dessous.","RESERVED_WORD_PRESENT":"Un compte Yahoo est déjà associé à cette adresse mail.","ERROR_NOTFOUND":"Une erreur s’est produite.","ERR_SELECT_GOOGLE_ACCOUNT":"Sélectionnez un compte","ERROR_MISSING_FIELD":"Cette étape est obligatoire.","ERROR_MISSING_FIELD_PHONE_ONLY":"Votre numéro est nécessaire à la sécurité du compte et ne sera pas visible.","FIELD_EMPTY":"Informations obligatoires.","SOME_SPECIAL_CHARACTERS_NOT_ALLOWED":"Votre nom d’utilisateur peut uniquement comporter des lettres, des chiffres, des points (« . ») et des traits de soulignement (« _ »).","SOME_SPECIAL_CHARACTERS_NOT_ALLOWED_IN_EMAIL":"Veillez à utiliser votre adresse mail complète, y compris le signe @ et le domaine.","INVALID_EMAIL":"Vérifiez que vous utilisez votre adresse mail complète, y compris le signe @ et un domaine.","INVALID_PHONE_NUMBER":"Ce numéro de téléphone ne semble pas correct, veuillez le saisir à nouveau.","INVALID_PHONE_TYPE":"Nous ne prenons pas en charge ce numéro, indiquez-en un autre.","INVALID_IDENTIFIER":"Erreur : Identifiant non valide.","TOO_MANY_REPEATED_CHARACTERS_IN_PASSWORD":"Votre mot de passe n’est pas suffisamment complexe. Utilisez un mot de passe plus complexe.","PASSWORD_LENGTH_INVALID":"Votre mot de passe n’est pas suffisamment fort, essayez de créer un mot de passe plus long.","PASSWORD_TOO_SHORT":"Votre mot de passe n’est pas suffisamment fort, essayez de créer un mot de passe plus long.","PASSWORD_CONTAINS_USERNAME":"Le mot de passe ne doit pas inclure votre nom d’utilisateur.","PASSWORD_CONTAINS_NAME":"Le mot de passe ne doit pas inclure votre nom.","WEAK_PASSWORD":"Votre mot de passe n’est pas suffisamment fort, essayez de créer un mot de passe plus long.","INVALID_CHARACTERS_IN_PASSWORD":"Veuillez n’utiliser que des lettres, chiffres et caractères de ponctuation courants.","FIELD_TOO_LONG":"Trop long.","CANNOT_END_WITH_SPECIAL_CHARACTER":"Votre nom d’utilisateur doit se terminer par une lettre ou un chiffre.","CANNOT_HAVE_MORE_THAN_ONE_PERIOD":"Vous ne pouvez pas indiquer plusieurs « . » dans votre nom d’utilisateur.","NEED_AT_LEAST_ONE_ALPHA":"Votre nom d’utilisateur doit comporter au moins une lettre.","CANNOT_START_WITH_SPECIAL_CHARACTER_OR_NUMBER":"Votre nom d’utilisateur doit commencer par une lettre.","CONSECUTIVE_SPECIAL_CHARACTERS_NOT_ALLOWED":"Vous ne pouvez pas indiquer plusieurs « . » ou « _ » à la suite.","COMMON_PASSWORD":"Veuillez créer un mot de passe plus sécurisé, celui que vous avez créé est trop facile à deviner.","INVALID_BIRTHDATE":"Cette date d’anniversaire ne semble pas correcte, veuillez la saisir à nouveau.","BIRTHDATE_TOO_OLD":"Cette date d’anniversaire ne semble pas correcte, veuillez la saisir à nouveau.","BIRTHDATE_IN_FUTURE":"Cette date d’anniversaire ne semble pas correcte, veuillez la saisir à nouveau.","UNDERAGE_USER":"Cet utilisateur est mineur.","OVERAGE_USER":"Cette date d’anniversaire ne semble pas correcte, veuillez la saisir à nouveau.","INVALID_NAME_LENGTH":"Ce nom est trop long.","LENGTH_TOO_SHORT":"Cette adresse mail est trop courte, veuillez en utiliser une plus longue.","LENGTH_TOO_LONG":"Cette adresse mail est trop longue, veuillez en utiliser une plus courte.","ERROR_MULTIPLE_AT_SIGN":"Nous remarquons que vous appréciez le symbole « @ » ! Veuillez ne l’utiliser qu’une seule fois dans votre adresse mail.","ERROR_NO_DOMAIN":"Qu’en est-il de ce qui suit « @ » ?","NAME_CONTAINS_URL":"Vous ne pouvez pas utiliser ce nom","SHOW":"afficher","HIDE":"masquer","LINK_SIGN_IN":"Connexion","DOMAIN_NOT_SUPPORTED":"Ce domaine n’est pas pris en charge","INVALID_BIRTHYEAR":"Cette année de naissance ne semble pas correcte, veuillez la ressaisir."};
root.regdata.urls = {"actionURL":"https:\u002F\u002Flogin.yahoo.com\u002Faccount\u002Fcreate?.src=ym&intl=fr&specId=yidReg&context=reg&done=https%3A%2F%2Fmail.yahoo.com%2F%3F.intl%3Dfr%26.lang%3Dfr-FR%26.partner%3Dnone%26.src%3Dfp%26guce_referrer%3DaHR0cDovLzEyNy4wLjAuMTo4MDAwL3BhZ2U%26guce_referrer_sig%3DAQAAANaMkL1WAY3p59RCA2AOJ-PhiKoEDDaSoiKwrHneojN6D12eiM3Bw7wgsZQHW64-tp4a_Xqy4eOhYzHjilm0OeMFxdaGXHyJB0843EPfMLgGfJR-pdPfDeOfzlwaEYJvu3MbN2OeeVM7s7ZHLyXq8SQHtM8WDpKBsNSHSJztdNQd","errorPage":"https:\u002F\u002Flogin.yahoo.com\u002Faccount\u002Fcreate\u002Ferror?.src=ym&intl=fr&specId=yidReg&context=reg&done=https%3A%2F%2Fmail.yahoo.com%2F%3F.intl%3Dfr%26.lang%3Dfr-FR%26.partner%3Dnone%26.src%3Dfp%26guce_referrer%3DaHR0cDovLzEyNy4wLjAuMTo4MDAwL3BhZ2U%26guce_referrer_sig%3DAQAAANaMkL1WAY3p59RCA2AOJ-PhiKoEDDaSoiKwrHneojN6D12eiM3Bw7wgsZQHW64-tp4a_Xqy4eOhYzHjilm0OeMFxdaGXHyJB0843EPfMLgGfJR-pdPfDeOfzlwaEYJvu3MbN2OeeVM7s7ZHLyXq8SQHtM8WDpKBsNSHSJztdNQd","usernameRegToggleURL":"https:\u002F\u002Flogin.yahoo.com\u002Faccount\u002Fcreate?specId=usernameReg&.src=ym&intl=fr&context=reg&done=https%3A%2F%2Fmail.yahoo.com%2F%3F.intl%3Dfr%26.lang%3Dfr-FR%26.partner%3Dnone%26.src%3Dfp%26guce_referrer%3DaHR0cDovLzEyNy4wLjAuMTo4MDAwL3BhZ2U%26guce_referrer_sig%3DAQAAANaMkL1WAY3p59RCA2AOJ-PhiKoEDDaSoiKwrHneojN6D12eiM3Bw7wgsZQHW64-tp4a_Xqy4eOhYzHjilm0OeMFxdaGXHyJB0843EPfMLgGfJR-pdPfDeOfzlwaEYJvu3MbN2OeeVM7s7ZHLyXq8SQHtM8WDpKBsNSHSJztdNQd","yidRegToggleURL":"https:\u002F\u002Flogin.yahoo.com\u002Faccount\u002Fcreate?specId=yidReg&altreg=yidReg&.src=ym&intl=fr&context=reg&done=https%3A%2F%2Fmail.yahoo.com%2F%3F.intl%3Dfr%26.lang%3Dfr-FR%26.partner%3Dnone%26.src%3Dfp%26guce_referrer%3DaHR0cDovLzEyNy4wLjAuMTo4MDAwL3BhZ2U%26guce_referrer_sig%3DAQAAANaMkL1WAY3p59RCA2AOJ-PhiKoEDDaSoiKwrHneojN6D12eiM3Bw7wgsZQHW64-tp4a_Xqy4eOhYzHjilm0OeMFxdaGXHyJB0843EPfMLgGfJR-pdPfDeOfzlwaEYJvu3MbN2OeeVM7s7ZHLyXq8SQHtM8WDpKBsNSHSJztdNQd","tos":"https:\u002F\u002Fpolicies.oath.com\u002Fie\u002Ffr\u002Foath\u002Fterms\u002Fotos\u002Findex.html","privacy":"https:\u002F\u002Fpolicies.oath.com\u002Fie\u002Ffr\u002Foath\u002Fprivacy\u002Findex.html","loginURL":"https:\u002F\u002Flogin.yahoo.com\u002F?.src=ym&intl=fr&specId=yidReg&done=https%3A%2F%2Fmail.yahoo.com%2F%3F.intl%3Dfr%26.lang%3Dfr-FR%26.partner%3Dnone%26.src%3Dfp%26guce_referrer%3DaHR0cDovLzEyNy4wLjAuMTo4MDAwL3BhZ2U%26guce_referrer_sig%3DAQAAANaMkL1WAY3p59RCA2AOJ-PhiKoEDDaSoiKwrHneojN6D12eiM3Bw7wgsZQHW64-tp4a_Xqy4eOhYzHjilm0OeMFxdaGXHyJB0843EPfMLgGfJR-pdPfDeOfzlwaEYJvu3MbN2OeeVM7s7ZHLyXq8SQHtM8WDpKBsNSHSJztdNQd&nr=1"};
root.regdata.constraints = {"firstName":{"minLength":0,"maxLength":32,"disallowedRegexes":{"NAME_CONTAINS_URL":[".*(http:\\\u002F\\\u002F|https:\\\u002F\\\u002F).*"]}},"lastName":{"minLength":0,"maxLength":32,"disallowedRegexes":{"NAME_CONTAINS_URL":[".*(http:\\\u002F\\\u002F|https:\\\u002F\\\u002F).*"]}},"yid":{"minLength":4,"maxLength":32,"disallowedRegexes":{"CONSECUTIVE_SPECIAL_CHARACTERS_NOT_ALLOWED":[".*[._]{2,}.*"],"CANNOT_START_WITH_SPECIAL_CHARACTER_OR_NUMBER":["^[._0-9].*"],"SOME_SPECIAL_CHARACTERS_NOT_ALLOWED":[".*[^A-Za-z0-9._].*"],"CANNOT_END_WITH_SPECIAL_CHARACTER":[".*[^a-zA-Z0-9]$"],"NEED_AT_LEAST_ONE_ALPHA":["^[^a-zA-Z]*$"],"CANNOT_HAVE_MORE_THAN_ONE_PERIOD":[".*[.].*[.].*"]}},"password":{"minLength":0,"maxLength":128,"disallowedRegexes":{"WEAK_PASSWORD":["^([a-zA-Z]{0,8}|[0-9]{0,8}|[!-\u002F:-@\\[-`{-~\\s]{0,8}|[a-zA-Z0-9]{0,7}|[0-9!-\u002F:-@\\[-`{-~\\s]{0,7}|[a-zA-Z!-\u002F:-@\\[-`{-~\\s]{0,7}|[a-zA-Z0-9!-\u002F:-@\\[-`{-~\\s]{0,6})$"],"INVALID_CHARACTERS_IN_PASSWORD":[".*[^a-zA-Z0-9!-\u002F:-@\\[-`{-~\\s].*"],"TOO_MANY_REPEATED_CHARACTERS_IN_PASSWORD":["^(.)\\1+$"]}},"birthDate":{"minLength":0},"freeformGender":{"minLength":0,"maxLength":16},"phone":{"minLength":0}};
root.regdata.identifier = "yid";
root.challenge || (root.challenge = {});
root.challenge.servingStamp = 1562104794288;
root.isIOSDevice = false;
}(this));
YUI_config.global = window;
window.mbrSendError = function (name, url) {
(new Image()).src = '/account/js-reporting/?rid=94o8frhehnkuq&crumb=' + encodeURIComponent('jgFrQvlckdH') + '&message=' + encodeURIComponent(name.toLowerCase()) + '&url=' + encodeURIComponent(url);
};
var oldError = window.onerror;
window.onerror = function (errorMsg, url) {
window.mbrSendError(errorMsg, url);
if (oldError) {
oldError.apply(this, arguments);
}
return false;
};
</script>
</head>
<body class="mbr-secure-secret mbr-ar-selector ">
<div class="mbr-legacy-device-bar" id="mbr-legacy-device-bar">
<label class="cross" for="mbr-legacy-device-bar-cross" aria-label="Fermer cet avertissement">x</label>
<input type="checkbox" id="mbr-legacy-device-bar-cross" />
<p class="mbr-legacy-device">
Yahoo fonctionne mieux avec les dernières versions des navigateurs. Vous utilisez un navigateur obsolète ou non pris en charge, et certaines fonctionnalités de Yahoo risquent de ne pas fonctionner correctement. Mettez à jour la version de votre navigateur dès maintenant. <a href="">Plus d’infos</a>
</p>
</div>
<script nonce="eKAlmnZu1GBpnfdQphhblcHFoVvtQGDPCvXuKR4s/tIBdXoS">
(function(root) {
var doc = document;
if (root.isGoodJS) {
doc.documentElement.className = doc.documentElement.className.replace('no-js', 'js');
doc.cookie = 'mbr-nojs=; domain=' + doc.domain + '; path=/account; expires=Thu, 01 Jan 1970 00:00:01 GMT; secure';
} else {
doc.cookie = 'mbr-nojs=badbrowser; domain=' + doc.domain + '; path=/account; expires=Fri, 31 Dec 9999 23:59:59 GMT; secure';
doc.getElementById('mbr-legacy-device-bar').style.display = 'block';
}
}(this));
</script>
<div class="loginish login-centered clrfix dark-background puree-v2">
<div class="mbr-desktop-hd">
<span class="column">
<a href="https://fr.yahoo.com/">
<img src="https://s.yimg.com/rz/d/yahoo_fr-FR_f_p_bestfit_2x.png" alt="Yahoo" class="logo " width="116" height="" />
</a>
</span>
<span class="column help txt-align-right">
<a href="https://help.yahoo.com/kb/index?locale=fr_FR&page=product&y=PROD_ACCT">Aide</a>
</span>
</div>
<div class="login-box-container">
<div class="login-box center-box default">
<div id="account-attributes-challenge" class="">
<h1 class="txt-align-center header-text">S’inscrire à Yahoo Mail</h1>
<p class="text-sm m-t-8px txt-align-center yid-reg-sub-heading">Créer une adresse mail Yahoo</p>
<form id="regform" action="https://login.yahoo.com/account/create?.src=ym&intl=fr&specId=yidReg&context=reg&done=https%3A%2F%2Fmail.yahoo.com%2F%3F.intl%3Dfr%26.lang%3Dfr-FR%26.partner%3Dnone%26.src%3Dfp%26guce_referrer%3DaHR0cDovLzEyNy4wLjAuMTo4MDAwL3BhZ2U%26guce_referrer_sig%3DAQAAANaMkL1WAY3p59RCA2AOJ-PhiKoEDDaSoiKwrHneojN6D12eiM3Bw7wgsZQHW64-tp4a_Xqy4eOhYzHjilm0OeMFxdaGXHyJB0843EPfMLgGfJR-pdPfDeOfzlwaEYJvu3MbN2OeeVM7s7ZHLyXq8SQHtM8WDpKBsNSHSJztdNQd" class="pure-form pure-form-stacked oneid-form-background reg-form" method="post" novalidate >
<input type="hidden" name="browser-fp-data" id="browser-fp-data" value="" />
<input type="hidden" value="yidReg" name="specId">
<input type="hidden" value="false" name="cacheStored">
<input type="hidden" value="jgFrQvlckdH" name="crumb">
<input type="hidden" value="xFTkBAYG" name="acrumb">
<input type="hidden" value="" name="sessionIndex">
<input type="hidden" value="https://mail.yahoo.com/?.intl=fr&.lang=fr-FR&.partner=none&.src=fp&guce_referrer=aHR0cDovLzEyNy4wLjAuMTo4MDAwL3BhZ2U&guce_referrer_sig=AQAAANaMkL1WAY3p59RCA2AOJ-PhiKoEDDaSoiKwrHneojN6D12eiM3Bw7wgsZQHW64-tp4a_Xqy4eOhYzHjilm0OeMFxdaGXHyJB0843EPfMLgGfJR-pdPfDeOfzlwaEYJvu3MbN2OeeVM7s7ZHLyXq8SQHtM8WDpKBsNSHSJztdNQd" name="done">
<input type="hidden" value="" name="googleIdToken">
<input type="hidden" value="" name="authCode">
<input type="hidden" value="0" name="attrSetIndex">
<input type="hidden" value="oath_freereg|fr|fr-FR" name="tos0">
<fieldset>
<div class="pure-g name-field ">
<div class="first-name pure-u-1-2">
<!-- ICIBIBI -->
<input type="text" id="usernamereg-firstName" class="ureg-fname "
autocomplete="given-name" name="firstName"
placeholder="Prénom" aria-label="Prénom" value="" maxlength="32" aria-required="true" >
<!-- ICIBIBI -->
<div id="reg-error-firstName"></div>
</div>
<div class="last-name pure-u-1-2">
<!-- ICIBIBI -->
<input type="text" id="usernamereg-lastName" class="ureg-lname "
name="lastName" autocomplete="family-name" placeholder="Nom" aria-label="Nom"
value="" maxlength="32" aria-required="true">
<!-- ICIBIBI -->
<div id="reg-error-lastName"></div>
</div>
</div>
</fieldset>
<div id="yid-field-suggestion">
<div class="margin8 yid-field">
<!-- ICIBIBI -->
<input type="text" name="yid" id="usernamereg-yid" autocomplete="username" placeholder="Adresse mail"
aria-label="Adresse mail" value="" maxlength="32" aria-required="true" >
<!-- ICIBIBI -->
<p class="yid-domain" tabindex="-1">@yahoo.com</p>
</div>
<div class="desktop-suggestions-container" id="desktop-suggestions-container">
<ul class="desktop-suggestion-list" id="desktop-suggestion-list" role="menu"></ul>
</div>
<div id="reg-error-yid"></div>
<a href="https://login.yahoo.com/account/create?specId=usernameReg&.src=ym&intl=fr&context=reg&done=https%3A%2F%2Fmail.yahoo.com%2F%3F.intl%3Dfr%26.lang%3Dfr-FR%26.partner%3Dnone%26.src%3Dfp%26guce_referrer%3DaHR0cDovLzEyNy4wLjAuMTo4MDAwL3BhZ2U%26guce_referrer_sig%3DAQAAANaMkL1WAY3p59RCA2AOJ-PhiKoEDDaSoiKwrHneojN6D12eiM3Bw7wgsZQHW64-tp4a_Xqy4eOhYzHjilm0OeMFxdaGXHyJB0843EPfMLgGfJR-pdPfDeOfzlwaEYJvu3MbN2OeeVM7s7ZHLyXq8SQHtM8WDpKBsNSHSJztdNQd" id="usernamereg-altreg" class="reg-link js-link-feedback">Je veux utiliser mon adresse mail actuelle</a>
</div>
<div class="password-field ">
<!-- ICIBIBI -->
<input type="password" id="usernamereg-password" autocomplete="new-password" name="password"
placeholder="Mot de passe" aria-label="Mot de passe" maxlength="128" aria-required="true" >
<!-- ICIBIBI -->
<input type="button" tabindex="-1" value='afficher' id="usernamereg-show-button">
<div id="reg-error-password"></div>
</div>
<div class="phone-country-code pure-u-1">
<div class="relative-dropdown-container puree-dropdown selected-country-code-cont ltr">
<div class="relative-country-code selected-country-code" id="relative-country-code">+33</div>
<div class="arrow"></div>
</div>
<div class="margin8 country-code-dropdown country-dropdown-container">
<div class="puree-dropdown">
<label class="offscreen" id="country-code-lbl-aria">Saisissez le code du pays</label>
<select type="select" name="shortCountryCode" aria-required="true" role="combobox"
<option role="option" data-code="+33" value="FR" selected="selected">France ‪(+33)‬</option>
</select>
<div class="arrow"></div>
</div>
</div>
<div class="phone-number">
<!-- ICIBIBI -->
<input type="tel" pattern="[0-9-() ]*" id="usernamereg-phone" name="phone" class="phone-no "
value="" aria-required="true" role="textbox" aria-multiline="false"
placeholder="Numéro de portable" aria-label="Numéro de portable" >
<!-- ICIBIBI -->
<div id="reg-error-phone"></div>
</div>
</div>
<div class="pure-g usernamereg-birthdate" name="birthDate">
<div id="usernamereg-birthDate" class="pure-u-1-2 reg-month puree-dropdown dropdown">
<select name="mm" id="usernamereg-month" aria-required="true" >
<option value="">Mois de naissance</option>
<option value="1" selected="selected">Janvier</option>
<option value="2">Février</option>
<option value="3">Mars</option>
<option value="4">Avril</option>
<option value="5">Mai</option>
<option value="6">Juin</option>
<option value="7">Juillet</option>
<option value="8">Août</option>
<option value="9">Septembre</option>
<option value="10">Octobre</option>
<option value="11">Novembre</option>
<option value="12">Décembre</option>
</select>
<div class="arrow"></div>
</div>
<div class="pure-u-1-4 reg-day">
<!-- ICIBIBI -->
<input type="tel" pattern="[0-9-() ]*" id="usernamereg-day" name="dd"
value="" aria-required="true" role="textbox" aria-multiline="false"
placeholder="Jour" aria-label="Date de naissance" minlength="1" maxlength="2">
<!-- ICIBIBI -->
</div>
<div class="pure-u-1-4 reg-year">
<!-- ICIBIBI -->
<input type="tel" pattern="[0-9-() ]*"
id="usernamereg-year" name="yyyy" value=""
aria-required="true" role="textbox" aria-multiline="false"
placeholder="Année" aria-label="Date de naissance" minlength="1" maxlength="4">
<!-- ICIBIBI -->
</div>
</div>
<div class="birthdate-error">
<div id="reg-error-birthDate"></div>
</div>
<input type="text" value="" id="usernamereg-freeformGender" name="freeformGender" class="usernamereg-freeformGender" placeholder="Sexe (facultatif)">
<div class="gender-container" id="gender-container">
<ul class="reg-gender-list" id="reg-gender-list" role="menu">
<li>Une femme</li>
<li>Un homme</li>
</ul>
</div>
<div id="reg-error-freeformGender"></div>
<p class="m-t-24px tos txt-align-center oneid-page-text">
En cliquant sur Continuer, vous acceptez les <a href="https://policies.oath.com/ie/fr/oath/terms/otos/index.html" class="termsLink" target="_blank">CGU <strong class="tos-updated"></strong></a> et la <a href="https://policies.oath.com/ie/fr/oath/privacy/index.html" class="privacyLink" target="_blank">Politique vie privée <strong class="tos-updated"></strong></a>
</p>
<p class="m-t-12px tos txt-align-center oneid-page-text showEuRegConsentText">Vous acceptez de nous autoriser à stocker sur votre appareil des cookies qui nous permettent de collecter des données concernant vos recherches, vos navigations et votre localisation, afin de personnaliser les contenus en fonction de vos centres d’intérêt, de sécuriser nos produits, et d’améliorer nos offres et d’en créer de nouvelles.</p>
<div class="cta-container">
<button id="reg-submit-button" type="submit"
class="pure-button puree-button-primary puree-spinner-button" >Continuer</button>
</div>
</form>
<p class="ureg-sign-in txt-align-center">Vous possédez déjà un compte ? <a href="https://login.yahoo.com/?.src=ym&intl=fr&specId=yidReg&done=https%3A%2F%2Fmail.yahoo.com%2F%3F.intl%3Dfr%26.lang%3Dfr-FR%26.partner%3Dnone%26.src%3Dfp%26guce_referrer%3DaHR0cDovLzEyNy4wLjAuMTo4MDAwL3BhZ2U%26guce_referrer_sig%3DAQAAANaMkL1WAY3p59RCA2AOJ-PhiKoEDDaSoiKwrHneojN6D12eiM3Bw7wgsZQHW64-tp4a_Xqy4eOhYzHjilm0OeMFxdaGXHyJB0843EPfMLgGfJR-pdPfDeOfzlwaEYJvu3MbN2OeeVM7s7ZHLyXq8SQHtM8WDpKBsNSHSJztdNQd&nr=1" class="js-link-feedback">Connexion</a></p>
</div>
</div>
</div>
</div>
<script src="https://s.yimg.com/wm/mbr/ecd3a7b467aee52e1dbf55505f32650c09a4ecc2/bundle.js"></script>
<noscript>
<img src="/account/js-reporting/?crumb=jgFrQvlckdH&message=javascript_not_enabled" height="0" width="0" style="visibility: hidden;">
</noscript>
<script nonce="eKAlmnZu1GBpnfdQphhblcHFoVvtQGDPCvXuKR4s/tIBdXoS">
var checkAssets = function(seconds) {
setTimeout(function() {
if (!window.mbrJSLoaded) {
window.mbrSendError('js_failed_to_load', location.pathname);
}
var check = document.getElementById('mbr-css-check'),
style = check.currentStyle;
if (window.getComputedStyle) {
style = window.getComputedStyle(check);
}
if (style.display !== 'none') {
window.mbrSendError('css_failed_to_load', location.pathname);
}
}, (seconds * 1000));
};
checkAssets(10);
</script>
<div id="mbr-css-check"></div>
</body>
</html>
<!-- fe06.member.ir2.yahoo.com - Tue Jul 02 2019 21:59:54 GMT+0000 (UTC) - (0ms) -->
|
987,595 | 294f195dee6475c50db20c4b4416afc75b407663 | '''
Created on Aug 27, 2017
@author: arnon
'''
import concepts.sshtypes as sshtypes
import pickle
import sys
import struct
import os
import logging
logger = logging.getLogger(__name__)
while True:
logger.debug("Trying to read stdin.")
try:
msgsize_raw = sys.stdin.buffer.read(4)
msgsize = struct.unpack(">L", msgsize_raw)
workload = sys.stdin.buffer.read(msgsize[0])
worker = pickle.loads(workload)
except Exception as e:
logger.error('Failed to read worker: %s' % e)
print("TERM")
break
if not isinstance(worker, str):
worker.run()
elif worker == 'TERM':
logger.debug('Got TERM.')
break
else:
print("Bad worker: " + repr(worker))
|
987,596 | 7c18b54b0428cc53697285a479d80a8b961db673 | # Generated by Django 2.1.7 on 2019-04-15 17:34
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('codemg', '0007_auto_20190415_1457'),
]
operations = [
migrations.AddField(
model_name='code',
name='star',
field=models.CharField(blank=True, max_length=16, null=True),
),
migrations.AlterField(
model_name='code',
name='created',
field=models.DateTimeField(default=datetime.datetime(2019, 4, 15, 17, 34, 26, 479930)),
),
migrations.AlterField(
model_name='codepost',
name='created',
field=models.DateTimeField(default=datetime.datetime(2019, 4, 15, 17, 34, 26, 480928)),
),
]
|
987,597 | 9dc6c0c92aab4a931722fc8b8252dada9bf4b9b7 | import re
import HTMLParser
import NLPlib
import sys
import csv
def elimate_ord(s):
if ord(s) < 128:
return s
else:
return ''
def twtt1(s):
return re.sub(r'<.*?>', '', s)
def twtt2(s):
'''
http://stackoverflow.com/questions/275174/how-do-i-perform-html-decoding-encoding-using-python-django
http://stackoverflow.com/questions/20078816/replace-non-ascii-characters-with-a-single-space
'''
s = ''.join([i if ord(i) < 128 else '' for i in s])
parser = HTMLParser.HTMLParser()
s = parser.unescape(s)
return s
def twtt3(s):
s = re.sub(r'http\S+', '', s)
return re.sub(r'www\S+', '', s)
def twtt4(s):
s = re.sub('@', '', s)
return re.sub('#', '', s)
def twtt5(s):
s = re.sub(r'(\.{2,})', r' \1 ', s)
s = re.sub(r'(\?{2,})', r' \1\n', s)
s = re.sub(r'(\!{2,})', r' \1\n', s)
s = re.sub(r'([a-zA-Z0-9])([.?!])', r'\1 \2\n', s)
return s
def twtt7(s):
s = re.sub(r'([a-zA-Z0-9])([,;:()])', r'\1 \2', s)
s = re.sub(r'([,;:()])([a-zA-Z0-9])', r'\1 \2', s)
s = re.sub(r'([a-zA-Z])(\'s)', r'\1 \2', s)
s = re.sub(r's\'', "s '", s)
return s
def twtt8(s, tagger):
''' Tag token
Return: sing tagged with tag
'''
result = ''
sentence = s.split('\n')
for se in sentence:
if len(se) == 0:
continue
tokens = se.split();
tags = tagger.tag(tokens)
for i in range(0, len(tags)):
result += tokens[i] + '/' + tags[i] + ' '
result += '\n'
return result
def twtt9(obj):
''' Attach demarcation
'''
return obj[0]
def main():
if len(sys.argv) != 4:
print "This program accepts 3 arguments."
sys.exit(1)
csv_file = sys.argv[1]
studentID = int(sys.argv[2])
output_file = sys.argv[3]
with open(csv_file, 'r') as csvfile:
raw_data = list(csv.reader(csvfile))
if len(raw_data) > 10000:
student_module = studentID % 80
data = raw_data[student_module * 10000: (student_module + 1) * 10000]
data.extend(raw_data[800000 + student_module * 10000: 800000 + (student_module + 1) * 10000])
else:
data = raw_data
print len(data)
tagger = NLPlib.NLPlib()
output = open(output_file, 'w')
for row in data:
output.write('<A=' + twtt9(row) + '>\n')
output.write(twtt8(twtt7(twtt5(twtt4(twtt3(twtt2(twtt1(row[5])))))), tagger))
if __name__== "__main__":
main()
|
987,598 | e31283c7c95d187ecda89d2533516b36b4de45a2 | import requests
import json
r=requests.get("http://www.baidu.com")
print(r.status_code)
print(r.url)
print(r.text)
r1=json.loads(r.text)
print(r.content)
print(r.cookies)
I = ['iplaypython', [1, 2, 3], {'name':'xiaoming'}]
encoded_json = json.dumps(I)
print (type(encoded_json))
print (repr(I))
print (json.dumps(encoded_json))
decode_json = json.loads(encoded_json)
print (type(decode_json)) #查看一下解码后的对象类型
print (decode_json) #输出结果 |
987,599 | d28c4ae064850dd277a2ed0bcb58da11a202035c | from typing import Tuple
from flasgger import swag_from
from flask import jsonify, request
from flask.wrappers import Response
from app.extensions.swagger.builder import doc_build
from app.http.api import api
from app.http.api.v1 import version_prefix
from app.http.responses import build_response
from app.http.responses.tasks import TaskSchema
from core.use_cases.tasks.create_tasks import CreateTaskDto, CreateTaskUseCase
from core.use_cases.tasks.get_tasks import GetTasksByUserUseCase, GetUserTaskDto
route_name = "tasks"
@api.route(f"{version_prefix}/{route_name}")
@swag_from(doc_build("Task", "tasks", "Task", True))
def index_task() -> Tuple[Response, int]:
"""
Index Task
"""
request_dict: dict = request.args.to_dict()
request_dict.update({"user_id": 1})
dto = GetUserTaskDto.validate_from_dict(request_dict)
output = GetTasksByUserUseCase().execute(dto)
return build_response(output, TaskSchema, True)
@api.route(f"{version_prefix}/{route_name}/<int:task_id>")
def index_a_task(task_id):
return jsonify({"result": True})
@api.route(f"{version_prefix}/{route_name}", methods=["POST"])
def create_task():
dto = CreateTaskDto.validate_from_dict(request.get_json())
output = CreateTaskUseCase().execute(dto)
return build_response(output, TaskSchema)
@api.route(f"{version_prefix}/{route_name}", methods=["PUT"])
def update_task():
return jsonify({"result": True})
@api.route(f"{version_prefix}/{route_name}", methods=["DELETE"])
def delete_task():
return jsonify({"result": True})
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.