blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
616
content_id
stringlengths
40
40
detected_licenses
listlengths
0
112
license_type
stringclasses
2 values
repo_name
stringlengths
5
115
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
777 values
visit_date
timestamp[us]date
2015-08-06 10:31:46
2023-09-06 10:44:38
revision_date
timestamp[us]date
1970-01-01 02:38:32
2037-05-03 13:00:00
committer_date
timestamp[us]date
1970-01-01 02:38:32
2023-09-06 01:08:06
github_id
int64
4.92k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]date
2012-06-04 01:52:49
2023-09-14 21:59:50
gha_created_at
timestamp[us]date
2008-05-22 07:58:19
2023-08-21 12:35:19
gha_language
stringclasses
149 values
src_encoding
stringclasses
26 values
language
stringclasses
1 value
is_vendor
bool
2 classes
is_generated
bool
2 classes
length_bytes
int64
3
10.2M
extension
stringclasses
188 values
content
stringlengths
3
10.2M
authors
listlengths
1
1
author_id
stringlengths
1
132
d76c7ac7230899afca2ec03da09f81a9ab6d1f03
b7939b343e52d2633857a93e19108dde49109008
/setup_finish.py
3bd9921ead93001611ff878fb4301620787d7fd6
[]
no_license
hobson/safety-monitor
040e74e0ac6d153b084860b3cdd6d9739fd0c10e
122b09bc7f55302cdd5fda576358b56dcd8ee03e
refs/heads/master
2021-01-22T05:28:23.350603
2012-04-15T04:45:09
2012-04-15T04:45:09
null
0
0
null
null
null
null
UTF-8
Python
false
false
500
py
import os import glob dist_dir = 'dist' files = ['C:/Python25/lib/site-packages/wx-2.8-msw-ansi/wx/MSVCP71.dll', 'C:/Python25/lib/site-packages/wx-2.8-msw-ansi/wx/gdiplus.dll', './rev20.log', 'images'] for f in files: os.system("cp -r "+f+" "+dist_dir+"/") os.system("rm -r "+dist_dir+"/images/.svn") os.system("rm -r "+dist_dir+"/images/Thumbs.db") #os.system("gzip -r -S .zip -9 "+dist_dir) os.system("7z a -tzip -mx=9 "+dist_dir+".zip "+dist_dir)
[ "hobsonlane@gmail.com" ]
hobsonlane@gmail.com
a1c2632983e12ba8f5a00201653014204fb6181f
14a853584c0c1c703ffd8176889395e51c25f428
/sem1/fop/lab9/static/strings.py
5a11cfaee8f14accb2823f0183f03c5641998655
[]
no_license
harababurel/homework
d0128f76adddbb29ac3d805c235cdedc9af0de71
16919f3b144de2d170cd6683d54b54bb95c82df9
refs/heads/master
2020-05-21T12:25:29.248857
2018-06-03T12:04:45
2018-06-03T12:04:45
43,573,199
6
4
null
null
null
null
UTF-8
Python
false
false
886
py
""" Most long messages displayed by the UI will be found here. """ from util.Color import * STRINGS = { 'helpPrompt': 'Commands:\n' + '\t%s - displays this prompt.\n' % Color.strong('help') + '\t%s - adds a new student or assignment.\n' % Color.strong('add') + '\t%s - removes an existing student or assignment.\n' % Color.strong('remove') + '\t%s - displays all students or assignments.\n' % Color.strong('list') + '\t%s - goes to previous state.\n' % Color.strong('undo') + '\t%s - goes to next state.\n' % Color.strong('redo') + '\t%s - displays statistics.\n' % Color.strong('stats') + '\t%s - clears the screen.\n' % Color.strong('clear') + '\t%s - saves the work session and exits the application.' % Color.strong('exit') }
[ "srg.pscs@gmail.com" ]
srg.pscs@gmail.com
664537e820a66d7f15136e41787f159ac3ab7b86
ba80ca143ba35fd481730786a27ebdb1f88ce835
/algorithm/f/test/RomanNumerals.py
50f14a15f212f49ed60fcc34487da6bd4748ab19
[]
no_license
uiandwe/TIL
c541020b65adc53578aeb1c3ba4c6770b3b2e8b3
186544469374dd0279099c6c6aa7555ee23e42fe
refs/heads/master
2022-02-15T08:33:07.270573
2022-01-01T15:22:54
2022-01-01T15:22:54
63,420,931
2
4
null
null
null
null
UTF-8
Python
false
false
728
py
''' I(1), V(5), X(10), L(50), C(100), D(500), M(1000) 1 -> I 2 -> II 3 -> III 4 -> IV 7 -> VII 10 -> X 39 -> XXXIX 246 -> CCXLVI 207 -> CCVII 1066 -> MLXVI 1776 -> MDCCLXXVI 1954 -> MCMLIV ''' def roman(n): dict = { 1000: 'M', 900: 'CM', 500: 'D', 400: 'CD', 100: 'C', 90: 'XC', 50: 'L', 40: 'XL', 10: 'X', 9: 'IX', 5: 'V', 4: 'IV', 1: 'I' } retStr = '' keys = list(dict.keys()) values = list(dict.values()) while n > 0: for index, key in enumerate(keys): if n >= key: retStr += values[index] n -= key break return retStr
[ "noreply@github.com" ]
uiandwe.noreply@github.com
c292451580a6c057267d586c1da1f9416fa0cefc
882cc558e786a82f3c0f11d3b332b2c26c59e8d0
/funker/handle.py
0d0870e0e8a539cfdf27e1bc1354498910403167
[ "Apache-2.0" ]
permissive
bfirsh/funker-python
79fbff296a909cf58ae8817ab42c6f8df1432122
e7e4f598a6ec2b0c14adde2f49af89aa88ec4dea
refs/heads/master
2020-06-21T18:53:11.309645
2016-11-29T16:13:35
2016-11-29T16:13:35
74,773,577
9
2
null
2017-01-29T17:23:46
2016-11-25T16:31:02
Python
UTF-8
Python
false
false
658
py
import json import six from six.moves import socketserver class HandleHandler(socketserver.StreamRequestHandler): def handle(self): kwargs = json.loads(six.text_type(self.rfile.read(), "utf-8")) return_value = self.server.func(**kwargs) return_str = json.dumps(return_value) self.wfile.write(return_str.encode("utf-8")) self.wfile.close() def handle(func): server = socketserver.TCPServer(("0.0.0.0", 9999), HandleHandler) server.request_queue_size = 1 # drop any connections except from the first server.timeout = None server.func = func server.handle_request() server.server_close()
[ "ben@firshman.co.uk" ]
ben@firshman.co.uk
55ffce84c42c62bceb73afa45c1838869dcec02b
2fa102b20ea99d796cc3677c9305f1a80be18e6b
/cf_1154_A.py
4edb3e6632103f67e9975c1130ae3888571ab9c4
[]
no_license
pronob1010/Codeforces_Solve
e5186b2379230790459328964d291f6b40a4bb07
457b92879a04f30aa0003626ead865b0583edeb2
refs/heads/master
2023-03-12T11:38:31.114189
2021-03-03T05:49:17
2021-03-03T05:49:17
302,124,730
3
0
null
null
null
null
UTF-8
Python
false
false
140
py
s = list(map(int, input().split())) s.sort() apb=s[0] apc = s[1] bpc = s[2] apbpc = s[3] c = apbpc - apb b = bpc - c a = apb-b print(a,b,c)
[ "pronobmozumder.info@gmail.com" ]
pronobmozumder.info@gmail.com
3147f1152d915a56edd4b17322b801527d96c1ea
ed0dd577f03a804cdc274f6c7558fafaac574dff
/python/pyre/applications/Executive.py
3205a28c66169bb035d90b03ef2457a2a234159b
[ "Apache-2.0" ]
permissive
leandromoreira/vmaf
fd26e2859136126ecc8e9feeebe38a51d14db3de
a4cf599444701ea168f966162194f608b4e68697
refs/heads/master
2021-01-19T03:43:15.677322
2016-10-08T18:02:22
2016-10-08T18:02:22
70,248,500
3
0
null
2016-10-07T13:21:28
2016-10-07T13:21:27
null
UTF-8
Python
false
false
2,919
py
#!/usr/bin/env python # # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # # Michael A.G. Aivazis # California Institute of Technology # (C) 1998-2005 All Rights Reserved # # {LicenseText} # # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # class Executive(object): # factories def createCommandlineParser(self): """create a command line parser""" import pyre.applications return pyre.applications.commandlineParser() def createRegistry(self, name=None): """create a registry instance to store my configuration""" if name is None: name = self.name import pyre.inventory return pyre.inventory.registry(name) def createCurator(self, name=None): """create a curator to handle the persistent store""" if name is None: name = self.name import pyre.inventory curator = pyre.inventory.curator(name) return curator # configuration def processCommandline(self, registry, parser=None): """convert the command line arguments to a trait registry""" if parser is None: parser = self.createCommandlineParser() help, unprocessedArguments = parser.parse(registry) return help, unprocessedArguments def verifyConfiguration(self, unknownProperties, unknownComponents, mode='strict'): """verify that the user input did not contain any typos""" if mode == 'relaxed': return True if unknownProperties: print " ## unrecognized properties:" for key, value, locator in unknownProperties: print " %s <- '%s' from %s" % (key, value, locator) self.usage() return False if mode == 'pedantic' and unknownComponents: print ' ## unknown components: %s' % ", ".join(unknownComponents) self.usage() return False return True def pruneRegistry(self): registry = self.registry for trait in self.inventory.properties(): name = trait.name registry.deleteProperty(name) for trait in self.inventory.components(): for name in trait.aliases: registry.extractNode(name) return registry # the default application action def main(self, *args, **kwds): return # user assistance def help(self): print 'Please consider writing a help screen for this application' return def usage(self): print 'Please consider writing a usage screen for this application' return # version __id__ = "$Id: Executive.py,v 1.1.1.1 2006-11-27 00:09:54 aivazis Exp $" # End of file
[ "zli@netflix.com" ]
zli@netflix.com
027107bfc9df6f0ba6ae047043cc917f2ccf3edb
9d7ae4ba781a06d96fb1f4cc51b42abcc0928da6
/sqlalchemy_utils/listeners.py
29970ffb5b90253f2ab092e7f3c4779177c3cd81
[]
no_license
tonyseek/sqlalchemy-utils
5a4d6d1ebaf1d72af04fce30ff5473210cfdbef3
0ef12b0a070694fb8ef4c177f9816305110114b1
refs/heads/master
2021-01-15T08:47:40.983766
2015-01-14T13:39:04
2015-01-14T13:39:04
29,289,223
1
0
null
2015-01-15T09:03:24
2015-01-15T09:03:24
null
UTF-8
Python
false
false
6,855
py
import sqlalchemy as sa from .exceptions import ImproperlyConfigured def coercion_listener(mapper, class_): """ Auto assigns coercing listener for all class properties which are of coerce capable type. """ for prop in mapper.iterate_properties: try: listener = prop.columns[0].type.coercion_listener except AttributeError: continue sa.event.listen( getattr(class_, prop.key), 'set', listener, retval=True ) def instant_defaults_listener(target, args, kwargs): for key, column in sa.inspect(target.__class__).columns.items(): if column.default is not None: if callable(column.default.arg): setattr(target, key, column.default.arg(target)) else: setattr(target, key, column.default.arg) def force_auto_coercion(mapper=None): """ Function that assigns automatic data type coercion for all classes which are of type of given mapper. The coercion is applied to all coercion capable properties. By default coercion is applied to all SQLAlchemy mappers. Before initializing your models you need to call force_auto_coercion. :: from sqlalchemy_utils import force_auto_coercion force_auto_coercion() Then define your models the usual way:: class Document(Base): __tablename__ = 'document' id = sa.Column(sa.Integer, autoincrement=True) name = sa.Column(sa.Unicode(50)) background_color = sa.Column(ColorType) Now scalar values for coercion capable data types will convert to appropriate value objects:: document = Document() document.background_color = 'F5F5F5' document.background_color # Color object session.commit() :param mapper: The mapper which the automatic data type coercion should be applied to """ if mapper is None: mapper = sa.orm.mapper sa.event.listen(mapper, 'mapper_configured', coercion_listener) def force_instant_defaults(mapper=None): """ Function that assigns object column defaults on object initialization time. By default calling this function applies instant defaults to all your models. Setting up instant defaults:: from sqlalchemy_utils import force_instant_defaults force_instant_defaults() Example usage:: class Document(Base): __tablename__ = 'document' id = sa.Column(sa.Integer, autoincrement=True) name = sa.Column(sa.Unicode(50)) created_at = sa.Column(sa.DateTime, default=datetime.now) document = Document() document.created_at # datetime object :param mapper: The mapper which the automatic instant defaults forcing should be applied to """ if mapper is None: mapper = sa.orm.mapper sa.event.listen(mapper, 'init', instant_defaults_listener) def auto_delete_orphans(attr): """ Delete orphans for given SQLAlchemy model attribute. This function can be used for deleting many-to-many associated orphans easily. For more information see https://bitbucket.org/zzzeek/sqlalchemy/wiki/UsageRecipes/ManyToManyOrphan. Consider the following model definition: :: from sqlalchemy.ext.associationproxy import association_proxy from sqlalchemy import * from sqlalchemy.orm import * from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import event Base = declarative_base() tagging = Table( 'tagging', Base.metadata, Column( 'tag_id', Integer, ForeignKey('tag.id', ondelete='CASCADE'), primary_key=True ), Column( 'entry_id', Integer, ForeignKey('entry.id', ondelete='CASCADE'), primary_key=True ) ) class Tag(Base): __tablename__ = 'tag' id = Column(Integer, primary_key=True) name = Column(String(100), unique=True, nullable=False) def __init__(self, name=None): self.name = name class Entry(Base): __tablename__ = 'entry' id = Column(Integer, primary_key=True) tags = relationship( 'Tag', secondary=tagging, backref='entries' ) Now lets say we want to delete the tags if all their parents get deleted ( all Entry objects get deleted). This can be achieved as follows: :: from sqlalchemy_utils import auto_delete_orphans auto_delete_orphans(Entry.tags) After we've set up this listener we can see it in action. :: e = create_engine('sqlite://') Base.metadata.create_all(e) s = Session(e) r1 = Entry() r2 = Entry() r3 = Entry() t1, t2, t3, t4 = Tag('t1'), Tag('t2'), Tag('t3'), Tag('t4') r1.tags.extend([t1, t2]) r2.tags.extend([t2, t3]) r3.tags.extend([t4]) s.add_all([r1, r2, r3]) assert s.query(Tag).count() == 4 r2.tags.remove(t2) assert s.query(Tag).count() == 4 r1.tags.remove(t2) assert s.query(Tag).count() == 3 r1.tags.remove(t1) assert s.query(Tag).count() == 2 .. versionadded: 0.26.4 :param attr: Association relationship attribute to auto delete orphans from """ parent_class = attr.parent.class_ target_class = attr.property.mapper.class_ backref = attr.property.backref if not backref: raise ImproperlyConfigured( 'The relationship argument given for auto_delete_orphans needs to ' 'have a backref relationship set.' ) @sa.event.listens_for(sa.orm.Session, 'after_flush') def delete_orphan_listener(session, ctx): # Look through Session state to see if we want to emit a DELETE for # orphans orphans_found = ( any( isinstance(obj, parent_class) and sa.orm.attributes.get_history(obj, attr.key).deleted for obj in session.dirty ) or any( isinstance(obj, parent_class) for obj in session.deleted ) ) if orphans_found: # Emit a DELETE for all orphans ( session.query(target_class) .filter( ~getattr(target_class, attr.property.backref).any() ) .delete(synchronize_session=False) )
[ "konsta.vesterinen@gmail.com" ]
konsta.vesterinen@gmail.com
e093a9d168e7b73683ab2dcdbec945c443c0eedf
325fde42058b2b82f8a4020048ff910cfdf737d7
/src/maintenance/azext_maintenance/tests/latest/test_maintenance_scenario.py
aba6a30c11220859b917d2ba8734bfbb18eeef80
[ "LicenseRef-scancode-generic-cla", "MIT" ]
permissive
ebencarek/azure-cli-extensions
46b0d18fe536fe5884b00d7ffa30f54c7d6887d1
42491b284e38f8853712a5af01836f83b04a1aa8
refs/heads/master
2023-04-12T00:28:44.828652
2021-03-30T22:34:13
2021-03-30T22:34:13
261,621,934
2
5
MIT
2020-10-09T18:21:52
2020-05-06T01:25:58
Python
UTF-8
Python
false
false
12,891
py
# -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- import os from azure.cli.testsdk import ScenarioTest from .. import try_manual, raise_if, calc_coverage from azure.cli.testsdk import ResourceGroupPreparer TEST_DIR = os.path.abspath(os.path.join(os.path.abspath(__file__), '..')) @try_manual def setup(test, rg): pass # EXAMPLE: /ApplyUpdates/put/ApplyUpdates_CreateOrUpdate @try_manual def step__applyupdates_put_applyupdates_createorupdate(test, rg): test.cmd('az maintenance applyupdate create ' '--provider-name "Microsoft.Compute" ' '--resource-group "{rg}" ' '--resource-name "smdtest1" ' '--resource-type "virtualMachineScaleSets"', checks=[]) # EXAMPLE: /ApplyUpdates/put/ApplyUpdates_CreateOrUpdateParent @try_manual def step__applyupdates_put_applyupdates_createorupdateparent(test, rg): test.cmd('az maintenance applyupdate create ' '--provider-name "Microsoft.Compute" ' '--resource-group "{rg}" ' '--resource-name "smdvm1" ' '--resource-parent-name "smdtest1" ' '--resource-parent-type "virtualMachineScaleSets" ' '--resource-type "virtualMachines"', checks=[]) # EXAMPLE: /ApplyUpdates/get/ApplyUpdates_Get @try_manual def step__applyupdates_get_applyupdates_get(test, rg): test.cmd('az maintenance applyupdate show ' '--name "{myApplyUpdate}" ' '--provider-name "Microsoft.Compute" ' '--resource-group "{rg}" ' '--resource-name "smdtest1" ' '--resource-type "virtualMachineScaleSets"', checks=[]) # EXAMPLE: /ApplyUpdates/get/ApplyUpdates_GetParent @try_manual def step__applyupdates_get_applyupdates_getparent(test, rg): test.cmd('az maintenance applyupdate get-parent ' '--name "{myApplyUpdate}" ' '--provider-name "Microsoft.Compute" ' '--resource-group "{rg}" ' '--resource-name "smdvm1" ' '--resource-parent-name "smdtest1" ' '--resource-parent-type "virtualMachineScaleSets" ' '--resource-type "virtualMachines"', checks=[]) # EXAMPLE: /MaintenanceConfigurations/put/MaintenanceConfigurations_CreateOrUpdateForResource @try_manual def step__maintenanceconfigurations_put_maintenanceconfigurations_createorupdateforresource(test, rg): test.cmd('az maintenance configuration create ' '--location "westus2" ' '--maintenance-scope "OSImage" ' '--maintenance-window-duration "05:00" ' '--maintenance-window-expiration-date-time "9999-12-31 00:00" ' '--maintenance-window-recur-every "Day" ' '--maintenance-window-start-date-time "2020-04-30 08:00" ' '--maintenance-window-time-zone "Pacific Standard Time" ' '--namespace "Microsoft.Maintenance" ' '--visibility "Custom" ' '--resource-group "{rg}" ' '--resource-name "{myMaintenanceConfiguration2}"', checks=[]) # EXAMPLE: /MaintenanceConfigurations/get/MaintenanceConfigurations_GetForResource @try_manual def step__maintenanceconfigurations_get_maintenanceconfigurations_getforresource(test, rg): test.cmd('az maintenance configuration show ' '--resource-group "{rg}" ' '--resource-name "{myMaintenanceConfiguration2}"', checks=[]) # EXAMPLE: /MaintenanceConfigurations/get/MaintenanceConfigurations_List @try_manual def step__maintenanceconfigurations_get_maintenanceconfigurations_list(test, rg): test.cmd('az maintenance configuration list', checks=[]) # EXAMPLE: /MaintenanceConfigurations/patch/MaintenanceConfigurations_UpdateForResource @try_manual def step__maintenanceconfigurations_patch_maintenanceconfigurations_updateforresource(test, rg): test.cmd('az maintenance configuration update ' '--location "westus2" ' '--maintenance-scope "OSImage" ' '--maintenance-window-duration "05:00" ' '--maintenance-window-expiration-date-time "9999-12-31 00:00" ' '--maintenance-window-recur-every "Month Third Sunday" ' '--maintenance-window-start-date-time "2020-04-30 08:00" ' '--maintenance-window-time-zone "Pacific Standard Time" ' '--namespace "Microsoft.Maintenance" ' '--visibility "Custom" ' '--resource-group "{rg}" ' '--resource-name "{myMaintenanceConfiguration2}"', checks=[]) # EXAMPLE: /ConfigurationAssignments/put/ConfigurationAssignments_CreateOrUpdate @try_manual def step__configurationassignments_put_configurationassignments_createorupdate(test, rg): test.cmd('az maintenance assignment create ' '--maintenance-configuration-id "/subscriptions/{subscription_id}/resourcegroups/{rg}/providers/Microsoft.' 'Maintenance/maintenanceConfigurations/{myMaintenanceConfiguration2}" ' '--name "{myConfigurationAssignment2}" ' '--provider-name "Microsoft.Compute" ' '--resource-group "{rg}" ' '--resource-name "smdtest1" ' '--resource-type "virtualMachineScaleSets"', checks=[]) # EXAMPLE: /ConfigurationAssignments/put/ConfigurationAssignments_CreateOrUpdateParent @try_manual def step__configurationassignments_put_configurationassignments_createorupdateparent(test, rg): test.cmd('az maintenance assignment create ' '--maintenance-configuration-id "/subscriptions/{subscription_id}/resourcegroups/{rg}/providers/Microsoft.' 'Maintenance/maintenanceConfigurations/{myMaintenanceConfiguration}" ' '--name "{myConfigurationAssignment}" ' '--provider-name "Microsoft.Compute" ' '--resource-group "{rg}" ' '--resource-name "smdvm1" ' '--resource-parent-name "smdtest1" ' '--resource-parent-type "virtualMachineScaleSets" ' '--resource-type "virtualMachines"', checks=[]) # EXAMPLE: /ConfigurationAssignments/get/ConfigurationAssignments_List @try_manual def step__configurationassignments_get_configurationassignments_list(test, rg): test.cmd('az maintenance assignment list ' '--provider-name "Microsoft.Compute" ' '--resource-group "{rg}" ' '--resource-name "smdtest1" ' '--resource-type "virtualMachineScaleSets"', checks=[]) # EXAMPLE: /ConfigurationAssignments/get/ConfigurationAssignments_ListParent @try_manual def step__configurationassignments_get_configurationassignments_listparent(test, rg): test.cmd('az maintenance assignment list-parent ' '--provider-name "Microsoft.Compute" ' '--resource-group "{rg}" ' '--resource-name "smdtestvm1" ' '--resource-parent-name "smdtest1" ' '--resource-parent-type "virtualMachineScaleSets" ' '--resource-type "virtualMachines"', checks=[]) # EXAMPLE: /ConfigurationAssignments/delete/ConfigurationAssignments_DeleteParent @try_manual def step__configurationassignments_delete_configurationassignments_deleteparent(test, rg): test.cmd('az maintenance assignment delete -y ' '--name "{myConfigurationAssignment2}" ' '--provider-name "Microsoft.Compute" ' '--resource-group "{rg}" ' '--resource-name "smdvm1" ' '--resource-parent-name "smdtest1" ' '--resource-parent-type "virtualMachineScaleSets" ' '--resource-type "virtualMachines"', checks=[]) # EXAMPLE: /PublicMaintenanceConfigurations/get/PublicMaintenanceConfigurations_GetForResource @try_manual def step__publicmaintenanceconfigurations_get_publicmaintenanceconfigurations_getforresource(test, rg): test.cmd('az maintenance public-configuration show ' '--resource-name "{myMaintenanceConfiguration2}"', checks=[]) # EXAMPLE: /PublicMaintenanceConfigurations/get/PublicMaintenanceConfigurations_List @try_manual def step__publicmaintenanceconfigurations_get_publicmaintenanceconfigurations_list(test, rg): test.cmd('az maintenance public-configuration list', checks=[]) # EXAMPLE: /Updates/get/Updates_List @try_manual def step__updates_get_updates_list(test, rg): test.cmd('az maintenance update list ' '--provider-name "Microsoft.Compute" ' '--resource-group "{rg}" ' '--resource-name "smdtest1" ' '--resource-type "virtualMachineScaleSets"', checks=[]) # EXAMPLE: /Updates/get/Updates_ListParent @try_manual def step__updates_get_updates_listparent(test, rg): test.cmd('az maintenance update list-parent ' '--provider-name "Microsoft.Compute" ' '--resource-group "{rg}" ' '--resource-name "1" ' '--resource-parent-name "smdtest1" ' '--resource-parent-type "virtualMachineScaleSets" ' '--resource-type "virtualMachines"', checks=[]) # EXAMPLE: /ConfigurationAssignments/delete/ConfigurationAssignments_Delete @try_manual def step__configurationassignments_delete_configurationassignments_delete(test, rg): test.cmd('az maintenance assignment delete -y ' '--name "{myConfigurationAssignment2}" ' '--provider-name "Microsoft.Compute" ' '--resource-group "{rg}" ' '--resource-name "smdtest1" ' '--resource-type "virtualMachineScaleSets"', checks=[]) # EXAMPLE: /MaintenanceConfigurations/delete/MaintenanceConfigurations_DeleteForResource @try_manual def step__maintenanceconfigurations_delete_maintenanceconfigurations_deleteforresource(test, rg): test.cmd('az maintenance configuration delete -y ' '--resource-group "{rg}" ' '--resource-name "example1"', checks=[]) @try_manual def cleanup(test, rg): pass @try_manual def call_scenario(test, rg): setup(test, rg) step__applyupdates_put_applyupdates_createorupdate(test, rg) step__applyupdates_put_applyupdates_createorupdateparent(test, rg) step__applyupdates_get_applyupdates_get(test, rg) step__applyupdates_get_applyupdates_getparent(test, rg) step__maintenanceconfigurations_put_maintenanceconfigurations_createorupdateforresource(test, rg) step__maintenanceconfigurations_get_maintenanceconfigurations_getforresource(test, rg) step__maintenanceconfigurations_get_maintenanceconfigurations_list(test, rg) step__maintenanceconfigurations_patch_maintenanceconfigurations_updateforresource(test, rg) step__configurationassignments_put_configurationassignments_createorupdate(test, rg) step__configurationassignments_put_configurationassignments_createorupdateparent(test, rg) step__configurationassignments_get_configurationassignments_list(test, rg) step__configurationassignments_get_configurationassignments_listparent(test, rg) step__configurationassignments_delete_configurationassignments_deleteparent(test, rg) step__publicmaintenanceconfigurations_get_publicmaintenanceconfigurations_getforresource(test, rg) step__publicmaintenanceconfigurations_get_publicmaintenanceconfigurations_list(test, rg) step__updates_get_updates_list(test, rg) step__updates_get_updates_listparent(test, rg) step__configurationassignments_delete_configurationassignments_delete(test, rg) step__maintenanceconfigurations_delete_maintenanceconfigurations_deleteforresource(test, rg) cleanup(test, rg) @try_manual class MaintenanceClientScenarioTest(ScenarioTest): @ResourceGroupPreparer(name_prefix='clitestmaintenance_examplerg'[:7], key='rg', parameter_name='rg') def test_maintenance(self, rg): self.kwargs.update({ 'subscription_id': self.get_subscription_id() }) self.kwargs.update({ 'e9b9685d-78e4-44c4-a81c-64a14f9b87b6': 'e9b9685d-78e4-44c4-a81c-64a14f9b87b6', 'policy1': 'policy1', 'MaintenanceConfigurations_2': 'configuration1', 'workervmConfiguration': 'workervmConfiguration', 'ConfigurationAssignments_2': 'workervmPolicy', }) call_scenario(self, rg) calc_coverage(__file__) raise_if()
[ "noreply@github.com" ]
ebencarek.noreply@github.com
66b67eedee61c580be05e07398fad94dcf884e02
716af8750041594a729461117cf1c6bcf28ae850
/ioflo/base/odicting.py
b0d13f7a6c6464977d94718b15e3e1780a8db544
[ "MIT", "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0" ]
permissive
systronix/ioflo
66c21dd134e7c7554d64658b5d7844bf0e401ba1
0b4397efede138216b518c46cca2e29e8c032dc1
refs/heads/master
2020-12-26T09:36:25.491800
2014-03-14T21:15:31
2014-03-14T21:15:31
null
0
0
null
null
null
null
UTF-8
Python
false
false
9,146
py
"""Ordered dictionary class. Modified 2007, 2008 by Samuel M Smith Modifications CopyRight 2007 by Samuel M smith Based on various ordered dict implementations found in the wild """ #print "module %s" % __name__ class odict(dict): """ Dictionary whose keys maintain the order they are added to the dict. Not order they are updated. Similar to the collections OrderedDict but with more flexible initialization and additional methods. The first key added to the dictionary is the first key in .keys() Changing the value of a key does not affect the order of the key """ __slots__ = ['_keys'] def __new__(cls, *args, **kwargs): self = dict.__new__(cls,*args, **kwargs) self._keys = [] return self def __init__(self, *pa, **kwa): """ Create new empty odict odict() returns new empty dictionary. odict(pa1, pa2, ...) creates new dictionary from pa = tuple of positional args, (pa1, pa2, ...) d = {} for a in pa: if isinstance(a, dict): for k, v in a.items(): d[k] = v else: for k, v in a: d[k] = v if pa is a sequence of duples (k,v) then ordering is preserved if pa is an ordered dictionary then ordering is preserved if pa is not an ordered dictionary then ordering is not preserved odict(k1 = v1, k2 = v2, ...) creates new dictionary from kwa = dictionary of keyword args, {k1: v1, k2 : v2, ...} d = {} for k, v in kwa: d[k] = v in this case key ordering is not preserved due to limitation of python """ dict.__init__(self) for a in pa: if isinstance(a, dict): #positional arg is dictionary for k in a: self[k] = a[k] else: #positional arg is sequence of duples (k,v) for k, v in a: self[k] = v for k in kwa: self[k] = kwa[k] def __delitem__(self, key): """ del x[y] """ dict.__delitem__(self, key) self._keys.remove(key) def __iter__(self): """ iter(x)""" for key in self._keys: yield key def __repr__(self): """ repr(x)""" itemreprs = ('%r: %r' % (key, self[key]) for key in self._keys) return '{' + ', '.join(itemreprs) + '}' def __setitem__(self, key, val): """ x[key]=val""" dict.__setitem__(self, key, val) if not hasattr(self, '_keys'): self._keys = [key] if key not in self._keys: self._keys.append(key) def __getnewargs__(self): """Needed to force __new__ which creates _keys. if empty odict then __getstate__ returns empty list which is logically false so __setstate__ is not called. """ return tuple() def __getstate__(self): """ return state as items list. need this so pickle works since defined slots""" return self.items() def __setstate__(self, state): """restore from state items list""" self.__init__(state) def append(self, key, item): """ D[key] = item.""" if key in self: raise KeyError('append(): key %r already in dictionary' % key) self[key] = item def clear(self): """ Remove all items from odict""" dict.clear(self) self._keys = [] def copy(self): """ Make a shallow copy of odict""" items = [(key, self[key]) for key in self._keys] return self.__class__(items) #creates new odict and populates with items def create(self, *pa, **kwa): """create items in this odict but only if key not already existent pa may be sequence of duples (k,v) or dict kwa is dict of keyword arguments """ for a in pa: if isinstance(a, dict): #positional arg is dictionary for k in a: if k not in self._keys: self[k] = a[k] else: #positional arg is sequence of duples (k,v) for k, v in a: if k not in self._keys: self[k] = v for k in kwa: if k not in self._keys: self[k] = kwa[k] def insert(self, index, key, val): """ Insert val at index if key not in odict""" if key in self: raise KeyError('Key %r already exists.' % key) dict.__setitem__(self, key, val) self._keys.insert(index, key) def items(self): return [(key, self[key]) for key in self._keys] def iterkeys(self): """ Return an iterator over the keys of odict""" return iter(self) def iteritems(self): """ Return an iterator over the items (key, value) of odict.""" return ((key, self[key]) for key in self._keys) def itervalues(self): """ Return an iterator over the values of odict.""" return (self[key] for key in self._keys) def keys(self): """ Return the list of keys of odict.""" return self._keys[:] def pop(self, key, *default): """ Remove key and the associated item and return the associated value If key not found return default if given otherwise raise KeyError """ value = dict.pop(self, key, *default) if key in self._keys: self._keys.remove(key) return value def popitem(self): """ Remove and return last item (key, value) duple If odict is empty raise KeyError """ try: key = self._keys[-1] except IndexError: raise KeyError('Empty odict.') value = self[key] del self[key] return (key, value) def reorder(self, other): """ Update values in this odict based on the `other` odict or dict. reorder is ignored if other is not an odict """ if not isinstance(other, odict): raise ValueError('other must be an odict') if other is self: #raise ValueError('other cannot be the same odict') pass #updating with self makes no changes dict.update(self, other) keys = self._keys for key in other: if key in keys: keys.remove(key) keys.append(key) def setdefault(self, key, default=None): """ If key in odict, return value at key Otherwise set value at key to default and return default """ value = dict.setdefault(self, key, default) if key not in self._keys: self._keys.append(key) return value def update(self, *pa, **kwa): """Update values in this odict pa may be sequence of duples (k,v) or dict kwa is dict of keyword arguments """ for a in pa: if isinstance(a, dict): #positional arg is dictionary for k in a: self[k] = a[k] else: #positional arg is sequence of duples (k,v) for k, v in a: self[k] = v for k in kwa: self[k] = kwa[k] def values(self): return [self[key] for key in self._keys] import optimize optimize.bind_all(odict) def TestPickle(): """tests ability of odict to be pickled and unpickled New-style types can provide a __getnewargs__() method that is used for protocol 2. Note that last phrase about requiring protocol 2. Your example works if you add a third parameter to pickle.dump() with the value of 2. Version 2 is not default. """ import pickle import StringIO x = odict([('z',1),('a',2),('r',3)]) s = StringIO.StringIO() pickle.dump(x,s,2) s.seek(0) y = pickle.load(s) print x print y #empty odict x = odict() s = StringIO.StringIO() pickle.dump(x,s,2) s.seek(0) y = pickle.load(s) print x print y def Test(): """Self test """ seq = [('b', 1), ('c', 2), ('a', 3)] dct = {} for k,v in seq: dct[k] = v odct = odict() for k,v in seq: odct[k] = v print "Intialized from sequence of duples 'seq' = %s" % seq x = odict(seq) print " odict(seq) = %s" % x print "Initialized from unordered dictionary 'dct' = %s" % dct x = odict(dct) print " odict(dct) = %s" % x print "Initialized from ordered dictionary 'odct' = %s" % odct x = odict(odct) print " odict(odct) = %s" % x print "Initialized from keyword arguments 'b = 1, c = 2, a = 3'" x = odict(b = 1, c = 2, a = 3) print " odict(b = 1, c = 2, a = 3) = %s" % x print "Initialized from mixed arguments" x = odict(odct, seq, [('e', 4)], d = 5) print " odict(odct, seq, d = 4) = %s" % x
[ "smith.samuel.m@gmail.com" ]
smith.samuel.m@gmail.com
d746fe4996011cd8732a10c60d661dbd2bc53eff
bb1e0e89fcf1f1ffb61214ddf262ba327dd10757
/plotly_study/graph_objs/waterfall/increasing/__init__.py
bacb03f40d90248bd3aad08622978e5ad5d72d1e
[ "MIT" ]
permissive
lucasiscovici/plotly_py
ccb8c3ced89a0f7eccf1ae98551fa712460033fe
42ab769febb45fbbe0a3c677dc4306a4f59cea36
refs/heads/master
2020-09-12T05:43:12.363609
2019-12-02T15:13:13
2019-12-02T15:13:13
222,328,180
0
0
null
null
null
null
UTF-8
Python
false
false
6,415
py
from plotly_study.basedatatypes import BaseTraceHierarchyType as _BaseTraceHierarchyType import copy as _copy class Marker(_BaseTraceHierarchyType): # color # ----- @property def color(self): """ Sets the marker color of all increasing values. The 'color' property is a color and may be specified as: - A hex string (e.g. '#ff0000') - An rgb/rgba string (e.g. 'rgb(255,0,0)') - An hsl/hsla string (e.g. 'hsl(0,100%,50%)') - An hsv/hsva string (e.g. 'hsv(0,100%,100%)') - A named CSS color: aliceblue, antiquewhite, aqua, aquamarine, azure, beige, bisque, black, blanchedalmond, blue, blueviolet, brown, burlywood, cadetblue, chartreuse, chocolate, coral, cornflowerblue, cornsilk, crimson, cyan, darkblue, darkcyan, darkgoldenrod, darkgray, darkgrey, darkgreen, darkkhaki, darkmagenta, darkolivegreen, darkorange, darkorchid, darkred, darksalmon, darkseagreen, darkslateblue, darkslategray, darkslategrey, darkturquoise, darkviolet, deeppink, deepskyblue, dimgray, dimgrey, dodgerblue, firebrick, floralwhite, forestgreen, fuchsia, gainsboro, ghostwhite, gold, goldenrod, gray, grey, green, greenyellow, honeydew, hotpink, indianred, indigo, ivory, khaki, lavender, lavenderblush, lawngreen, lemonchiffon, lightblue, lightcoral, lightcyan, lightgoldenrodyellow, lightgray, lightgrey, lightgreen, lightpink, lightsalmon, lightseagreen, lightskyblue, lightslategray, lightslategrey, lightsteelblue, lightyellow, lime, limegreen, linen, magenta, maroon, mediumaquamarine, mediumblue, mediumorchid, mediumpurple, mediumseagreen, mediumslateblue, mediumspringgreen, mediumturquoise, mediumvioletred, midnightblue, mintcream, mistyrose, moccasin, navajowhite, navy, oldlace, olive, olivedrab, orange, orangered, orchid, palegoldenrod, palegreen, paleturquoise, palevioletred, papayawhip, peachpuff, peru, pink, plum, powderblue, purple, red, rosybrown, royalblue, rebeccapurple, saddlebrown, salmon, sandybrown, seagreen, seashell, sienna, silver, skyblue, slateblue, slategray, slategrey, snow, springgreen, steelblue, tan, teal, thistle, tomato, turquoise, violet, wheat, white, whitesmoke, yellow, yellowgreen Returns ------- str """ return self["color"] @color.setter def color(self, val): self["color"] = val # line # ---- @property def line(self): """ The 'line' property is an instance of Line that may be specified as: - An instance of plotly_study.graph_objs.waterfall.increasing.marker.Line - A dict of string/value properties that will be passed to the Line constructor Supported dict properties: color Sets the line color of all increasing values. width Sets the line width of all increasing values. Returns ------- plotly_study.graph_objs.waterfall.increasing.marker.Line """ return self["line"] @line.setter def line(self, val): self["line"] = val # property parent name # -------------------- @property def _parent_path_str(self): return "waterfall.increasing" # Self properties description # --------------------------- @property def _prop_descriptions(self): return """\ color Sets the marker color of all increasing values. line plotly_study.graph_objects.waterfall.increasing.marker.Line instance or dict with compatible properties """ def __init__(self, arg=None, color=None, line=None, **kwargs): """ Construct a new Marker object Parameters ---------- arg dict of properties compatible with this constructor or an instance of plotly_study.graph_objs.waterfall.increasing.Marker color Sets the marker color of all increasing values. line plotly_study.graph_objects.waterfall.increasing.marker.Line instance or dict with compatible properties Returns ------- Marker """ super(Marker, self).__init__("marker") # Validate arg # ------------ if arg is None: arg = {} elif isinstance(arg, self.__class__): arg = arg.to_plotly_json() elif isinstance(arg, dict): arg = _copy.copy(arg) else: raise ValueError( """\ The first argument to the plotly_study.graph_objs.waterfall.increasing.Marker constructor must be a dict or an instance of plotly_study.graph_objs.waterfall.increasing.Marker""" ) # Handle skip_invalid # ------------------- self._skip_invalid = kwargs.pop("skip_invalid", False) # Import validators # ----------------- from plotly_study.validators.waterfall.increasing import marker as v_marker # Initialize validators # --------------------- self._validators["color"] = v_marker.ColorValidator() self._validators["line"] = v_marker.LineValidator() # Populate data dict with properties # ---------------------------------- _v = arg.pop("color", None) self["color"] = color if color is not None else _v _v = arg.pop("line", None) self["line"] = line if line is not None else _v # Process unknown kwargs # ---------------------- self._process_kwargs(**dict(arg, **kwargs)) # Reset skip_invalid # ------------------ self._skip_invalid = False __all__ = ["Marker", "marker"] from plotly_study.graph_objs.waterfall.increasing import marker
[ "you@example.com" ]
you@example.com
789c0fd16ea82c8264607f3c813fe7c1703ceb81
660e35c822423685aea19d038daa8356722dc744
/party/category.py
a35b8795bf2973d2c3aa84d30eef643b06b6e910
[]
no_license
saifkazi/tryton_modules
a05cb4a90ae2c46ba39d60d2005ffc18ce5e44bb
94bd3a4e3fd86556725cdff33b314274dcb20afd
refs/heads/main
2023-05-05T12:20:02.059236
2021-05-19T10:46:37
2021-05-19T10:46:37
368,768,310
0
0
null
null
null
null
UTF-8
Python
false
false
1,462
py
# This file is part of Tryton. The COPYRIGHT file at the top level of # this repository contains the full copyright notices and license terms. from sql.conditionals import Coalesce from sql.operators import Equal from trytond.model import ( ModelView, ModelSQL, DeactivableMixin, fields, Exclude, tree) class Category(DeactivableMixin, tree(separator=' / '), ModelSQL, ModelView): "Category" __name__ = 'party.category' name = fields.Char( "Name", required=True, translate=True, help="The main identifier of the category.") parent = fields.Many2One( 'party.category', "Parent", select=True, help="Add the category below the parent.") childs = fields.One2Many( 'party.category', 'parent', "Children", help="Add children below the category.") @classmethod def __setup__(cls): super(Category, cls).__setup__() t = cls.__table__() cls._sql_constraints = [ ('name_parent_exclude', Exclude(t, (t.name, Equal), (Coalesce(t.parent, -1), Equal)), 'party.msg_category_name_unique'), ] cls._order.insert(0, ('name', 'ASC')) @classmethod def __register__(cls, module_name): super(Category, cls).__register__(module_name) table_h = cls.__table_handler__(module_name) # Migration from 4.6: replace unique by exclude table_h.drop_constraint('name_parent_uniq')
[ "saif.kazi76@gmail.com" ]
saif.kazi76@gmail.com
cf53335750949034c20cc3ef5786467e683305df
9811904ef72f0832c5fce44444f8f3b106dea165
/admin_tools_stats/migrations/0001_initial.py
36a32afa4b3c225c0ee7912bdce6010276ffb40e
[ "MIT" ]
permissive
areski/django-admin-tools-stats
3b8d9f39ba41dbe733076e6d1f62c69d328637ff
20fb537388895ed1f0913805bca18b97723b7dc1
refs/heads/develop
2023-02-22T18:53:01.672623
2020-01-16T14:48:21
2020-01-16T14:48:21
2,348,691
214
41
NOASSERTION
2023-02-11T17:57:17
2011-09-08T14:11:07
Python
UTF-8
Python
false
false
3,865
py
# -*- coding: utf-8 -*- # Generated by Django 1.9 on 2015-12-13 11:29 from __future__ import unicode_literals from django.db import migrations, models import jsonfield.fields class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='DashboardStats', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('graph_key', models.CharField(help_text='it needs to be one word unique. ex. auth, mygraph', max_length=90, unique=True, verbose_name='graph key')), ('graph_title', models.CharField(db_index=True, help_text='heading title of graph box', max_length=90, verbose_name='graph title')), ('model_app_name', models.CharField(help_text='ex. auth / dialer_cdr', max_length=90, verbose_name='app name')), ('model_name', models.CharField(help_text='ex. User', max_length=90, verbose_name='model name')), ('date_field_name', models.CharField(help_text='ex. date_joined', max_length=90, verbose_name='date field name')), ('operation_field_name', models.CharField(blank=True, help_text='The field you want to aggregate, ex. amount', max_length=90, null=True, verbose_name='Operate field name')), ('type_operation_field_name', models.CharField(blank=True, choices=[(b'Count', b'Count'), (b'Sum', b'Sum'), (b'Avg', b'Avg'), (b'Max', b'Max'), (b'Min', b'Min'), (b'StdDev', b'StdDev'), (b'Variance', b'Variance')], help_text='choose the type operation what you want to aggregate, ex. Sum', max_length=90, null=True, verbose_name='Choose Type operation')), ('is_visible', models.BooleanField(default=True, verbose_name='visible')), ('created_date', models.DateTimeField(auto_now_add=True, verbose_name='date')), ('updated_date', models.DateTimeField(auto_now=True)), ], options={ 'db_table': 'dashboard_stats', 'verbose_name': 'dashboard stats', 'verbose_name_plural': 'dashboard stats', }, ), migrations.CreateModel( name='DashboardStatsCriteria', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('criteria_name', models.CharField(db_index=True, help_text='it needs to be one word unique. Ex. status, yesno', max_length=90, verbose_name='criteria name')), ('criteria_fix_mapping', jsonfield.fields.JSONField(blank=True, help_text='a JSON dictionary of key-value pairs that will be used for the criteria', null=True, verbose_name='fixed criteria / value')), ('dynamic_criteria_field_name', models.CharField(blank=True, help_text='ex. for call records - disposition', max_length=90, null=True, verbose_name='dynamic criteria field name')), ('criteria_dynamic_mapping', jsonfield.fields.JSONField(blank=True, help_text='a JSON dictionary of key-value pairs that will be used for the criteria', null=True, verbose_name='dynamic criteria / value')), ('created_date', models.DateTimeField(auto_now_add=True, verbose_name='date')), ('updated_date', models.DateTimeField(auto_now=True)), ], options={ 'db_table': 'dash_stats_criteria', 'verbose_name': 'dashboard stats criteria', 'verbose_name_plural': 'dashboard stats criteria', }, ), migrations.AddField( model_name='dashboardstats', name='criteria', field=models.ManyToManyField(blank=True, to='admin_tools_stats.DashboardStatsCriteria'), ), ]
[ "areski@gmail.com" ]
areski@gmail.com
cbce07708e421612df9f4943eec5efae3a595746
2a68ce2f0f47370e2f57b9279cc8e1aab85e26da
/trojsten/dbsanitizer/tests.py
45308305cf9ed8198fdb56412d4331066df8d443
[ "MIT" ]
permissive
trojsten/web
52007c3d575b21603bf205c1e7294a482eedbf85
97b7b3ae3ac46be786bde9c49a2cae6609dbf50f
refs/heads/master
2023-08-17T23:30:16.857469
2023-07-30T16:31:34
2023-07-30T16:31:34
10,618,952
6
10
MIT
2023-09-04T19:09:09
2013-06-11T10:04:10
Python
UTF-8
Python
false
false
2,543
py
import datetime from django.test import TestCase from trojsten.contests.models import Competition, Round, Semester, Task from trojsten.people.models import User, UserProperty, UserPropertyKey from .model_sanitizers import ( GeneratorFieldSanitizer, TaskSanitizer, UserPropertySanitizer, UserSanitizer, ) class GeneratorFieldSanitizerTest(TestCase): def test_data_replaced_by_generated_data(self): def fake_generator(): return "generated_data" sanitized_data = GeneratorFieldSanitizer(fake_generator).sanitize("original_data") self.assertEquals(sanitized_data, "generated_data") class TaskSanitizerTest(TestCase): def test_task_data_sanitized(self): c = Competition.objects.create(name="ABCD") s = Semester.objects.create(year=47, competition=c, number=1) r = Round.objects.create(number=3, semester=s, visible=True, solutions_visible=True) Task.objects.create(number=2, name="foo", round=r) TaskSanitizer().sanitize() sanitized_task = Task.objects.get() self.assertNotEquals(sanitized_task.name, "foo") class UserSanitizerTest(TestCase): def test_user_data_sanitized(self): User.objects.create( username="foo", password="pwd", first_name="Ferko", last_name="Mrkvicka", birth_date=datetime.date(year=2000, month=1, day=1), email="ferko@example.com", ) UserSanitizer().sanitize() sanitized_user = User.objects.get() self.assertNotEquals(sanitized_user.username, "foo") self.assertEquals(sanitized_user.password, "") self.assertNotEquals(sanitized_user.first_name, "Ferko") self.assertNotEquals(sanitized_user.last_name, "Mrkvicka") self.assertNotEquals(sanitized_user.birth_date, datetime.date(year=2000, month=1, day=1)) self.assertNotEquals(sanitized_user.last_name, "ferko@example.com") class UserPropertySanitizerTest(TestCase): def test_userproperty_data_sanitized(self): key = UserPropertyKey.objects.create(key_name="foo") user = User.objects.create(username="user") UserProperty.objects.create(user=user, key=key, value="bar") UserPropertySanitizer().sanitize() sanitized_userproperty = UserProperty.objects.get() self.assertEquals(sanitized_userproperty.key, key) self.assertNotEquals(sanitized_userproperty.value, "bar") self.assertEquals(len(sanitized_userproperty.value), 3)
[ "mhozza@gmail.com" ]
mhozza@gmail.com
15737f4817cf53b326364b6d29fe9fd568947d70
517d461257edd1d6b239200b931c6c001b99f6da
/Circuit_Playground/CircuitPython/libraries/adafruit-circuitpython-bundle-6.x-mpy-20211013/examples/emc2101_lut_example.py
e40521c8205807f188e5d8c7ce4b8be76f169be6
[]
no_license
cmontalvo251/Microcontrollers
7911e173badff93fc29e52fbdce287aab1314608
09ff976f2ee042b9182fb5a732978225561d151a
refs/heads/master
2023-06-23T16:35:51.940859
2023-06-16T19:29:30
2023-06-16T19:29:30
229,314,291
5
3
null
null
null
null
UTF-8
Python
false
false
843
py
# SPDX-FileCopyrightText: 2020 Bryan Siepert, written for Adafruit Industries # # SPDX-License-Identifier: MIT import time import board from adafruit_emc2101.emc2101_lut import EMC2101_LUT as EMC2101 i2c = board.I2C() # uses board.SCL and board.SDA FAN_MAX_RPM = 1700 emc = EMC2101(i2c) emc.manual_fan_speed = 50 time.sleep(1) emc.lut[27] = 25 emc.lut[34] = 50 emc.lut[42] = 75 emc.lut_enabled = True emc.forced_temp_enabled = True print("Lut:", emc.lut) emc.forced_ext_temp = 28 # over 25, should be 25% time.sleep(3) print("25%% duty cycle is %f RPM:" % emc.fan_speed) emc.forced_ext_temp = 35 # over 30, should be 50% time.sleep(3) print("50%% duty cycle is %f RPM:" % emc.fan_speed) emc.forced_ext_temp = 43 # over 42, should be 75% time.sleep(3) print("75%% duty cycle is %f RPM:" % emc.fan_speed)
[ "cmontalvo@southalabama.edu" ]
cmontalvo@southalabama.edu
4445e59c151d0526998628fc5e6f48826e731efe
9e988c0dfbea15cd23a3de860cb0c88c3dcdbd97
/sdBs/AllRun/sdssj_132556.93-032329.6/sdB_sdssj_132556.93-032329.6_lc.py
40f5f972dc38f9ea75f637b807ff08d9e12c39a9
[]
no_license
tboudreaux/SummerSTScICode
73b2e5839b10c0bf733808f4316d34be91c5a3bd
4dd1ffbb09e0a599257d21872f9d62b5420028b0
refs/heads/master
2021-01-20T18:07:44.723496
2016-08-08T16:49:53
2016-08-08T16:49:53
65,221,159
0
0
null
null
null
null
UTF-8
Python
false
false
371
py
from gPhoton.gAperture import gAperture def main(): gAperture(band="NUV", skypos=[201.487208,-3.391556], stepsz=30., csvfile="/data2/fleming/GPHOTON_OUTPU/LIGHTCURVES/sdBs/sdB_sdssj_132556.93-032329.6/sdB_sdssj_132556.93-032329.6_lc.csv", maxgap=1000., overwrite=True, radius=0.00555556, annulus=[0.005972227,0.0103888972], verbose=3) if __name__ == "__main__": main()
[ "thomas@boudreauxmail.com" ]
thomas@boudreauxmail.com
553f97fb014b172cd5365d8b22bf2ebbb4f7bd97
0d0b8236ff06027037d2a8a724d13a1866a9999c
/0x11-python-network_1/100-github_commits.py
246b7b51fe87ce6eb9f1acda243b8b3831205621
[]
no_license
Danucas/holbertonschool-higher_level_programming
3f8e81a610bf80890280b764362b56ad8803e2df
b963d41af8bccf764dff67f80ea16f1184c0a96d
refs/heads/master
2022-07-31T05:53:57.046789
2020-05-21T21:29:54
2020-05-21T21:29:54
null
0
0
null
null
null
null
UTF-8
Python
false
false
461
py
#!/usr/bin/python3 """ Python script to fetch an https request """ import requests import sys def main(): url = "https://api.github.com/repos/{}/{}/commits" url = url.format(sys.argv[2], sys.argv[1]) response = requests.get(url) commits = response.json() for com in commits[:10]: sha = com['sha'] author = com['commit']['author']['name'] print('{}: {}'.format(sha, author)) if __name__ == '__main__': main()
[ "danrodcastillo1994@gmail.com" ]
danrodcastillo1994@gmail.com
4994f8e2ea7c14a3f49a1cc6ec20ccf81e3033c5
5779d964d5ee42b586697a640ff0f977e0fa1e55
/synclient/model/paginated_results_of_submission_status.py
dfbe22b68739ed6283ac18d415da2dae69a78377
[]
no_license
thomasyu888/synpy-sdk-client
03db42c3c8411c8c1f8808e1145d7c2a8bcc3df1
d1e19e26db5376c78c4ce0ff181ac3c4e0709cbb
refs/heads/main
2023-02-28T09:33:12.386220
2021-02-02T15:09:59
2021-02-02T15:09:59
333,744,741
3
0
null
2021-01-30T12:10:50
2021-01-28T11:57:48
Python
UTF-8
Python
false
false
7,401
py
""" Platform Repository Service Platform Repository Service - Sage Bionetworks Platform # noqa: E501 The version of the OpenAPI document: develop-SNAPSHOT Contact: thomas.yu@sagebionetworks.org Generated by: https://openapi-generator.tech """ import re # noqa: F401 import sys # noqa: F401 import nulltype # noqa: F401 from synclient.model_utils import ( # noqa: F401 ApiTypeError, ModelComposed, ModelNormal, ModelSimple, cached_property, change_keys_js_to_python, convert_js_args_to_python_args, date, datetime, file_type, none_type, validate_get_composed_info, ) def lazy_import(): from synclient.model.submission_status_model import SubmissionStatusModel globals()['SubmissionStatusModel'] = SubmissionStatusModel class PaginatedResultsOfSubmissionStatus(ModelNormal): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. Attributes: allowed_values (dict): The key is the tuple path to the attribute and the for var_name this is (var_name,). The value is a dict with a capitalized key describing the allowed value and an allowed value. These dicts store the allowed enum values. attribute_map (dict): The key is attribute name and the value is json key in definition. discriminator_value_class_map (dict): A dict to go from the discriminator variable value to the discriminator class name. validations (dict): The key is the tuple path to the attribute and the for var_name this is (var_name,). The value is a dict that stores validations for max_length, min_length, max_items, min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, inclusive_minimum, and regex. additional_properties_type (tuple): A tuple of classes accepted as additional properties values. """ allowed_values = { } validations = { } additional_properties_type = None _nullable = False @cached_property def openapi_types(): """ This must be a method because a model may have properties that are of type self, this must run after the class is loaded Returns openapi_types (dict): The key is attribute name and the value is attribute type. """ lazy_import() return { 'results': ([SubmissionStatusModel],), # noqa: E501 'total_number_of_results': (int,), # noqa: E501 } @cached_property def discriminator(): return None attribute_map = { 'results': 'results', # noqa: E501 'total_number_of_results': 'totalNumberOfResults', # noqa: E501 } _composed_schemas = {} required_properties = set([ '_data_store', '_check_type', '_spec_property_naming', '_path_to_item', '_configuration', '_visited_composed_classes', ]) @convert_js_args_to_python_args def __init__(self, *args, **kwargs): # noqa: E501 """PaginatedResultsOfSubmissionStatus - a model defined in OpenAPI Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be raised if the wrong type is input. Defaults to True _path_to_item (tuple/list): This is a list of keys or values to drill down to the model in received_data when deserializing a response _spec_property_naming (bool): True if the variable names in the input data are serialized names, as specified in the OpenAPI document. False if the variable names in the input data are pythonic names, e.g. snake case (default) _configuration (Configuration): the instance to use when deserializing a file_type parameter. If passed, type conversion is attempted If omitted no type conversion is done. _visited_composed_classes (tuple): This stores a tuple of classes that we have traveled through so that if we see that class again we will not use its discriminator again. When traveling through a discriminator, the composed schema that is is traveled through is added to this set. For example if Animal has a discriminator petType and we pass in "Dog", and the class Dog allOf includes Animal, we move through Animal once using the discriminator, and pick Dog. Then in Dog, we will make an instance of the Animal class but this time we won't travel through its discriminator because we passed in _visited_composed_classes = (Animal,) results ([SubmissionStatusModel]): The the id of the entity to which this reference refers. [optional] # noqa: E501 total_number_of_results (int): Calculating the actual totalNumberOfResults is not longer supported. Therefore, for each page, the totalNumberOfResults is estimated using the current page, limit, and offset. When the page size equals the limit, the totalNumberOfResults will be offset+pageSize+ 1. Otherwise, the totalNumberOfResults will be offset+pageSize. . [optional] # noqa: E501 """ _check_type = kwargs.pop('_check_type', True) _spec_property_naming = kwargs.pop('_spec_property_naming', False) _path_to_item = kwargs.pop('_path_to_item', ()) _configuration = kwargs.pop('_configuration', None) _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) if args: raise ApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, ), path_to_item=_path_to_item, valid_classes=(self.__class__,), ) self._data_store = {} self._check_type = _check_type self._spec_property_naming = _spec_property_naming self._path_to_item = _path_to_item self._configuration = _configuration self._visited_composed_classes = _visited_composed_classes + (self.__class__,) for var_name, var_value in kwargs.items(): if var_name not in self.attribute_map and \ self._configuration is not None and \ self._configuration.discard_unknown_keys and \ self.additional_properties_type is None: # discard variable. continue setattr(self, var_name, var_value)
[ "thomas.yu@sagebase.org" ]
thomas.yu@sagebase.org
77dbd599f3c0b21c50f8a630b45f745368c7c237
663d429e1f552ef958d37cfe4a0707354b544a9a
/rimi_linux_mysql/tcp_ip_socket/Io_test/io_select_test/test5.py
5305eb8f5071b28540bcab38f841a1e131f9fe30
[]
no_license
nie000/mylinuxlearn
72a33024648fc4393442511c85d7c439e169a960
813ed75a0018446cd661001e8803f50880d09fff
refs/heads/main
2023-06-20T07:46:11.842538
2021-07-15T13:46:43
2021-07-15T13:46:43
307,377,665
0
0
null
null
null
null
UTF-8
Python
false
false
578
py
import socket import select r = [] server = socket.socket(socket.AF_INET,socket.SOCK_STREAM) server.bind(('127.0.0.1',28889)) server.listen(1) r.append(server) while True: rlist,wlist,xlist = select.select(r,[],[]) for i in rlist: if i is server: con,add = i.accept() print(add) r.append(con) else: try: m = i.recv(1024) if not m: i.close() r.remove(i) continue except: r.remove(i)
[ "1073438012@qq.com" ]
1073438012@qq.com
e6a4e9ddf7a5f4d895cab6048734f09fac8132c9
f7a797f88c197bcab75d5906b1e5f655ef69ebec
/WDC 2021 Jan 31.py
91bb7a672a0b22feda50cd41158b036b340a8f2f
[]
no_license
ramlaxman/wdc-2021-jan-advanced-python
3bcac28c0d5d6bdbb53ef17dc5e9db4522c886cd
e96ef09b9a5e6366f780af7a030aecf9fb252a96
refs/heads/main
2023-04-13T04:51:26.329823
2021-02-23T07:32:43
2021-02-23T07:32:43
342,255,655
0
0
null
2023-04-04T00:15:56
2021-02-25T13:36:08
null
UTF-8
Python
false
false
11,205
py
#!/usr/bin/env python # coding: utf-8 # In[1]: print('Hello, world!') # # Agenda # # 0. About assignment, `==` and `is` # 1. Basic data structures — how they work # 2. `Decimal` # 3. `namedtuple` # 4. Variations on `dict` # In[2]: import sys sys.version # In[3]: x = 100 y = 100 x == y # In[4]: x is y # In[5]: x = 1000 y = 1000 x == y # In[6]: x is y # In[7]: x == y # x.__eq__(y) # In[8]: x is y # In[9]: id(x) # In[10]: id(y) # In[11]: x is y # id(x) == id(y) # In[12]: x = 100 y = 100 x is y # In[13]: x = 1000 y = 1000 x is y # In[14]: x = None if x == None: # non-Pythonic print('Yes, it is None!') # In[15]: if x is None: # VERY Pythonic print('Yes, it is None!') # In[16]: x = 100 y = x x = 200 y # In[17]: x = 100 x += 5 x # In[18]: x = 'abcde' x[0] = '!' # str is immutable # In[19]: x = 'fghij' # In[20]: import sys x = 0 sys.getsizeof(x) # In[21]: x = 1234567890 sys.getsizeof(x) # In[22]: x = x ** 10 sys.getsizeof(x) # In[23]: x = x ** 100 sys.getsizeof(x) # In[1]: a = 1 type(a) # In[2]: a = 1.0 type(a) # In[3]: 0.1 + 0.2 # In[4]: 0.1 + 0.2 == 0.3 # In[5]: round(0.1 + 0.2, 2) # In[6]: round(0.1 + 0.2, 2) == 0.3 # In[7]: # BCD -- binary coded decimals # In[8]: 123 # 0b1 0b2 0b3 # In[9]: from decimal import Decimal a = Decimal('0.1') b = Decimal('0.2') a + b # In[10]: float(a+b) # In[12]: import sys sys.getsizeof(a) # In[13]: sys.getsizeof(b) # In[14]: sys.getsizeof(0.1) # In[15]: a = Decimal(0.1) b = Decimal(0.2) a + b # In[16]: a # In[17]: b # In[18]: 1/3 # In[19]: from math import isclose # In[20]: isclose(0.1+0.2, 0.3) # In[21]: isclose(0.1+0.2, 0.3, rel_tol=0.000000000000000001) # In[22]: isclose(0.1+0.2, 0.3, rel_tol=0.1) # In[24]: x = 0.1 y = 0.2 f'{x} + {y} = {x+y:0.2}' # In[25]: x = 'abcd' y = 'abcd' x == y # In[26]: x is y # In[27]: x = 'abcd' * 5000 y = 'abcd' * 5000 x == y # In[28]: x is y # In[29]: x = 'ab.cd' y = 'ab.cd' x == y # In[30]: x is y # In[31]: a = 100 b = [10, 20, 30] # In[32]: globals() # In[33]: globals()['a'] # In[34]: globals()['b'] # In[35]: globals()['a'] = 987 a # In[36]: print(a) # In[37]: # interning -- cache of string # In[38]: x = 'abcde' y = 'abcde' x is y # In[39]: x = 'abcde' * 2000 y = 'abcde' * 2000 x is y # In[40]: x = 'ab.cd' y = 'ab.cd' # In[41]: x is y # In[43]: x = sys.intern('ab.cde') y = sys.intern('ab.cde') # In[44]: x is y # In[45]: for i in range(5): print(x) # print(globals()['x']) # In[46]: # f-string # str.format # str % ('a', 'b') -- printf-ish # In[47]: x = 100 y = [10, 20, 30] z = {'a':1, 'b':2} s = f'x = {x}, y = {y}, z = {z}' # In[48]: print(s) # In[49]: d = {'a':1, 'b':200, 'cdefg': 3, 'hijklmn': 45678} for key, value in d.items(): print(f'{key}: {value}') # In[50]: for key, value in d.items(): print(f'{key:8}: {value:8}') # In[51]: for key, value in d.items(): print(f'{key:8}{value:8}') # In[52]: for key, value in d.items(): print(f'{key:.<8}{value:*>8}') # In[54]: for key, value in d.items(): print(f'{key:.>8} {value:*<8}') # In[55]: f = 123456.7890123 print(f'The number is {f}.') # In[58]: print(f'The number is {f:6.5}.') # In[59]: x # In[60]: y # In[61]: z # In[62]: print(f'x = {x}, y = {y}, z = {z}') # In[63]: # From Python 3.8, we can do this: print(f'{x=}, {y=}, {z=}') # In[64]: mylist = [10, 20, 30, 40, 50] # In[65]: type(mylist) # In[66]: mylist.append(60) mylist # In[68]: mylist = [] for i in range(60): print(f'{i}: len(mylist) = {len(mylist)}, sys.getsizeof(mylist) = {sys.getsizeof(mylist)}') mylist.append(i) # In[69]: [1] * 100 # In[70]: # sequence -- string, list, tuple t = (10, 20, 30, 40, 50) type(t) # In[71]: # no parens needed! t = 10, 20, 30, 40, 50 t # In[72]: type(t) # In[73]: t = ([10, 20, 30], [100, 200,300, 400, 500]) t # In[74]: t[0] = '!' # In[75]: t[0].append(40) t # In[76]: p = ('Reuven', 'Lerner', 46) p # In[77]: p[0] # In[79]: p[1] # In[80]: p[2] # In[81]: # named tuples # In[82]: from collections import namedtuple Person = namedtuple('Person', ['first', 'last', 'shoesize']) # In[83]: class Foo: pass # In[84]: Foo.__name__ # In[87]: # namedtuple returns a new class # the list of strings shows the fields that we can create Person = namedtuple('Person', ['first', 'last', 'shoesize']) # In[88]: Person.__name__ # In[89]: p = Person('Reuven', 'Lerner', 46) # In[90]: p # In[91]: p[0] # In[92]: p[1] # In[93]: p[2] # In[94]: p.first # In[95]: p.last # In[96]: p.shoesize # In[97]: type(Person) # In[98]: type(Person) # In[99]: p1 = Person('first1', 'last1', 1) p2 = Person('first2', 'last2', 2) # In[100]: p1 # In[101]: p2 # In[102]: type(p1) # In[103]: type(p2) # In[104]: p1.first # In[105]: p1.first = 'asdfafafa' # In[106]: p1._replace(first='zzzzz') # In[107]: p1 = p1._replace(first='zzzzz') p1 # In[108]: t # In[109]: t[0].append(50) t # In[110]: t[0] += [60, 70, 80] # __iadd__ # (1) adds (2) assigns # In[111]: t # In[112]: t[0].extend([90, 91, 92]) t # In[113]: # tuple with 1 element t = (10,) type(t) # In[114]: t = (10) type(t) # # Exercise: Bookstore # # 1. Create, using `namedtuple`, a new `Book` class, which has three attributes: `title`, `author`, and `price`. # 2. Create a list of `Book` objects (3-4 is fine), and put them inain a list. # 3. Ask the user repeatedly to enter the name of a book they want to buy. # - If the book is in inventory, then print all of its details, and add the price to the total # - If the book is *not* in inventory, then tell the user # - If we get an empty string, then we stop asking # 4. At the end, tell the user the final price. # In[115]: from collections import namedtuple Book = namedtuple('Book', ['title', 'author', 'price']) b1 = Book('title1', 'author1', 50) b2 = Book('title2', 'author1', 100) b3 = Book('title3', 'author2', 200) all_books = [b1, b2, b3] all_books # In[118]: total = 0 while True: s = input('Enter book title: ').strip() if not s: # if s is empty, then exit from the loop break found_book = False for one_book in all_books: if one_book.title == s: print(f'Found {s} by {one_book.author}, price {one_book.price}') total += one_book.price found_book = True break if not found_book: print(f'Did not find {s}') print(f'Total is {total}') # In[119]: total = 0 while True: s = input('Enter book title: ').strip() if not s: # if s is empty, then exit from the loop break for one_book in all_books: if one_book.title == s: print(f'Found {s} by {one_book.author}, price {one_book.price}') total += one_book.price break else: # got_to_end_of_loop_without_encountering_a_break print(f'Did not find {s}') print(f'Total is {total}') # In[121]: total = 0 # := "assignment expression" # "walrus" # starting with Python 3.8 while s := input('Enter book title: ').strip(): for one_book in all_books: if one_book.title == s: print(f'Found {s} by {one_book.author}, price {one_book.price}') total += one_book.price break else: # got_to_end_of_loop_without_encountering_a_break print(f'Did not find {s}') print(f'Total is {total}') # In[123]: if x := 5: print(x) # In[124]: print(f'{b1=}, {b2=}, {b3=}') # In[125]: # unpacking mylist = [10, 20, 30] x,y,z = mylist # In[126]: print(f'{x=}, {y=}, {z=}') # In[127]: title, author, price = b1 # In[128]: title # In[129]: author # In[130]: price # In[131]: total = 0 # := "assignment expression" # "walrus" # starting with Python 3.8 while s := input('Enter book title: ').strip(): for title, author, price in all_books: if title == s: print(f'Found {s} by {author}, price {price}') total += price break else: # got_to_end_of_loop_without_encountering_a_break print(f'Did not find {s}') print(f'Total is {total}') # In[132]: mylist = [10, 20, 30, 40, 50, 60] x,y,z = mylist # In[133]: x, *y, z = mylist # In[134]: x # In[135]: z # In[136]: y # In[137]: x,y,*z = mylist # In[138]: z # In[139]: x # In[140]: y # In[141]: d = {'a':1, 'b':2, 'c':3} # In[142]: # keys must be immutable -- typically, int, float, or string # values can be anything at all # In[143]: globals() # In[144]: d['a'] # In[145]: d['b'] # In[146]: d['c'] # In[147]: k = 'b' d[k] # In[148]: 'b' in d # In[149]: 3 in d # In[151]: k = 'b' if k in d: print(d[k]) else: print(f'{k} is not a key in d') # In[152]: k = 'v' if k in d: print(d[k]) else: print(f'{k} is not a key in d') # In[ ]: d.get('b') # if 'b' in d, we get d['b'] # In[154]: d.get('v') # if 'b' in d, we get d['b']... otherwise None # In[155]: print(d.get('v')) # In[156]: d.get('v', 'No such key in d') # # Exercise: Travel # # 1. Start with an empty dictionary, `all_places`. # 2. Ask the user, repeatedly, to give us a city + country in the form `city, country` # 3. If we got an empty string, we stop asking. # 4. If we got a string without `,`, scold the user and try again. # 5. Otherwise, take the city and country, and add to the dict: # - The countries will be keys (as string) # - The cities will be in a list. # 6. At the end, print all countries, and then all cities within those countries. # # Example: # # Where have you gone: New York, USA # Where have you gone: Chicago, USA # Where have you gone: Beijing, China # Where have you gone: Shanghai, China # Where have you gone: [ENTER] # # Our data structure: # # {'USA': ['New York', 'Chicago'], 'China': ['Beijing', 'Shanghai'} # # USA # New York # Chicago # China # Beijing # Shanghai # # In[159]: all_places = {} while s := input('Enter place: ').strip(): if ',' not in s: print(f'Enter "city, country"') continue city, country = s.split(',') city = city.strip() country = country.strip() # if country not in all_places: # all_places[country.strip()] = [] all_places.setdefault(country, []) if city in all_places[country]: print(f'We already got {city}!') continue all_places[country].append(city) for country, all_cities in all_places.items(): print(country) for one_city in all_cities: print(f'\t{one_city}') # In[158]: all_places # In[ ]:
[ "reuven@lerner.co.il" ]
reuven@lerner.co.il
6aa870cef6388448f00bc19edcd80f5e465a6ca7
fa4df5c5790b4c7af37c46ef82aeac1230e36a0e
/VRD/backend/factory/modifier_factory.py
b0b36c65ff883eab7821c81539e9fc22790904d7
[]
no_license
Gorgious56/VRD
32d548b6f2e096b151c49f83b80c48c351b1265d
f7d5bbb665ebaa4f3b1d274909c15fffb7b74bf5
refs/heads/master
2022-11-15T10:14:39.196704
2020-07-18T15:29:30
2020-07-18T15:29:30
280,684,740
0
0
null
null
null
null
UTF-8
Python
false
false
902
py
import bpy from typing import Iterable class ModSettings: def __init__(self, mod_type: str, mod_name: str, attributes: dict = None): self.mod_type = mod_type self.mod_name = mod_name self.attributes = attributes def add_modifier( obj: bpy.types.Object, settings: ModSettings, replace: bool = True) -> None: if settings.mod_name in obj.modifiers and not replace: return new_mod = obj.modifiers.new(name=settings.mod_name, type=settings.mod_type) if settings.attributes: for attr, value in settings.attributes.items(): if hasattr(new_mod, attr): setattr(new_mod, attr, value) new_mod.show_expanded = False def add_modifiers( obj: bpy.types.Object, mods: Iterable[ModSettings], replace: bool = True) -> None: (add_modifier(obj, mod, replace) for mod in mods)
[ "nathan.hild@gmail.com" ]
nathan.hild@gmail.com
2986f1a06afe7c78517613346f8667e2a57ab23a
525a0588ed3eb7ae5843e55522b6cc83ac2abd59
/biodivhack/urls.py
4febb1b8d565cc1db71a64ad24b5e976e748dafb
[]
no_license
dvoong/biodivhack
1601d51dc2a34b5a8002bbf7efd3faccfd5b93e1
618ce01016d212ed0463957180ee06c0b9d62fa0
refs/heads/master
2020-12-24T16:23:42.746356
2015-06-20T19:22:04
2015-06-20T19:22:04
37,766,232
0
0
null
null
null
null
UTF-8
Python
false
false
1,021
py
"""biodivhack URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.8/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Add an import: from blog import urls as blog_urls 2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls)) """ from django.conf.urls import include, url from django.contrib import admin from biodivhack import views urlpatterns = [ url(r'^$', views.index), url(r'^keyword-summary/(\d+)', views.keyword_summary), url(r'^reviews/(\d+)/(\d+)', views.review), url(r'^statuses/(\d+)', views.status), url(r'^add-to-database', views.add_to_database), url(r'^admin/', include(admin.site.urls)), ]
[ "voong.david@gmail.com" ]
voong.david@gmail.com
413e356a52c9f144199c7e864701249b61464792
541b292bda3e78b384b785335f2e6399c4702015
/hypergolix/cli.py
3eeb7a409a3906221519c552d042d028e6c18e39
[ "Unlicense" ]
permissive
Muterra/py_hypergolix
7b674bf83a79d7d4a503794f63f6d3d6c9de54e0
6d9ce0e0e4473ad2dc715d984b83e6c277260288
refs/heads/master
2021-04-22T04:58:23.005851
2017-05-19T00:52:41
2017-05-19T00:52:41
53,230,798
80
5
null
2017-05-19T00:52:41
2016-03-06T00:53:19
Python
UTF-8
Python
false
false
11,715
py
''' LICENSING ------------------------------------------------- hypergolix: A python Golix client. Copyright (C) 2016 Muterra, Inc. Contributors ------------ Nick Badger badg@muterra.io | badg@nickbadger.com | nickbadger.com This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA ------------------------------------------------------ ''' import argparse # ############################################### # Command-specific entry points # ############################################### from hypergolix.service import start as start_server from hypergolix.service import stop as stop_server from hypergolix.daemon import start as start_app from hypergolix.daemon import stop as stop_app from hypergolix.config import handle_args as config from hypergolix.config import NAMED_REMOTES # ############################################### # Root parsers # ############################################### root_parser = argparse.ArgumentParser( description = 'Hypergolix -- "programmable Dropbox" -- runs as a ' + 'background service for internet-connected applications. ' + 'Run and configure the Hypergolix daemon, or start or ' + 'stop a Hypergolix server, with this command.', prog = 'hypergolix' ) subparsers = root_parser.add_subparsers() start_parser = subparsers.add_parser( 'start', help = 'Start a Hypergolix app or server daemon.', prog = 'hypergolix start' ) start_subparsers = start_parser.add_subparsers() stop_parser = subparsers.add_parser( 'stop', help = 'Stop an existing Hypergolix app or server daemon.', prog = 'hypergolix stop' ) stop_subparsers = stop_parser.add_subparsers() config_parser = subparsers.add_parser( 'config', help = 'Configure the Hypergolix app.', prog = 'hypergolix config' ) # config_subparsers = config_parser.add_subparsers() # ############################################### # App start parser (hypergolix start app) # ############################################### app_start_parser = start_subparsers.add_parser( 'app', help = 'Start the Hypergolix app daemon.' ) app_start_parser.set_defaults(entry_point=start_app) # ############################################### # Server start parser (hypergolix start server) # ############################################### server_start_parser = start_subparsers.add_parser( 'server', help = 'Start the Hypergolix server daemon.', prog = 'hypergolix start server' ) server_start_parser.set_defaults(entry_point=start_server) server_start_parser.add_argument( 'pidfile', action = 'store', type = str, default = None, nargs = '?', help = 'The full path to the PID file we should use for the service.' ) server_start_parser.add_argument( '--cachedir', '-c', action = 'store', required = False, dest = 'cachedir', default = None, type = str, help = 'Specify a directory to use as a persistent cache for files. ' + 'If none is specified, will default to an in-memory-only ' + 'cache, which is, quite obviously, rather volatile.' ) server_start_parser.add_argument( '--host', '-H', action = 'store', dest = 'host', default = None, type = str, help = 'Specify the TCP host to use. Defaults to localhost only. ' + 'Passing the special (case-sensitive) string "AUTO" will ' + 'determine the current local IP address and bind to that. ' + 'Passing the special (case-sensitive) string "ANY" will bind ' + 'to any host at the specified port (not recommended).' ) server_start_parser.add_argument( '--port', '-p', action = 'store', dest = 'port', default = None, type = int, help = 'Specify the TCP port to use. Defaults to 7770.' ) server_start_parser.add_argument( '--chdir', action = 'store', default = None, type = str, help = 'Once the daemon starts, chdir it into the specified full ' + 'directory path. By default, the daemon will remain in the ' + 'current directory, which may create DirectoryBusy errors.' ) server_start_parser.add_argument( '--logdir', action = 'store', default = None, type = str, help = 'Specify a directory to use for logs. Every service failure, ' + 'error, message, etc will go to dev/null without this.' ) server_start_parser.add_argument( '--debug', default = None, action = 'store_true', help = 'Enable debug mode. Sets verbosity to debug unless overridden.' ) server_start_parser.add_argument( '--traceur', default = None, action = 'store_true', help = 'Enable thorough analysis, including stack tracing. ' 'Implies verbosity of debug.' ) server_start_parser.add_argument( '--verbosity', '-V', action = 'store', dest = 'verbosity', type = str, choices = ['debug', 'info', 'warning', 'error', 'shouty', 'extreme'], default = None, help = 'Sets the log verbosity. Only applicable if --logdir is set.' ) # ############################################### # App stop parser (hypergolix stop app) # ############################################### app_stop_parser = stop_subparsers.add_parser( 'app', help = 'Stop the Hypergolix app daemon.', prog = 'hypergolix stop server' ) app_stop_parser.set_defaults(entry_point=stop_app) # ############################################### # Server stop parser (hypergolix stop server) # ############################################### server_stop_parser = stop_subparsers.add_parser( 'server', help = 'Stop the Hypergolix server daemon.' ) server_stop_parser.set_defaults(entry_point=stop_server) server_stop_parser.add_argument( 'pidfile', action = 'store', type = str, default = None, nargs = '?', help = 'The full path to the PID file we should use for the service.' ) # ############################################### # Config parser (hypergolix config) # ############################################### config_parser.set_defaults(entry_point=config) config_parser.add_argument( '--root', action = 'store', type = str, help = 'Manually specify the Hypergolix root directory.', dest = 'cfg_root', default = None ) # Remotes config # ----------------------------------------------- remote_group = config_parser.add_argument_group( title = 'Remotes configuration', description = 'Specify which remote persistence servers Hypergolix ' + 'should use.' ) # Exclusive autoconfig (also, clear all hosts) remote_group.add_argument( '--only', '-o', action = 'store', type = str, help = 'Automatically configure Hypergolix to use only a single, ' + 'named remote (or no remote). Does not affect the remainder ' + 'of the configuration.', choices = ['local', *NAMED_REMOTES], dest = 'only_remotes', default = None, ) # Auto-add remote_group.add_argument( '--add', '-a', action = 'append', type = str, help = 'Add a named remote to the Hypergolix configuration. Cannot ' + 'be combined with --only.', choices = NAMED_REMOTES, dest = 'add_remotes' ) # Auto-remove remote_group.add_argument( '--remove', '-r', action = 'append', type = str, help = 'Remove a named remote from the Hypergolix configuration. ' + 'Cannot be combined with --only.', choices = NAMED_REMOTES, dest = 'remove_remotes' ) # Manually add a host remote_group.add_argument( '--addhost', '-ah', action = 'append', type = str, help = 'Add a remote host, of form "hostname port use_TLS". Example ' + 'usage: "hypergolix.config --adhost 192.168.0.1 7770 False". ' + 'Cannot be combined with --only.', nargs = 3, metavar = ('HOST', 'PORT', 'TLS'), dest = 'add_remotes' ) # Manually remove a host remote_group.add_argument( '--removehost', '-rh', action = 'append', type = str, help = 'Remove a remote host, of form "hostname port". Example ' + 'usage: "hypergolix.config --removehost 192.168.0.1 7770". ' + 'Cannot be combined with --only.', nargs = 2, metavar = ('HOST', 'PORT'), dest = 'remove_remotes' ) # Set defaults for those two as well config_parser.set_defaults(remove_remotes=[], add_remotes=[]) # Runtime config # ----------------------------------------------- runtime_group = config_parser.add_argument_group( title = 'Runtime configuration', description = 'Specify Hypergolix runtime options.' ) # Set debug mode. # Make the debug parser a mutually exclusive group with flags. debug_parser = runtime_group.add_mutually_exclusive_group(required=False) debug_parser.add_argument( '--debug', action = 'store_true', dest = 'debug', help = 'Enables debug mode.' ) debug_parser.add_argument( '--no-debug', action = 'store_false', dest = 'debug', help = 'Clears debug mode.' ) config_parser.set_defaults(debug=None) # Set verbosity runtime_group.add_argument( '--verbosity', '-v', action = 'store', default = None, type = str, choices = ['extreme', 'shouty', 'debug', 'louder', 'info', 'loud', 'warning', 'normal', 'error', 'quiet'], help = 'Specify the logging level.' ) # Set verbosity runtime_group.add_argument( '--ipc-port', '-ipc', action = 'store', default = None, type = int, help = 'Configure which port to use for Hypergolix IPC.', metavar = 'PORT' ) # Etc # ----------------------------------------------- etc_group = config_parser.add_argument_group( title = 'Miscellaneous commands' ) # Set verbosity etc_group.add_argument( '--whoami', action = 'store_true', help = 'Print the fingerprint and user ID for the current ' + 'Hypergolix configuration.' ) # Set verbosity etc_group.add_argument( '--register', action = 'store_true', help = 'Register the current Hypergolix user, allowing them access ' + 'to the hgx.hypergolix.com remote persister. Requires a web ' + 'browser.' ) # ############################################### # Master entry point (hypergolix) # ############################################### def main(argv=None): ''' Entry point for all command line stuff. ''' # This allows us to test with an explicit argstring instead of through the # command line only args = root_parser.parse_args(args=argv) try: # This invokes the entry point with the parsed args args.entry_point(args) except AttributeError: # Let the invoker know that no command was selected print('Invalid command selected. Type "hypergolix -h" for usage.') except Exception as exc: root_parser.error(str(exc)) if __name__ == '__main__': # We now return to your regularly scheduled programming main()
[ "badg@nickbadger.com" ]
badg@nickbadger.com
79724f1ea72d380422927eb99113cb5d4c02866d
4af454bced0f99e4ed8269d71e97284f0ef13afb
/gameserver/api/__init__.py
7c75af4919b7a1a0716aba1e04d76f1cb60c1af0
[]
no_license
L2jBrasil/L2py
c46db78238b4caf272a2399f4e4910fc256b3cca
d1c2e7bddb54d222f9a3d04262c09ad70329a226
refs/heads/master
2022-11-19T01:39:02.019777
2020-07-24T20:07:15
2020-07-24T20:07:15
292,115,581
1
1
null
2020-09-01T21:53:54
2020-09-01T21:53:54
null
UTF-8
Python
false
false
38
py
from .login_client import LoginClient
[ "yurzs@icloud.com" ]
yurzs@icloud.com
d1a50006728152eb14ee0200eb479b5264089dc0
28b1036824bfa4c3290d285090f073c3676a4389
/my1stsite/settings/testing.py
2d67d73d80806b9830c7bdded15661987ba366f5
[]
no_license
zoie0312/my1stsite
ee0154409d2ac9ed1408f1b8736ef6a1547e82fb
b147102e332f789ee430e4666717189ae6e88d51
refs/heads/master
2021-01-22T04:41:15.006631
2013-11-29T02:36:30
2013-11-29T02:36:30
null
0
0
null
null
null
null
UTF-8
Python
false
false
387
py
from .base import * DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', 'USER': '', 'PASSWORD': '', 'HOST': '', 'PORT': '', } } TEST_RUNNER = 'discover_runner.DiscoverRunner' TEST_DISCOVER_TOP_LEVEL = root('..') TEST_DISCOVER_ROOT = root('..') TEST_DISCOVER_PATTERN = 'test_*'
[ "vagrant@precise64.(none)" ]
vagrant@precise64.(none)
c4681ca77b4913f01fadb65694fba7264ec93bb4
f2b172f7c1dcf0ac28fe7465b5844b48facade18
/12/1207/1207.py
5d2fce8683456a4a169c17b65ac51d8606aae2cc
[]
no_license
0gravity000/IntroducingPython
2fde12485d0597e72a7da801a08d5048a47f2ff5
5d3281dbe37ed1a08d71cb6a36841781f9ac0ccf
refs/heads/master
2023-07-19T02:53:23.081806
2021-09-30T01:51:44
2021-09-30T01:51:44
403,935,207
0
0
null
null
null
null
UTF-8
Python
false
false
280
py
# 12.7 Pythonコードのデバッグ # デバックでもっとも単純なのは、文字列を表示すること # vars()は、関数への引数を含むローカル変数の値を抽出する def func(*args, **kwargs): print(vars()) func(1, 2, 3) func(['a', 'b', 'argh'])
[ "0gravity000@gmail.com" ]
0gravity000@gmail.com
fbfb74e10109085225bb38751b05a62c682c4b98
321b4ed83b6874eeb512027eaa0b17b0daf3c289
/701/701.insert-into-a-binary-search-tree.291646803.Wrong-Answer.leetcode.python3.py
3687f08550163587025901f57d3b5e1f85a4cfef
[]
no_license
huangyingw/submissions
7a610613bdb03f1223cdec5f6ccc4391149ca618
bfac1238ecef8b03e54842b852f6fec111abedfa
refs/heads/master
2023-07-25T09:56:46.814504
2023-07-16T07:38:36
2023-07-16T07:38:36
143,352,065
0
1
null
null
null
null
UTF-8
Python
false
false
533
py
class Solution(): def insertIntoBST(self, root, val): root_head = root root_val = TreeNode(val) while True: if val < root.val: if not root.left: root = root.left else: root.left = root_val break else: if not root.right: root = root.right else: root.right = root_val break return root_head
[ "huangyingw@gmail.com" ]
huangyingw@gmail.com
cce56bc46a072cd4a07a8d3c7507c78ed15de20d
62e58c051128baef9452e7e0eb0b5a83367add26
/edifact/D98B/REQOTED98BUN.py
830d94b77397c27e9f72d80b435724d8e803eb91
[]
no_license
dougvanhorn/bots-grammars
2eb6c0a6b5231c14a6faf194b932aa614809076c
09db18d9d9bd9d92cefbf00f1c0de1c590fe3d0d
refs/heads/master
2021-05-16T12:55:58.022904
2019-05-17T15:22:23
2019-05-17T15:22:23
105,274,633
0
0
null
2017-09-29T13:21:21
2017-09-29T13:21:21
null
UTF-8
Python
false
false
7,917
py
#Generated by bots open source edi translator from UN-docs. from bots.botsconfig import * from edifact import syntax from recordsD98BUN import recorddefs structure = [ {ID: 'UNH', MIN: 1, MAX: 1, LEVEL: [ {ID: 'BGM', MIN: 1, MAX: 1}, {ID: 'DTM', MIN: 1, MAX: 35}, {ID: 'PAI', MIN: 0, MAX: 1}, {ID: 'ALI', MIN: 0, MAX: 5}, {ID: 'IMD', MIN: 0, MAX: 999}, {ID: 'IRQ', MIN: 0, MAX: 10}, {ID: 'FTX', MIN: 0, MAX: 99}, {ID: 'RFF', MIN: 0, MAX: 9999, LEVEL: [ {ID: 'DTM', MIN: 0, MAX: 5}, ]}, {ID: 'AJT', MIN: 0, MAX: 1, LEVEL: [ {ID: 'FTX', MIN: 0, MAX: 5}, ]}, {ID: 'TAX', MIN: 0, MAX: 5, LEVEL: [ {ID: 'MOA', MIN: 0, MAX: 1}, {ID: 'LOC', MIN: 0, MAX: 5}, ]}, {ID: 'CUX', MIN: 0, MAX: 5, LEVEL: [ {ID: 'DTM', MIN: 0, MAX: 5}, ]}, {ID: 'PAT', MIN: 0, MAX: 10, LEVEL: [ {ID: 'DTM', MIN: 0, MAX: 5}, {ID: 'PCD', MIN: 0, MAX: 1}, {ID: 'MOA', MIN: 0, MAX: 1}, ]}, {ID: 'TOD', MIN: 0, MAX: 10, LEVEL: [ {ID: 'LOC', MIN: 0, MAX: 2}, ]}, {ID: 'EQD', MIN: 0, MAX: 10, LEVEL: [ {ID: 'HAN', MIN: 0, MAX: 5}, {ID: 'MEA', MIN: 0, MAX: 5}, {ID: 'FTX', MIN: 0, MAX: 5}, ]}, {ID: 'RCS', MIN: 0, MAX: 999, LEVEL: [ {ID: 'RFF', MIN: 0, MAX: 5}, {ID: 'DTM', MIN: 0, MAX: 5}, {ID: 'FTX', MIN: 0, MAX: 99999}, ]}, {ID: 'APR', MIN: 0, MAX: 25, LEVEL: [ {ID: 'PRI', MIN: 0, MAX: 1}, {ID: 'QTY', MIN: 0, MAX: 2}, {ID: 'DTM', MIN: 0, MAX: 1}, {ID: 'MOA', MIN: 0, MAX: 2}, {ID: 'RNG', MIN: 0, MAX: 2}, ]}, {ID: 'DLM', MIN: 0, MAX: 1, LEVEL: [ {ID: 'MOA', MIN: 0, MAX: 1}, {ID: 'DTM', MIN: 0, MAX: 1}, ]}, {ID: 'NAD', MIN: 0, MAX: 99, LEVEL: [ {ID: 'LOC', MIN: 0, MAX: 25}, {ID: 'FII', MIN: 0, MAX: 5}, {ID: 'RFF', MIN: 0, MAX: 99, LEVEL: [ {ID: 'DTM', MIN: 0, MAX: 5}, ]}, {ID: 'DOC', MIN: 0, MAX: 5, LEVEL: [ {ID: 'DTM', MIN: 0, MAX: 1}, ]}, {ID: 'CTA', MIN: 0, MAX: 5, LEVEL: [ {ID: 'COM', MIN: 0, MAX: 5}, ]}, ]}, {ID: 'TDT', MIN: 0, MAX: 10, LEVEL: [ {ID: 'QTY', MIN: 0, MAX: 5}, {ID: 'LOC', MIN: 0, MAX: 10, LEVEL: [ {ID: 'DTM', MIN: 0, MAX: 5}, ]}, ]}, {ID: 'PAC', MIN: 0, MAX: 99, LEVEL: [ {ID: 'MEA', MIN: 0, MAX: 5}, {ID: 'PCI', MIN: 0, MAX: 10, LEVEL: [ {ID: 'RFF', MIN: 0, MAX: 1}, {ID: 'DTM', MIN: 0, MAX: 5}, {ID: 'GIN', MIN: 0, MAX: 10}, ]}, ]}, {ID: 'SCC', MIN: 0, MAX: 10, LEVEL: [ {ID: 'FTX', MIN: 0, MAX: 5}, {ID: 'QTY', MIN: 0, MAX: 10, LEVEL: [ {ID: 'DTM', MIN: 0, MAX: 5}, ]}, ]}, {ID: 'ALC', MIN: 0, MAX: 99, LEVEL: [ {ID: 'ALI', MIN: 0, MAX: 5}, {ID: 'QTY', MIN: 0, MAX: 1, LEVEL: [ {ID: 'RNG', MIN: 0, MAX: 1}, ]}, {ID: 'PCD', MIN: 0, MAX: 1, LEVEL: [ {ID: 'RNG', MIN: 0, MAX: 1}, ]}, {ID: 'MOA', MIN: 0, MAX: 2, LEVEL: [ {ID: 'RNG', MIN: 0, MAX: 1}, ]}, {ID: 'RTE', MIN: 0, MAX: 1, LEVEL: [ {ID: 'RNG', MIN: 0, MAX: 1}, ]}, {ID: 'TAX', MIN: 0, MAX: 5, LEVEL: [ {ID: 'MOA', MIN: 0, MAX: 1}, ]}, ]}, {ID: 'LIN', MIN: 1, MAX: 200000, LEVEL: [ {ID: 'PIA', MIN: 0, MAX: 25}, {ID: 'IMD', MIN: 0, MAX: 99}, {ID: 'MEA', MIN: 0, MAX: 5}, {ID: 'QTY', MIN: 0, MAX: 99}, {ID: 'PCD', MIN: 0, MAX: 1}, {ID: 'ALI', MIN: 0, MAX: 5}, {ID: 'DTM', MIN: 0, MAX: 35}, {ID: 'GIN', MIN: 0, MAX: 1000}, {ID: 'GIR', MIN: 0, MAX: 1000}, {ID: 'QVR', MIN: 0, MAX: 1}, {ID: 'FTX', MIN: 0, MAX: 99}, {ID: 'PAI', MIN: 0, MAX: 1}, {ID: 'DOC', MIN: 0, MAX: 99}, {ID: 'CCI', MIN: 0, MAX: 999, LEVEL: [ {ID: 'CAV', MIN: 0, MAX: 10}, {ID: 'MEA', MIN: 0, MAX: 10}, ]}, {ID: 'MOA', MIN: 0, MAX: 100, LEVEL: [ {ID: 'QTY', MIN: 0, MAX: 2}, {ID: 'IMD', MIN: 0, MAX: 1}, {ID: 'CUX', MIN: 0, MAX: 1}, {ID: 'DTM', MIN: 0, MAX: 2}, ]}, {ID: 'AJT', MIN: 0, MAX: 1, LEVEL: [ {ID: 'FTX', MIN: 0, MAX: 5}, ]}, {ID: 'PRI', MIN: 0, MAX: 99, LEVEL: [ {ID: 'APR', MIN: 0, MAX: 1}, {ID: 'RNG', MIN: 0, MAX: 1}, {ID: 'CUX', MIN: 0, MAX: 5}, {ID: 'DTM', MIN: 0, MAX: 5}, ]}, {ID: 'RFF', MIN: 0, MAX: 9999, LEVEL: [ {ID: 'DTM', MIN: 0, MAX: 5}, ]}, {ID: 'LOC', MIN: 0, MAX: 100, LEVEL: [ {ID: 'QTY', MIN: 0, MAX: 1}, {ID: 'DTM', MIN: 0, MAX: 5}, ]}, {ID: 'TAX', MIN: 0, MAX: 10, LEVEL: [ {ID: 'MOA', MIN: 0, MAX: 1}, {ID: 'LOC', MIN: 0, MAX: 5}, ]}, {ID: 'TOD', MIN: 0, MAX: 5, LEVEL: [ {ID: 'LOC', MIN: 0, MAX: 2}, ]}, {ID: 'EQD', MIN: 0, MAX: 10, LEVEL: [ {ID: 'HAN', MIN: 0, MAX: 5}, {ID: 'MEA', MIN: 0, MAX: 5}, {ID: 'FTX', MIN: 0, MAX: 5}, ]}, {ID: 'RCS', MIN: 0, MAX: 999, LEVEL: [ {ID: 'RFF', MIN: 0, MAX: 5}, {ID: 'DTM', MIN: 0, MAX: 5}, {ID: 'FTX', MIN: 0, MAX: 99999}, ]}, {ID: 'PAT', MIN: 0, MAX: 10, LEVEL: [ {ID: 'DTM', MIN: 0, MAX: 5}, {ID: 'PCD', MIN: 0, MAX: 1}, {ID: 'MOA', MIN: 0, MAX: 1}, ]}, {ID: 'PAC', MIN: 0, MAX: 99, LEVEL: [ {ID: 'MEA', MIN: 0, MAX: 5}, {ID: 'QTY', MIN: 0, MAX: 5}, {ID: 'DTM', MIN: 0, MAX: 5}, {ID: 'RFF', MIN: 0, MAX: 5, LEVEL: [ {ID: 'DTM', MIN: 0, MAX: 5}, ]}, {ID: 'PCI', MIN: 0, MAX: 10, LEVEL: [ {ID: 'RFF', MIN: 0, MAX: 1}, {ID: 'DTM', MIN: 0, MAX: 5}, {ID: 'GIN', MIN: 0, MAX: 10}, ]}, ]}, {ID: 'NAD', MIN: 0, MAX: 999, LEVEL: [ {ID: 'LOC', MIN: 0, MAX: 5}, {ID: 'RFF', MIN: 0, MAX: 99, LEVEL: [ {ID: 'DTM', MIN: 0, MAX: 5}, ]}, {ID: 'DOC', MIN: 0, MAX: 5, LEVEL: [ {ID: 'DTM', MIN: 0, MAX: 5}, ]}, {ID: 'CTA', MIN: 0, MAX: 5, LEVEL: [ {ID: 'COM', MIN: 0, MAX: 5}, ]}, ]}, {ID: 'ALC', MIN: 0, MAX: 99, LEVEL: [ {ID: 'ALI', MIN: 0, MAX: 5}, {ID: 'QTY', MIN: 0, MAX: 1, LEVEL: [ {ID: 'RNG', MIN: 0, MAX: 1}, ]}, {ID: 'PCD', MIN: 0, MAX: 1, LEVEL: [ {ID: 'RNG', MIN: 0, MAX: 1}, ]}, {ID: 'MOA', MIN: 0, MAX: 2, LEVEL: [ {ID: 'RNG', MIN: 0, MAX: 1}, ]}, {ID: 'RTE', MIN: 0, MAX: 1, LEVEL: [ {ID: 'RNG', MIN: 0, MAX: 1}, ]}, {ID: 'TAX', MIN: 0, MAX: 5, LEVEL: [ {ID: 'MOA', MIN: 0, MAX: 1}, ]}, ]}, {ID: 'TDT', MIN: 0, MAX: 10, LEVEL: [ {ID: 'QTY', MIN: 0, MAX: 5}, {ID: 'LOC', MIN: 0, MAX: 10, LEVEL: [ {ID: 'DTM', MIN: 0, MAX: 5}, ]}, ]}, {ID: 'SCC', MIN: 0, MAX: 100, LEVEL: [ {ID: 'FTX', MIN: 0, MAX: 5}, {ID: 'QTY', MIN: 0, MAX: 10, LEVEL: [ {ID: 'DTM', MIN: 0, MAX: 5}, ]}, ]}, ]}, {ID: 'UNS', MIN: 1, MAX: 1}, {ID: 'MOA', MIN: 0, MAX: 15}, {ID: 'CNT', MIN: 0, MAX: 10}, {ID: 'ALC', MIN: 0, MAX: 10, LEVEL: [ {ID: 'MOA', MIN: 1, MAX: 1}, {ID: 'ALI', MIN: 0, MAX: 1}, ]}, {ID: 'UNT', MIN: 1, MAX: 1}, ]}, ]
[ "jason.capriotti@gmail.com" ]
jason.capriotti@gmail.com
c07f51e53dc8e49f9eef1416a8fd830023679490
9dba277eeb0d5e9d2ac75e2e17ab5b5eda100612
/exercises/1901040051/day11/mymodule/main1.py
6d64c07eba011299f1539a221de2d0c5df683f51
[]
no_license
shen-huang/selfteaching-python-camp
e8410bfc06eca24ee2866c5d890fd063e9d4be89
459f90c9f09bd3a3df9e776fc64dfd64ac65f976
refs/heads/master
2022-05-02T05:39:08.932008
2022-03-17T07:56:30
2022-03-17T07:56:30
201,287,222
9
6
null
2019-08-08T15:34:26
2019-08-08T15:34:25
null
UTF-8
Python
false
false
2,360
py
import jieba import re import json import sys import collections from collections import Counter sys.path.append("c:") # import stats_word with open("mymodule/tang300.json", "r", encoding="utf-8") as file: try: read_data = file.read() except ValueError as e: print(e) def stats_text_en(en,count) : ''' 1. 英文词频统计:使用正则表达式过滤英文字符,使用Counter统计并排序。 2. 参数类型检查,不为字符串抛出异常。 ''' if type(en) == str : text_en = re.sub("[^A-Za-z]", " ", en.strip()) # text_en = ''.join(text_en) enList = text_en.split( ) return collections.Counter(enList).most_common(count) else : raise ValueError ('type of argumengt is not str') # print(stats_text_en(read_data, 4)) def stats_text_cn(cn,count) : ''' 1. 使用jieba第三方库精确模式分词。 2. 使用正则表达式过滤汉字字符。 3. 使用for循环判断分词后词频列表元素长度大于等于2的生成新列表。 4. 使用标准库collections.Counter()统计词频并限制统计数量。 5. 参数类型检查,不为字符串抛出异常。 ''' if type(cn) == str : cnList = re.findall(u'[\u4e00-\u9fff]+', cn.strip()) cnString = ''.join(cnList) segList = jieba.cut(cnString,cut_all=False) cnnewList = [] for i in segList : if len(i) >= 2 : cnnewList.append(i) else : pass return collections.Counter(cnnewList).most_common(count) else : raise ValueError ('type of argumengt is not str') # print(stats_text_cn(read_data, 2)) def stats_text(text_en_cn,count_en_cn) : ''' 1. 合并英汉词频统计:调用stats_text_en()和stats_text_cn()并合并其结果。 2. 参数类型检查,不为字符串抛出异常。 ''' if type(text_en_cn) == str : return stats_text_en(text_en_cn,count_en_cn)+stats_text_cn(text_en_cn,count_en_cn) else : raise ValueError ('type of argumengt is not str') print('输出词频最高的前20个中文词:\n ', stats_text_cn(read_data,20))
[ "40155646+seven-tears@users.noreply.github.com" ]
40155646+seven-tears@users.noreply.github.com
a8ddc101a423861f9bad5474af8d432f66c1eb80
f0d713996eb095bcdc701f3fab0a8110b8541cbb
/RzrKedEonc3BJGhY5_12.py
a021d787d5af49db12fceee016b509e732de9173
[]
no_license
daniel-reich/turbo-robot
feda6c0523bb83ab8954b6d06302bfec5b16ebdf
a7a25c63097674c0a81675eed7e6b763785f1c41
refs/heads/main
2023-03-26T01:55:14.210264
2021-03-23T16:08:01
2021-03-23T16:08:01
350,773,815
0
0
null
null
null
null
UTF-8
Python
false
false
1,372
py
""" **Mubashir** needs your help to plant some trees. He can give you three parameters of the land: * **width** of the land `w` * **length** of the land `l` * **gap** between the trees `g` You have to create an algorithm to return the **number of trees** which can be planted **on the edges** of the given land in a **symmetrical layout** shown below (unsymmetrical gap = x, tree = o, gap = -): w=3, l=3, g=1 plant_trees(w, l, g) ➞ 4 o - o - - o - o # Mubashir can plant 4 trees. w=3, l=3, g=3 plant_trees(w, l, g) ➞ 2 o - - - - - - o # Mubashir can plant 2 trees. If the layout is not symmetrical, you have to return `0`: w=3, l=3, g=2 plant_trees(w, l, g) ➞ 0 o - - x o x x x # Planting 2 trees mean the gap of two trees will be greater than 2. o - - x o o - - # Planting 3 trees mean the gap of two trees will be less than 2. Another Example for better understanding: w=3, l=3, g=0 plant_trees(w, l, g) ➞ 8 o o o o o o o o # Mubashir can plant 8 trees. ### Notes N/A """ def plant_trees(w, l, g): perimeter = 2*w + 2*l - 4 if w == 0 or l == 0: return 0 elif perimeter%(g+1) == 0: return int(perimeter/(g+1)) else: return 0
[ "daniel.reich@danielreichs-MacBook-Pro.local" ]
daniel.reich@danielreichs-MacBook-Pro.local
dd533c06790b50ac9ae03e9af75ebdd783e97e20
e9983a186a30a461507064533aa7459d2df0a6ef
/afmformats/fmt_jpk/read_jpk.py
be85886b7d9d290cbb6119063e7ba20a213bf04d
[ "MIT" ]
permissive
ericpre/afmformats
f8f04647d51cf3d974660e36bcf67d031de8a7f8
f783eb0ae8faae3919daef501e06eb8e43ec36ec
refs/heads/master
2021-02-08T23:28:09.214311
2020-02-19T11:01:58
2020-02-19T11:01:58
244,210,475
0
0
null
2020-03-01T19:29:04
2020-03-01T19:29:03
null
UTF-8
Python
false
false
18,939
py
"""Methods to open JPK data files and to obtain meta data""" import pathlib import shutil import zipfile import numpy as np from . import read_jpk_meta as meta from ..errors import FileFormatNotSupportedError class ReadJPKError(FileFormatNotSupportedError): pass class ReadJPKColumnError(BaseException): pass VALID_IDS_FORCE = ["vDeflection"] VALID_IDS_HEIGHT = ["strainGaugeHeight", "capacitiveSensorHeight", "measuredHeight"] VALID_IDS_PIEZO = ["height", "head-height"] def find_column(loc_list, id_list): """Find a column in a list of strings Parameters ---------- loc_list: list of str The segment's data location list (within the archive), e.g. ['segments/0/channels/height.dat', 'segments/0/channels/vDeflection.dat', 'segments/0/channels/strainGaugeHeight.dat'] id_list: list of str Data identifiers to match up, e.g. `VALID_IDS_HEIGHT` Returns ------- column: str Matched column name, e.g. "strainGaugeHeight" loc: str Matched segment location, e.g. "segments/0/channels/strainGaugeHeight.dat" """ col = None for dd in loc_list: cn = dd.rsplit("/")[-1].rsplit(".")[0] for vc in id_list: if vc == cn: col = vc break if col: break else: msg = "No data found for: {}".format(id_list) raise ReadJPKError(msg) return col, dd def load_jpk(path, callback=None): """Extracts force, measured height, and time from JPK files All columns are returned in SI units. Parameters ---------- path: str Path to a JPK force file callback: callable or None A method that accepts a float between 0 and 1 to externally track the process of loading the data. """ path = pathlib.Path(path) if callback: callback(0) # First, only extract the properties tdir = meta.extract_jpk(path, props_only=True) # Get data file names indexlist = meta.get_data_list(path) measurements = [] try: with zipfile.ZipFile(str(path)) as arc: for ii, item in enumerate(indexlist): mm = [] segroot = tdir / item[0][0].rsplit("segments", 1)[0] # go through the segments for mi, curve in enumerate(item): if segroot == tdir: enum = 0 else: enum = int(segroot.name) # mi == 0: approach # mi == 1: retract # get meta data # (segfolder contains "segment-header.properties") segfolder = tdir / curve[0].rsplit("channels")[0] try: mdi = meta.get_meta_data_seg(segfolder) except meta.ReadJPKMetaKeyError as exc: exc.args = ("{}, File: '{}'".format(exc.args[0], path)) raise mdi["enum"] = enum segment = {} # segment time segment["time"] = np.linspace(0, mdi["duration"], mdi["point count"], endpoint=False) # load force data force_col, force_dat = find_column(loc_list=curve, id_list=VALID_IDS_FORCE) arc.extract(force_dat, str(tdir)) force, unit, _n = load_jpk_single_curve(segroot, segment=mi, column=force_col, slot="force") if unit != "N": msg = "Unknown unit for force: {}".format(unit) raise ReadJPKError(msg) segment["force"] = force # load height (measured) data meas_col, meas_dat = find_column(loc_list=curve, id_list=VALID_IDS_HEIGHT) arc.extract(meas_dat, str(tdir)) height, unit, _ = load_jpk_single_curve(segroot, segment=mi, column=meas_col, slot="nominal") if unit != "m": msg = "Unknown unit for height: {}".format(unit) raise ReadJPKError(msg) segment["height (measured)"] = height # load height (piezo) data piezo_col, piezo_dat = find_column(loc_list=curve, id_list=VALID_IDS_PIEZO) arc.extract(piezo_dat, str(tdir)) heightp, unit, _ = load_jpk_single_curve(segroot, segment=mi, column=piezo_col, slot="calibrated") if unit != "m": msg = "Unknown unit for piezo height: {}".format(unit) raise ReadJPKError(msg) segment["height (piezo)"] = heightp mm.append([segment, mdi, path]) if callback: # Callback with a float between 0 and 1 to update # a progress dialog or somesuch. callback(ii/len(indexlist)) measurements.append(mm) shutil.rmtree(str(segroot)) except BaseException: raise finally: shutil.rmtree(str(tdir), ignore_errors=True) return measurements def load_jpk_single_curve(path_jpk, segment=0, column="vDeflection", slot="default"): """Load a single curve from a jpk-force file Parameters ---------- path_jpk : str Path to a jpk-force file or to a directory containing "segments" segment: int Index of the segment to use. column: str Column name; one of: - "height" : piezzo height - "vDeflection": measured deflection - "straingGaugeHeight": measured height slot: str The .dat files in the JPK measurement zip files come with different calibration slots. Valid values are - For the height of the piezo crystal during measurement (the piezo height is not as accurate as the measured height from the height sensor; the piezo movement is not linear): "height.dat": "volts", "nominal", "calibrated" - For the measured height of the cantilever: "strainGaugeHeight.dat": "volts", "nominal", "absolute" "measuredHeight.dat": "volts", "nominal", "absolute" "capacitiveSensorHeight": "volts", "nominal", "absolute" (they are all the same) - For the recorded cantilever deflection: "vDeflection.dat": "volts", "distance", "force" Returns ------- data: 1d ndarray A numpy array containing the scaled data. unit: str A string representing the metric unit of the data. name: str The name of the data column. Notes ----- This method does is not designed for directly opening JPK files. Please use the `load_jpk` method instead, which wraps around this method and handles exceptions better. """ path_jpk = pathlib.Path(path_jpk) if path_jpk.is_dir(): tdir = path_jpk cleanup = False else: tdir = meta.extract_jpk(path_jpk) cleanup = True segroot = tdir / "segments" if not segroot.exists(): raise OSError("No `segments` subdir found in {}!".format(tdir)) if not (segroot / str(segment)).exists(): raise ValueError("Segment {} not found in {}!".format(segment, path_jpk)) chroot = segroot / str(segment) / "channels" channels = chroot.glob("*.dat") for ch in channels: key = ch.stem if key == column: data = load_dat_unit(ch, slot=slot) break else: msg = "No data for column '{}' and slot '{}'".format(column, slot) raise ReadJPKColumnError(msg) if cleanup: shutil.rmtree(str(tdir)) return data def retrieve_segments_data(path_dir): """From an extracted jpk file, retrieve the containing segments This is a convenience method that returns a list of the measurement data with the default slot, including units and column names. Parameters ---------- path_dir: str Path to a directory containing a "segments" folder. Returns ------- segment_list: list A list with items: [data, unit, column_name] """ path_dir = pathlib.Path(path_dir) segroot = path_dir / "segments" segment_data = [] for se in sorted(segroot.glob("[0-1]")): chan_data = [] chroot = se / "channels" for ch in chroot.glob("*.dat"): chan_data.append(load_dat_unit(ch)) segment_data.append(chan_data) return segment_data def load_dat_raw(path_dat): """Load data from binary JPK .dat files Parameters ---------- path_dat: str Path to a .dat file. A `segment-header.properties` file must be present in the parent folder. Returns ------- data: 1d ndarray A numpy array with the raw data. Notes ----- This method tries to correctly determine the data type of the binary data and scales it with the `data.encoder.scaling` values given in the header files. See Also -------- load_dat_unit: Includes conversion to useful units """ path_dat = pathlib.Path(path_dat).resolve() key = path_dat.stem # open header file header_file = path_dat.parents[1] / "segment-header.properties" prop = meta.get_seg_head_prop(header_file) # extract multiplier and offset from header # multiplier mult_str1 = "channel.{}.data.encoder.scaling.multiplier".format(key) mult_str2 = "channel.{}.encoder.scaling.multiplier".format(key) try: mult = prop[mult_str1] except BaseException: mult = prop[mult_str2] # offset off_str1 = "channel.{}.data.encoder.scaling.offset".format(key) off_str2 = "channel.{}.encoder.scaling.offset".format(key) try: off = prop[off_str1] except BaseException: off = prop[off_str2] # get encoder enc_str1 = "channel.{}.data.encoder.type".format(key) enc_str2 = "channel.{}.encoder.type".format(key) try: enc = prop[enc_str1] except BaseException: enc = prop[enc_str2] # determine encoder if enc == "signedshort": mydtype = np.dtype(">i2") elif enc == "unsignedshort": mydtype = np.dtype(">u2") elif enc == "signedinteger": mydtype = np.dtype(">i4") elif enc == "unsignedinteger": mydtype = np.dtype(">u4") elif enc == "signedlong": mydtype = np.dtype(">i8") else: raise NotImplementedError("Data file format '{}' not supported". format(enc)) data = np.fromfile(str(path_dat), dtype=mydtype) * mult + off return data def load_dat_unit(path_dat, slot="default"): """Load data from a JPK .dat file with a specific calibration slot Parameters ---------- path_dat : str Path to a .dat file slot: str The .dat files in the JPK measurement zip files come with different calibration slots. Valid values are - For the height of the piezo crystal during measurement (the piezo height is not as accurate as the measured height from the height sensor; the piezo movement is not linear): "height.dat": "volts", "nominal", "calibrated" - For the measured height of the cantilever: "strainGaugeHeight.dat": "volts", "nominal", "absolute" "measuredHeight.dat": "volts", "nominal", "absolute" "capacitiveSensorHeight": "volts", "nominal", "absolute" (they are all the same) - For the recorded cantilever deflection: "vDeflection.dat": "volts", "distance", "force" Returns ------- data: 1d ndarray A numpy array containing the scaled data. unit: str A string representing the metric unit of the data. name: str The name of the data column. Notes ----- The raw data (see `load_dat_raw`) is usually stored in "volts" and needs to be converted to e.g. "force" for "vDeflection" or "nominal" for "strainGaugeHeight". The conversion parameters (offset, multiplier) are stored in the header files and they are not stored separately for each slot, but the conversion parameters are stored relative to the slots. For instance, to compute the "force" slot from the raw "volts" data, one first needs to compute the "distance" slot. This conversion is taken care of by this method. This is an example header: channel.vDeflection.data.file.name=channels/vDeflection.dat channel.vDeflection.data.file.format=raw channel.vDeflection.data.type=short channel.vDeflection.data.encoder.type=signedshort channel.vDeflection.data.encoder.scaling.type=linear channel.vDeflection.data.encoder.scaling.style=offsetmultiplier channel.vDeflection.data.encoder.scaling.offset=-0.00728873489143207 channel.vDeflection.data.encoder.scaling.multiplier=3.0921021713588157E-4 channel.vDeflection.data.encoder.scaling.unit.type=metric-unit channel.vDeflection.data.encoder.scaling.unit.unit=V channel.vDeflection.channel.name=vDeflection channel.vDeflection.conversion-set.conversions.list=distance force channel.vDeflection.conversion-set.conversions.default=force channel.vDeflection.conversion-set.conversions.base=volts channel.vDeflection.conversion-set.conversion.volts.name=Volts channel.vDeflection.conversion-set.conversion.volts.defined=false channel.vDeflection.conversion-set.conversion.distance.name=Distance channel.vDeflection.conversion-set.conversion.distance.defined=true channel.vDeflection.conversion-set.conversion.distance.type=simple channel.vDeflection.conversion-set.conversion.distance.comment=Distance channel.vDeflection.conversion-set.conversion.distance.base-calibration-slot=volts channel.vDeflection.conversion-set.conversion.distance.calibration-slot=distance channel.vDeflection.conversion-set.conversion.distance.scaling.type=linear channel.vDeflection.conversion-set.conversion.distance.scaling.style=offsetmultiplier channel.vDeflection.conversion-set.conversion.distance.scaling.offset=0.0 channel.vDeflection.conversion-set.conversion.distance.scaling.multiplier=7.000143623002982E-8 channel.vDeflection.conversion-set.conversion.distance.scaling.unit.type=metric-unit channel.vDeflection.conversion-set.conversion.distance.scaling.unit.unit=m channel.vDeflection.conversion-set.conversion.force.name=Force channel.vDeflection.conversion-set.conversion.force.defined=true channel.vDeflection.conversion-set.conversion.force.type=simple channel.vDeflection.conversion-set.conversion.force.comment=Force channel.vDeflection.conversion-set.conversion.force.base-calibration-slot=distance channel.vDeflection.conversion-set.conversion.force.calibration-slot=force channel.vDeflection.conversion-set.conversion.force.scaling.type=linear channel.vDeflection.conversion-set.conversion.force.scaling.style=offsetmultiplier channel.vDeflection.conversion-set.conversion.force.scaling.offset=0.0 channel.vDeflection.conversion-set.conversion.force.scaling.multiplier=0.043493666407368466 channel.vDeflection.conversion-set.conversion.force.scaling.unit.type=metric-unit channel.vDeflection.conversion-set.conversion.force.scaling.unit.unit=N To convert from the raw "volts" data to force data, these steps are performed: - Convert from "volts" to "distance" first, because the "base-calibration-slot" for force is "distance". distance = volts*7.000143623002982E-8 + 0.0 - Convert from "distance" to "force": force = distance*0.043493666407368466 + 0.0 The multipliers shown above are the values for sensitivity and spring constant: sensitivity = 7.000143623002982E-8 m/V spring_constant = 0.043493666407368466 N/m """ path_dat = pathlib.Path(path_dat).resolve() key = path_dat.stem # open header file header_file = path_dat.parents[1] / "segment-header.properties" prop = meta.get_seg_head_prop(header_file) conv = "channel.{}.conversion-set".format(key) if slot == "default": slot = prop[conv+".conversions.default"] # get base unit base = prop[conv+".conversions.base"] # Now iterate through the conversion sets until we have the base converter. # A list of multipliers and offsets converters = [] curslot = slot while curslot != base: # Get current slot multipliers and offsets off_str = conv+".conversion.{}.scaling.offset".format(curslot) off = prop[off_str] mult_str = conv+".conversion.{}.scaling.multiplier".format(curslot) mult = prop[mult_str] converters.append([mult, off]) sl_str = conv+".conversion.{}.base-calibration-slot".format(curslot) curslot = prop[sl_str] # Get raw data data = load_dat_raw(path_dat) for c in converters[::-1]: data[:] = c[0] * data[:] + c[1] if base == slot: unit_str = "channel.{}.data.encoder.scaling.unit.unit".format(key) unit = prop[unit_str] else: try: unit_str = conv+".conversion.{}.scaling.unit".format(slot) unit = prop[unit_str] except KeyError: unit_str = conv+".conversion.{}.scaling.unit.unit".format(slot) unit = prop[unit_str] name_str = conv+".conversion.{}.name".format(slot) name = prop[name_str] return data, unit, "{} ({})".format(key, name)
[ "dev@craban.de" ]
dev@craban.de
49b4f104d0a3ffacd0a6920cd0f12b858d6768e7
83b9910372a8246c947c7365b9eb39d9b20cde13
/src/model/plainEffNet.py
c7dddc5608db4d3bd223d3d118df0da818b4556e
[ "MIT" ]
permissive
comword/TCD20-DP-DeepModel
977394a9b1c9ce350efdf944919f034a28ff878a
7dca097957b745cf6345d8ac218ff28f306a5218
refs/heads/main
2023-07-09T15:12:45.228999
2021-08-22T14:05:01
2021-08-22T14:05:01
338,325,944
0
0
null
null
null
null
UTF-8
Python
false
false
1,633
py
import tensorflow as tf class PlainEffNet(tf.keras.Model): def __init__(self, input_shape=[3, 15, 224, 224], backbone='EfficientNetB0', MLP_DIM=256, n_classes=16, MLP_DROPOUT_RATE=0.4, **kwargs): super(PlainEffNet, self).__init__(**kwargs) self.img_input = tf.keras.layers.Input(input_shape) self.pos_input = tf.keras.layers.Input(input_shape[1]) self.backbone = getattr(tf.keras.applications, backbone)( include_top=False, weights='imagenet', classes=n_classes, input_shape=[input_shape[2], input_shape[3], input_shape[0]]) self.pool = tf.keras.layers.GlobalAveragePooling2D(name='avg_pool') self.dense = tf.keras.layers.Dense(MLP_DIM, activation='relu') self.dropout = tf.keras.layers.Dropout( MLP_DROPOUT_RATE, name='top_dropout') self.dense_out = tf.keras.layers.Dense(n_classes, activation='softmax') # self.out = self.call([self.img_input, self.pos_input]) # super(PlainEffNet, self).__init__( # inputs=[self.img_input, self.pos_input], outputs=self.out, **kwargs) def call(self, x, training=False): x, position_ids = x shape = tf.shape(x) B, C, F, H, W = shape[0], shape[1], shape[2], shape[3], shape[4] x = tf.transpose(x, perm=[0, 2, 3, 4, 1]) # B, F, H, W, C x = tf.reshape(x, (B * F, H, W, C)) x = self.backbone(x, training=training) x = self.pool(x) x = tf.reshape(x, (B, -1)) x = self.dense(x) x = self.dropout(x, training=training) x = self.dense_out(x) return x
[ "comword@live.com" ]
comword@live.com
cf3cf7a93963bbf5a088a5e1c72b59a4549b56c9
145f57f0418924d982444598f12b291f9c280657
/roboticstoolbox/tools/models.py
3fdfee260d919f196663e064d2178c7f06ebc3fa
[ "MIT" ]
permissive
HaoWangSir/robotics-toolbox-python
3b56fd7abc094df1555f7c0aa8d015ef6c344c53
a93165018e9fa165bde353193af2eb1534bba992
refs/heads/master
2022-12-18T22:41:18.642417
2020-09-18T01:15:13
2020-09-18T01:15:13
null
0
0
null
null
null
null
UTF-8
Python
false
false
778
py
import roboticstoolbox.models as m def models(): """ Display all robot models in summary form ``models()`` displays a list of all models provided by the Toolbox. It lists the name, manufacturer, and number of joints. """ for category in ['DH', 'URDF', 'ETS']: print(category + ':') group = m.__dict__[category] for cls in group.__dict__.values(): # TODO should check that cls issubclass of Robot superclass (when there is one) try: robot = cls() except: continue s = robot.name if robot.manufacturer is not None: s += ' (' + robot.manufacturer + ')' print(f" {s:40s} {robot.n:d} dof") models()
[ "peter.i.corke@gmail.com" ]
peter.i.corke@gmail.com
ff539193b88130070464951bfe9d6c30cd6969a6
9833cd31d96f2c38fd4d6291d660c534cbee638e
/code/visualize-dataset.py
2fbb6a72df8418329a2ba66bf6f4ea5f9ef0ff06
[]
no_license
AspirinCode/drug-discovery-feature-selection
35129cdeb6665db0d04111364925dc5f62dd0661
69ae43ef498aaf1e3523220547732c5d3f7f310e
refs/heads/master
2020-03-27T20:17:39.215137
2018-07-20T06:20:11
2018-07-20T06:20:11
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,733
py
""" Visualize dataset: * Feature importances using Extra Trees * 2D plot using t-SNE with various perplexities Execution time: real 15m50.854s user 14m30.858s sys 0m30.375s @author yohanes.gultom@gmail.com """ import numpy as np import matplotlib import matplotlib.pyplot as plt import pandas import os from matplotlib.ticker import NullFormatter from sklearn import manifold, datasets from sklearn.preprocessing import StandardScaler, MinMaxScaler from sklearn.ensemble import ExtraTreesClassifier from time import time # config dataset_file = '../dataset/dataset.csv' n_components = 2 perplexities = [5, 30, 50, 100] chart_importances_filename = 'visualize-dataset_importances.png' chart_filename_tpl = 'visualize-dataset_tsne_{}.png' # check if display available if os.name == 'posix' and "DISPLAY" not in os.environ: matplotlib.use('Agg') # read dataset df = pandas.read_csv(dataset_file, index_col=0) feature_names = list(df[df.columns.drop('Class')]) # split to data X and labels y X = df[df.columns.drop('Class')].values.astype('float32') y = df['Class'].values # separate data by class red = y == 0 green = y == 1 # scale data scaler = MinMaxScaler() X = scaler.fit_transform(X) # feature importance check using Extra Trees forest = ExtraTreesClassifier(n_estimators=250, random_state=0) forest.fit(X, y) importances = forest.feature_importances_ indices = np.argsort(importances)[::-1] # reverse n = 10 print("Top {} most important features:".format(n)) for f in range(min(X.shape[1], n)): print("{}. feature {} ({}): {:.4g}".format(f + 1, indices[f], feature_names[indices[f]], importances[indices[f]])) # Set figure size to 1200 x 880 px plt.figure(figsize=(15, 11)) # Plot the feature importances of the forest plt.title("Feature importances") plt.bar(range(X.shape[1]), importances, color="r", align="center") plt.xlim([-1, X.shape[1]]) plt.ylabel("Importance") plt.xlabel("Feature Index") plt.savefig(chart_importances_filename) # visualize dataset with TSNE for i, perplexity in enumerate(perplexities): t0 = time() tsne = manifold.TSNE(n_components=n_components, init='random', random_state=0, perplexity=perplexity) Y = tsne.fit_transform(X) t1 = time() print("t-SNE perplexity={} in {:.2g} sec".format(perplexity, t1 - t0)) # plot fig, ax = plt.subplots() ax.set_title("Perplexity=%d" % perplexity) ax.scatter(Y[red, 0], Y[red, 1], c="r") ax.scatter(Y[green, 0], Y[green, 1], c="g") ax.xaxis.set_major_formatter(NullFormatter()) ax.yaxis.set_major_formatter(NullFormatter()) ax.axis('tight') filename = chart_filename_tpl.format(perplexity) plt.savefig(filename) print("chart saved in {}".format(filename)) plt.show()
[ "yohanes.gultom@gmail.com" ]
yohanes.gultom@gmail.com
ced609ff3700746a595cba6e854a51c4d16c80b6
cfd7cd86b7098952910e7addf84ee96bbe463c4b
/iprPy-tools/process/process_structure_static.py
eeff1ef1535c0198bc273cd0230f24091a97cd67
[]
no_license
vtran61/iprPy
58519896abfd59bb7477bd8943e8a72ae0cce6cc
53bc2b82863ac381710c3b20e90fd6f21db946f5
refs/heads/master
2021-01-14T14:23:16.459995
2016-03-30T19:32:11
2016-03-30T19:32:11
null
0
0
null
null
null
null
UTF-8
Python
false
false
4,202
py
import os import glob from DataModelDict import DataModelDict def structure_static(xml_lib_dir): calc_name = 'structure_static' groups = os.path.join(xml_lib_dir, '*', calc_name, '*') error_dict = DataModelDict() for group_dir in glob.iglob(groups): if os.path.isdir(group_dir): calc_dir, group_name = os.path.split(group_dir) pot_name = os.path.basename(os.path.dirname(calc_dir)) print pot_name try: with open(os.path.join(calc_dir, 'badlist.txt'), 'r') as f: badlist = f.read().split() except: badlist = [] data = DataModelDict() for sim_path in glob.iglob(os.path.join(group_dir, '*.xml')): sim_file = os.path.basename(sim_path) sim_name = sim_file[:-4] if sim_name in badlist: continue with open(sim_path) as f: sim = DataModelDict(f)['calculation-crystal-phase'] if 'error' in sim: badlist.append(sim_name) error_message = sim['error'] error = 'Unknown error' for line in error_message.split('\n'): if 'Error' in line: error = line error_dict.append(error, sim_name) continue try: cell = sim['relaxed-atomic-system']['cell'] except: tar_gz_path = sim_path[:-4] + '.tar.gz' if os.isfile(tar_gz_path): error_dict.append('Unknown error', sim_name) continue data.append('key', sim.get('calculation-id', '')) data.append('file', sim['crystal-info'].get('artifact', '')) data.append('symbols', '_'.join(sim['crystal-info'].aslist('symbols'))) data.append('Temperature (K)', sim['phase-state']['temperature']['value']) data.append('Pressure (GPa)', sim['phase-state']['pressure']['value']) cell = cell[cell.keys()[0]] data.append('Ecoh (eV)', sim['cohesive-energy']['value'] ) if 'a' in cell: data.append('a (A)', cell['a']['value']) else: data.append('a (A)', '') if 'b' in cell: data.append('b (A)', cell['b']['value']) else: data.append('b (A)', '') if 'c' in cell: data.append('c (A)', cell['c']['value']) else: data.append('c (A)', '') C_dict = {} for C in sim['elastic-constants'].iteraslist('C'): C_dict[C['ij']] = C['stiffness']['value'] data.append('C11 (GPa)', C_dict.get('1 1', '')) data.append('C22 (GPa)', C_dict.get('2 2', '')) data.append('C33 (GPa)', C_dict.get('3 3', '')) data.append('C12 (GPa)', C_dict.get('1 2', '')) data.append('C13 (GPa)', C_dict.get('1 3', '')) data.append('C23 (GPa)', C_dict.get('2 3', '')) data.append('C44 (GPa)', C_dict.get('4 4', '')) data.append('C55 (GPa)', C_dict.get('5 5', '')) data.append('C66 (GPa)', C_dict.get('6 6', '')) if len(data.keys()) > 0: with open(os.path.join(calc_dir, 'structure_static_'+group_name+'.csv'), 'w') as f: f.write(','.join(data.keys())+'\n') for i in xrange(len(data.aslist('key'))): f.write(','.join([str(data.aslist(k)[i]) for k in data.keys()]) + '\n') with open(os.path.join(calc_dir, 'badlist.txt'), 'w') as f: for bad in badlist: f.write(bad+'\n')
[ "lucas.hale@nist.gov" ]
lucas.hale@nist.gov
1c6f5308ee148577f7f5e8389a9945efc8506c3e
15f321878face2af9317363c5f6de1e5ddd9b749
/solutions_python/Problem_96/514.py
caadd24b565d411ff0959939b90e3e6c793fb7b7
[]
no_license
dr-dos-ok/Code_Jam_Webscraper
c06fd59870842664cd79c41eb460a09553e1c80a
26a35bf114a3aa30fc4c677ef069d95f41665cc0
refs/heads/master
2020-04-06T08:17:40.938460
2018-10-14T10:12:47
2018-10-14T10:12:47
null
0
0
null
null
null
null
UTF-8
Python
false
false
822
py
#!/usr/bin/python import sys ns = [0]*31 s = [-1]*31 for i in xrange(1,31): if i % 3 == 0: ns[i] = i // 3 s[i] = i // 3 + 1 elif i % 3 == 1: ns[i] = i // 3 + 1 s[i] = i // 3 + 1 elif i % 3 == 2: ns[i] = i // 3 + 1 s[i] = i // 3 + 2 i = iter(map(int, sys.stdin.read().split())) T = next(i) for case in xrange(1,T+1): N = next(i) S = next(i) p = next(i) t = iter(sorted((next(i) for n in xrange(N)), reverse=True)) result = 0 while True: try: ti = next(t) if ns[ti] >= p: result += 1 elif s[ti] >= p and S > 0: result += 1 S -= 1 else: break except: break print "Case #%d:" % case, result
[ "miliar1732@gmail.com" ]
miliar1732@gmail.com
e48daae6ec102de56d95f2ca83541aae1805e989
d3e2a5fec27ae2272ff9191f45af84c8eacc7693
/snakemakelib/graphics/axes.py
cefa25eb6f0b4fa0d06c5d8c7230925f1388ef4e
[ "MIT" ]
permissive
jfear/snakemakelib-core
c49b9308a66361722b75869b7f461e340fef188b
b2d3cf1ecb84d630d0cc04646f86859ccac7f4c1
refs/heads/master
2021-01-21T00:44:32.396115
2016-02-07T22:49:08
2016-02-07T22:49:08
50,690,606
0
0
null
2016-01-29T20:53:48
2016-01-29T20:53:48
null
UTF-8
Python
false
false
4,374
py
''' Author: Per Unneberg Created: Wed Dec 2 07:52:08 2015 ''' from . import utils from snakemakelib.log import LoggerManager smllogger = LoggerManager().getLogger(__name__) __all__ = ['xaxis', 'yaxis', 'main', 'grid', 'legend'] def xaxis(fig, i=None, **kwargs): """xaxis - modify the xaxis Args: fig (:py:class:`~bokeh.plotting.Plot`): bokeh Plot object i (int): index to use if setting tick formatters and the like; see `tick label formats <http://bokeh.pydata.org/en/latest/docs/user_guide/styling.html#tick-label-formats>`_ kwargs: keyword arguments to pass to figure xaxis Example: .. bokeh-plot:: :source-position: above import pandas as pd import numpy as np from bokeh.plotting import figure, show, hplot from snakemakelib.graphics import points, xaxis, yaxis, grid, main, legend df = pd.DataFrame([[1,2], [2,5], [3,9]], columns=["x", "y"]) f = figure(title="Test", plot_width=300, plot_height=300) points(f, "x", "y", df, color="red") points(f, "y", "x", df, legend="y") xaxis(f, axis_label="x", major_label_orientation=np.pi/3) yaxis(f, axis_label=None, axis_line_color=None) grid(f, grid_line_color="black") main(f, title="My plot", title_text_font_style="italic", title_text_color="olive", title_text_font="times") legend(f, orientation="bottom_left") show(f) """ kwargs = {k.replace("x_", ""):v for k,v in kwargs.items()} try: props = fig.xaxis[0].properties() except: raise kwaxis = utils.fig_args(kwargs, props) try: if i is None: for i in range(len(fig.xaxis)): fig.xaxis[i].set(**kwaxis) else: fig.xaxis[i].set(**kwaxis) except AttributeError: raise def yaxis(fig, i=None, **kwargs): """yaxis - modify the yaxis Args: fig (:py:class:`~bokeh.plotting.Plot`): bokeh Plot object i (int): index to use if setting tick formatters and the like; see `tick label formats <http://bokeh.pydata.org/en/latest/docs/user_guide/styling.html#tick-label-formats>`_ kwargs: keyword arguments to pass to figure yaxis Example: see xaxis example """ kwargs = {k.replace("y_", ""):v for k,v in kwargs.items()} try: props = fig.yaxis[0].properties() except: raise kwaxis = utils.fig_args(kwargs, props) try: if i is None: for i in range(len(fig.yaxis)): fig.yaxis[i].set(**kwaxis) else: fig.yaxis[i].set(**kwaxis) except AttributeError: raise def main(fig, **kwargs): """main - modify the title Args: fig (:py:class:`~bokeh.plotting.Plot`): bokeh Plot object kwargs: keyword arguments to pass to figure.title Example: """ for k, v in kwargs.items(): if not k.startswith("title"): smllogger.warn("trying to set attribute {} via title".format(k)) continue try: setattr(fig, k, v) except AttributeError: smllogger.error("unexpected attribute {} to 'main'".format(k)) raise def legend(fig, **kwargs): """legend - modify the legend Args: fig (:py:class:`~bokeh.plotting.Plot`): bokeh Plot object kwargs: keyword arguments to pass to figure.legend Example: See xaxis. """ if len(fig.legend) == 0: smllogger.warn("no legend defined in figure; creation of new legend currently not supported") return for k, v in kwargs.items(): try: setattr(fig.legend, k, v) except AttributeError: smllogger.error("unexpected attribute {} to {}".format(k, fig.legend)) raise except: raise def grid(fig, **kwargs): """grid - modify the grid Args: fig (:py:class:`~bokeh.plotting.Plot`): bokeh Plot object kwargs: keyword arguments to pass to figure grid Example: see xaxis example """ for k, v in kwargs.items(): try: setattr(fig.grid, k, v) except AttributeError: smllogger.error("unexpected attribute {} to {}".format(k, fig.grid)) raise
[ "per.unneberg@scilifelab.se" ]
per.unneberg@scilifelab.se
686480212b8364d3ab57598f0cbbe63d471e740d
a838d4bed14d5df5314000b41f8318c4ebe0974e
/sdk/translation/azure-ai-translation-document/tests/asynctestcase.py
b1c7a3b9c6813d0e7969edfc55beae0aed351f78
[ "LicenseRef-scancode-generic-cla", "MIT", "LGPL-2.1-or-later" ]
permissive
scbedd/azure-sdk-for-python
ee7cbd6a8725ddd4a6edfde5f40a2a589808daea
cc8bdfceb23e5ae9f78323edc2a4e66e348bb17a
refs/heads/master
2023-09-01T08:38:56.188954
2021-06-17T22:52:28
2021-06-17T22:52:28
159,568,218
2
0
MIT
2019-08-11T21:16:01
2018-11-28T21:34:49
Python
UTF-8
Python
false
false
4,458
py
# coding=utf-8 # ------------------------------------ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. # ------------------------------------ import os from testcase import DocumentTranslationTest, Document from azure.ai.translation.document import DocumentTranslationInput, TranslationTarget class AsyncDocumentTranslationTest(DocumentTranslationTest): def __init__(self, method_name): super(AsyncDocumentTranslationTest, self).__init__(method_name) def generate_oauth_token(self): if self.is_live: from azure.identity.aio import ClientSecretCredential return ClientSecretCredential( os.getenv("TRANSLATION_TENANT_ID"), os.getenv("TRANSLATION_CLIENT_ID"), os.getenv("TRANSLATION_CLIENT_SECRET"), ) async def _begin_and_validate_translation_async(self, async_client, translation_inputs, total_docs_count, language=None): # submit operation poller = await async_client.begin_translation(translation_inputs) self.assertIsNotNone(poller.id) # wait for result doc_statuses = await poller.result() # validate self._validate_translation_metadata(poller=poller, status='Succeeded', total=total_docs_count, succeeded=total_docs_count) async for doc in doc_statuses: self._validate_doc_status(doc, language) return poller.id # client helpers async def _begin_multiple_translations_async(self, async_client, operations_count, **kwargs): wait_for_operation = kwargs.pop('wait', True) language_code = kwargs.pop('language_code', "es") docs_per_operation = kwargs.pop('docs_per_operation', 2) result_ids = [] for i in range(operations_count): # prepare containers and test data ''' # note since we're only testing the client library we can use sync container calls in here no need for async container clients! ''' blob_data = Document.create_dummy_docs(docs_per_operation) source_container_sas_url = self.create_source_container(data=blob_data) target_container_sas_url = self.create_target_container() # prepare translation inputs translation_inputs = [ DocumentTranslationInput( source_url=source_container_sas_url, targets=[ TranslationTarget( target_url=target_container_sas_url, language_code=language_code ) ] ) ] # submit multiple operations poller = await async_client.begin_translation(translation_inputs) self.assertIsNotNone(poller.id) if wait_for_operation: await poller.result() else: await poller.wait() result_ids.append(poller.id) return result_ids async def _begin_and_validate_translation_with_multiple_docs_async(self, async_client, docs_count, **kwargs): # get input parms wait_for_operation = kwargs.pop('wait', False) language_code = kwargs.pop('language_code', "es") # prepare containers and test data blob_data = Document.create_dummy_docs(docs_count=docs_count) source_container_sas_url = self.create_source_container(data=blob_data) target_container_sas_url = self.create_target_container() # prepare translation inputs translation_inputs = [ DocumentTranslationInput( source_url=source_container_sas_url, targets=[ TranslationTarget( target_url=target_container_sas_url, language_code=language_code ) ] ) ] # submit operation poller = await async_client.begin_translation(translation_inputs) self.assertIsNotNone(poller.id) # wait for result if wait_for_operation: result = await poller.result() async for doc in result: self._validate_doc_status(doc, "es") # validate self._validate_translation_metadata(poller=poller) return poller
[ "noreply@github.com" ]
scbedd.noreply@github.com
ae7f88407fe7d2451eb8774356d45933f90af59a
ca7aa979e7059467e158830b76673f5b77a0f5a3
/Python_codes/p03340/s635836646.py
2c571bf6e84d7cac823b0f125ae5db4cf672e286
[]
no_license
Aasthaengg/IBMdataset
7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901
f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8
refs/heads/main
2023-04-22T10:22:44.763102
2021-05-13T17:27:22
2021-05-13T17:27:22
367,112,348
0
0
null
null
null
null
UTF-8
Python
false
false
296
py
n = int(input()) A = list(map(int,input().split())) ans = 0 l = 0 r = 0 bit = A[0] total = A[0] while True: if bit == total: ans += r-l+1 r += 1 if r == n: break total += A[r] bit ^= A[r] else: total -= A[l] bit ^= A[l] l += 1 print(ans)
[ "66529651+Aastha2104@users.noreply.github.com" ]
66529651+Aastha2104@users.noreply.github.com
ed684da54409de93089b30bba581a10520c3695c
d12c7b974285a9ca0d4ddd06bd43223a03db5126
/bkup_files/switchdb2.py
de040cb1d162e22ed404edfb5a92408a5984534d
[]
no_license
xod442/sad
6b0006bdeb0ca31dc383b15de8197433c1a21733
0a1179b2730ee5a47c6e2d888b8bd748c9a46a0a
refs/heads/master
2020-04-25T06:38:26.934968
2019-02-25T21:31:20
2019-02-25T21:31:20
172,587,665
0
0
null
null
null
null
UTF-8
Python
false
false
2,120
py
#!/usr/bin/env python ''' Copyright 2016 Hewlett Packard Enterprise Development LP. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. __author__ = "@netwookie" __copyright__ = "Copyright 2016, Hewlett Packard Enterprise Development LP." __credits__ = ["Rick Kauffman"] __license__ = "Apache2" __version__ = "1.0.0" __maintainer__ = "Rick Kauffman" __email__ = "rick@rickkauffman.com" __status__ = "Prototype" switchdb A database tool for managing switches in the Ansible VAR file ''' from flask import Flask, request, render_template, redirect, url_for, flash, session from flask.ext.bootstrap import Bootstrap from flask_sqlalchemy import SQLAlchemy from sdb_maker import db from sdb_maker import Students app = Flask(__name__) bootstrap = Bootstrap(app) # Moving on @app.route('/') @app.route('/index') def show_all(): return render_template('show_all.html', students = Students.query.all() ) @app.route('/new', methods = ['GET', 'POST']) def new(): if request.method == 'POST': if not request.form['name'] or not request.form['city'] or not request.form['addr']: flash('Please enter all the fields', 'error') else: student = Students(request.form['name'], request.form['city'], request.form['addr'], request.form['pin']) db.session.add(student) db.session.commit() flash('Record was successfully added') return redirect(url_for('show_all')) return render_template('new.html') if __name__ == '__main__': db.create_all() app.secret_key = 'SuperSecret' app.debug = True app.run(host='0.0.0.0')
[ "rick@rickkauffman.com" ]
rick@rickkauffman.com
85c357808c48b54144a7b87a95e364a7db447d23
3eeee2ab87695b5e9f209ba4601dbcebd5d00036
/AndroidApp/app_hello.py
8fc554a906525fa547bbd1abcd92ebc3908161f0
[]
no_license
pangxie1987/WebApp
483fbdd6c65f78e35ab2f1bd98701a7fb1fbb8f9
7d3e679bf1af4a5a4d4e89866789bb6f583eae71
refs/heads/master
2020-03-18T17:53:01.030177
2018-07-02T11:09:32
2018-07-02T11:09:32
135,057,400
0
0
null
null
null
null
UTF-8
Python
false
false
228
py
# -*- coding:utf-8 -*- #qpy:kivy import kivy kivy.require('1.10.0') from kivy.app import App from kivy.uix.button import Button class TestApp(App): def build(self): return Button(text='hello,kivy') TestApp().run()
[ "lpb.waln@outlook.com" ]
lpb.waln@outlook.com
ecda99ac45a8c50659a0c956bd055386e192a895
27455af4306bdb2d470bc7aa6a412ffb7950e1e1
/cask/accounts/models.py
cd6dbae3e1fef3870e44d171a3457f357b2ed62c
[ "Apache-2.0" ]
permissive
dcramer/cask-server
7a647a31cb798273ee9d3d8c7e43c28e829dec80
32535229a907479c3645aa34b75755d3e2b12dda
refs/heads/master
2022-12-09T10:00:57.842269
2018-08-30T15:50:44
2018-08-30T15:50:44
143,897,850
3
0
Apache-2.0
2022-10-18T19:15:29
2018-08-07T16:08:56
Python
UTF-8
Python
false
false
2,658
py
from uuid import uuid4 from django.conf import settings from django.contrib.auth.models import AbstractUser, BaseUserManager from django.db import models from django.utils.translation import ugettext_lazy as _ class UserManager(BaseUserManager): use_in_migrations = True def _create_user(self, email, password, **extra_fields): if not email: raise ValueError("The given email must be set") email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): extra_fields.setdefault("is_staff", False) extra_fields.setdefault("is_superuser", False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault("is_staff", True) extra_fields.setdefault("is_superuser", True) if extra_fields.get("is_staff") is not True: raise ValueError("Superuser must have is_staff=True.") if extra_fields.get("is_superuser") is not True: raise ValueError("Superuser must have is_superuser=True.") return self._create_user(email, password, **extra_fields) class Follower(models.Model): id = models.UUIDField(primary_key=True, default=uuid4, editable=False) from_user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="following" ) to_user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="followers" ) created_at = models.DateTimeField(auto_now_add=True) class Meta: unique_together = (("from_user", "to_user"),) class Identity(models.Model): id = models.UUIDField(primary_key=True, default=uuid4, editable=False) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) provider = models.CharField(max_length=32) external_id = models.CharField(max_length=32) class Meta: unique_together = (("provider", "external_id"),) class User(AbstractUser): id = models.UUIDField(primary_key=True, default=uuid4, editable=False) username = None first_name = None last_name = None name = models.CharField(max_length=128, null=True) email = models.EmailField(_("email address"), unique=True) USERNAME_FIELD = "email" REQUIRED_FIELDS = [] objects = UserManager() def get_full_name(self): return self.name def get_short_name(self): return self.name
[ "dcramer@gmail.com" ]
dcramer@gmail.com
e6179298367cbd15cd408ea1aff67299148fb15c
531947701b18907ab1646bc1666ad3129f20ccec
/ttp/formatters/n2g_formatter.py
d22e2fdf8b02047f75ae55b30b9f059645d323e5
[ "MIT" ]
permissive
dmulyalin/ttp
45a0df04c089874f677670e1105dd2c544b095b2
483863e7966f9ab2be5e8cbd8b6316c82e380f1a
refs/heads/master
2023-07-06T01:46:40.799147
2023-06-25T00:40:39
2023-06-25T00:40:39
216,000,389
322
44
MIT
2022-10-21T09:32:32
2019-10-18T10:33:52
Python
UTF-8
Python
false
false
1,501
py
import logging log = logging.getLogger(__name__) def n2g(data, **kwargs): # load kwargs module = kwargs.get("module", "yed") method = kwargs.get("method", "from_list") path = kwargs.get("path", []) node_dups = kwargs.get("node_duplicates", "skip") link_dups = kwargs.get("link_duplicates", "skip") method_kwargs = kwargs.get("method_kwargs", {}) algo = kwargs.get("algo", None) # import N2G library try: if module.lower() == "yed": from N2G import yed_diagram as create_diagram elif module.lower() == "drawio": from N2G import drawio_diagram as create_diagram else: log.error( "No N2G module '{}', supported values are 'yEd', 'DrawIO'".format( module ) ) return data except ImportError: log.error("Failed to import N2G '{}' module".format(module)) return data diagram_obj = create_diagram(node_duplicates=node_dups, link_duplicates=link_dups) # normalize results_data to list: if isinstance(data, dict): # handle the case for group specific output data = [data] # make graph for result in data: result_datum = _ttp_["output"]["traverse"](result, path) getattr(diagram_obj, method)(result_datum, **method_kwargs) # layout graph if algo: diagram_obj.layout(algo=algo) # return results XML data = diagram_obj.dump_xml() return data
[ "d.mulyalin@gmail.com" ]
d.mulyalin@gmail.com
31f519dcb85e758e5d904e064226e0b0b4d5cae2
0e1e643e864bcb96cf06f14f4cb559b034e114d0
/Exps_7_v3/doc3d/I_to_M_Gk3_no_pad/wiColorJ/pyr_Tcrop255_p60_j15/Sob_k33_s001/pyr_2s/L4/step10_a.py
e5d17650ad1f771bdfb4e5864b7e912ecfa372d0
[]
no_license
KongBOy/kong_model2
33a94a9d2be5b0f28f9d479b3744e1d0e0ebd307
1af20b168ffccf0d5293a393a40a9fa9519410b2
refs/heads/master
2022-10-14T03:09:22.543998
2022-10-06T11:33:42
2022-10-06T11:33:42
242,080,692
3
0
null
null
null
null
UTF-8
Python
false
false
12,549
py
############################################################################################################################################################################################################# ############################################################################################################################################################################################################# ### 把 kong_model2 加入 sys.path import os code_exe_path = os.path.realpath(__file__) ### 目前執行 step10_b.py 的 path code_exe_path_element = code_exe_path.split("\\") ### 把 path 切分 等等 要找出 kong_model 在第幾層 code_dir = "\\".join(code_exe_path_element[:-1]) kong_layer = code_exe_path_element.index("kong_model2") ### 找出 kong_model2 在第幾層 kong_model2_dir = "\\".join(code_exe_path_element[:kong_layer + 1]) ### 定位出 kong_model2 的 dir import sys ### 把 kong_model2 加入 sys.path sys.path.append(kong_model2_dir) sys.path.append(code_dir) # print(__file__.split("\\")[-1]) # print(" code_exe_path:", code_exe_path) # print(" code_exe_path_element:", code_exe_path_element) # print(" code_dir:", code_dir) # print(" kong_layer:", kong_layer) # print(" kong_model2_dir:", kong_model2_dir) ############################################################################################################################################################################################################# kong_to_py_layer = len(code_exe_path_element) - 1 - kong_layer ### 中間 -1 是為了長度轉index # print(" kong_to_py_layer:", kong_to_py_layer) if (kong_to_py_layer == 0): template_dir = "" elif(kong_to_py_layer == 2): template_dir = code_exe_path_element[kong_layer + 1][0:] ### [7:] 是為了去掉 step1x_, 後來覺得好像改有意義的名字不去掉也行所以 改 0 elif(kong_to_py_layer == 3): template_dir = code_exe_path_element[kong_layer + 1][0:] + "/" + code_exe_path_element[kong_layer + 2][0:] ### [5:] 是為了去掉 mask_ ,前面的 mask_ 是為了python 的 module 不能 數字開頭, 隨便加的這樣子, 後來覺得 自動排的順序也可以接受, 所以 改0 elif(kong_to_py_layer > 3): template_dir = code_exe_path_element[kong_layer + 1][0:] + "/" + code_exe_path_element[kong_layer + 2][0:] + "/" + "/".join(code_exe_path_element[kong_layer + 3: -1]) # print(" template_dir:", template_dir) ### 舉例: template_dir: 7_mask_unet/5_os_book_and_paper_have_dtd_hdr_mix_bg_tv_s04_mae ############################################################################################################################################################################################################# exp_dir = template_dir ############################################################################################################################################################################################################# from step06_a_datas_obj import * from step09_2side_L4 import * from step10_a2_loss_info_obj import * from step10_b2_exp_builder import Exp_builder rm_paths = [path for path in sys.path if code_dir in path] for rm_path in rm_paths: sys.path.remove(rm_path) rm_moduless = [module for module in sys.modules if "step09" in module] for rm_module in rm_moduless: del sys.modules[rm_module] ############################################################################################################################################################################################################# ''' exp_dir 是 決定 result_dir 的 "上一層"資料夾 名字喔! exp_dir要巢狀也沒問題~ 比如:exp_dir = "6_mask_unet/自己命的名字",那 result_dir 就都在: 6_mask_unet/自己命的名字/result_a 6_mask_unet/自己命的名字/result_b 6_mask_unet/自己命的名字/... ''' use_db_obj = type8_blender_kong_doc3d_in_I_gt_MC use_loss_obj = [G_sobel_k33_loss_info_builder.set_loss_target("UNet_Mask").copy()] ### z, y, x 順序是看 step07_b_0b_Multi_UNet 來對應的喔 ############################################################# ### 為了resul_analyze畫空白的圖,建一個empty的 Exp_builder empty = Exp_builder().set_basic("train", use_db_obj, ch032_pyramid_1side_1__2side_1, use_loss_obj, exp_dir=exp_dir, code_exe_path=code_exe_path, describe_end=ch032_pyramid_1side_1__2side_1.kong_model.model_describe) .set_train_args(epochs= 1) .set_train_iter_args(it_see_fq=900, it_save_fq=900 * 2, it_down_step="half", it_down_fq=900).set_train_in_gt_use_range(use_in_range=Range(0, 1), use_gt_range=Range(0, 1)).set_result_name(result_name="為了resul_analyze畫空白的圖,建一個empty的 Exp_builder") ############################################################# ch032_1side_1__2side_1 = Exp_builder().set_basic("train", use_db_obj, ch032_pyramid_1side_1__2side_1, use_loss_obj, exp_dir=exp_dir, code_exe_path=code_exe_path, describe_end=ch032_pyramid_1side_1__2side_1.kong_model.model_describe) .set_train_args(epochs= 1) .set_train_iter_args(it_see_fq=900, it_save_fq=900 * 2, it_down_step="half", it_down_fq=900).set_train_in_gt_use_range(use_in_range=Range(0, 1), use_gt_range=Range(0, 1)).set_result_name(result_name="") ch032_1side_2__2side_1 = Exp_builder().set_basic("train", use_db_obj, ch032_pyramid_1side_2__2side_1, use_loss_obj, exp_dir=exp_dir, code_exe_path=code_exe_path, describe_end=ch032_pyramid_1side_2__2side_1.kong_model.model_describe) .set_train_args(epochs= 1) .set_train_iter_args(it_see_fq=900, it_save_fq=900 * 2, it_down_step="half", it_down_fq=900).set_train_in_gt_use_range(use_in_range=Range(0, 1), use_gt_range=Range(0, 1)).set_result_name(result_name="") ch032_1side_2__2side_2 = Exp_builder().set_basic("train", use_db_obj, ch032_pyramid_1side_2__2side_2, use_loss_obj, exp_dir=exp_dir, code_exe_path=code_exe_path, describe_end=ch032_pyramid_1side_2__2side_2.kong_model.model_describe) .set_train_args(epochs= 1) .set_train_iter_args(it_see_fq=900, it_save_fq=900 * 2, it_down_step="half", it_down_fq=900).set_train_in_gt_use_range(use_in_range=Range(0, 1), use_gt_range=Range(0, 1)).set_result_name(result_name="") ch032_1side_3__2side_1 = Exp_builder().set_basic("train", use_db_obj, ch032_pyramid_1side_3__2side_1, use_loss_obj, exp_dir=exp_dir, code_exe_path=code_exe_path, describe_end=ch032_pyramid_1side_3__2side_1.kong_model.model_describe) .set_train_args(epochs= 1) .set_train_iter_args(it_see_fq=900, it_save_fq=900 * 2, it_down_step="half", it_down_fq=900).set_train_in_gt_use_range(use_in_range=Range(0, 1), use_gt_range=Range(0, 1)).set_result_name(result_name="") ch032_1side_3__2side_2 = Exp_builder().set_basic("train", use_db_obj, ch032_pyramid_1side_3__2side_2, use_loss_obj, exp_dir=exp_dir, code_exe_path=code_exe_path, describe_end=ch032_pyramid_1side_3__2side_2.kong_model.model_describe) .set_train_args(epochs= 1) .set_train_iter_args(it_see_fq=900, it_save_fq=900 * 2, it_down_step="half", it_down_fq=900).set_train_in_gt_use_range(use_in_range=Range(0, 1), use_gt_range=Range(0, 1)).set_result_name(result_name="") ch032_1side_3__2side_3 = Exp_builder().set_basic("train", use_db_obj, ch032_pyramid_1side_3__2side_3, use_loss_obj, exp_dir=exp_dir, code_exe_path=code_exe_path, describe_end=ch032_pyramid_1side_3__2side_3.kong_model.model_describe) .set_train_args(epochs= 1) .set_train_iter_args(it_see_fq=900, it_save_fq=900 * 2, it_down_step="half", it_down_fq=900).set_train_in_gt_use_range(use_in_range=Range(0, 1), use_gt_range=Range(0, 1)).set_result_name(result_name="") ch032_1side_4__2side_1 = Exp_builder().set_basic("train", use_db_obj, ch032_pyramid_1side_4__2side_1, use_loss_obj, exp_dir=exp_dir, code_exe_path=code_exe_path, describe_end=ch032_pyramid_1side_4__2side_1.kong_model.model_describe) .set_train_args(epochs= 1) .set_train_iter_args(it_see_fq=900, it_save_fq=900 * 2, it_down_step="half", it_down_fq=900).set_train_in_gt_use_range(use_in_range=Range(0, 1), use_gt_range=Range(0, 1)).set_result_name(result_name="") ch032_1side_4__2side_2 = Exp_builder().set_basic("train", use_db_obj, ch032_pyramid_1side_4__2side_2, use_loss_obj, exp_dir=exp_dir, code_exe_path=code_exe_path, describe_end=ch032_pyramid_1side_4__2side_2.kong_model.model_describe) .set_train_args(epochs= 1) .set_train_iter_args(it_see_fq=900, it_save_fq=900 * 2, it_down_step="half", it_down_fq=900).set_train_in_gt_use_range(use_in_range=Range(0, 1), use_gt_range=Range(0, 1)).set_result_name(result_name="") ch032_1side_4__2side_3 = Exp_builder().set_basic("train", use_db_obj, ch032_pyramid_1side_4__2side_3, use_loss_obj, exp_dir=exp_dir, code_exe_path=code_exe_path, describe_end=ch032_pyramid_1side_4__2side_3.kong_model.model_describe) .set_train_args(epochs= 1) .set_train_iter_args(it_see_fq=900, it_save_fq=900 * 2, it_down_step="half", it_down_fq=900).set_train_in_gt_use_range(use_in_range=Range(0, 1), use_gt_range=Range(0, 1)).set_result_name(result_name="") ch032_1side_4__2side_4 = Exp_builder().set_basic("train", use_db_obj, ch032_pyramid_1side_4__2side_4, use_loss_obj, exp_dir=exp_dir, code_exe_path=code_exe_path, describe_end=ch032_pyramid_1side_4__2side_4.kong_model.model_describe) .set_train_args(epochs= 1) .set_train_iter_args(it_see_fq=900, it_save_fq=900 * 2, it_down_step="half", it_down_fq=900).set_train_in_gt_use_range(use_in_range=Range(0, 1), use_gt_range=Range(0, 1)).set_result_name(result_name="") ch032_1side_5__2side_1 = Exp_builder().set_basic("train", use_db_obj, ch032_pyramid_1side_5__2side_1, use_loss_obj, exp_dir=exp_dir, code_exe_path=code_exe_path, describe_end=ch032_pyramid_1side_5__2side_1.kong_model.model_describe) .set_train_args(epochs= 1) .set_train_iter_args(it_see_fq=900, it_save_fq=900 * 2, it_down_step="half", it_down_fq=900).set_train_in_gt_use_range(use_in_range=Range(0, 1), use_gt_range=Range(0, 1)).set_result_name(result_name="") ch032_1side_5__2side_2 = Exp_builder().set_basic("train", use_db_obj, ch032_pyramid_1side_5__2side_2, use_loss_obj, exp_dir=exp_dir, code_exe_path=code_exe_path, describe_end=ch032_pyramid_1side_5__2side_2.kong_model.model_describe) .set_train_args(epochs= 1) .set_train_iter_args(it_see_fq=900, it_save_fq=900 * 2, it_down_step="half", it_down_fq=900).set_train_in_gt_use_range(use_in_range=Range(0, 1), use_gt_range=Range(0, 1)).set_result_name(result_name="") ch032_1side_5__2side_3 = Exp_builder().set_basic("train", use_db_obj, ch032_pyramid_1side_5__2side_3, use_loss_obj, exp_dir=exp_dir, code_exe_path=code_exe_path, describe_end=ch032_pyramid_1side_5__2side_3.kong_model.model_describe) .set_train_args(epochs= 1) .set_train_iter_args(it_see_fq=900, it_save_fq=900 * 2, it_down_step="half", it_down_fq=900).set_train_in_gt_use_range(use_in_range=Range(0, 1), use_gt_range=Range(0, 1)).set_result_name(result_name="") ch032_1side_5__2side_4 = Exp_builder().set_basic("train", use_db_obj, ch032_pyramid_1side_5__2side_4, use_loss_obj, exp_dir=exp_dir, code_exe_path=code_exe_path, describe_end=ch032_pyramid_1side_5__2side_4.kong_model.model_describe) .set_train_args(epochs= 1) .set_train_iter_args(it_see_fq=900, it_save_fq=900 * 2, it_down_step="half", it_down_fq=900).set_train_in_gt_use_range(use_in_range=Range(0, 1), use_gt_range=Range(0, 1)).set_result_name(result_name="") ch032_1side_5__2side_5 = Exp_builder().set_basic("train", use_db_obj, ch032_pyramid_1side_5__2side_5, use_loss_obj, exp_dir=exp_dir, code_exe_path=code_exe_path, describe_end=ch032_pyramid_1side_5__2side_5.kong_model.model_describe) .set_train_args(epochs= 1) .set_train_iter_args(it_see_fq=900, it_save_fq=900 * 2, it_down_step="half", it_down_fq=900).set_train_in_gt_use_range(use_in_range=Range(0, 1), use_gt_range=Range(0, 1)).set_result_name(result_name="") ############################################################# if(__name__ == "__main__"): print("build exps cost time:", time.time() - start_time) if len(sys.argv) < 2: ############################################################################################################ ### 直接按 F5 或打 python step10_b1_exp_obj_load_and_train_and_test.py,後面沒有接東西喔!才不會跑到下面給 step10_b_subprocss.py 用的程式碼~~~ ch032_1side_1__2side_0.build().run() # print('no argument') sys.exit() ### 以下是給 step10_b_subprocess.py 用的,相當於cmd打 python step10_b1_exp_obj_load_and_train_and_test.py 某個exp.build().run() eval(sys.argv[1])
[ "s89334roy@yahoo.com.tw" ]
s89334roy@yahoo.com.tw
042568a8ee2acf18093ebb5b70a37e1db07273dd
acb8e84e3b9c987fcab341f799f41d5a5ec4d587
/langs/6/o0v.py
fb34f375bd962237285840ba0c98437fa4444cb0
[]
no_license
G4te-Keep3r/HowdyHackers
46bfad63eafe5ac515da363e1c75fa6f4b9bca32
fb6d391aaecb60ab5c4650d4ae2ddd599fd85db2
refs/heads/master
2020-08-01T12:08:10.782018
2016-11-13T20:45:50
2016-11-13T20:45:50
73,624,224
0
1
null
null
null
null
UTF-8
Python
false
false
486
py
import sys def printFunction(lineRemaining): if lineRemaining[0] == '"' and lineRemaining[-1] == '"': if len(lineRemaining) > 2: #data to print lineRemaining = lineRemaining[1:-1] print ' '.join(lineRemaining) else: print def main(fileName): with open(fileName) as f: for line in f: data = line.split() if data[0] == 'o0V': printFunction(data[1:]) else: print 'ERROR' return if __name__ == '__main__': main(sys.argv[1])
[ "juliettaylorswift@gmail.com" ]
juliettaylorswift@gmail.com
16d282009891a2c4adc9dddaac41212fbcddde77
42c48f3178a48b4a2a0aded547770027bf976350
/google/ads/google_ads/v4/services/transports/user_data_service_grpc_transport.py
ec4db4762b7980b03241c7cdc39e9b4037068321
[ "Apache-2.0" ]
permissive
fiboknacky/google-ads-python
e989464a85f28baca1f28d133994c73759e8b4d6
a5b6cede64f4d9912ae6ad26927a54e40448c9fe
refs/heads/master
2021-08-07T20:18:48.618563
2020-12-11T09:21:29
2020-12-11T09:21:29
229,712,514
0
0
Apache-2.0
2019-12-23T08:44:49
2019-12-23T08:44:49
null
UTF-8
Python
false
false
4,394
py
# -*- coding: utf-8 -*- # # Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import google.api_core.grpc_helpers from google.ads.google_ads.v4.proto.services import user_data_service_pb2_grpc class UserDataServiceGrpcTransport(object): """gRPC transport class providing stubs for google.ads.googleads.v4.services UserDataService API. The transport provides access to the raw gRPC stubs, which can be used to take advantage of advanced features of gRPC. """ # The scopes needed to make gRPC calls to all of the methods defined # in this service. _OAUTH_SCOPES = ( ) def __init__(self, channel=None, credentials=None, address='googleads.googleapis.com:443'): """Instantiate the transport class. Args: channel (grpc.Channel): A ``Channel`` instance through which to make calls. This argument is mutually exclusive with ``credentials``; providing both will raise an exception. credentials (google.auth.credentials.Credentials): The authorization credentials to attach to requests. These credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. address (str): The address where the service is hosted. """ # If both `channel` and `credentials` are specified, raise an # exception (channels come with credentials baked in already). if channel is not None and credentials is not None: raise ValueError( 'The `channel` and `credentials` arguments are mutually ' 'exclusive.', ) # Create the channel. if channel is None: channel = self.create_channel( address=address, credentials=credentials, ) self._channel = channel # gRPC uses objects called "stubs" that are bound to the # channel and provide a basic method for each RPC. self._stubs = { 'user_data_service_stub': user_data_service_pb2_grpc.UserDataServiceStub(channel), } @classmethod def create_channel( cls, address='googleads.googleapis.com:443', credentials=None, **kwargs): """Create and return a gRPC channel object. Args: address (str): The host for the channel to use. credentials (~.Credentials): The authorization credentials to attach to requests. These credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. kwargs (dict): Keyword arguments, which are passed to the channel creation. Returns: grpc.Channel: A gRPC channel object. """ return google.api_core.grpc_helpers.create_channel( address, credentials=credentials, scopes=cls._OAUTH_SCOPES, **kwargs ) @property def channel(self): """The gRPC channel used by the transport. Returns: grpc.Channel: A gRPC channel object. """ return self._channel @property def upload_user_data(self): """Return the gRPC stub for :meth:`UserDataServiceClient.upload_user_data`. Uploads the given user data. Returns: Callable: A callable which accepts the appropriate deserialized request object and returns a deserialized response object. """ return self._stubs['user_data_service_stub'].UploadUserData
[ "noreply@github.com" ]
fiboknacky.noreply@github.com
0d2350576ecf378e8d10e1a1b24cde6cb267ba87
c7967ec500b210513aa0b1f540144c931ca687ac
/알고리즘 스터디/개인공부/BinarySearch/LIS2.py
779a83856bf648e87df66face366164bdbfb6827
[]
no_license
sunminky/algorythmStudy
9a88e02c444b10904cebae94170eba456320f8e8
2ee1b5cf1f2e5f7ef87b44643210f407c4aa90e2
refs/heads/master
2023-08-17T01:49:43.528021
2023-08-13T08:11:37
2023-08-13T08:11:37
225,085,243
1
3
null
null
null
null
UTF-8
Python
false
false
478
py
# https://www.acmicpc.net/problem/12015 # https://www.acmicpc.net/problem/12738 #세그먼트 트리로도 구현 가능 import sys from bisect import bisect_left if __name__ == '__main__': n_number = int(sys.stdin.readline()) numbers = list(map(int, sys.stdin.readline().split())) lis = [] for n in numbers: idx = bisect_left(lis, n) if idx == len(lis): lis.append(n) else: lis[idx] = n print(len(lis))
[ "suns1502@gmail.com" ]
suns1502@gmail.com
e998cf66ff60d424742afe61f74535b053faffa7
cc9a87e975546e2ee2957039cceffcb795850d4f
/venv/lib/python3.7/site-packages/pip-19.0.3-py3.7.egg/pip/_internal/models/link.py
141f2d2c35393534ffdd72be7baa027e24c5b1d5
[]
no_license
CodeHunterDev/Belajar-Python
304d3243801b91b3605d2b9bd09e49a30735e51b
9dd2ffb556eed6b2540da19c5f206fedb218ae99
refs/heads/master
2023-03-19T22:12:46.330272
2020-02-04T08:02:00
2020-02-04T08:02:00
null
0
0
null
null
null
null
UTF-8
Python
false
false
4,860
py
# Copyright (c) 2020. Adam Arthur Faizal import posixpath import re from pip._vendor.six.moves.urllib import parse as urllib_parse from pip._internal.download import path_to_url from pip._internal.utils.misc import ( WHEEL_EXTENSION, redact_password_from_url, splitext, ) from pip._internal.utils.models import KeyBasedCompareMixin from pip._internal.utils.typing import MYPY_CHECK_RUNNING if MYPY_CHECK_RUNNING: from typing import Optional, Tuple, Union, Text # noqa: F401 from pip._internal.index import HTMLPage # noqa: F401 class Link(KeyBasedCompareMixin): """Represents a parsed link from a Package Index's simple URL """ def __init__(self, url, comes_from=None, requires_python=None): # type: (str, Optional[Union[str, HTMLPage]], Optional[str]) -> None """ url: url of the resource pointed to (href of the link) comes_from: instance of HTMLPage where the link was found, or string. requires_python: String containing the `Requires-Python` metadata field, specified in PEP 345. This may be specified by a data-requires-python attribute in the HTML link tag, as described in PEP 503. """ # url can be a UNC windows share if url.startswith('\\\\'): url = path_to_url(url) self.url = url self.comes_from = comes_from self.requires_python = requires_python if requires_python else None super(Link, self).__init__( key=(self.url), defining_class=Link ) def __str__(self): if self.requires_python: rp = ' (requires-python:%s)' % self.requires_python else: rp = '' if self.comes_from: return '%s (from %s)%s' % (redact_password_from_url(self.url), self.comes_from, rp) else: return redact_password_from_url(str(self.url)) def __repr__(self): return '<Link %s>' % self @property def filename(self): # type: () -> str _, netloc, path, _, _ = urllib_parse.urlsplit(self.url) name = posixpath.basename(path.rstrip('/')) or netloc name = urllib_parse.unquote(name) assert name, ('URL %r produced no filename' % self.url) return name @property def scheme(self): # type: () -> str return urllib_parse.urlsplit(self.url)[0] @property def netloc(self): # type: () -> str return urllib_parse.urlsplit(self.url)[1] @property def path(self): # type: () -> str return urllib_parse.unquote(urllib_parse.urlsplit(self.url)[2]) def splitext(self): # type: () -> Tuple[str, str] return splitext(posixpath.basename(self.path.rstrip('/'))) @property def ext(self): # type: () -> str return self.splitext()[1] @property def url_without_fragment(self): # type: () -> str scheme, netloc, path, query, fragment = urllib_parse.urlsplit(self.url) return urllib_parse.urlunsplit((scheme, netloc, path, query, None)) _egg_fragment_re = re.compile(r'[#&]egg=([^&]*)') @property def egg_fragment(self): # type: () -> Optional[str] match = self._egg_fragment_re.search(self.url) if not match: return None return match.group(1) _subdirectory_fragment_re = re.compile(r'[#&]subdirectory=([^&]*)') @property def subdirectory_fragment(self): # type: () -> Optional[str] match = self._subdirectory_fragment_re.search(self.url) if not match: return None return match.group(1) _hash_re = re.compile( r'(sha1|sha224|sha384|sha256|sha512|md5)=([a-f0-9]+)' ) @property def hash(self): # type: () -> Optional[str] match = self._hash_re.search(self.url) if match: return match.group(2) return None @property def hash_name(self): # type: () -> Optional[str] match = self._hash_re.search(self.url) if match: return match.group(1) return None @property def show_url(self): # type: () -> Optional[str] return posixpath.basename(self.url.split('#', 1)[0].split('?', 1)[0]) @property def is_wheel(self): # type: () -> bool return self.ext == WHEEL_EXTENSION @property def is_artifact(self): # type: () -> bool """ Determines if this points to an actual artifact (e.g. a tarball) or if it points to an "abstract" thing like a path or a VCS location. """ from pip._internal.vcs import vcs if self.scheme in vcs.all_schemes: return False return True
[ "adam.faizal.af6@gmail.com" ]
adam.faizal.af6@gmail.com
0cb2292823c2f8a42d1cff2808998981ab7b4e92
0ff91fa3bcd9cc115d5f9e73d82dca4d777143aa
/hackerrank/python/Strings/find-a-string-English.py
59f84647150fc1b03d914bd883a9ebdb033c0039
[]
no_license
Cekurok/codes-competition
1b335851b3e07b58a276b29c72df16ddbeff6b80
834afa2cc50549c82c72f5b0285661cd81f9a837
refs/heads/master
2021-09-16T05:08:58.689661
2018-06-16T18:35:16
2018-06-16T18:35:16
null
0
0
null
null
null
null
UTF-8
Python
false
false
232
py
def count_substring(string, sub_string): count = 0 subLen = len(sub_string) strLen = len(string) strLen -= subLen for i in range(0,strLen+1): if (sub_string == string[i:i+subLen]): count += 1 return count
[ "rrangarajan.85@gmail.com" ]
rrangarajan.85@gmail.com
353c0067d968cb6f3ae5b0d88ad3817aec595d26
5a52ccea88f90dd4f1acc2819997fce0dd5ffb7d
/alipay/aop/api/domain/KbAdvertChannelResponse.py
4713f34ba023cae3655b08598ab7e21203a5508d
[ "Apache-2.0" ]
permissive
alipay/alipay-sdk-python-all
8bd20882852ffeb70a6e929038bf88ff1d1eff1c
1fad300587c9e7e099747305ba9077d4cd7afde9
refs/heads/master
2023-08-27T21:35:01.778771
2023-08-23T07:12:26
2023-08-23T07:12:26
133,338,689
247
70
Apache-2.0
2023-04-25T04:54:02
2018-05-14T09:40:54
Python
UTF-8
Python
false
false
2,569
py
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * class KbAdvertChannelResponse(object): def __init__(self): self._channel_id = None self._memo = None self._name = None self._status = None self._type = None @property def channel_id(self): return self._channel_id @channel_id.setter def channel_id(self, value): self._channel_id = value @property def memo(self): return self._memo @memo.setter def memo(self, value): self._memo = value @property def name(self): return self._name @name.setter def name(self, value): self._name = value @property def status(self): return self._status @status.setter def status(self, value): self._status = value @property def type(self): return self._type @type.setter def type(self, value): self._type = value def to_alipay_dict(self): params = dict() if self.channel_id: if hasattr(self.channel_id, 'to_alipay_dict'): params['channel_id'] = self.channel_id.to_alipay_dict() else: params['channel_id'] = self.channel_id if self.memo: if hasattr(self.memo, 'to_alipay_dict'): params['memo'] = self.memo.to_alipay_dict() else: params['memo'] = self.memo if self.name: if hasattr(self.name, 'to_alipay_dict'): params['name'] = self.name.to_alipay_dict() else: params['name'] = self.name if self.status: if hasattr(self.status, 'to_alipay_dict'): params['status'] = self.status.to_alipay_dict() else: params['status'] = self.status if self.type: if hasattr(self.type, 'to_alipay_dict'): params['type'] = self.type.to_alipay_dict() else: params['type'] = self.type return params @staticmethod def from_alipay_dict(d): if not d: return None o = KbAdvertChannelResponse() if 'channel_id' in d: o.channel_id = d['channel_id'] if 'memo' in d: o.memo = d['memo'] if 'name' in d: o.name = d['name'] if 'status' in d: o.status = d['status'] if 'type' in d: o.type = d['type'] return o
[ "liuqun.lq@alibaba-inc.com" ]
liuqun.lq@alibaba-inc.com
b3d499fb081e6e3f518bdc86e8f89fb91acb6430
754f2e0cc83a16efda4f7a9c76b34dceb082bec6
/myblog/project/blog/models.py
90f126c98a839a791c3f635a734c0273983e8491
[]
no_license
veujs/myblog
b520c7742c6e761c851bbe9be13b235ef49587ea
326613e1563d3e63af35604c6592f014b35177d2
refs/heads/master
2020-04-15T17:14:34.161131
2019-02-27T06:51:17
2019-02-27T06:51:17
164,866,687
1
0
null
null
null
null
UTF-8
Python
false
false
501
py
from django.db import models # Create your models here. from django.utils import timezone from django.contrib.auth.models import User class BlogArticles(models.Model): title = models.CharField(max_length=100) author = models.ForeignKey(User,related_name="blog_posts") body = models.TextField() publish = models.DateTimeField(default=timezone.now) class Meta(): db_table = "blog_articles" ordering = ["-publish"] def _str_(self): return self.title
[ "624040034@qq.com" ]
624040034@qq.com
eb7c616950b5af0ac046e3f4e20c015ceb71c733
b1b77bb1ed47586f96d8f2554a65bcbd0c7162cc
/NETFLIX/NfWebCrypto/plugin/ppapi/ppapi/ppapi_ipc_untrusted.gyp
f1711feb5727c6987e611615c579f35dc1ca2e24
[ "BSD-3-Clause", "Apache-2.0" ]
permissive
DanHefrman/stuff
b3624d7089909972ee806211666374a261c02d08
b98a5c80cfe7041d8908dcfd4230cf065c17f3f6
refs/heads/master
2023-07-10T09:47:04.780112
2021-08-13T09:55:17
2021-08-13T09:55:17
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,510
gyp
# Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. { 'variables': { 'chromium_code': 1, }, 'includes': [ '../native_client/build/untrusted.gypi', 'ppapi_ipc.gypi', ], 'conditions': [ ['disable_nacl==0 and disable_nacl_untrusted==0', { 'targets': [ { 'target_name': 'ppapi_ipc_untrusted', 'type': 'none', 'variables': { 'ppapi_ipc_target': 1, 'nacl_win64_target': 0, 'nacl_untrusted_build': 1, 'nlib_target': 'libppapi_ipc_untrusted.a', 'build_glibc': 0, 'build_newlib': 1, 'defines': [ 'NACL_PPAPI_IPC_PROXY', # Enable threading for the untrusted side of the proxy. # TODO(bbudge) remove when this is the default. 'ENABLE_PEPPER_THREADING', ], }, 'include_dirs': [ '..', ], 'dependencies': [ '../native_client/tools.gyp:prep_toolchain', '../base/base_untrusted.gyp:base_untrusted', '../gpu/gpu_untrusted.gyp:gpu_ipc_untrusted', '../ipc/ipc_untrusted.gyp:ipc_untrusted', '../ppapi/ppapi_shared_untrusted.gyp:ppapi_shared_untrusted', '../components/components_tracing_untrusted.gyp:tracing_untrusted', ], }, ], }], ], }
[ "bryan.guner@gmail.com" ]
bryan.guner@gmail.com
0515d3547fc81361b6a0ce562a54675280caf442
f4dcde4b7b91bf293d9f1f626ff2d609c29fbd79
/common/configDB.py
1cffde0d8724676b17179dc96b4add15aa6f93b5
[]
no_license
hanzhichao/interfaceTest
ce182486336f276431f849e5b7b49978b22a37a2
bc75261ed246e3b18433a98ab91700281dca45ca
refs/heads/master
2020-03-08T02:17:52.004295
2018-04-03T05:28:26
2018-04-03T05:28:26
127,855,407
0
0
null
null
null
null
UTF-8
Python
false
false
1,391
py
"""数据库操作""" import pymysql import sys sys.path.append("..") import readConfig as readConfig from common.Log import MyLog as Log localReadConfig = readConfig.ReadConfig() class MyDB(object): global host, username, password, port, database, readConfig host = localReadConfig.get_db("host") username = localReadConfig.get_db("username") password = localReadConfig.get_db("password") port = localReadConfig.get_db("port") database = localReadConfig.get_db("database") config = { 'host': str(host), 'user': username, 'passwd': password, 'db': database } def __init__(self): self.log = Log.get_log() self.logger = self.log.get_logger() def connectDB(self): try: self.db = pymsql.connect(**config) self.cursor = self.db.cursor() print("连接数据库成功") except ConnectionError as ex: self.logger.error(str(ex)) def executeSQL(self, sql, params): self.connectDB() self.cursor = excute(sql, params) self.db.commit() return self.cursor def get_all(sefl, cursor): value = cursor.fetchall() return value def get_one(self, cursor): value = cursor.fetchone() return value def closeDB(self): self.db.close() print("数据库关闭")
[ "han_zhichao@sina.cn" ]
han_zhichao@sina.cn
bdc0f69515b694afde031a265ab90f53cd14d3b0
44064ed79f173ddca96174913910c1610992b7cb
/Second_Processing_app/temboo/Library/USPS/DeliveryInformationAPI/TrackConfirmFields.py
b3eb3882fb518cf16065c175fb1206576e708c22
[]
no_license
dattasaurabh82/Final_thesis
440fb5e29ebc28dd64fe59ecd87f01494ed6d4e5
8edaea62f5987db026adfffb6b52b59b119f6375
refs/heads/master
2021-01-20T22:25:48.999100
2014-10-14T18:58:00
2014-10-14T18:58:00
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,238
py
# -*- coding: utf-8 -*- ############################################################################### # # TrackConfirmFields # Track a package sent via USPS and return tracking information with details in separate XML tags. # # Python version 2.6 # ############################################################################### from temboo.core.choreography import Choreography from temboo.core.choreography import InputSet from temboo.core.choreography import ResultSet from temboo.core.choreography import ChoreographyExecution import json class TrackConfirmFields(Choreography): def __init__(self, temboo_session): """ Create a new instance of the TrackConfirmFields Choreo. A TembooSession object, containing a valid set of Temboo credentials, must be supplied. """ Choreography.__init__(self, temboo_session, '/Library/USPS/DeliveryInformationAPI/TrackConfirmFields') def new_input_set(self): return TrackConfirmFieldsInputSet() def _make_result_set(self, result, path): return TrackConfirmFieldsResultSet(result, path) def _make_execution(self, session, exec_id, path): return TrackConfirmFieldsChoreographyExecution(session, exec_id, path) class TrackConfirmFieldsInputSet(InputSet): """ An InputSet with methods appropriate for specifying the inputs to the TrackConfirmFields Choreo. The InputSet object is used to specify input parameters when executing this Choreo. """ def set_Endpoint(self, value): """ Set the value of the Endpoint input for this Choreo. ((optional, string) If you are accessing the production server, set to 'production'. Defaults to 'testing' which indicates that you are using the sandbox.) """ InputSet._set_input(self, 'Endpoint', value) def set_Password(self, value): """ Set the value of the Password input for this Choreo. ((required, password) The password assigned by USPS) """ InputSet._set_input(self, 'Password', value) def set_TrackID(self, value): """ Set the value of the TrackID input for this Choreo. ((required, string) The tracking number. Can be alphanumeric characters.) """ InputSet._set_input(self, 'TrackID', value) def set_UserId(self, value): """ Set the value of the UserId input for this Choreo. ((required, string) Alphanumeric ID assigned by USPS) """ InputSet._set_input(self, 'UserId', value) class TrackConfirmFieldsResultSet(ResultSet): """ A ResultSet with methods tailored to the values returned by the TrackConfirmFields Choreo. The ResultSet object is used to retrieve the results of a Choreo execution. """ def getJSONFromString(self, str): return json.loads(str) def get_Response(self): """ Retrieve the value for the "Response" output from this Choreo execution. ((xml) The response from USPS Web Service) """ return self._output.get('Response', None) class TrackConfirmFieldsChoreographyExecution(ChoreographyExecution): def _make_result_set(self, response, path): return TrackConfirmFieldsResultSet(response, path)
[ "dattasaurabh82@gmail.com" ]
dattasaurabh82@gmail.com
017e7f2ed891206d9d845f61c7bdc5467026b6d5
15f321878face2af9317363c5f6de1e5ddd9b749
/solutions_python/Problem_148/218.py
d6a472b10295e9b40fed81edb93442d25c164db7
[]
no_license
dr-dos-ok/Code_Jam_Webscraper
c06fd59870842664cd79c41eb460a09553e1c80a
26a35bf114a3aa30fc4c677ef069d95f41665cc0
refs/heads/master
2020-04-06T08:17:40.938460
2018-10-14T10:12:47
2018-10-14T10:12:47
null
0
0
null
null
null
null
UTF-8
Python
false
false
848
py
import sys def prework(argv): '''do something according to argv, return a message describing what have been done.''' return "nothing" def once(): '''to cope once''' n, x = [int(_) for _ in input().split()] ss = [int(_) for _ in input().split()] ss.sort() cnt = 0 while len(ss) > 1 : big = ss.pop() if ss[0] + big <= x : ss.pop(0) cnt += 1 if len(ss) > 0 : cnt += 1 return cnt def printerr(*v): print(*v, file=sys.stderr) def main(): TT = int(input()) for tt in range(1,TT+1): printerr("coping Case %d.."%(tt)) ans = once() print("Case #%d: %s"%(tt, (ans))) if __name__ == '__main__' : msg = prework(sys.argv) print("prework down with", msg, file=sys.stderr) main()
[ "miliar1732@gmail.com" ]
miliar1732@gmail.com
3231720c659ace7a738b91243cdd3c9dcfc2283a
acb8e84e3b9c987fcab341f799f41d5a5ec4d587
/langs/6/p4c.py
85276715e5d3795dbf4bcd582233ab98028579b1
[]
no_license
G4te-Keep3r/HowdyHackers
46bfad63eafe5ac515da363e1c75fa6f4b9bca32
fb6d391aaecb60ab5c4650d4ae2ddd599fd85db2
refs/heads/master
2020-08-01T12:08:10.782018
2016-11-13T20:45:50
2016-11-13T20:45:50
73,624,224
0
1
null
null
null
null
UTF-8
Python
false
false
486
py
import sys def printFunction(lineRemaining): if lineRemaining[0] == '"' and lineRemaining[-1] == '"': if len(lineRemaining) > 2: #data to print lineRemaining = lineRemaining[1:-1] print ' '.join(lineRemaining) else: print def main(fileName): with open(fileName) as f: for line in f: data = line.split() if data[0] == 'p4C': printFunction(data[1:]) else: print 'ERROR' return if __name__ == '__main__': main(sys.argv[1])
[ "juliettaylorswift@gmail.com" ]
juliettaylorswift@gmail.com
f99b17b6e18c5be816cfc3a835d3e975bcc42435
85b402cd9e762b2749c978105ea362b10d335e5c
/219-unet_model_with_functions_of_blocks.py
2fe553b815fa93ba3cdb1597aaf31e80f749f4f1
[]
no_license
bnsreenu/python_for_microscopists
29c08f17461baca95b5161fd4cd905be515605c4
4b8c0bd4274bc4d5e906a4952988c7f3e8db74c5
refs/heads/master
2023-09-04T21:11:25.524753
2023-08-24T18:40:53
2023-08-24T18:40:53
191,218,511
3,010
2,206
null
2023-07-25T07:15:22
2019-06-10T17:53:14
Jupyter Notebook
UTF-8
Python
false
false
1,734
py
# Building Unet by dividing encoder and decoder into blocks from keras.models import Model from keras.layers import Input, Conv2D, MaxPooling2D, UpSampling2D, concatenate, Conv2DTranspose, BatchNormalization, Dropout, Lambda from keras.optimizers import Adam from keras.layers import Activation, MaxPool2D, Concatenate def conv_block(input, num_filters): x = Conv2D(num_filters, 3, padding="same")(input) x = BatchNormalization()(x) #Not in the original network. x = Activation("relu")(x) x = Conv2D(num_filters, 3, padding="same")(x) x = BatchNormalization()(x) #Not in the original network x = Activation("relu")(x) return x #Encoder block: Conv block followed by maxpooling def encoder_block(input, num_filters): x = conv_block(input, num_filters) p = MaxPool2D((2, 2))(x) return x, p #Decoder block #skip features gets input from encoder for concatenation def decoder_block(input, skip_features, num_filters): x = Conv2DTranspose(num_filters, (2, 2), strides=2, padding="same")(input) x = Concatenate()([x, skip_features]) x = conv_block(x, num_filters) return x #Build Unet using the blocks def build_unet(input_shape): inputs = Input(input_shape) s1, p1 = encoder_block(inputs, 64) s2, p2 = encoder_block(p1, 128) s3, p3 = encoder_block(p2, 256) s4, p4 = encoder_block(p3, 512) b1 = conv_block(p4, 1024) #Bridge d1 = decoder_block(b1, s4, 512) d2 = decoder_block(d1, s3, 256) d3 = decoder_block(d2, s2, 128) d4 = decoder_block(d3, s1, 64) outputs = Conv2D(1, 1, padding="same", activation="sigmoid")(d4) #Binary (can be multiclass) model = Model(inputs, outputs, name="U-Net") return model
[ "noreply@github.com" ]
bnsreenu.noreply@github.com
0c281ae6304261a2e7ecb3ffae3479c22088a9b6
d12b59b33df5c467abf081d48e043dac70cc5a9c
/ixnetwork_restpy/testplatform/sessions/ixnetwork/topology/ospfpseudointerface_f8951a0e4c7d97b10ce403458d4a9a66.py
e316b694921985962f4f1eb39cbe5286557d5a52
[ "MIT" ]
permissive
ajbalogh/ixnetwork_restpy
59ce20b88c1f99f95a980ff01106bda8f4ad5a0f
60a107e84fd8c1a32e24500259738e11740069fd
refs/heads/master
2023-04-02T22:01:51.088515
2021-04-09T18:39:28
2021-04-09T18:39:28
null
0
0
null
null
null
null
UTF-8
Python
false
false
25,993
py
# MIT LICENSE # # Copyright 1997 - 2020 by IXIA Keysight # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. from ixnetwork_restpy.base import Base from ixnetwork_restpy.files import Files class OspfPseudoInterface(Base): """Information for Simulated Router Interfaces The OspfPseudoInterface class encapsulates a list of ospfPseudoInterface resources that are managed by the system. A list of resources can be retrieved from the server using the OspfPseudoInterface.find() method. """ __slots__ = () _SDM_NAME = 'ospfPseudoInterface' _SDM_ATT_MAP = { 'AdjSID': 'adjSID', 'AdministratorGroup': 'administratorGroup', 'BFlag': 'bFlag', 'BandwidthPriority0': 'bandwidthPriority0', 'BandwidthPriority1': 'bandwidthPriority1', 'BandwidthPriority2': 'bandwidthPriority2', 'BandwidthPriority3': 'bandwidthPriority3', 'BandwidthPriority4': 'bandwidthPriority4', 'BandwidthPriority5': 'bandwidthPriority5', 'BandwidthPriority6': 'bandwidthPriority6', 'BandwidthPriority7': 'bandwidthPriority7', 'Count': 'count', 'Dedicated1Plus1': 'dedicated1Plus1', 'Dedicated1To1': 'dedicated1To1', 'DescriptiveName': 'descriptiveName', 'EnLinkProtection': 'enLinkProtection', 'Enable': 'enable', 'EnableAdjSID': 'enableAdjSID', 'EnableSRLG': 'enableSRLG', 'Enhanced': 'enhanced', 'ExtraTraffic': 'extraTraffic', 'LFlag': 'lFlag', 'MaxBandwidth': 'maxBandwidth', 'MaxReservableBandwidth': 'maxReservableBandwidth', 'Metric': 'metric', 'MetricLevel': 'metricLevel', 'Name': 'name', 'PFlag': 'pFlag', 'Reserved40': 'reserved40', 'Reserved80': 'reserved80', 'SFlag': 'sFlag', 'Shared': 'shared', 'SrlgCount': 'srlgCount', 'Unprotected': 'unprotected', 'VFlag': 'vFlag', 'Weight': 'weight', } def __init__(self, parent): super(OspfPseudoInterface, self).__init__(parent) @property def SrlgValueList(self): """ Returns ------- - obj(ixnetwork_restpy.testplatform.sessions.ixnetwork.topology.srlgvaluelist_355b617a5f46ce90d800290d21158418.SrlgValueList): An instance of the SrlgValueList class Raises ------ - ServerError: The server has encountered an uncategorized error condition """ from ixnetwork_restpy.testplatform.sessions.ixnetwork.topology.srlgvaluelist_355b617a5f46ce90d800290d21158418 import SrlgValueList return SrlgValueList(self) @property def AdjSID(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): Adjacency SID """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['AdjSID'])) @property def AdministratorGroup(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): Administrator Group """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['AdministratorGroup'])) @property def BFlag(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): Backup Flag """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['BFlag'])) @property def BandwidthPriority0(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): Bandwidth for Priority 0 (B/sec) """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['BandwidthPriority0'])) @property def BandwidthPriority1(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): Bandwidth for Priority 1 (B/sec) """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['BandwidthPriority1'])) @property def BandwidthPriority2(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): Bandwidth for Priority 2 (B/sec) """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['BandwidthPriority2'])) @property def BandwidthPriority3(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): Bandwidth for Priority 3 (B/sec) """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['BandwidthPriority3'])) @property def BandwidthPriority4(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): Bandwidth for Priority 4 (B/sec) """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['BandwidthPriority4'])) @property def BandwidthPriority5(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): Bandwidth for Priority 5 (B/sec) """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['BandwidthPriority5'])) @property def BandwidthPriority6(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): Bandwidth for Priority 6 (B/sec) """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['BandwidthPriority6'])) @property def BandwidthPriority7(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): Bandwidth for Priority 7 (B/sec) """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['BandwidthPriority7'])) @property def Count(self): """ Returns ------- - number: Number of elements inside associated multiplier-scaled container object, e.g. number of devices inside a Device Group. """ return self._get_attribute(self._SDM_ATT_MAP['Count']) @property def Dedicated1Plus1(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): This is a Protection Scheme with value 0x10. It means that a dedicated disjoint link is protecting this link. However, the protecting link is not advertised in the link state database and is therefore not available for the routing of LSPs. """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['Dedicated1Plus1'])) @property def Dedicated1To1(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): This is a Protection Scheme with value 0x08. It means that there is one dedicated disjoint link of type Extra Traffic that is protecting this link. """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['Dedicated1To1'])) @property def DescriptiveName(self): """ Returns ------- - str: Longer, more descriptive name for element. It's not guaranteed to be unique like -name-, but may offer more context. """ return self._get_attribute(self._SDM_ATT_MAP['DescriptiveName']) @property def EnLinkProtection(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): This enables the link protection on the OSPF link between two mentioned interfaces. """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['EnLinkProtection'])) @property def Enable(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): TE Enabled """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['Enable'])) @property def EnableAdjSID(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): Enable Adj SID """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['EnableAdjSID'])) @property def EnableSRLG(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): This enables the SRLG on the OSPF link between two mentioned interfaces. """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['EnableSRLG'])) @property def Enhanced(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): This is a Protection Scheme with value 0x20. It means that a protection scheme that is more reliable than Dedicated 1+1, e.g., 4 fiber BLSR/MS-SPRING, is being used to protect this link. """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['Enhanced'])) @property def ExtraTraffic(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): This is a Protection Scheme with value 0x01. It means that the link is protecting another link or links. The LSPs on a link of this type will be lost if any of the links it is protecting fail. """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['ExtraTraffic'])) @property def LFlag(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): Local/Global Flag """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['LFlag'])) @property def MaxBandwidth(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): Maximum Bandwidth (B/sec) """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['MaxBandwidth'])) @property def MaxReservableBandwidth(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): Maximum Reservable Bandwidth (B/sec) """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['MaxReservableBandwidth'])) @property def Metric(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): Link Metric """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['Metric'])) @property def MetricLevel(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): TE Metric Level """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['MetricLevel'])) @property def Name(self): """ Returns ------- - str: Name of NGPF element, guaranteed to be unique in Scenario """ return self._get_attribute(self._SDM_ATT_MAP['Name']) @Name.setter def Name(self, value): self._set_attribute(self._SDM_ATT_MAP['Name'], value) @property def PFlag(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): Persistent Flag """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['PFlag'])) @property def Reserved40(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): This is a Protection Scheme with value 0x40. """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['Reserved40'])) @property def Reserved80(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): This is a Protection Scheme with value 0x80. """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['Reserved80'])) @property def SFlag(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): Set/Group Flag """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['SFlag'])) @property def Shared(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): This is a Protection Scheme with value 0x04. It means that there are one or more disjoint links of type Extra Traffic that are protecting this link. These Extra Traffic links are shared between one or more links of type Shared. """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['Shared'])) @property def SrlgCount(self): """ Returns ------- - number: This field value shows how many SRLG Value columns would be there in the GUI. """ return self._get_attribute(self._SDM_ATT_MAP['SrlgCount']) @SrlgCount.setter def SrlgCount(self, value): self._set_attribute(self._SDM_ATT_MAP['SrlgCount'], value) @property def Unprotected(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): This is a Protection Scheme with value 0x02. It means that there is no other link protecting this link. The LSPs on a link of this type will be lost if the link fails. """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['Unprotected'])) @property def VFlag(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): Value/Index Flag """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['VFlag'])) @property def Weight(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): Weight """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['Weight'])) def update(self, Name=None, SrlgCount=None): """Updates ospfPseudoInterface resource on the server. This method has some named parameters with a type: obj (Multivalue). The Multivalue class has documentation that details the possible values for those named parameters. Args ---- - Name (str): Name of NGPF element, guaranteed to be unique in Scenario - SrlgCount (number): This field value shows how many SRLG Value columns would be there in the GUI. Raises ------ - ServerError: The server has encountered an uncategorized error condition """ return self._update(self._map_locals(self._SDM_ATT_MAP, locals())) def find(self, Count=None, DescriptiveName=None, Name=None, SrlgCount=None): """Finds and retrieves ospfPseudoInterface resources from the server. All named parameters are evaluated on the server using regex. The named parameters can be used to selectively retrieve ospfPseudoInterface resources from the server. To retrieve an exact match ensure the parameter value starts with ^ and ends with $ By default the find method takes no parameters and will retrieve all ospfPseudoInterface resources from the server. Args ---- - Count (number): Number of elements inside associated multiplier-scaled container object, e.g. number of devices inside a Device Group. - DescriptiveName (str): Longer, more descriptive name for element. It's not guaranteed to be unique like -name-, but may offer more context. - Name (str): Name of NGPF element, guaranteed to be unique in Scenario - SrlgCount (number): This field value shows how many SRLG Value columns would be there in the GUI. Returns ------- - self: This instance with matching ospfPseudoInterface resources retrieved from the server available through an iterator or index Raises ------ - ServerError: The server has encountered an uncategorized error condition """ return self._select(self._map_locals(self._SDM_ATT_MAP, locals())) def read(self, href): """Retrieves a single instance of ospfPseudoInterface data from the server. Args ---- - href (str): An href to the instance to be retrieved Returns ------- - self: This instance with the ospfPseudoInterface resources from the server available through an iterator or index Raises ------ - NotFoundError: The requested resource does not exist on the server - ServerError: The server has encountered an uncategorized error condition """ return self._read(href) def get_device_ids(self, PortNames=None, AdjSID=None, AdministratorGroup=None, BFlag=None, BandwidthPriority0=None, BandwidthPriority1=None, BandwidthPriority2=None, BandwidthPriority3=None, BandwidthPriority4=None, BandwidthPriority5=None, BandwidthPriority6=None, BandwidthPriority7=None, Dedicated1Plus1=None, Dedicated1To1=None, EnLinkProtection=None, Enable=None, EnableAdjSID=None, EnableSRLG=None, Enhanced=None, ExtraTraffic=None, LFlag=None, MaxBandwidth=None, MaxReservableBandwidth=None, Metric=None, MetricLevel=None, PFlag=None, Reserved40=None, Reserved80=None, SFlag=None, Shared=None, Unprotected=None, VFlag=None, Weight=None): """Base class infrastructure that gets a list of ospfPseudoInterface device ids encapsulated by this object. Use the optional regex parameters in the method to refine the list of device ids encapsulated by this object. Args ---- - PortNames (str): optional regex of port names - AdjSID (str): optional regex of adjSID - AdministratorGroup (str): optional regex of administratorGroup - BFlag (str): optional regex of bFlag - BandwidthPriority0 (str): optional regex of bandwidthPriority0 - BandwidthPriority1 (str): optional regex of bandwidthPriority1 - BandwidthPriority2 (str): optional regex of bandwidthPriority2 - BandwidthPriority3 (str): optional regex of bandwidthPriority3 - BandwidthPriority4 (str): optional regex of bandwidthPriority4 - BandwidthPriority5 (str): optional regex of bandwidthPriority5 - BandwidthPriority6 (str): optional regex of bandwidthPriority6 - BandwidthPriority7 (str): optional regex of bandwidthPriority7 - Dedicated1Plus1 (str): optional regex of dedicated1Plus1 - Dedicated1To1 (str): optional regex of dedicated1To1 - EnLinkProtection (str): optional regex of enLinkProtection - Enable (str): optional regex of enable - EnableAdjSID (str): optional regex of enableAdjSID - EnableSRLG (str): optional regex of enableSRLG - Enhanced (str): optional regex of enhanced - ExtraTraffic (str): optional regex of extraTraffic - LFlag (str): optional regex of lFlag - MaxBandwidth (str): optional regex of maxBandwidth - MaxReservableBandwidth (str): optional regex of maxReservableBandwidth - Metric (str): optional regex of metric - MetricLevel (str): optional regex of metricLevel - PFlag (str): optional regex of pFlag - Reserved40 (str): optional regex of reserved40 - Reserved80 (str): optional regex of reserved80 - SFlag (str): optional regex of sFlag - Shared (str): optional regex of shared - Unprotected (str): optional regex of unprotected - VFlag (str): optional regex of vFlag - Weight (str): optional regex of weight Returns ------- - list(int): A list of device ids that meets the regex criteria provided in the method parameters Raises ------ - ServerError: The server has encountered an uncategorized error condition """ return self._get_ngpf_device_ids(locals()) def Abort(self): """Executes the abort operation on the server. Abort CPF control plane (equals to demote to kUnconfigured state). Raises ------ - NotFoundError: The requested resource does not exist on the server - ServerError: The server has encountered an uncategorized error condition """ payload = { "Arg1": self } return self._execute('abort', payload=payload, response_object=None) def Disconnect(self, *args, **kwargs): """Executes the disconnect operation on the server. Disconnect Simulated Interface The IxNetwork model allows for multiple method Signatures with the same name while python does not. disconnect(SessionIndices=list) ------------------------------- - SessionIndices (list(number)): This parameter requires an array of session numbers 1 2 3 disconnect(SessionIndices=string) --------------------------------- - SessionIndices (str): This parameter requires a string of session numbers 1-4;6;7-12 Raises ------ - NotFoundError: The requested resource does not exist on the server - ServerError: The server has encountered an uncategorized error condition """ payload = { "Arg1": self } for i in range(len(args)): payload['Arg%s' % (i + 2)] = args[i] for item in kwargs.items(): payload[item[0]] = item[1] return self._execute('disconnect', payload=payload, response_object=None) def Reconnect(self, *args, **kwargs): """Executes the reconnect operation on the server. Reconnect Simulated Interface The IxNetwork model allows for multiple method Signatures with the same name while python does not. reconnect(SessionIndices=list) ------------------------------ - SessionIndices (list(number)): This parameter requires an array of session numbers 1 2 3 reconnect(SessionIndices=string) -------------------------------- - SessionIndices (str): This parameter requires a string of session numbers 1-4;6;7-12 Raises ------ - NotFoundError: The requested resource does not exist on the server - ServerError: The server has encountered an uncategorized error condition """ payload = { "Arg1": self } for i in range(len(args)): payload['Arg%s' % (i + 2)] = args[i] for item in kwargs.items(): payload[item[0]] = item[1] return self._execute('reconnect', payload=payload, response_object=None) def Start(self): """Executes the start operation on the server. Start CPF control plane (equals to promote to negotiated state). Raises ------ - NotFoundError: The requested resource does not exist on the server - ServerError: The server has encountered an uncategorized error condition """ payload = { "Arg1": self } return self._execute('start', payload=payload, response_object=None) def Stop(self): """Executes the stop operation on the server. Stop CPF control plane (equals to demote to PreValidated-DoDDone state). Raises ------ - NotFoundError: The requested resource does not exist on the server - ServerError: The server has encountered an uncategorized error condition """ payload = { "Arg1": self } return self._execute('stop', payload=payload, response_object=None)
[ "andy.balogh@keysight.com" ]
andy.balogh@keysight.com
697935f155a7bdd2c57c63062706724a1ee2d1c3
c264153f9188d3af187905d846fa20296a0af85d
/Python/Python3网络爬虫开发实战/《Python3网络爬虫开发实战》随书源代码/scrapyseleniumtest/scrapyseleniumtest/items.py
383caae92fceee363746119211b6714f0b0d361a
[]
no_license
IS-OSCAR-YU/ebooks
5cd3c1089a221759793524df647e231a582b19ba
b125204c4fe69b9ca9ff774c7bc166d3cb2a875b
refs/heads/master
2023-05-23T02:46:58.718636
2021-06-16T12:15:13
2021-06-16T12:15:13
null
0
0
null
null
null
null
UTF-8
Python
false
false
389
py
# -*- coding: utf-8 -*- # Define here the models for your scraped items # # See documentation in: # http://doc.scrapy.org/en/latest/topics/items.html from scrapy import Item, Field class ProductItem(Item): collection = 'products' image = Field() price = Field() deal = Field() title = Field() shop = Field() location = Field()
[ "jiangzhangha@163.com" ]
jiangzhangha@163.com
60194a6d0d99911e72ce15440b1a894e43f1cb31
c20a356220d3f66d49bbad88e6bd56a26aac1465
/tf_test_4_4_2.py
2c4f0eb10427a9ae2fd3635bea1995c04a5a6e4e
[]
no_license
liuwei881/tensorflow_example
5f7164f94a3cec63b47c78764fd6a3023de3247e
5bed141ee0c64f3e62d508a171ed735edbfbffff
refs/heads/master
2020-06-12T04:27:02.016333
2019-05-30T09:58:05
2019-05-30T09:58:05
194,194,167
1
0
null
null
null
null
UTF-8
Python
false
false
1,990
py
# coding=utf-8 import tensorflow as tensorflow def get_weight(shape, lambd): # 生成一个变量 var = tf.Variable(tf.random_normal(shape), dtype=tf.float32) # add_to_collection 函数将这个新生成变量的L2正则化损失项加入集合 # 这个函数的第一个参数'losses'是集合的名字, 第二个参数是要加入这个集合的内容 tf.add_to_collection( 'losses', tf.contrib.layers.l2_regularizer(lambd)(var)) return var x = tf.placeholder(tf.float32, shape=(None, 2)) y_ = tf.placeholder(tf.float32, shape=(None, 1)) batch_size = 8 # 定义了每一层网络中节点的个数 layer_dimension = [2, 10, 10, 10, 1] # 神经网络的层数 n_layers = len(layer_dimension) # 这个变量维护前向传播时最深层的节点, 开始的时候就是输入层 cur_layer = x # 当前层的节点个数 in_dimension = layer_dimension[0] for i in range(1, n_layers): # layer_dimension[i]为下一层节点个数 out_dimension = layer_dimension[i] # 生成当前层中权重的变量, 并将这个变量的L2正则化损失加入计算图上的集合 weight = get_weight([in_dimension, out_dimension], 0.001) bias = tf.Variable(tf.constant(0.1, shape=[out_dimension])) # 使用ReLU激活函数 cur_layer = tf.nn.relu(tf.matmul(cur_layer, weight) + bias) # 进入下一层之前将下一层的节点个数更新为当前层节点的个数 in_dimension = layer_dimension[i] # 在定义神经网络前向传播的同时已经将所有的L2正则化损失加入了图上的集合, # 这里只需要计算刻画模型在训练数据上表现的损失函数 mse_loss = tf.reduce_mean(tf.square(y_ - cur_layer)) # 将均方误差损失函数加入损失集合 tf.add_to_collection('losses', mse_loss) # get_collection返回一个列表, 这个列表是所有这个集合中的元素. 在这个样例中, # 这些元素就是损失函数的不同部分, 将它们加起来就可以得到最终的损失函数 loss = tf.add_n(tf.get_collection('losses'))
[ "liuweia@mail.open.com.cn" ]
liuweia@mail.open.com.cn
c5b4385fbf41eb155af8c374bb450da4b85d0662
98efe1aee73bd9fbec640132e6fb2e54ff444904
/loldib/getratings/models/NA/na_nocturne/na_nocturne_mid.py
e6ba0b8402afbf89e98fd709a52024e8f59a786d
[ "Apache-2.0" ]
permissive
koliupy/loldib
be4a1702c26546d6ae1b4a14943a416f73171718
c9ab94deb07213cdc42b5a7c26467cdafaf81b7f
refs/heads/master
2021-07-04T03:34:43.615423
2017-09-21T15:44:10
2017-09-21T15:44:10
104,359,388
0
0
null
null
null
null
UTF-8
Python
false
false
6,821
py
from getratings.models.ratings import Ratings class NA_Nocturne_Mid_Aatrox(Ratings): pass class NA_Nocturne_Mid_Ahri(Ratings): pass class NA_Nocturne_Mid_Akali(Ratings): pass class NA_Nocturne_Mid_Alistar(Ratings): pass class NA_Nocturne_Mid_Amumu(Ratings): pass class NA_Nocturne_Mid_Anivia(Ratings): pass class NA_Nocturne_Mid_Annie(Ratings): pass class NA_Nocturne_Mid_Ashe(Ratings): pass class NA_Nocturne_Mid_AurelionSol(Ratings): pass class NA_Nocturne_Mid_Azir(Ratings): pass class NA_Nocturne_Mid_Bard(Ratings): pass class NA_Nocturne_Mid_Blitzcrank(Ratings): pass class NA_Nocturne_Mid_Brand(Ratings): pass class NA_Nocturne_Mid_Braum(Ratings): pass class NA_Nocturne_Mid_Caitlyn(Ratings): pass class NA_Nocturne_Mid_Camille(Ratings): pass class NA_Nocturne_Mid_Cassiopeia(Ratings): pass class NA_Nocturne_Mid_Chogath(Ratings): pass class NA_Nocturne_Mid_Corki(Ratings): pass class NA_Nocturne_Mid_Darius(Ratings): pass class NA_Nocturne_Mid_Diana(Ratings): pass class NA_Nocturne_Mid_Draven(Ratings): pass class NA_Nocturne_Mid_DrMundo(Ratings): pass class NA_Nocturne_Mid_Ekko(Ratings): pass class NA_Nocturne_Mid_Elise(Ratings): pass class NA_Nocturne_Mid_Evelynn(Ratings): pass class NA_Nocturne_Mid_Ezreal(Ratings): pass class NA_Nocturne_Mid_Fiddlesticks(Ratings): pass class NA_Nocturne_Mid_Fiora(Ratings): pass class NA_Nocturne_Mid_Fizz(Ratings): pass class NA_Nocturne_Mid_Galio(Ratings): pass class NA_Nocturne_Mid_Gangplank(Ratings): pass class NA_Nocturne_Mid_Garen(Ratings): pass class NA_Nocturne_Mid_Gnar(Ratings): pass class NA_Nocturne_Mid_Gragas(Ratings): pass class NA_Nocturne_Mid_Graves(Ratings): pass class NA_Nocturne_Mid_Hecarim(Ratings): pass class NA_Nocturne_Mid_Heimerdinger(Ratings): pass class NA_Nocturne_Mid_Illaoi(Ratings): pass class NA_Nocturne_Mid_Irelia(Ratings): pass class NA_Nocturne_Mid_Ivern(Ratings): pass class NA_Nocturne_Mid_Janna(Ratings): pass class NA_Nocturne_Mid_JarvanIV(Ratings): pass class NA_Nocturne_Mid_Jax(Ratings): pass class NA_Nocturne_Mid_Jayce(Ratings): pass class NA_Nocturne_Mid_Jhin(Ratings): pass class NA_Nocturne_Mid_Jinx(Ratings): pass class NA_Nocturne_Mid_Kalista(Ratings): pass class NA_Nocturne_Mid_Karma(Ratings): pass class NA_Nocturne_Mid_Karthus(Ratings): pass class NA_Nocturne_Mid_Kassadin(Ratings): pass class NA_Nocturne_Mid_Katarina(Ratings): pass class NA_Nocturne_Mid_Kayle(Ratings): pass class NA_Nocturne_Mid_Kayn(Ratings): pass class NA_Nocturne_Mid_Kennen(Ratings): pass class NA_Nocturne_Mid_Khazix(Ratings): pass class NA_Nocturne_Mid_Kindred(Ratings): pass class NA_Nocturne_Mid_Kled(Ratings): pass class NA_Nocturne_Mid_KogMaw(Ratings): pass class NA_Nocturne_Mid_Leblanc(Ratings): pass class NA_Nocturne_Mid_LeeSin(Ratings): pass class NA_Nocturne_Mid_Leona(Ratings): pass class NA_Nocturne_Mid_Lissandra(Ratings): pass class NA_Nocturne_Mid_Lucian(Ratings): pass class NA_Nocturne_Mid_Lulu(Ratings): pass class NA_Nocturne_Mid_Lux(Ratings): pass class NA_Nocturne_Mid_Malphite(Ratings): pass class NA_Nocturne_Mid_Malzahar(Ratings): pass class NA_Nocturne_Mid_Maokai(Ratings): pass class NA_Nocturne_Mid_MasterYi(Ratings): pass class NA_Nocturne_Mid_MissFortune(Ratings): pass class NA_Nocturne_Mid_MonkeyKing(Ratings): pass class NA_Nocturne_Mid_Mordekaiser(Ratings): pass class NA_Nocturne_Mid_Morgana(Ratings): pass class NA_Nocturne_Mid_Nami(Ratings): pass class NA_Nocturne_Mid_Nasus(Ratings): pass class NA_Nocturne_Mid_Nautilus(Ratings): pass class NA_Nocturne_Mid_Nidalee(Ratings): pass class NA_Nocturne_Mid_Nocturne(Ratings): pass class NA_Nocturne_Mid_Nunu(Ratings): pass class NA_Nocturne_Mid_Olaf(Ratings): pass class NA_Nocturne_Mid_Orianna(Ratings): pass class NA_Nocturne_Mid_Ornn(Ratings): pass class NA_Nocturne_Mid_Pantheon(Ratings): pass class NA_Nocturne_Mid_Poppy(Ratings): pass class NA_Nocturne_Mid_Quinn(Ratings): pass class NA_Nocturne_Mid_Rakan(Ratings): pass class NA_Nocturne_Mid_Rammus(Ratings): pass class NA_Nocturne_Mid_RekSai(Ratings): pass class NA_Nocturne_Mid_Renekton(Ratings): pass class NA_Nocturne_Mid_Rengar(Ratings): pass class NA_Nocturne_Mid_Riven(Ratings): pass class NA_Nocturne_Mid_Rumble(Ratings): pass class NA_Nocturne_Mid_Ryze(Ratings): pass class NA_Nocturne_Mid_Sejuani(Ratings): pass class NA_Nocturne_Mid_Shaco(Ratings): pass class NA_Nocturne_Mid_Shen(Ratings): pass class NA_Nocturne_Mid_Shyvana(Ratings): pass class NA_Nocturne_Mid_Singed(Ratings): pass class NA_Nocturne_Mid_Sion(Ratings): pass class NA_Nocturne_Mid_Sivir(Ratings): pass class NA_Nocturne_Mid_Skarner(Ratings): pass class NA_Nocturne_Mid_Sona(Ratings): pass class NA_Nocturne_Mid_Soraka(Ratings): pass class NA_Nocturne_Mid_Swain(Ratings): pass class NA_Nocturne_Mid_Syndra(Ratings): pass class NA_Nocturne_Mid_TahmKench(Ratings): pass class NA_Nocturne_Mid_Taliyah(Ratings): pass class NA_Nocturne_Mid_Talon(Ratings): pass class NA_Nocturne_Mid_Taric(Ratings): pass class NA_Nocturne_Mid_Teemo(Ratings): pass class NA_Nocturne_Mid_Thresh(Ratings): pass class NA_Nocturne_Mid_Tristana(Ratings): pass class NA_Nocturne_Mid_Trundle(Ratings): pass class NA_Nocturne_Mid_Tryndamere(Ratings): pass class NA_Nocturne_Mid_TwistedFate(Ratings): pass class NA_Nocturne_Mid_Twitch(Ratings): pass class NA_Nocturne_Mid_Udyr(Ratings): pass class NA_Nocturne_Mid_Urgot(Ratings): pass class NA_Nocturne_Mid_Varus(Ratings): pass class NA_Nocturne_Mid_Vayne(Ratings): pass class NA_Nocturne_Mid_Veigar(Ratings): pass class NA_Nocturne_Mid_Velkoz(Ratings): pass class NA_Nocturne_Mid_Vi(Ratings): pass class NA_Nocturne_Mid_Viktor(Ratings): pass class NA_Nocturne_Mid_Vladimir(Ratings): pass class NA_Nocturne_Mid_Volibear(Ratings): pass class NA_Nocturne_Mid_Warwick(Ratings): pass class NA_Nocturne_Mid_Xayah(Ratings): pass class NA_Nocturne_Mid_Xerath(Ratings): pass class NA_Nocturne_Mid_XinZhao(Ratings): pass class NA_Nocturne_Mid_Yasuo(Ratings): pass class NA_Nocturne_Mid_Yorick(Ratings): pass class NA_Nocturne_Mid_Zac(Ratings): pass class NA_Nocturne_Mid_Zed(Ratings): pass class NA_Nocturne_Mid_Ziggs(Ratings): pass class NA_Nocturne_Mid_Zilean(Ratings): pass class NA_Nocturne_Mid_Zyra(Ratings): pass
[ "noreply@github.com" ]
koliupy.noreply@github.com
820d18976ceb036fc4e268a237ec43a25998aa45
f5f771cd8600c2aeb7fc9b192d9084ec5fdf3616
/lux/extensions/rest/user.py
8c79233356ca1acf51458387f80667140e8413dc
[ "BSD-3-Clause" ]
permissive
SirZazu/lux
75fe9fde4ddaee1c9c17e55c6e6d07a289ea2f5b
d647c34d11d1172d40e16b6afaba4ee67950fb5a
refs/heads/master
2021-01-21T19:40:46.536485
2015-06-02T16:30:18
2015-06-02T16:30:18
36,931,033
0
3
null
2015-10-09T14:08:26
2015-06-05T12:15:21
Python
UTF-8
Python
false
false
4,779
py
import time from importlib import import_module from datetime import datetime, timedelta from pulsar import PermissionDenied, Http404 from pulsar.utils.pep import to_bytes, to_string import lux from lux.utils.crypt import get_random_string, digest __all__ = ['AuthenticationError', 'LoginError', 'LogoutError', 'MessageMixin', 'UserMixin', 'normalise_email', 'PasswordMixin', 'Anonymous', 'CREATE', 'READ', 'UPDATE', 'DELETE'] UNUSABLE_PASSWORD = '!' CREATE = 30 # C READ = 10 # R UPDATE = 20 # U DELETE = 40 # D class AuthenticationError(ValueError): pass class LoginError(RuntimeError): pass class LogoutError(RuntimeError): pass class MessageMixin(object): '''Mixin for models which support messages ''' def success(self, message): '''Store a ``success`` message to show to the web user ''' self.message('success', message) def info(self, message): '''Store an ``info`` message to show to the web user ''' self.message('info', message) def warning(self, message): '''Store a ``warning`` message to show to the web user ''' self.message('warning', message) def error(self, message): '''Store an ``error`` message to show to the web user ''' self.message('danger', message) def message(self, level, message): '''Store a ``message`` of ``level`` to show to the web user. Must be implemented by session classes. ''' raise NotImplementedError def remove_message(self, data): '''Remove a message from the list of messages''' raise NotImplementedError def get_messages(self): '''Retrieve messages ''' return () class UserMixin(MessageMixin): '''Mixin for a User model ''' email = None def is_superuser(self): return False def is_authenticated(self): '''Return ``True`` if the user is is_authenticated ''' return True def is_active(self): return False def is_anonymous(self): return False def get_id(self): raise NotImplementedError def get_oauths(self): '''Return a dictionary of oauths account''' return {} def set_oauth(self, name, data): raise NotImplementedError def remove_oauth(self, name): '''Remove a connected oauth account. Return ``True`` if successfully removed ''' raise NotImplementedError def todict(self): '''Return a dictionary with information about the user''' def email_user(self, app, subject, body, sender=None): backend = app.email_backend backend.send_mail(app, sender, self.email, subject, body) @classmethod def get_by_username(cls, username): '''Retrieve a user from username ''' raise NotImplementedError @classmethod def get_by_email(cls, email): raise NotImplementedError @classmethod def get_by_oauth(cls, name, identifier): '''Retrieve a user from OAuth ``name`` with ``identifier`` ''' raise NotImplementedError class Anonymous(UserMixin): def is_authenticated(self): return False def is_anonymous(self): return True def get_id(self): return 0 class PasswordMixin: def on_config(self, app): cfg = app.config self.encoding = cfg['ENCODING'] self.secret_key = cfg['SECRET_KEY'].encode() self.salt_size = cfg['AUTH_SALT_SIZE'] algorithm = cfg['CRYPT_ALGORITHM'] self.crypt_module = import_module(algorithm) def decript(self, password=None): if password: p = self.crypt_module.decrypt(to_bytes(password, self.encoding), self.secret_key) return to_string(p, self.encoding) else: return UNUSABLE_PASSWORD def encript(self, password): p = self.crypt_module.encrypt(to_bytes(password, self.encoding), self.secret_key, self.salt_size) return to_string(p, self.encoding) def password(self, raw_password=None): if raw_password: return self.encript(raw_password) else: return UNUSABLE_PASSWORD def set_password(self, user, password): '''Set the password for ``user``. This method should commit changes.''' pass def normalise_email(email): """ Normalise the address by lowercasing the domain part of the email address. """ email_name, domain_part = email.strip().rsplit('@', 1) email = '@'.join([email_name, domain_part.lower()]) return email
[ "luca.sbardella@gmail.com" ]
luca.sbardella@gmail.com
73e35aa72ced86eef9739609dfcb0a5cc7ba54f9
290394852b7fb70f791c6c4bb96141523ab96090
/ExpertIdeas_WikipediaProxyServer_Bot_EmailTracking/ExpertIdeas/core/scripts/blockreview.py
5d76775fa0189a1c5c2a336beb4f5c6c4e06d997
[ "MIT" ]
permissive
ImanYZ/ExpertIdeas
da1564671f2cfe92d9de3fce68b82552cc6f33f7
23e23240854aef59108b16b63a567fffb2aabb69
refs/heads/master
2022-07-27T08:11:36.481824
2022-07-16T20:32:47
2022-07-16T20:32:47
144,018,052
0
0
null
null
null
null
UTF-8
Python
false
false
13,664
py
#!/usr/bin/python # -*- coding: utf-8 -*- """ This bot implements a blocking review process for de-wiki first. For other sites this bot script must be changed. This script is run by [[de:User:xqt]]. It should not be run by other users without prior contact. The following parameters are supported: - All other parameters will be regarded as part of the title of a single page, and the bot will only work on that single page. """ # # (C) xqt, 2010-2014 # # Distributed under the terms of the MIT license. # __version__ = '$Id: 6dac7b1808d40f970371ef2b12e548fb5986bca4 $' # import pywikibot from pywikibot.compat import query class BlockreviewBot: # notes note_admin = { 'de': u""" == Sperrprüfungswunsch == Hallo %(admin)s, [[%(user)s]] wünscht die Prüfung seiner/ihrer Sperre vom %(time)s über die Dauer von %(duration)s. Kommentar war ''%(comment)s''. Bitte äußere Dich dazu auf der [[%(usertalk)s#%(section)s|Diskussionsseite]]. -~~~~""" } note_project = { 'de': u""" == [[%(user)s]] == * gesperrt am %(time)s durch {{Benutzer|%(admin)s}} für eine Dauer von %(duration)s. * Kommentar war ''%(comment)s''. * [[Benutzer:%(admin)s]] wurde [[Benutzer Diskussion:%(admin)s#Sperrprüfungswunsch|benachrichtigt]]. * [[%(usertalk)s#%(section)s|Link zur Diskussion]] :<small>-~~~~</small> ;Antrag entgegengenommen""" } # edit summaries msg_admin = { 'de': u'Bot-Benachrichtigung: Sperrprüfungswunsch von [[%(user)s]]', } msg_user = { 'de': u'Bot: Administrator [[Benutzer:%(admin)s|%(admin)s]] für Sperrprüfung benachrichtigt', } msg_done = { 'de': u'Bot: Sperrprüfung abgeschlossen. Benutzer ist entsperrt.', } unblock_tpl = { 'de': u'Benutzer:TAXman/Sperrprüfungsverfahren', 'pt': u'Predefinição:Discussão de bloqueio', } review_cat = { 'de': u'Wikipedia:Sperrprüfung', } project_name = { 'de': u'Benutzer:TAXman/Sperrprüfung Neu', 'pt': u'Wikipedia:Pedidos a administradores/Discussão de bloqueio', } def __init__(self, dry=False): """ Constructor. Parameters: * generator - The page generator that determines on which pages to work on. * dry - If True, doesn't do any real changes, but only shows what would have been changed. """ self.site = pywikibot.Site() self.dry = dry self.info = None self.parts = None def run(self): # TODO: change the generator for template to the included category try: genPage = pywikibot.Page(self.site, self.unblock_tpl[self.site.code], defaultNamespace=10) except KeyError: pywikibot.error(u'Language "%s" not supported by this bot.' % self.site.code) else: for page in genPage.getReferences(follow_redirects=False, withTemplateInclusion=True, onlyTemplateInclusion=True): if page.namespace() == 3: self.treat(page) else: pywikibot.output(u'Ignoring %s, user namespace required' % page.title(asLink=True)) def treat(self, userPage): """ Loads the given page, does some changes, and saves it. """ talkText = self.load(userPage) if not talkText: # sanity check. No talk page found. return unblock_tpl = self.unblock_tpl[self.site.code] project_name = self.project_name[self.site.code] user = pywikibot.User(self.site, userPage.title(withNamespace=False)) # saveAdmin = saveProject = False talkComment = None for templates in userPage.templatesWithParams(): if templates[0] == unblock_tpl: self.getInfo(user) # Step 1 # a new template is set on blocked users talk page. # Notify the blocking admin if templates[1] == [] or templates[1][0] == u'1': if self.info['action'] == 'block' or user.isBlocked(): if self.site.sitename() == 'wikipedia:de': admin = pywikibot.User(self.site, self.info['user']) adminPage = admin.getUserTalkPage() adminText = adminPage.get() note = i18n.translate(self.site.code, self.note_admin, self.parts) comment = i18n.translate(self.site.code, self.msg_admin, self.parts) adminText += note self.save(adminText, adminPage, comment, False) ### test for pt-wiki ### just print all sysops talk pages elif self.site.sitename() == 'wikipedia:pt': from pywikibot import pagegenerators as pg gen = pg.PreloadingGenerator(self.SysopGenerator()) for sysop in gen: print sysop.title() talkText = talkText.replace(u'{{%s}}' % unblock_tpl, u'{{%s|2}}' % unblock_tpl) talkText = talkText.replace(u'{{%s|1}}' % unblock_tpl, u'{{%s|2}}' % unblock_tpl) talkComment = i18n.translate(self.site.code, self.msg_user % self.parts) # some test stuff if pywikibot.logger.isEnabledFor(pywikibot.DEBUG) \ and self.site().loggedInAs() == u'Xqbot:': testPage = pywikibot.Page(self.site, 'Benutzer:Xqt/Test') test = testPage.get() test += note self.save(test, testPage, '[[WP:BA#SPP-Bot|SPPB-Test]]') else: # nicht blockiert. Fall auf DS abschließen talkText = talkText.replace(u'{{%s}}' % unblock_tpl, u'{{%s|4}}' % unblock_tpl) talkText = talkText.replace(u'{{%s|1}}' % unblock_tpl, u'{{%s|4}}' % unblock_tpl) talkComment = i18n.translate(self.site.code, self.msg_done) # Step 2 # Admin has been notified. # Wait for 2 hours, than put a message to the project page elif templates[1][0] == u'2': if self.info['action'] == 'block' or user.isBlocked(): # TODO: check whether wait time is gone # check whether this entry already esists project = pywikibot.Page(self.site, project_name) projText = project.get() note = i18n.translate(self.site.code, self.note_project, self.parts) comment = i18n.translate(self.site.code, self.msg_admin, self.parts) projText += note self.save(projText, project, comment, botflag=False) talkText = talkText.replace(u'{{%s|2}}' % unblock_tpl, u'{{%s|3}}' % unblock_tpl) talkComment = u'Bot: [[%s|Wikipedia:Sperrprüfung]] eingetragen' \ % project_name else: # User is unblocked. Review can be closed talkText = talkText.replace(u'{{%s|2}}' % unblock_tpl, u'{{%s|4}}' % unblock_tpl) talkComment = i18n.translate(self.site.code, self.msg_done) # Step 3 # Admin is notified, central project page has a message # Discussion is going on # Check whether it can be closed elif templates[1][0] == u'3': if self.info['action'] == 'block' or user.isBlocked(): pass else: # User is unblocked. Review can be closed talkText = talkText.replace(u'{{%s|3}}' % unblock_tpl, u'{{%s|4}}' % unblock_tpl) talkComment = i18n.translate(self.site.code, self.msg_done) # Step 4 # Review is closed elif templates[1][0] == u'4': # nothing left to do pass else: # wrong template found pass # at last if there is a talk comment, users talk page must be changed if talkComment: self.save(talkText, userPage, talkComment) def getInfo(self, user): if not self.info: self.info = self.site.logpages(1, mode='block', title=user.getUserPage().title(), dump=True).next() self.parts = { 'admin': self.info['user'], 'user': self.info['title'], 'usertalk': user.getUserTalkPage().title(), 'section': u'Sperrprüfung', 'time': self.info['timestamp'], 'duration': self.info['block']['duration'], 'comment': self.info['comment'], } def SysopGenerator(self): params = { 'action': 'query', 'list': 'allusers', 'augroup': 'sysop', 'auprop': 'groups', 'aulimit': 500, } data = query.GetData(params, self.site) for user in data['query']['allusers']: # exclude sysop bots if 'bot' not in user['groups']: # yield the sysop talkpage yield pywikibot.Page(self.site, user['name'], defaultNamespace=3) def load(self, page): """ Loads the given page, does some changes, and saves it. """ try: # Load the page text = page.get() except pywikibot.NoPage: pywikibot.output(u"Page %s does not exist; skipping." % page.title(asLink=True)) except pywikibot.IsRedirectPage: pywikibot.output(u"Page %s is a redirect; skipping." % page.title(asLink=True)) else: return text def save(self, text, page, comment, minorEdit=True, botflag=True): if text != page.text: # Show the title of the page we're working on. # Highlight the title in purple. pywikibot.output(u"\n\n>>> \03{lightpurple}%s\03{default} <<<" % page.title()) # show what was changed pywikibot.showDiff(page.get(), text) pywikibot.output(u'Comment: %s' % comment) if not self.dry: choice = pywikibot.inputChoice( u'Do you want to accept these changes?', ['Yes', 'No'], ['y', 'N'], 'N') if choice == 'y': page.text = text try: # Save the page page.save(comment=comment, minorEdit=minorEdit, botflag=botflag) except pywikibot.LockedPage: pywikibot.output(u"Page %s is locked; skipping." % page.title(asLink=True)) except pywikibot.EditConflict: pywikibot.output( u'Skipping %s because of edit conflict' % (page.title())) except pywikibot.SpamfilterError, error: pywikibot.output( u'Cannot change %s because of spam blacklist entry ' u'%s' % (page.title(), error.url)) else: return True def main(): show = False # Parse command line arguments for arg in pywikibot.handleArgs(): show = True if not show: bot = BlockreviewBot() bot.run() else: pywikibot.showHelp() if __name__ == "__main__": main()
[ "oneweb@umich.edu" ]
oneweb@umich.edu
7b9ed189a2e8a042b0c9614fde530a77d4c760df
897d3299ef2eb9747ed21b9857b3c5dfda841f97
/cnns/graphs/distortion_graph/distortion2.py
6514b5b161779ddc90b89a85fcc4f0f9c3ebc379
[ "Apache-2.0" ]
permissive
stjordanis/bandlimited-cnns
59a286cdae16fb07d4418ac2008c34f7849c35da
e2b20efd391a971e128d62acc1801c81dc1bf4d7
refs/heads/master
2020-07-03T07:01:17.732061
2019-08-07T23:33:40
2019-08-07T23:33:40
null
0
0
null
null
null
null
UTF-8
Python
false
false
6,469
py
import matplotlib # matplotlib.use('TkAgg') matplotlib.rcParams['pdf.fonttype'] = 42 matplotlib.rcParams['ps.fonttype'] = 42 import matplotlib.pyplot as plt import csv import os print(matplotlib.get_backend()) # plt.interactive(True) # http://ksrowell.com/blog-visualizing-data/2012/02/02/optimal-colors-for-graphs/ MY_BLUE = (56, 106, 177) MY_RED = (204, 37, 41) MY_ORANGE = (218, 124, 48) MY_GREEN = (62, 150, 81) MY_BLACK = (83, 81, 84) MY_GOLD = (148, 139, 61) def get_color(COLOR_TUPLE_255): return [x / 255 for x in COLOR_TUPLE_255] # fontsize=20 fontsize = 30 legend_size = 22 title_size = 30 font = {'size': fontsize} matplotlib.rc('font', **font) dir_path = os.path.dirname(os.path.realpath(__file__)) print("dir path: ", dir_path) GPU_MEM_SIZE = 16280 def read_columns(dataset, columns=5): file_name = dir_path + "/" + dataset + ".csv" with open(file_name) as csvfile: data = csv.reader(csvfile, delimiter=",", quotechar='|') cols = [] for column in range(columns): cols.append([]) for i, row in enumerate(data): if i > 0: # skip header for column in range(columns): try: cols[column].append(float(row[column])) except ValueError as ex: print("Exception: ", ex) return cols ylabel = "ylabel" title = "title" legend_pos = "center_pos" bbox = "bbox" file_name = "file_name" column_nr = "column_nr" labels = "labels" legend_cols = "legend_cols" xlim = "xlim" ylim = "ylim" carlini_cifar10 = {ylabel: "Accuracy (%)", file_name: "distortionCarliniCifar", title: "C&W L$_2$ CIFAR-10", legend_pos: "upper right", # bbox: (0.0, 0.0), column_nr: 12, legend_cols: 2, labels: ['FC', 'CD', 'Unif', 'Gauss', 'Laplace', 'SVD'], xlim: (0, 12), ylim: (0, 100)} carlini_imagenet = {ylabel: "Accuracy (%)", file_name: "distortionCarliniImageNet", title: "C&W L$_2$ ImageNet", # legend_pos: "lower left", legend_pos: "upper right", # bbox: (0.0, 0.0), column_nr: 12, legend_cols: 2, labels: ['FC', 'CD', 'Unif', 'Gauss', 'Laplace', 'SVD'], xlim: (0, 100), ylim: (0, 100)} pgd_cifar10 = {ylabel: "Accuracy (%)", file_name: "distortionPGDCifar", title: "PGD L$_{\infty}$ CIFAR-10", # legend_pos: "lower left", legend_pos: "upper right", # bbox: (0.0, 0.0), column_nr: 12, legend_cols: 2, labels: ['FC', 'CD', 'Unif', 'Gauss', 'Laplace', 'SVD'], xlim: (0, 12), ylim: (0, 100)} random_pgd_cifar10 = {ylabel: "Accuracy (%)", file_name: "distortionRandomPGDCifar", title: "PGD (random start) L$_{\infty}$ CIFAR-10", # legend_pos: "lower left", legend_pos: "upper right", # bbox: (0.0, 0.0), column_nr: 12, legend_cols: 2, labels: ['FC', 'CD', 'Unif', 'Gauss', 'Laplace', 'SVD'], xlim: (0, 12), ylim: (0, 100)} pgd_imagenet = {ylabel: "Accuracy (%)", file_name: "distortionPGDImageNet", title: "PGD L$_{\infty}$ ImageNet", # legend_pos: "lower left", legend_pos: "upper right", # bbox: (0.0, 0.0), column_nr: 12, legend_cols: 2, labels: ['FC', 'CD', 'Unif', 'Gauss', 'Laplace', 'SVD'], xlim: (0, 100), ylim: (0, 100)} fgsm_imagenet = {ylabel: "Accuracy (%)", file_name: "distortionFGSMImageNet2", title: "FGSM L$_{\infty}$ ImageNet", # legend_pos: "lower left", legend_pos: "upper right", # bbox: (0.0, 0.0), column_nr: 12, legend_cols: 2, labels: ['FC', 'CD', 'Unif', 'Gauss', 'Laplace', 'SVD'], xlim: (0, 100), ylim: (0, 100)} colors = [get_color(color) for color in [MY_GREEN, MY_BLUE, MY_ORANGE, MY_RED, MY_BLACK, MY_GOLD]] markers = ["+", "o", "v", "s", "D", "^", "+"] linestyles = [":", "-", "--", ":", "-", "--", ":", "-"] datasets = [carlini_cifar10, carlini_imagenet, # pgd_cifar10, random_pgd_cifar10, pgd_imagenet, fgsm_imagenet] # width = 12 # height = 5 # lw = 3 fig_size = 10 width = 10 height = 10 line_width = 4 layout = "horizontal" # "horizontal" or "vertical" fig = plt.figure(figsize=(len(datasets) * width, height)) for j, dataset in enumerate(datasets): if layout == "vertical": plt.subplot(len(datasets), 1, j + 1) else: plt.subplot(1, len(datasets), j + 1) print("dataset: ", dataset) columns = dataset[column_nr] cols = read_columns(dataset[file_name], columns=columns) print("col 0: ", cols[0]) print("col 1: ", cols[1]) for col in range(0, columns, 2): if col == 8: # skip Laplace continue i = col // 2 plt.plot(cols[col], cols[col + 1], label=f"{dataset[labels][i]}", lw=line_width, color=colors[i], linestyle=linestyles[i]) plt.grid() plt.legend(loc=dataset[legend_pos], ncol=dataset[legend_cols], frameon=False, prop={'size': legend_size}, # bbox_to_anchor=dataset[bbox] ) plt.xlabel('L2 distortion') plt.title(dataset[title], fontsize=title_size) if j == 0: plt.ylabel(dataset[ylabel]) plt.ylim(dataset[ylim]) plt.xlim(dataset[xlim]) # plt.gcf().autofmt_xdate() # plt.xticks(rotation=0) # plt.interactive(False) # plt.imshow() plt.subplots_adjust(hspace=0.3) format = "pdf" # "pdf" or "png" destination = dir_path + "/" + "distortionCarliniPgdFgsm2." + format print("destination: ", destination) fig.savefig(destination, bbox_inches='tight', # transparent=True ) # plt.show(block=False) # plt.interactive(False) plt.close()
[ "adam.dziedzi@gmail.com" ]
adam.dziedzi@gmail.com
72e7f4e7fd84a20bfa099d9c9aae57b6505f71a2
e9ef3cd143478660d098668a10e67544a42b5878
/Lib/corpuscrawler/crawl_fit.py
889a9f9b40d3cc5385c37d05a86cd79592d13c05
[ "Apache-2.0" ]
permissive
google/corpuscrawler
a5c790c19b26e6397b768ce26cf12bbcb641eb90
10adaecf4ed5a7d0557c8e692c186023746eb001
refs/heads/master
2023-08-26T04:15:59.036883
2022-04-20T08:18:11
2022-04-20T08:18:11
102,909,145
119
40
NOASSERTION
2022-04-20T08:18:12
2017-09-08T22:21:03
Python
UTF-8
Python
false
false
802
py
# Copyright 2017 Google Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import absolute_import, print_function, unicode_literals import re def crawl(crawler): out = crawler.get_output(language='fit') crawler.crawl_sverigesradio(out, program_id=1017)
[ "sascha@brawer.ch" ]
sascha@brawer.ch
a3206f4e1b6da273c4478040585ac8b75ed083b0
df2cbe914f463ad050d7ed26194424afbe3a0a52
/addons/website_event_track_quiz/controllers/community.py
7748a2dc1db19bac7ade948bd9df677a27aada67
[ "Apache-2.0" ]
permissive
SHIVJITH/Odoo_Machine_Test
019ed339e995be980606a2d87a63312ddc18e706
310497a9872db7844b521e6dab5f7a9f61d365a4
refs/heads/main
2023-07-16T16:23:14.300656
2021-08-29T11:48:36
2021-08-29T11:48:36
401,010,175
0
0
Apache-2.0
2021-08-29T10:13:58
2021-08-29T10:13:58
null
UTF-8
Python
false
false
4,477
py
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import math from odoo import http from odoo.addons.http_routing.models.ir_http import slug from odoo.addons.website_event.controllers.community import EventCommunityController from odoo.http import request class WebsiteEventTrackQuizCommunityController(EventCommunityController): _visitors_per_page = 30 _pager_max_pages = 5 @http.route(['/event/<model("event.event"):event>/community/leaderboard/results', '/event/<model("event.event"):event>/community/leaderboard/results/page/<int:page>'], type='http', auth="public", website=True, sitemap=False) def leaderboard(self, event, page=1, lang=None, **kwargs): values = self._get_community_leaderboard_render_values(event, kwargs.get('search'), page) return request.render('website_event_track_quiz.event_leaderboard', values) @http.route('/event/<model("event.event"):event>/community/leaderboard', type='http', auth="public", website=True, sitemap=False) def community_leaderboard(self, event, **kwargs): values = self._get_community_leaderboard_render_values(event, None, None) return request.render('website_event_track_quiz.event_leaderboard', values) @http.route('/event/<model("event.event"):event>/community', type='http', auth="public", website=True, sitemap=False) def community(self, event, **kwargs): values = self._get_community_leaderboard_render_values(event, None, None) return request.render('website_event_track_quiz.event_leaderboard', values) def _get_community_leaderboard_render_values(self, event, search_term, page): values = self._get_leaderboard(event, search_term) values.update({'event': event, 'search': search_term}) user_count = len(values['visitors']) if user_count: page_count = math.ceil(user_count / self._visitors_per_page) url = '/event/%s/community/leaderboard/results' % (slug(event)) if values.get('current_visitor_position') and not page: values['scroll_to_position'] = True page = math.ceil(values['current_visitor_position'] / self._visitors_per_page) elif not page: page = 1 pager = request.website.pager(url=url, total=user_count, page=page, step=self._visitors_per_page, scope=page_count if page_count < self._pager_max_pages else self._pager_max_pages) values['visitors'] = values['visitors'][(page - 1) * self._visitors_per_page: (page) * self._visitors_per_page] else: pager = {'page_count': 0} values.update({'pager': pager}) return values def _get_leaderboard(self, event, searched_name=None): current_visitor = request.env['website.visitor']._get_visitor_from_request(force_create=False) track_visitor_data = request.env['event.track.visitor'].sudo().read_group( [('track_id', 'in', event.track_ids.ids), ('visitor_id', '!=', False), ('quiz_points', '>', 0)], ['id', 'visitor_id', 'points:sum(quiz_points)'], ['visitor_id'], orderby="points DESC") data_map = {datum['visitor_id'][0]: datum['points'] for datum in track_visitor_data if datum.get('visitor_id')} leaderboard = [] position = 1 current_visitor_position = False visitors_by_id = { visitor.id: visitor for visitor in request.env['website.visitor'].sudo().browse(data_map.keys()) } for visitor_id, points in data_map.items(): visitor = visitors_by_id.get(visitor_id) if not visitor: continue if (searched_name and searched_name.lower() in visitor.display_name.lower()) or not searched_name: leaderboard.append({'visitor': visitor, 'points': points, 'position': position}) if current_visitor and current_visitor == visitor: current_visitor_position = position position = position + 1 return { 'top3_visitors': leaderboard[:3], 'visitors': leaderboard, 'current_visitor_position': current_visitor_position, 'current_visitor': current_visitor, 'searched_name': searched_name }
[ "36736117+SHIVJITH@users.noreply.github.com" ]
36736117+SHIVJITH@users.noreply.github.com
23a549649db32408d622701f911b724d3231db54
1d60c5a7b8ce6277bff514e376f79848f706344c
/Data Scientist with Python - Career Track /15. Interactive Data Visualization with Bokeh/02. Layouts, Interactions, and Annotations/03. Nesting rows and columns of plots.py
4a34c4b1509d2e81c41dfc8db282991c297c849f
[]
no_license
DidiMilikina/DataCamp
338c6e6d3b4f5b6c541c1aba155a36e9ee24949d
3bf2cf3c1430190a7f8e54efda7d50a5fd66f244
refs/heads/master
2020-12-15T13:16:54.178967
2020-05-06T17:30:54
2020-05-06T17:30:54
235,113,616
4
3
null
null
null
null
UTF-8
Python
false
false
952
py
''' Nesting rows and columns of plots You can create nested layouts of plots by combining row and column layouts. In this exercise, you'll make a 3-plot layout in two rows using the auto-mpg data set. Three plots have been created for you of average mpg vs year (avg_mpg), mpg vs hp (mpg_hp), and mpg vs weight (mpg_weight). Your job is to use the row() and column() functions to make a two-row layout where the first row will have only the average mpg vs year plot and the second row will have mpg vs hp and mpg vs weight plots as columns. By using the sizing_mode argument, you can scale the widths to fill the whole figure. Instructions 100 XP Import row and column from bokeh.layouts. Create a row layout called row2 with the figures mpg_hp and mpg_weight in a list and set sizing_mode='scale_width'. Create a column layout called layout with the figure avg_mpg and the row layout row2 in a list and set sizing_mode='scale_width'. ''' SOLUTION
[ "didimilikina8@gmail.com" ]
didimilikina8@gmail.com
29c223f3be9ebfbf847f6f23addf34933a47d3bc
0ef8d98726078a75bc9e4d7001ca3eb4d0dd43f4
/tests/queries/select/where/expressive_tests.py
3e8f8a6776f5a5bc95892070529b102fc1e6346f
[]
no_license
fuzeman/byte
b32a5ff02cb5aa37aa9f86b0ec2fa1814fa8838e
cfd552583a20afded620058e18b950fe344b0245
refs/heads/master
2021-01-20T11:56:07.164270
2017-05-19T05:47:48
2017-05-19T05:47:48
82,638,124
0
0
null
null
null
null
UTF-8
Python
false
false
2,501
py
from __future__ import absolute_import, division, print_function from byte.collection import Collection from byte.core.models.expressions.proxy import ProxyEqual, ProxyGreaterThanOrEqual, ProxyLessThan, ProxyNotEqual from tests.base.models.dynamic.user import User from hamcrest import * users = Collection(User) def test_simple(): """Test select() query can be created with expressions.""" query = users.select().where( User['id'] < 35, User['username'] != 'alpha' ) assert_that(query, has_property('state', has_entries({ # where() 'where': all_of( has_length(2), has_items( # User['id'] < 35 all_of(instance_of(ProxyLessThan), has_properties({ 'lhs': User['id'], 'rhs': 35 })), # User['username'] != 'alpha' all_of(instance_of(ProxyNotEqual), has_properties({ 'lhs': User['username'], 'rhs': 'alpha' })) ) ) }))) def test_chain(): """Test select() query can be created with chained expressions.""" query = users.select().where( User['id'] >= 12 ).where( User['username'] != 'beta' ) assert_that(query, has_property('state', has_entries({ # where() 'where': all_of( has_length(2), has_items( # User['id'] >= 12 all_of(instance_of(ProxyGreaterThanOrEqual), has_properties({ 'lhs': User['id'], 'rhs': 12 })), # User['username'] != 'beta' all_of(instance_of(ProxyNotEqual), has_properties({ 'lhs': User['username'], 'rhs': 'beta' })) ) ) }))) def test_match(): """Test select() query can be created with property matching expressions.""" query = users.select().where( User['username'] == User['password'] ) assert_that(query, has_property('state', has_entries({ # where() 'where': all_of( has_length(1), has_items( # User['username'] == User['password'] all_of(instance_of(ProxyEqual), has_properties({ 'lhs': User['username'], 'rhs': User['password'] })) ) ) })))
[ "me@dgardiner.net" ]
me@dgardiner.net
cdb6db06ca510e1725ee054c97aacb151761f4e3
c065ff2a6a377aea2303b7b8482558049958a7ec
/spam/1562226369/tactile.tac
10ddf48fe2a06c4f6386cf59674fe64707965772
[]
no_license
waedbara/vision2tactile
7bc9861eecb4247fd254ea58dc508ed18a03b1af
edbc9dfee61b4a4b1f0caebb2f16faef090dff32
refs/heads/master
2022-04-02T20:43:16.621687
2019-12-11T08:07:39
2019-12-11T08:07:39
null
0
0
null
null
null
null
UTF-8
Python
false
false
290
tac
,3620,3726,3686,3728,3416,3675,3764,3588,3589,3537,3511,3678,3384,3398,3293,3293,3452,3489,3004,2809,3696,3658,3585,3218,2013,2007,1854,2299,2611,3211,3418,2241,3186,3327,2730,3426,3364,3299,3049,3253,3472,3232,3331,3345,3255,3343,3312,2862,2718,3456,3442,3467,3351,2045,2046,2880,2034,2477
[ "brayan.inf@gmail.com" ]
brayan.inf@gmail.com
f606251b65cb39a42ee14338420816cf79dc988b
67ebe31bd561bad451f4cc1274f89b06c3c4f1e5
/ldLib/GUI/Button.py
3ed66d1ee9e7f4b842bc93039004f422536b86dd
[]
no_license
Bobsleigh/LDEngine
9c7e60a887c1c118fa5348aaf2891ea800bb26b6
110aaf53f7843e9f18579f156b38f57c0fcc0ba6
refs/heads/master
2020-12-24T10:23:58.963627
2020-08-25T20:42:33
2020-08-25T20:42:33
73,085,051
1
0
null
null
null
null
UTF-8
Python
false
false
1,975
py
import pygame from app.settings import * class Button(pygame.sprite.Sprite): def __init__(self, pos, size, text, callback): super().__init__() self.method = callback self.fontSize = 24 self.buttonFont = pygame.font.SysFont(FONT_NAME, self.fontSize) self.width = size[0] self.height = size[1] self.image = pygame.Surface((self.width, self.height)) self.rect = self.image.get_rect() self.rect.x = pos[0] self.rect.y = pos[1] self.borderButton = 5 self.interior = pygame.Rect(self.borderButton, self.borderButton, self.width - 2 * self.borderButton, self.height - 2 * self.borderButton) self.text = text self.textPos = [0, 0] self.isSelected = False # Color self.color1 = COLOR_MENU_1 self.color2 = COLOR_MENU_2 def doNothing(self): print('You did nothing') def update(self): if self.isSelected: self.color1 = COLOR_MENU_SELECT_1 self.color2 = COLOR_MENU_SELECT_2 self.printedText = self.buttonFont.render(self.text, True, COLOR_MENU_FONTS_SELECT) else: self.color1 = COLOR_MENU_1 self.color2 = COLOR_MENU_2 self.printedText = self.buttonFont.render(self.text, True, COLOR_MENU_FONTS) self.setUpgradeSpec() self.image.fill(self.color2) self.image.fill(self.color1, self.interior) self.image.blit(self.printedText, self.textPos) def setUpgradeSpec(self): self.textPos = [(self.image.get_width() - self.printedText.get_width()) / 2, (self.image.get_height() - self.printedText.get_height()) / 2] def notify(self, event): if event.type == pygame.MOUSEBUTTONDOWN: if event.button == MOUSE_LEFT: if self.rect.collidepoint(event.pos): self.method()
[ "philippe.gendreau.2@ulaval.ca" ]
philippe.gendreau.2@ulaval.ca
60f43fe61e1fa6fc5236f134ab1fd87d002bcfbd
0529196c4d0f8ac25afa8d657413d4fc1e6dd241
/runnie0427/05054/5054.py2.py
62c2c79226369578246b4836b928612466f4dc1d
[]
no_license
riyuna/boj
af9e1054737816ec64cbef5df4927c749808d04e
06420dd38d4ac8e7faa9e26172b30c9a3d4e7f91
refs/heads/master
2023-03-17T17:47:37.198570
2021-03-09T06:11:41
2021-03-09T06:11:41
345,656,935
0
0
null
null
null
null
UTF-8
Python
false
false
17,370
py
<!DOCTYPE html> <html lang="ko"> <head> <title>Baekjoon Online Judge</title><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta charset="utf-8"><meta name="author" content="스타트링크 (Startlink)"><meta name="keywords" content="ACM-ICPC, ICPC, 프로그래밍, 온라인 저지, 정보올림피아드, 코딩, 알고리즘, 대회, 올림피아드, 자료구조"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta property="og:type" content="website"><meta property="og:image" content="http://onlinejudgeimages.s3-ap-northeast-1.amazonaws.com/images/boj-og-1200.png"><meta property="og:site_name" content="Baekjoon Online Judge"><meta name="format-detection" content = "telephone=no"><meta name="msapplication-config" content="none"><link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png"><link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png"><link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png"><link rel="manifest" href="/site.webmanifest"><link rel="mask-icon" href="/safari-pinned-tab.svg" color="#0076c0"><meta name="msapplication-TileColor" content="#00aba9"><meta name="theme-color" content="#ffffff"><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.2.0/css/bootstrap.min.css"><link rel="stylesheet" href="https://ddo7jzca0m2vt.cloudfront.net/unify/css/style.css?version=20210107"><link href="https://fonts.googleapis.com/css?family=Noto+Sans+KR:400,700|Open+Sans:400,400i,700,700i|Source+Code+Pro&amp;subset=korean" rel="stylesheet"><link rel="stylesheet" href="https://ddo7jzca0m2vt.cloudfront.net/css/connect.css?version=20210107"><link rel="stylesheet" href="https://ddo7jzca0m2vt.cloudfront.net/css/result.css?version=20210107"><link rel="stylesheet" href="https://ddo7jzca0m2vt.cloudfront.net/unify/css/custom.css?version=20210107"><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.6.3/css/font-awesome.css"><link rel="stylesheet" href="https://ddo7jzca0m2vt.cloudfront.net/unify/css/theme-colors/blue.css?version=20210107"><link rel="stylesheet" href="https://ddo7jzca0m2vt.cloudfront.net/css/pace.css"> <script async src="https://www.googletagmanager.com/gtag/js?id=UA-10874097-3"></script> <script> window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'UA-10874097-3'); </script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/noty/3.1.4/noty.min.css" /><meta name="username" content=""> <link rel="stylesheet" href="https://ddo7jzca0m2vt.cloudfront.net/unify/css/pages/page_404_error.css"> </head> <body> <div class="wrapper"> <div class="header no-print"><div class="topbar"><div class="container"><ul class="loginbar pull-right"><li><a href = "/register">회원가입</a></li><li class="topbar-devider"></li><li><a href = "/login?next=%2Fsource%2Fdownload%2F5646021">로그인</a></li></ul></div></div><div class="navbar navbar-default mega-menu" role="navigation"><div class="container"><div class="navbar-header"><button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-responsive-collapse"><span class="sr-only">Toggle navigation</span><span class="fa fa-bars"></span></button><a class="navbar-brand" href="/"><img id="logo-header" src="https://d2gd6pc034wcta.cloudfront.net/images/logo@2x.png" alt="Logo" data-retina></a></div><div class="collapse navbar-collapse navbar-responsive-collapse"><ul class="nav navbar-nav"><li class="dropdown mega-menu-fullwidth "><a href="javascript:void(0);" class="dropdown-toggle" data-toggle="dropdown">문제</a><ul class="dropdown-menu"><li><div class="mega-menu-content"><div class="container"><div class="row equal-height"><div class="col-md-3 equal-height-in"><ul class="list-unstyled equal-height-list"><li><h3>문제</h3></li><li><a href = "/problemset">전체 문제</a></li><li><a href = "/category">문제 출처</a></li><li><a href = "/step">단계별로 풀어보기</a></li><li><a href = "/problem/tags">알고리즘 분류</a></li><li><a href = "/problem/added">새로 추가된 문제</a></li><li><a href = "/problem/added/1">새로 추가된 영어 문제</a></li><li><a href = "/problem/ranking">문제 순위</a></li></ul></div><div class="col-md-3 equal-height-in"><ul class="list-unstyled equal-height-list"><li><h3>문제</h3></li><li><a href="/problem/only">푼 사람이 한 명인 문제</a></li><li><a href="/problem/nobody">아무도 못 푼 문제</a></li><li><a href="/problem/recent/submit">최근 제출된 문제</a></li><li><a href="/problem/recent/accepted">최근 풀린 문제</a></li><li><a href="/problem/random">랜덤</a></li></ul></div><div class="col-md-3 equal-height-in"><ul class="list-unstyled equal-height-list"><li><h3>출처</h3></li><li><a href = "/category/1">ICPC</a></li><li><a href = "/category/2">Olympiad</a></li><li><a href = "/category/55">한국정보올림피아드</a></li><li><a href = "/category/57">한국정보올림피아드시․도지역본선</a></li><li><a href = "/category/318">전국 대학생 프로그래밍 대회 동아리 연합</a></li><li><a href = "/category/5">대학교 대회</a></li><li><a href = "/category/428">카카오 코드 페스티벌</a></li><li><a href = "/category/215">Coder's High</a></li></ul></div><div class="col-md-3 equal-height-in"><ul class="list-unstyled equal-height-list"><li><h3>ICPC</h3></li><li><a href = "/category/7">Regionals</a></li><li><a href = "/category/4">World Finals</a></li><li><a href = "/category/211">Korea Regional</a></li><li><a href = "/category/34">Africa and the Middle East Regionals</a></li><li><a href = "/category/10">Europe Regionals</a></li><li><a href = "/category/103">Latin America Regionals</a></li><li><a href = "/category/8">North America Regionals</a></li><li><a href = "/category/92">South Pacific Regionals</a></li></ul></div></div></div></div></li></ul></li><li><a href = "/workbook/top">문제집</a></li><li><a href = "/contest/official/list">대회<span class='badge badge-red rounded-2x'>2</span></a></li><li><a href = "/status">채점 현황</a></li><li><a href = "/ranklist">랭킹</a></li><li><a href = "/board/list/all">게시판</a></li><li><a href = "/group/list/all">그룹</a></li><li><a href = "/blog/list">블로그</a></li><li><a href = "/lectures">강의</a></li><li><a href = "/search"><i class="fa fa-search search-btn"></i></a></li></ul></div></div></div></div><form action="/logout" method="post" id="logout_form"><input type='hidden' value='%2Fsource%2Fdownload%2F5646021' name="next"></form> <div class="container content"> <div class="col-md-8 col-md-offset-2"> <div class="error-v1"> <span class="error-v1-title">404</span> <span>Not found</span> <div class="margin-bottom-20"></div> </div> <div class="text-center"> <span style="font-size:18px;">강의 슬라이드의 첨부 소스 코드가 404 에러가 뜨는 경우에는 링크를 복사/붙여넣기 해주세요.</span> </div> <div class="margin-bottom-40"></div> </div> </div> <div class="footer-v3 no-print"><div class="footer"><div class="container"><div class="row"><div class="col-sm-3 md-margin-bottom-40"><div class="thumb-headline"><h2>Baekjoon Online Judge</h2></div><ul class="list-unstyled simple-list margin-bottom-10"><li><a href="/about">소개</a></li><li><a href="/news">뉴스</a></li><li><a href="/live">생중계</a></li><li><a href="/poll">설문조사</a></li><li><a href="/blog">블로그</a></li><li><a href="/calendar">캘린더</a></li><li><a href="/donate">기부하기</a></li><li><a href="https://github.com/Startlink/BOJ-Feature-Request">기능 추가 요청</a></li><li><a href="https://github.com/Startlink/BOJ-spj">스페셜 저지 제작</a></li><li><a href="/labs">실험실</a></li></ul><div class="thumb-headline"><h2>채점 현황</h2></div><ul class="list-unstyled simple-list"><li><a href="/status">채점 현황</a></li></ul></div><div class="col-sm-3 md-margin-bottom-40"><div class="thumb-headline"><h2>문제</h2></div><ul class="list-unstyled simple-list margin-bottom-10"><li><a href="/problemset">문제</a></li><li><a href="/step">단계별로 풀어보기</a></li><li><a href="/problem/tags">알고리즘 분류</a></li><li><a href="/problem/added">새로 추가된 문제</a></li><li><a href="/problem/added/1">새로 추가된 영어 문제</a></li><li><a href="/problem/ranking">문제 순위</a></li><li><a href="/problem/recent/submit">최근 제출된 문제</a></li><li><a href="/problem/recent/accepted">최근 풀린 문제</a></li><li><a href="/change">재채점 및 문제 수정</a></li></ul><div class="thumb-headline"><h2>유저 대회 / 고등학교 대회</h2></div><ul class="list-inline simple-list margin-bottom"><li><a href="/category/353">FunctionCup</a></li><li><a href="/category/319">kriiicon</a></li><li><a href="/category/420">구데기컵</a></li><li><a href="/category/358">꼬마컵</a></li><li><a href="/category/421">네블컵</a></li><li><a href="/category/413">소프트콘</a></li><li><a href="/category/416">웰노운컵</a></li><li><a href="/category/detail/1743">HYEA Cup</a></li><li><a href="/category/364">경기과학고등학교</a></li><li><a href="/category/417">대구과학고등학교</a></li><li><a href="/category/429">부산일과학고</a></li><li><a href="/category/435">서울과학고등학교</a></li><li><a href="/category/394">선린인터넷고등학교</a></li></ul></div><div class="col-sm-3 md-margin-bottom-40"><div class="thumb-headline"><h2>출처</h2></div><ul class="list-unstyled simple-list margin-bottom-10"><li><a href="/category/1">ICPC</a></li><li><a href="/category/211">ICPC Korea Regional</a></li><li><a href="/category/2">Olympiad</a></li><li><a href="/category/55">한국정보올림피아드</a></li><li><a href="/category/57">한국정보올림피아드시․도지역본선</a></li><li><a href="/category/318">전국 대학생 프로그래밍 대회 동아리 연합</a></li><li><a href="/category/5">대학교 대회</a></li><li><a href="/category/428">카카오 코드 페스티벌</a></li><li><a href="/category/215">Coder's High</a></li></ul><div class="thumb-headline"><h2>대학교 대회</h2></div><ul class="list-inline simple-list"><li><a href="/category/320">KAIST</a></li><li><a href="/category/426">POSTECH</a></li><li><a href="/category/341">고려대학교</a></li><li><a href="/category/434">광주과학기술원</a></li><li><a href="/category/361">국민대학교</a></li><li><a href="/category/83">서강대학교</a></li><li><a href="/category/354">서울대학교</a></li><li><a href="/category/352">숭실대학교</a></li><li><a href="/category/408">아주대학교</a></li><li><a href="/category/334">연세대학교</a></li><li><a href="/category/336">인하대학교</a></li><li><a href="/category/347">전북대학교</a></li><li><a href="/category/400">중앙대학교</a></li><li><a href="/category/402">충남대학교</a></li><li><a href="/category/418">한양대 ERICA</a></li><li><a href="/category/363">홍익대학교</a></li><li><a href="/category/409">경인지역 6개대학 연합 프로그래밍 경시대회</a></li></ul></div><div class="col-sm-3 md-margin-bottom-40"><div class="thumb-headline"><h2>도움말</h2></div><ul class="list-unstyled simple-list margin-bottom-10"><li><a href="/help/judge">채점 도움말 및 채점 환경</a></li><li><a href="/help/rejudge">재채점 안내</a></li><li><a href="/help/rte">런타임 에러 도움말</a></li><li><a href="/help/problem">문제 스타일 안내</a></li><li><a href="/help/language">컴파일 또는 실행 옵션, 컴파일러 버전, 언어 도움말</a></li><li><a href="/help/workbook">문제집 도움말</a></li><li><a href="/help/contest">대회 개최 안내</a></li><li><a href="/help/problem-add">문제 출제 안내</a></li><li><a href="/help/rule">이용 규칙</a></li><li><a href="/help/stat">통계 도움말</a></li><li><a href="/help/question">질문 도움말</a></li><li><a href="/help/faq">자주묻는 질문</a></li><li><a href="/help/lecture">강의 안내</a></li><li><a href="/help/short">짧은 주소 안내</a></li><li><a href="/help/ad">광고 안내</a></li></ul></div></div></div><div class="copyright"><div class="container"><div class="row"><div class="col-md-9 col-sm-12"><p>&copy; 2021 All Rights Reserved. <a href="https://startlink.io">주식회사 스타트링크</a>&nbsp;|&nbsp;<a href="/terms">서비스 약관</a>&nbsp;|&nbsp;<a href="/privacy">개인정보 보호</a>&nbsp;|&nbsp;<a href="/terms/payment">결제 이용 약관</a>&nbsp;|&nbsp;<a href="https://boj.startlink.help/hc/ko">도움말</a>&nbsp;|&nbsp;<a href="http://startl.ink/2pmlJaY">광고 문의</a>&nbsp;|&nbsp;<a href="https://github.com/Startlink/update-note/blob/master/boj.md">업데이트 노트</a>&nbsp;|&nbsp;<a href="https://github.com/Startlink/update-note/blob/master/boj-issues.md">이슈</a>&nbsp;|&nbsp;<a href="https://github.com/Startlink/update-note/blob/master/boj-todo.md">TODO</a></p></div><div class="col-md-3 col-sm-12"><ul class="social-icons pull-right"><li><a href="https://www.facebook.com/onlinejudge" data-original-title="Facebook" class="rounded-x social_facebook"></a></li><li><a href="https://startlink.blog" data-original-title="Wordpress" class="rounded-x social_wordpress"></a></li></ul></div></div><div class="row"><div class="col-sm-12"><a href="https://startlink.io" class="hidden-xs"><img src="https://d2gd6pc034wcta.cloudfront.net/logo/startlink-logo-white-only.png" class="pull-right startlink-logo"></a><ul class="list-unstyled simple-list"><li>사업자 등록 번호: 541-88-00682</li><li>대표자명: 최백준</li><li>주소: 서울시 서초구 서초대로74길 29 서초파라곤 412호</li><li>전화번호: 02-521-0487 (이메일로 연락 주세요)</li><li>이메일: <a href="mailto:contacts@startlink.io">contacts@startlink.io</a></li><li>통신판매신고번호: 제 2017-서울서초-2193 호</li></ul></div><div class="col-xs-9"><p id="no-acm-icpc"></p></div><div class="col-xs-3"></div></div></div></div></div> </div> <div id="fb-root"></div><script> window.fbAsyncInit = function() { FB.init({ appId : '322026491226049', cookie : true, xfbml : true, version : 'v2.8' }); }; (function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/ko_KR/sdk.js"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk')); </script> <script> !function(f,b,e,v,n,t,s){ if(f.fbq)return;n=f.fbq=function(){ n.callMethod? n.callMethod.apply(n,arguments):n.queue.push(arguments) };if(!f._fbq)f._fbq=n; n.push=n;n.loaded=!0;n.version='2.0';n.queue=[];t=b.createElement(e);t.async=!0; t.src=v;s=b.getElementsByTagName(e)[0];s.parentNode.insertBefore(t,s) }(window, document,'script','//connect.facebook.net/en_US/fbevents.js'); fbq('init', '1670563073163149'); fbq('track', 'PageView'); </script> <noscript><img height="1" width="1" style="display:none" src="https://www.facebook.com/tr?id=1670563073163149&ev=PageView&noscript=1"/></noscript><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-migrate/3.0.1/jquery-migrate.min.js"></script><script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.2.0/js/bootstrap.min.js"></script><script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.21.0/moment.min.js"></script><script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.21.0/locale/ko.js"></script><script type="text/javascript" src="https://ddo7jzca0m2vt.cloudfront.net/unify/js/app.min.js?version=20210107"></script><script type="text/javascript">jQuery(document).ready(function() {App.init(0);});</script><!--[if lt IE 9]><script src="https://ddo7jzca0m2vt.cloudfront.net/unify/plugins/respond.js"></script><script src="https://ddo7jzca0m2vt.cloudfront.net/unify/plugins/html5shiv.js"></script><script src="https://ddo7jzca0m2vt.cloudfront.net/unify/js/plugins/placeholder-IE-fixes.js"></script><![endif]--><script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pace/1.0.2/pace.min.js"></script><script src="https://js.pusher.com/4.2/pusher.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/noty/3.1.4/noty.min.js"></script> <script> window.MathJax = { tex: { inlineMath: [ ['$', '$'], ['\\(', '\\)'] ], displayMath: [ ['$$','$$'], ["\\[","\\]"] ], processEscapes: true, tags: "ams", autoload: { color: [], colorv2: ['color'] }, packages: { '[+]': ['noerrors'] } }, options: { ignoreHtmlClass: "no-mathjax|redactor-editor", processHtmlClass: 'mathjax', enableMenu: false }, chtml: { scale: 0.9 }, loader: { load: ['input/tex', 'output/chtml', '[tex]/noerrors'], } }; </script><script src="https://polyfill.io/v3/polyfill.min.js?features=es6"></script><script id="MathJax-script" async src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script> </body> </html>
[ "riyuna0427@gmail.com" ]
riyuna0427@gmail.com
b35a279c534a0599d23de680ac9e6fad6a6ead3c
b46f5825b809c0166622149fc5561c23750b379c
/AppImageBuilder/app_dir/bundlers/apt/package_lists.py
2a9ebdbd72908f76f446d8de376dd6127592ef65
[ "MIT" ]
permissive
gouchi/appimage-builder
22b85cb682f1b126515a6debd34874bd152a4211
40e9851c573179e066af116fb906e9cad8099b59
refs/heads/master
2022-09-28T09:46:11.783837
2020-06-07T19:44:48
2020-06-07T19:44:48
267,360,199
0
0
MIT
2020-05-27T15:42:25
2020-05-27T15:42:24
null
UTF-8
Python
false
false
1,936
py
# Copyright 2020 Alexis Lopez Zubieta # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation the # rights to use, copy, modify, merge, publish, distribute, sublicense, and/or # sell copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. apt_core_packages = [ 'util-linux', 'coreutils', 'adduser', 'avahi-daemon', 'base-files', 'bind9-host', 'consolekit', 'dbus', 'debconf', 'dpkg', 'lsb-base', 'libcap2-bin', 'libinput-bin', 'multiarch-support', 'passwd', 'systemd', 'systemd-sysv', 'ucf', 'iso-codes', 'shared-mime-info', 'mount', 'xdg-user-dirs', 'sysvinit-utils', 'debianutils', 'init-system-helpers', 'libpam-runtime', 'libpam-modules-bin', ] apt_font_config_packages = [ 'libfontconfig*', 'fontconfig', 'fontconfig-config', 'libfreetype*', ] apt_xclient_packages = [ 'x11-common', 'libx11-*', 'libxcb1', 'libxcb-shape0', 'libxcb-shm0', 'libxcb-glx0', 'libxcb-xfixes0', 'libxcb-present0', 'libxcb-render0', 'libxcb-dri2-0', 'libxcb-dri3-0', ] apt_graphics_stack_packages = [ 'libglvnd*', 'libglx*', 'libgl1*', 'libdrm*', 'libegl1*', 'libegl1-*', 'libglapi*', 'libgles2*', 'libgbm*', 'mesa-*', ] apt_glibc_packages = ['libc6', 'zlib1g', 'libstdc++6'] # packages required by the runtime generators apt_proot_apprun_packages = ['proot', 'coreutils'] apt_classic_apprun_packages = ['coreutils'] apt_wrapper_apprun_packages = []
[ "contact@azubieta.net" ]
contact@azubieta.net
40fa34f31d61c6e5ac53b3bd7e6e3f4adeb6fd93
79661312d54643ce9dcfe3474058f514b01bfbe6
/model/main_window_8_btc.py
7259dfb9dd2b86c0e24dfdde1dc30162d7187831
[]
no_license
davis-9fv/Project
5c4c8ac03f5bf9db28704e63de9b004f56a52f10
f2bd22b3ac440b91d1d1defc8da9e2ba2e67265e
refs/heads/master
2020-03-20T22:24:07.244521
2019-02-28T16:58:04
2019-02-28T16:58:04
137,796,517
0
0
null
null
null
null
UTF-8
Python
false
false
4,750
py
from sklearn.utils import shuffle import datetime from Util import algorithm from pandas import read_csv from sklearn.metrics import mean_squared_error from math import sqrt from Util import misc from Util import data_misc import numpy def compare(y_test, y_predicted): predictions = list() for i in range(len(y_test)): X = x_test[i] yhat = y_predicted[i] yhat = data_misc.invert_scale(scaler, X, yhat) #Stationary d = avg_values[split + window_size - 1:] yhat = data_misc.inverse_difference(d, yhat, len(y_test) + 1 - i) predictions.append(yhat) d = avg_values[split + window_size + 1:] #d = avg_values[split + window_size :] rmse = sqrt(mean_squared_error(d, predictions)) #rmse = sqrt(mean_squared_error(y_test, y_predicted)) return rmse, predictions seed = 5 numpy.random.seed(seed) time_start = datetime.datetime.now() result = list() shuffle_data = False write_file = False print('Start time: %s' % str(time_start.strftime('%Y-%m-%d %H:%M:%S'))) print('Shuffle: %i' % (shuffle_data)) path = 'C:/tmp/bitcoin/' #input_file = 'bitcoin_usd_11_10_2018.csv' input_file = 'bitcoin_usd_bitcoin_block_chain_trend_by_day.csv' window_size = 7 # 7 result = list() print('') print('') print('Window Size: %i' % (window_size)) # To pair with the other models, this model gets 1438 first rows. series = read_csv(path + input_file, header=0, sep=',', nrows=1438) series = series.iloc[::-1] date = series['Date'] avg = series['Avg'] date = date.iloc[window_size:] date = date.values avg_values = avg.values # Stationary Data diff_values = data_misc.difference(avg_values, 1) #diff_values= avg_values supervised = data_misc.timeseries_to_supervised(diff_values, window_size) # The first [Window size number] contains zeros which need to be cut. supervised = supervised.values[window_size:, :] if shuffle_data: supervised = shuffle(supervised, random_state=9) size_supervised = len(supervised) split = int(size_supervised * 0.80) train, test = supervised[0:split], supervised[split:] # transform the scale of the data scaler, train_scaled, test_scaled = data_misc.scale(train, test) x_train, y_train = train_scaled[:, 0:-1], train_scaled[:, -1] x_test, y_test = test_scaled[:, 0:-1], test_scaled[:, -1] print('Size size_supervised %i' % (size_supervised)) print('------- Test --------') # No Prediction y_hat_predicted_es = y_test rmse, y_hat_predicted = compare(y_test, y_hat_predicted_es) print('RMSE NoPredic %.3f' % (rmse)) # Dummy y_predicted_dummy_es = x_test[:, 0] rmse, y_predicted_dummy = compare(y_test, y_predicted_dummy_es) print('RMSE Dummy %.3f' % (rmse)) # ElasticNet y_predicted_en_es, y_future_en_es = algorithm.elastic_net(x_train, y_train, x_test, y_test, normalize=False) rmse, y_predicted_en = compare(y_test, y_predicted_en_es) print('RMSE Elastic %.3f' % (rmse)) # y_future_en = compare(y_test, y_future_en_es) # KNN5 y_predicted_knn5_es = algorithm.knn_regressor(x_train, y_train, x_test, 5) rmse, y_predicted_knn5 = compare(y_test, y_predicted_knn5_es) print('RMSE KNN(5) %.3f' % (rmse)) # KNN10 y_predicted_knn10_es = algorithm.knn_regressor(x_train, y_train, x_test, 10) rmse, y_predicted_knn10 = compare(y_test, y_predicted_knn10_es) print('RMSE KNN(10) %.3f' % (rmse)) # SGD y_predicted_sgd_es = algorithm.sgd_regressor(x_train, y_train, x_test) rmse, y_predicted_sgd = compare(y_test, y_predicted_sgd_es) print('RMSE SGD %.3f' % (rmse)) # Lasso y_predicted_la_sc = algorithm.lasso(x_train, y_train, x_test, normalize=False) rmse, y_predicted_la = compare(y_test, y_predicted_la_sc) print('RMSE Lasso %.3f' % (rmse)) # LSTM y_predicted_lstm = algorithm.lstm(x_train, y_train, x_test, batch_size=1, nb_epoch=60, neurons=14) rmse, y_predicted_lstm = compare(y_test, y_predicted_lstm) print('RMSE LSTM %.3f' % (rmse)) titles = ['Y', 'ElasticNet', 'KNN5', 'KNN10', 'SGD', 'Lasso', 'LSTM'] data = [y_hat_predicted, y_predicted_en, y_predicted_knn5, y_predicted_knn10, y_predicted_sgd, y_predicted_la, y_predicted_lstm] # titles = ['Y', 'ElasticNet', 'ElasticNet Future', 'KNN5', 'KNN10', 'SGD'] # data = [y_test, y_predicted_en, y_future_en, y_predicted_knn5, y_predicted_knn10] # y_future_en = y_future_en[1] # data = [y_hat_predicted, y_predicted_en, y_future_en, y_predicted_knn5, y_predicted_knn10, y_predicted_sgd] date_test = date[split + 1:] print('Length date test:' + str(len(date_test))) print('Length data test:' + str(len(y_test))) misc.plot_lines_graph('Stationary - Normalization,Test Data ', date_test, titles, data) time_end = datetime.datetime.now() print('End time: %s' % str(time_end.strftime('%Y-%m-%d %H:%M:%S'))) print('Duration of the script: %s' % (str(time_end - time_start)))
[ "francisco.vinueza@alterbios.com" ]
francisco.vinueza@alterbios.com
f4cfce085f2bee40324b89a91182e3026dbc3fec
4fd84e0e1097d1153ed477a5e76b4972f14d273a
/myvirtualenv/lib/python3.7/site-packages/azure/servicefabric/models/cluster_health_report_expired_event.py
d09441c8e9559e4bdf055e5d5613c9698a8815f4
[ "MIT" ]
permissive
peterchun2000/TerpV-U
c045f4a68f025f1f34b89689e0265c3f6da8b084
6dc78819ae0262aeefdebd93a5e7b931b241f549
refs/heads/master
2022-12-10T09:31:00.250409
2019-09-15T15:54:40
2019-09-15T15:54:40
208,471,905
0
2
MIT
2022-12-08T06:09:33
2019-09-14T16:49:41
Python
UTF-8
Python
false
false
3,889
py
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- from .cluster_event import ClusterEvent class ClusterHealthReportExpiredEvent(ClusterEvent): """Cluster Health Report Expired event. All required parameters must be populated in order to send to Azure. :param event_instance_id: Required. The identifier for the FabricEvent instance. :type event_instance_id: str :param time_stamp: Required. The time event was logged. :type time_stamp: datetime :param has_correlated_events: Shows there is existing related events available. :type has_correlated_events: bool :param kind: Required. Constant filled by server. :type kind: str :param source_id: Required. Id of report source. :type source_id: str :param property: Required. Describes the property. :type property: str :param health_state: Required. Describes the property health state. :type health_state: str :param time_to_live_ms: Required. Time to live in milli-seconds. :type time_to_live_ms: long :param sequence_number: Required. Sequence number of report. :type sequence_number: long :param description: Required. Description of report. :type description: str :param remove_when_expired: Required. Indicates the removal when it expires. :type remove_when_expired: bool :param source_utc_timestamp: Required. Source time. :type source_utc_timestamp: datetime """ _validation = { 'event_instance_id': {'required': True}, 'time_stamp': {'required': True}, 'kind': {'required': True}, 'source_id': {'required': True}, 'property': {'required': True}, 'health_state': {'required': True}, 'time_to_live_ms': {'required': True}, 'sequence_number': {'required': True}, 'description': {'required': True}, 'remove_when_expired': {'required': True}, 'source_utc_timestamp': {'required': True}, } _attribute_map = { 'event_instance_id': {'key': 'EventInstanceId', 'type': 'str'}, 'time_stamp': {'key': 'TimeStamp', 'type': 'iso-8601'}, 'has_correlated_events': {'key': 'HasCorrelatedEvents', 'type': 'bool'}, 'kind': {'key': 'Kind', 'type': 'str'}, 'source_id': {'key': 'SourceId', 'type': 'str'}, 'property': {'key': 'Property', 'type': 'str'}, 'health_state': {'key': 'HealthState', 'type': 'str'}, 'time_to_live_ms': {'key': 'TimeToLiveMs', 'type': 'long'}, 'sequence_number': {'key': 'SequenceNumber', 'type': 'long'}, 'description': {'key': 'Description', 'type': 'str'}, 'remove_when_expired': {'key': 'RemoveWhenExpired', 'type': 'bool'}, 'source_utc_timestamp': {'key': 'SourceUtcTimestamp', 'type': 'iso-8601'}, } def __init__(self, **kwargs): super(ClusterHealthReportExpiredEvent, self).__init__(**kwargs) self.source_id = kwargs.get('source_id', None) self.property = kwargs.get('property', None) self.health_state = kwargs.get('health_state', None) self.time_to_live_ms = kwargs.get('time_to_live_ms', None) self.sequence_number = kwargs.get('sequence_number', None) self.description = kwargs.get('description', None) self.remove_when_expired = kwargs.get('remove_when_expired', None) self.source_utc_timestamp = kwargs.get('source_utc_timestamp', None) self.kind = 'ClusterHealthReportExpired'
[ "peterchun2000@gmail.com" ]
peterchun2000@gmail.com
a0c559f5b6acd5920910dc1440eafcf7205673ca
4461af13a595982b2940e45796c336d3ba7a14ac
/test/dygraph_to_static/test_word2vec.py
a17bf5e5f9e57fa8162caad888b2173d1b1ac837
[ "Apache-2.0" ]
permissive
Xreki/Paddle
6659c3c5ad727bc071a302e510c9da202d4f1bf4
5e1ee1064052ffe285bc18e3fdeb5667824f1c20
refs/heads/develop
2023-08-31T18:23:12.073614
2023-04-24T03:44:36
2023-04-24T03:44:36
66,993,970
2
0
Apache-2.0
2023-04-24T05:17:59
2016-08-31T02:08:14
Python
UTF-8
Python
false
false
9,658
py
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import math import random import unittest import numpy as np import paddle from paddle import fluid from paddle.jit.api import to_static from paddle.nn import Embedding def fake_text(): corpus = [] for i in range(100): line = "i love paddlepaddle" corpus.append(line) return corpus corpus = fake_text() def data_preprocess(corpus): new_corpus = [] for line in corpus: line = line.strip().lower() line = line.split(" ") new_corpus.append(line) return new_corpus corpus = data_preprocess(corpus) def build_dict(corpus, min_freq=3): word_freq_dict = {} for line in corpus: for word in line: if word not in word_freq_dict: word_freq_dict[word] = 0 word_freq_dict[word] += 1 word_freq_dict = sorted( word_freq_dict.items(), key=lambda x: x[1], reverse=True ) word2id_dict = {} word2id_freq = {} id2word_dict = {} word2id_freq[0] = 1.0 word2id_dict['[oov]'] = 0 id2word_dict[0] = '[oov]' for word, freq in word_freq_dict: if freq < min_freq: word2id_freq[0] += freq continue curr_id = len(word2id_dict) word2id_dict[word] = curr_id word2id_freq[word2id_dict[word]] = freq id2word_dict[curr_id] = word return word2id_freq, word2id_dict, id2word_dict word2id_freq, word2id_dict, id2word_dict = build_dict(corpus) vocab_size = len(word2id_freq) print("there are totoally %d different words in the corpus" % vocab_size) for _, (word, word_id) in zip(range(50), word2id_dict.items()): print( "word %s, its id %d, its word freq %d" % (word, word_id, word2id_freq[word_id]) ) def convert_corpus_to_id(corpus, word2id_dict): new_corpus = [] for line in corpus: new_line = [ word2id_dict[word] if word in word2id_dict else word2id_dict['[oov]'] for word in line ] new_corpus.append(new_line) return new_corpus corpus = convert_corpus_to_id(corpus, word2id_dict) def subsampling(corpus, word2id_freq): def keep(word_id): return random.uniform(0, 1) < math.sqrt( 1e-4 / word2id_freq[word_id] * len(corpus) ) new_corpus = [] for line in corpus: new_line = [word for word in line if keep(word)] new_corpus.append(line) return new_corpus corpus = subsampling(corpus, word2id_freq) def build_data( corpus, word2id_dict, word2id_freq, max_window_size=3, negative_sample_num=10, ): dataset = [] for line in corpus: for center_word_idx in range(len(line)): window_size = random.randint(1, max_window_size) center_word = line[center_word_idx] positive_word_range = ( max(0, center_word_idx - window_size), min(len(line) - 1, center_word_idx + window_size), ) positive_word_candidates = [ line[idx] for idx in range( positive_word_range[0], positive_word_range[1] + 1 ) if idx != center_word_idx and line[idx] != line[center_word_idx] ] if not positive_word_candidates: continue for positive_word in positive_word_candidates: dataset.append((center_word, positive_word, 1)) i = 0 while i < negative_sample_num: negative_word_candidate = random.randint(0, vocab_size - 1) if negative_word_candidate not in positive_word_candidates: dataset.append((center_word, negative_word_candidate, 0)) i += 1 return dataset dataset = build_data(corpus, word2id_dict, word2id_freq) for _, (center_word, target_word, label) in zip(range(50), dataset): print( "center_word %s, target %s, label %d" % (id2word_dict[center_word], id2word_dict[target_word], label) ) def build_batch(dataset, batch_size, epoch_num): center_word_batch = [] target_word_batch = [] label_batch = [] eval_word_batch = [] for epoch in range(epoch_num): for center_word, target_word, label in dataset: center_word_batch.append([center_word]) target_word_batch.append([target_word]) label_batch.append([label]) if len(eval_word_batch) < 5: eval_word_batch.append([random.randint(0, 99)]) elif len(eval_word_batch) < 10: eval_word_batch.append([random.randint(0, vocab_size - 1)]) if len(center_word_batch) == batch_size: yield np.array(center_word_batch).astype("int64"), np.array( target_word_batch ).astype("int64"), np.array(label_batch).astype( "float32" ), np.array( eval_word_batch ).astype( "int64" ) center_word_batch = [] target_word_batch = [] label_batch = [] eval_word_batch = [] if len(center_word_batch) > 0: yield np.array(center_word_batch).astype("int64"), np.array( target_word_batch ).astype("int64"), np.array(label_batch).astype("float32"), np.array( eval_word_batch ).astype( "int64" ) class SkipGram(paddle.nn.Layer): def __init__(self, name_scope, vocab_size, embedding_size, init_scale=0.1): super().__init__(name_scope) self.vocab_size = vocab_size self.embedding_size = embedding_size self.embedding = Embedding( self.vocab_size, self.embedding_size, weight_attr=fluid.ParamAttr( name='embedding_para', initializer=paddle.nn.initializer.Uniform( low=-0.5 / self.embedding_size, high=0.5 / self.embedding_size, ), ), ) self.embedding_out = Embedding( self.vocab_size, self.embedding_size, weight_attr=fluid.ParamAttr( name='embedding_out_para', initializer=paddle.nn.initializer.Uniform( low=-0.5 / self.embedding_size, high=0.5 / self.embedding_size, ), ), ) @to_static def forward(self, center_words, target_words, label): center_words_emb = self.embedding(center_words) target_words_emb = self.embedding_out(target_words) # center_words_emb = [batch_size, embedding_size] # target_words_emb = [batch_size, embedding_size] word_sim = paddle.multiply(center_words_emb, target_words_emb) word_sim = paddle.sum(word_sim, axis=-1) pred = paddle.nn.functional.sigmoid(word_sim) loss = paddle.nn.functional.binary_cross_entropy_with_logits( word_sim, label ) loss = paddle.mean(loss) return pred, loss batch_size = 512 epoch_num = 1 embedding_size = 200 learning_rate = 1e-3 total_steps = len(dataset) * epoch_num // batch_size def train(to_static): paddle.jit.enable_to_static(to_static) random.seed(0) np.random.seed(0) place = ( fluid.CUDAPlace(0) if fluid.is_compiled_with_cuda() else fluid.CPUPlace() ) with fluid.dygraph.guard(place): fluid.default_startup_program().random_seed = 1000 fluid.default_main_program().random_seed = 1000 skip_gram_model = SkipGram( "skip_gram_model", vocab_size, embedding_size ) adam = fluid.optimizer.AdamOptimizer( learning_rate=learning_rate, parameter_list=skip_gram_model.parameters(), ) step = 0 ret = [] for center_words, target_words, label, eval_words in build_batch( dataset, batch_size, epoch_num ): center_words_var = fluid.dygraph.to_variable(center_words) target_words_var = fluid.dygraph.to_variable(target_words) label_var = fluid.dygraph.to_variable(label) pred, loss = skip_gram_model( center_words_var, target_words_var, label_var ) loss.backward() adam.minimize(loss) skip_gram_model.clear_gradients() step += 1 mean_loss = np.mean(loss.numpy()) print("step %d / %d, loss %f" % (step, total_steps, mean_loss)) ret.append(mean_loss) return np.array(ret) class TestWord2Vec(unittest.TestCase): def test_dygraph_static_same_loss(self): dygraph_loss = train(to_static=False) static_loss = train(to_static=True) np.testing.assert_allclose(dygraph_loss, static_loss, rtol=1e-05) if __name__ == '__main__': unittest.main()
[ "noreply@github.com" ]
Xreki.noreply@github.com
c1d6d7777b160f039547f7ae9d7740a8f555281d
9e8e8026e575bbe791770ec4b8630c818b1aab61
/backend/perfil/models.py
d07743edf026397cb4aa4515b4a336db51bd98fc
[ "MIT" ]
permissive
marcusgabrields/gabr
d4b47e0df35dfca4e8ce1e657c0e4e77cded18ec
95ade6094ed7675ca267f2f16f77f0033eae9c1f
refs/heads/master
2023-01-12T16:25:16.610427
2020-04-16T23:55:37
2020-04-16T23:55:37
249,736,516
0
0
MIT
2023-01-05T16:58:31
2020-03-24T14:53:42
Python
UTF-8
Python
false
false
542
py
from django.db import models from django.utils.translation import ugettext_lazy as _ from common.models import TimeStampedModel class Perfil(TimeStampedModel): slug = models.SlugField(_('slug'), max_length=300, unique=True) user = models.OneToOneField( 'users.User', on_delete=models.CASCADE, primary_key=True, verbose_name=_('user'), ) name = models.CharField(_('name'), max_length=255) avatar = models.URLField(_('avatar'), null=True) def __str__(self): return self.name
[ "marcusgabriel.ds@gmail.com" ]
marcusgabriel.ds@gmail.com
99a637e6bb615e7ca38345ad4eab10e7d6cfd66b
3cadd7873d22de23a2b6ba030a422f7343ca0622
/cloudbench/version.py
42b8659f2dbcf9ba38eb0d49b555b7cfc2b3e152
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
wo083053253/cloudbench
6620fb1e58e1cc638c7cb2a6032aa0ab10944e95
df3f7d4e9ce1465d43b57c894da3623aad58c926
refs/heads/master
2021-05-03T08:50:23.780043
2014-05-30T11:05:31
2014-05-30T11:05:31
null
0
0
null
null
null
null
UTF-8
Python
false
false
37
py
#coding:utf-8 __version__ = "0.14.1"
[ "thomas@orozco.fr" ]
thomas@orozco.fr
159149a9c5d8223eb83ff1f41461f63ee257711c
b521802cca8e4ee4ff5a5ffe59175a34f2f6d763
/maya/maya-utils/Scripts/Animation/2019-2-15 Tim Cam_Route_Manager/.history/Cam_Main/Cam_Main/Cam_Item_Layout_20190119205543.py
8083e5043cdb9a60da3d9f28cc65246da25b9252
[]
no_license
all-in-one-of/I-Do-library
2edf68b29558728ce53fe17168694ad0353a076e
8972ebdcf1430ccc207028d8482210092acf02ce
refs/heads/master
2021-01-04T06:58:57.871216
2019-12-16T04:52:20
2019-12-16T04:52:20
null
0
0
null
null
null
null
UTF-8
Python
false
false
8,809
py
# -*- coding:utf-8 -*- # Require Header import os import json from functools import partial # Sys Header import sys import traceback import subprocess import plugin.Qt as Qt from Qt.QtCore import * from Qt.QtGui import * from Qt.QtWidgets import * def loadUiType(uiFile): import plugin.Qt as Qt if Qt.__binding__.startswith('PyQt'): from Qt import _uic as uic return uic.loadUiType(uiFile) elif Qt.__binding__ == 'PySide': import pysideuic as uic else: import pyside2uic as uic import xml.etree.ElementTree as xml from cStringIO import StringIO parsed = xml.parse(uiFile) widget_class = parsed.find('widget').get('class') form_class = parsed.find('class').text with open(uiFile, 'r') as f: o = StringIO() frame = {} uic.compileUi(f, o, indent=0) pyc = compile(o.getvalue(), '<string>', 'exec') exec pyc in frame # Fetch the base_class and form class based on their type # in the xml from designer form_class = frame['Ui_%s'%form_class] base_class = eval('%s'%widget_class) return form_class, base_class from Qt.QtCompat import wrapInstance DIR = os.path.dirname(__file__) UI_PATH = os.path.join(DIR,"ui","Cam_Item_Layout.ui") GUI_STATE_PATH = os.path.join(DIR, "json" ,'GUI_STATE.json') form_class , base_class = loadUiType(UI_PATH) from maya import cmds class Cam_Item_Layout(form_class,base_class): def __init__(self,MainWindow): super(Cam_Item_Layout,self).__init__() self.setupUi(self) self.MainWindow = MainWindow self.Item_Add_BTN.clicked.connect(self.Item_Add_Fn) self.Item_Clear_BTN.clicked.connect(self.Item_Clear_Fn) self.Cam_Item_Num = 0 self.Cam_Item_Scroll.verticalScrollBar().valueChanged.connect(self.Scroll_Fn) self.Scroll_Offset = 0 self.Attr = {} self.Attr["Add_Crv_LE"] = "" self.Attr["Add_Motion_Path_LE"] = "" self.Attr["Add_CamGrp_LE"] = "" self.Attr["Add_Loc_LE"] = "" self.Attr["Name"] = "" # Note 功能按键 self.Batch_Keyframe_BTN.clicked.connect(self.Batch_Keyframe_Fn) self.Select_Path_BTN.clicked.connect(self.Select_Path_Fn) self.Batch_Position_BTN.clicked.connect(self.Batch_Position_Fn) self.Batch_Constraint_BTN.clicked.connect(self.Batch_Constraint_Fn) def Batch_Constraint_Fn(self): Cam_Grp = self.Attr["Add_CamGrp_LE"] Loc = self.Attr["Add_Loc_LE"] if not cmds.objExists(Cam_Grp): return if not cmds.objExists(Loc): return cmds.select(cl=1) cmds.select(Loc,add=1) ChildrenList = self.Item_Layout.children() for i,child in enumerate(ChildrenList): if i != 0: Cam_Loc = child.Attr["Add_Loc_LE"] if not cmds.objExists(Cam_Loc): continue cmds.select(Cam_Loc,add=1) child.Cam_Con_CB.setEnabled(True) cmds.select(Cam_Grp,add=1) pnCns = cmds.parentConstraint(mo=0) Attr_List = cmds.listAttr(pnCns,k=1,string="*W*") for i,child in enumerate(ChildrenList): if i != 0: try : child.Cam_Con_CB.stateChanged.disconnect() except: pass child.Cam_Con_CB.stateChanged.connect(partial(self.Cam_Con_CB_Fn,pnCns,child,Attr_List)) def Cam_Con_CB_Fn(self,CB,Con,Attr,state): ChildrenList = self.Item_Layout.children() for i,child in enumerate(ChildrenList): if i != 0: if child != CB: child.Cam_Con_CB.blockSignals(True) child.Cam_Con_CB.setChecked(False) if state == 2: CB.Cam_Con_CB.setChecked(True) cmds.setAttr("%s.%s" % (Con,Attr),1) else: CB.Cam_Con_CB.setChecked(False) for i,child in enumerate(ChildrenList): if i != 0: if child != CB: child.Cam_Con_CB.blockSignals(False) def Batch_Position_Fn(self): ChildrenList = self.Item_Layout.children() for i,child in enumerate(ChildrenList): if i != 0: Base_Curve = self.Attr["Add_Crv_LE"] CamGrp = child.Attr["Add_CamGrp_LE"] if not cmds.objExists(Base_Curve): continue if not cmds.objExists(CamGrp): continue cmds.setAttr("%s.tx" % CamGrp,0) cmds.setAttr("%s.ty" % CamGrp,0) cmds.setAttr("%s.tz" % CamGrp,0) cmds.setAttr("%s.rx" % CamGrp,0) cmds.setAttr("%s.ry" % CamGrp,0) cmds.setAttr("%s.rz" % CamGrp,0) cmds.xform( CamGrp,cp=1 ) cmds.delete(cmds.parentConstraint( Base_Curve,CamGrp )) Target_Curve = child.Attr["Add_Crv_LE"] if not cmds.objExists(Target_Curve): continue cmds.xform( Target_Curve,cp=1 ) # Note 解除曲线的锁定 cmds.setAttr("%s.tx" % Target_Curve,lock=False) cmds.setAttr("%s.ty" % Target_Curve,lock=False) cmds.setAttr("%s.tz" % Target_Curve,lock=False) cmds.setAttr("%s.rx" % Target_Curve,lock=False) cmds.setAttr("%s.ry" % Target_Curve,lock=False) cmds.setAttr("%s.rz" % Target_Curve,lock=False) cmds.delete(cmds.parentConstraint( Base_Curve,Target_Curve )) cmds.headsUpMessage(u"位置匹配完成") def Batch_Keyframe_Fn(self): ChildrenList = self.Item_Layout.children() for i,child in enumerate(ChildrenList): if i != 0: Path = child.Attr["Add_Motion_Path_LE"] if cmds.objExists(Path): offset = cmds.keyframe(Path,q=1)[0] cmds.keyframe("%s.uValue"% Path,e=1,iub=1,r=1,o="over",tc=-offset) def Select_Path_Fn(self): cmds.select(cl=1) ChildrenList = self.Item_Layout.children() for i,child in enumerate(ChildrenList): if i != 0: if cmds.objExists(child.Attr["Add_Motion_Path_LE"]): cmds.select(child.Attr["Add_Motion_Path_LE"],add=1) def Item_Add_Fn(self): self.Cam_Item_Num += 1 return Cam_Item(self,self.MainWindow) def Item_Clear_Fn(self): self.Attr["Add_Crv_LE"] = "" self.Attr["Add_Motion_Path_LE"] = "" self.Attr["Name"] = "" for i,child in enumerate(self.Item_Layout.children()): if i != 0: child.deleteLater() def Scroll_Fn(self): self.Scroll_Offset = self.Cam_Item_Scroll.verticalScrollBar().value() UI_PATH = os.path.join(DIR,"ui","Cam_Item.ui") form_class , base_class = loadUiType(UI_PATH) class Cam_Item(form_class,base_class): def __init__(self,parent,MainWindow): super(Cam_Item,self).__init__() self.setupUi(self) self.MainWindow = MainWindow self.Cam_Del_BTN.clicked.connect(self.Cam_Del_BTN_Fn) # self.Cam_Con_CB.stateChanged.connect(self.Cam_Con_CB_Fn) # Note 初始化创建参数 TotalCount = len(parent.Item_Layout.children()) parent.Item_Layout.layout().insertWidget(TotalCount-1,self) self.Cam_LE.setText("Cam_Item_%s" % parent.Cam_Item_Num) self.Cam_Num_Label.setText(u"镜头%s" % TotalCount) self.setObjectName("Cam_Item_%s" % TotalCount) self.Num = TotalCount self.Attr = {} self.Attr["Add_CamGrp_LE"] = "" self.Attr["Add_Loc_LE"] = "" self.Attr["Add_Crv_LE"] = "" self.Attr["Add_Motion_Path_LE"] = "" self.Attr["Strat_Time_SB"] = 0 self.Attr["End_Time_SB"] = 0 self.MainWindow.Save_Json_Fun() def Cam_Del_BTN_Fn(self): self.deleteLater() ChildrenList = self.parent().children() for i,child in enumerate(ChildrenList): if i != 0: if i > self.Num: # Note 修正 child 的序号 child.Num -= 1 child.Cam_Num_Label.setText(u"镜头%s" % (i-1)) child.setObjectName("Cam_Item_%s" % (i-1)) else: child.Cam_Num_Label.setText(u"镜头%s" % i) child.setObjectName("Cam_Item_%s" % i) self.Attr["Add_CamGrp_LE"] = "" self.Attr["Add_Loc_LE"] = "" self.Attr["Add_Crv_LE"] = "" self.Attr["Add_Motion_Path_LE"] = "" self.Attr["Strat_Time_SB"] = "" self.Attr["End_Time_SB"] = "" self.MainWindow.Save_Json_Fun()
[ "2595715768@qq.com" ]
2595715768@qq.com
03d43e7eadc35e0ce127897a908e6e2af12eedee
832eec4d9e618f9f3bdaeec259a79884283ac817
/books/admin.py
53abe34d35bd74067b5ad741bcf89a34861fc492
[]
no_license
mconstantin/books-project
d0a5035014c9e61c5331b64b8879fce694e06540
aa9acc64bf9a4bd654e98eaad5afbc23adbea312
refs/heads/master
2021-01-23T04:28:44.006164
2017-03-26T00:51:53
2017-03-26T00:51:53
86,197,860
0
0
null
null
null
null
UTF-8
Python
false
false
2,202
py
from django.contrib import admin from .models import Publisher, Author, Book, BookCategory, BookFormat # class BooksInLine(admin.StackedInline): class BooksInLine(admin.TabularInline): """ Example of modifying the admin interface to show a list for a model in tabular form (multicolumn). """ model = Book # add forms to add 2 additional books extra = 2 # use 'fieldsets' to group the fields for the model, using a list of 2-tuples, where # first tuple element is the name of the fieldset (or None for empty), and the second is a # dictionary with 'fields' as the key and the list of model's fields as value. fieldsets = [ (None, {'fields': ['title', 'authors']}), ("Publishing Information", {'fields': ['publisher', 'pub_date', 'isbn']}), ("Book Information", {'fields': ['format', 'category']}) ] # add a filter on the right-hand site # Django sets predefined filters, e.g. last 7 days, etc. list_filter = ['pub_date'] class PublisherAdmin(admin.ModelAdmin): # list of display columns list_display = ['name', 'website', 'published_books', 'address', 'city', 'state', 'country'] # 'fieldsets' grouping for an individual publisher fieldsets = [ (None, {'fields': ['name', 'website']}), ('Address', {'fields': ['address', 'city', 'state', 'country']}) ] # for a specific publisher, show the list of (its published) books, using the 'BooksInLine' UI above inlines = [BooksInLine] list_filter = ['name', 'city'] class BookAdmin(admin.ModelAdmin): model = Book fieldsets = [ (None, {'fields': ['title', 'authors']}), ("Publishing Information", {'fields': ['publisher', 'pub_date', 'isbn']}), ("Book Information", {'fields': ['format', 'category']}) ] list_display = ['title', 'authors_names', 'publisher_name', 'pub_date', 'isbn'] list_filter = ['pub_date'] # register all the models with the corresponding new templates (if any), with the admin site admin.site.register(Publisher, PublisherAdmin) admin.site.register(Author) admin.site.register(BookCategory) admin.site.register(BookFormat) admin.site.register(Book, BookAdmin)
[ "constantinm@sharplabs.com" ]
constantinm@sharplabs.com
743e3a712fdca05eef0079ce7d5c9ebefe17394d
b3d655616ec8a7caa12e0c65d89519dd0b055802
/prediction.ml/tensorflow/src/main/python/model_server_python3.py
e8e448693cfe25b3fc88faa93b08236dd6b3e5c4
[ "Apache-2.0" ]
permissive
akram-mohammed/pipeline
0d295e62ffa8bfc09896170d6fb5fa6efcde4a0a
5d97c8c66b8157230f98db3b0d2b69e446864a2f
refs/heads/master
2021-01-23T12:54:48.491126
2017-06-02T21:42:47
2017-06-02T21:42:47
93,211,853
1
1
null
2017-06-02T23:50:52
2017-06-02T23:50:52
null
UTF-8
Python
false
false
10,982
py
#!/usr/bin/env python3 import os import sys import tornado.ioloop import tornado.web import tornado.httpserver import tornado.httputil import tornado.gen import importlib.util from grpc.beta import implementations import asyncio import tensorflow as tf import predict_pb2 import prediction_service_pb2 import tarfile import subprocess import logging from tornado.options import define, options from prometheus_client import start_http_server, Summary from pio_model import PioRequestTransformer from pio_model import PioResponseTransformer from pio_model import PioModelInitializer from pio_model import PioModel define("PIO_MODEL_STORE_HOME", default="model_store", help="path to model_store", type=str) define("PIO_MODEL_TYPE", default="", help="prediction model type", type=str) define("PIO_MODEL_NAMESPACE", default="", help="prediction model namespace", type=str) define("PIO_MODEL_NAME", default="", help="prediction model name", type=str) define("PIO_MODEL_VERSION", default="", help="prediction model version", type=str) define("PIO_MODEL_SERVER_PORT", default="9876", help="tornado http server listen port", type=int) define("PIO_MODEL_SERVER_PROMETHEUS_PORT", default="8080", help="port to run the prometheus http metrics server on", type=int) define("PIO_MODEL_SERVER_TENSORFLOW_SERVING_PORT", default="9000", help="port to run the prometheus http metrics server on", type=int) # Create a metric to track time spent and requests made. REQUEST_TIME = Summary('request_processing_seconds', 'Model Server: Time spent processing request') REQUEST_TIME.observe(1.0) # Observe 1.0 (seconds in this case) logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) logger.addHandler(ch) class Application(tornado.web.Application): def __init__(self): handlers = [ #(r"/", IndexHandler), # url: /api/v1/model/predict/$PIO_MODEL_TYPE/$PIO_MODEL_NAMESPACE/$PIO_MODEL_NAME/$PIO_MODEL_VERSION/ (r"/api/v1/model/predict/([a-zA-Z\-0-9\.:,_]+)/([a-zA-Z\-0-9\.:,_]+)/([a-zA-Z\-0-9\.:,_]+)/([a-zA-Z\-0-9\.:,_]+)", ModelPredictTensorFlowHandler), # TODO: Disable this if we're not explicitly in PIO_MODEL_ENVIRONMENT=dev mode # url: /api/v1/model/deploy/$PIO_MODEL_TYPE/$PIO_MODEL_NAMESPACE/$PIO_MODEL_NAME/$PIO_MODEL_VERSION/ (r"/api/v1/model/deploy/([a-zA-Z\-0-9\.:,_]+)/([a-zA-Z\-0-9\.:,_]+)/([a-zA-Z\-0-9\.:,_]+)/([a-zA-Z\-0-9\.:,_]+)", ModelDeployTensorFlowHandler), ] settings = dict( model_store_path=options.PIO_MODEL_STORE_HOME, model_type=options.PIO_MODEL_TYPE, model_namespace=options.PIO_MODEL_NAMESPACE, model_name=options.PIO_MODEL_NAME, model_version=options.PIO_MODEL_VERSION, model_server_port=options.PIO_MODEL_SERVER_PORT, model_server_prometheus_server_port=options.PIO_MODEL_SERVER_PROMETHEUS_PORT, model_server_tensorflow_serving_host='127.0.0.1', model_server_tensorflow_serving_port=options.PIO_MODEL_SERVER_TENSORFLOW_SERVING_PORT, template_path=os.path.join(os.path.dirname(__file__), "templates"), static_path=os.path.join(os.path.dirname(__file__), "static"), request_timeout=120, debug=True, autoescape=None, ) tornado.web.Application.__init__(self, handlers, **settings) def fallback(self): logger.warn('Model Server Application fallback: %s' % self) return 'fallback!' class IndexHandler(tornado.web.RequestHandler): @tornado.web.asynchronous def get(self): self.render("index.html") class ModelPredictTensorFlowHandler(tornado.web.RequestHandler): registry = {} @REQUEST_TIME.time() @tornado.web.asynchronous def post(self, model_type, model_namespace, model_name, model_version): (model_base_path, transformers_module) = self.get_model_assets(model_type, model_namespace, model_name, model_version) # TODO: Reuse instead of creating this channel everytime channel = implementations.insecure_channel(self.settings['model_server_tensorflow_serving_host'], int(self.settings['model_server_tensorflow_serving_port'])) stub = prediction_service_pb2.beta_create_PredictionService_stub(channel) # Transform raw inputs to TensorFlow PredictRequest transformed_inputs_request = transformers_module.transform_inputs(self.request.body) transformed_inputs_request.model_spec.name = model_name transformed_inputs_request.model_spec.version.value = int(model_version) # Transform TensorFlow PredictResponse into output outputs = stub.Predict(transformed_inputs_request, self.settings['request_timeout']) transformed_outputs = transformers_module.transform_outputs(outputs) self.write(transformed_outputs) self.finish() @REQUEST_TIME.time() def get_model_assets(self, model_type, model_namespace, model_name, model_version): model_key = '%s_%s_%s_%s' % (model_type, model_namespace, model_name, model_version) if model_key not in self.registry: model_base_path = self.settings['model_store_path'] model_base_path = os.path.expandvars(model_base_path) model_base_path = os.path.expanduser(model_base_path) model_base_path = os.path.abspath(model_base_path) bundle_path = os.path.join(model_base_path, model_type) bundle_path = os.path.join(bundle_path, model_namespace) bundle_path = os.path.join(bundle_path, model_name) bundle_path = os.path.join(bundle_path, model_version) # TODO: remove filter + listdir - only need to check specific file model_filenames = fnmatch.filter(os.listdir(bundle_path), "saved_model.pb") if (len(model_filenames) == 0): log.error("Invalid bundle. Please re-deploy a directory/bundle that contains 'saved_model.pb'" % model_name) raise "Invalid bundle. Please re-deploy a directory/bundle that contains 'saved_model.pb'" % model_name # Load model_io_transformers from model directory transformers_module_name = 'model_io_transformers' transformers_source_path = os.path.join(model_base_path, '%s.py' % transformers_module_name) spec = importlib.util.spec_from_file_location(transformers_module_name, transformers_source_path) transformers_module = importlib.util.module_from_spec(spec) spec.loader.exec_module(transformers_module) self.registry[model_key] = (model_base_path, transformers_module) return self.registry[model_key] class ModelDeployTensorFlowHandler(tornado.web.RequestHandler): @REQUEST_TIME.time() def post(self, model_type, model_namespace, model_name, model_version): fileinfo = self.request.files['file'][0] model_file_source_bundle_path = fileinfo['filename'] (_, filename) = os.path.split(model_file_source_bundle_path) model_base_path = self.settings['model_store_path'] model_base_path = os.path.expandvars(model_base_path) model_base_path = os.path.expanduser(model_base_path) model_base_path = os.path.abspath(model_base_path) bundle_path = os.path.join(model_base_path, model_type) bundle_path = os.path.join(bundle_path, model_namespace) bundle_path = os.path.join(bundle_path, model_name) bundle_path = os.path.join(bundle_path, model_version) bundle_path_filename = os.path.join(bundle_path, filename) try: os.makedirs(bundle_path, exist_ok=True) with open(bundle_path_filename, 'wb+') as fh: fh.write(fileinfo['body']) print("") print("%s uploaded %s, saved as %s" % ( str(self.request.remote_ip), str(filename), bundle_path_filename) ) print("") print("Uploading and extracting bundle '%s' into '%s'..." % (filename, bundle_path)) print("") with tarfile.open(bundle_path_filename, "r:gz") as tar: tar.extractall(path=bundle_path) print("") print("...Done!") print("") logger.info('Installing bundle and updating environment...\n') # TODO: Restart TensorFlow Model Serving and point to bundle_path_with_model_name #completed_process = subprocess.run('cd %s && ./install.sh' % bundle_path, completed_process = subprocess.run('cd %s && [ -s ./requirements_conda.txt ] && conda install --yes --file ./requirements_conda.txt' % bundle_path, timeout=600, shell=True, stdout=subprocess.PIPE) completed_process = subprocess.run('cd %s && [ -s ./requirements.txt ] && pip install -r ./requirements.txt' % bundle_path, timeout=600, shell=True, stdout=subprocess.PIPE) logger.info('...Done!') except IOError as e: print('Failed to write file due to IOError %s' % str(e)) self.write('Failed to write file due to IOError %s' % str(e)) raise e def write_error(self, status_code, **kwargs): self.write('Error %s' % status_code) if "exc_info" in kwargs: self.write(", Exception: %s" % kwargs["exc_info"][0].__name__) def main(): # Start up a web server to expose request made and time spent metrics to Prometheus # TODO: Potentially expose metrics to Prometheus using the Tornado HTTP server as long as it's not blocking # See the MetricsHandler class which provides a BaseHTTPRequestHandler # https://github.com/prometheus/client_python/blob/ce5542bd8be2944a1898e9ac3d6e112662153ea4/prometheus_client/exposition.py#L79 logger.info("Starting Prometheus Http Server on port '%s'" % options.PIO_MODEL_SERVER_PROMETHEUS_PORT) start_http_server(int(options.PIO_MODEL_SERVER_PROMETHEUS_PORT)) logger.info("Starting Model Predict and Deploy Http Server on port '%s'" % options.PIO_MODEL_SERVER_PORT) http_server = tornado.httpserver.HTTPServer(Application()) http_server.listen(int(options.PIO_MODEL_SERVER_PORT)) tornado.ioloop.IOLoop.current().start() if __name__ == '__main__': main()
[ "chris@fregly.com" ]
chris@fregly.com
7788549a3662ca1e2a17c904ac5f22ecd49ac69b
67416177cd9e221db0b20332c02dcc7680fcdd0e
/이것이 취업을 위한 코딩 테스트다/Chapter06_Sorting/Q02.py
5f904fd8060abd698a7a21fca906fefb6368fa34
[]
no_license
svclaw2000/Algorithm
4fe5e3bf50888b974df4f3d87387a003b5249352
b6d92cf0d18997e9e973d5f731ecb44a7935d93a
refs/heads/main
2023-06-21T21:50:13.089719
2021-07-11T14:18:47
2021-07-11T14:18:47
363,825,838
0
0
null
null
null
null
UTF-8
Python
false
false
181
py
# 00:02 / 00:20 N = int(input()) student = [] for _ in range(N): inp = input().split() student.append((int(inp[1]), inp[0])) student.sort() print(*[s[1] for s in student])
[ "svclaw2000@gmail.com" ]
svclaw2000@gmail.com
24e45112ef804b859c5fac4694945f26f9faf26d
f1738cd603e0b2e31143f4ebf7eba403402aecd6
/ucs/test/ucs-test/tests/52_s4connector/s4connector.py
4931adb730b3043036fbd0357bf0b3e45c5f64b7
[]
no_license
m-narayan/smart
92f42bf90d7d2b24f61915fac8abab70dd8282bc
1a6765deafd8679079b64dcc35f91933d37cf2dd
refs/heads/master
2016-08-05T17:29:30.847382
2013-01-04T04:50:26
2013-01-04T04:50:26
7,079,786
8
6
null
2015-04-29T08:54:12
2012-12-09T14:56:27
Python
UTF-8
Python
false
false
3,597
py
import ldap import univention.config_registry from ldap.controls import LDAPControl import ldap.modlist as modlist import time import ldap_glue_s4 import univention.s4connector.s4 as s4 configRegistry = univention.config_registry.ConfigRegistry() configRegistry.load() class S4Connection(ldap_glue_s4.LDAPConnection): '''helper functions to modify AD-objects''' def __init__(self, configbase='connector', no_starttls=False): self.configbase = configbase self.adldapbase = configRegistry['%s/s4/ldap/base' % configbase] self.addomain = self.adldapbase.replace (',DC=', '.').replace ('DC=', '') self.login_dn = configRegistry['%s/s4/ldap/binddn' % configbase] self.pw_file = configRegistry['%s/s4/ldap/bindpw' % configbase] self.host = configRegistry['%s/s4/ldap/host' % configbase] self.port = configRegistry['%s/s4/ldap/port' % configbase] self.ssl = configRegistry.get('%s/s4/ldap/ssl', "no") self.ca_file = configRegistry['%s/s4/ldap/certificate' % configbase] self.protocol = configRegistry.get('%s/s4/ldap/protocol' % self.configbase, 'ldap').lower() self.socket = configRegistry.get('%s/s4/ldap/socket' % self.configbase, '') self.connect (no_starttls) def createuser(self, username, position=None, cn=None, sn=None, description=None): if not position: position = 'cn=users,%s' % self.adldapbase if not cn: cn = username if not sn: sn = 'SomeSurName' newdn = 'cn=%s,%s' % (cn, position) attrs = {} attrs['objectclass'] = ['top', 'user', 'person', 'organizationalPerson'] attrs['cn'] = cn attrs['sn'] = sn attrs['sAMAccountName'] = username attrs['userPrincipalName'] = '%s@%s' % (username, self.addomain) attrs['displayName'] = '%s %s' % (username, sn) if description: attrs['description'] = description self.create(newdn, attrs) def group_create(self, groupname, position=None, description=None): if not position: position = 'cn=groups,%s' % self.adldapbase attrs = {} attrs['objectclass'] = ['top', 'group'] attrs['sAMAccountName'] = groupname if description: attrs['description'] = description self.create('cn=%s,%s' % (groupname, position), attrs) def getprimarygroup(self, user_dn): try: res = self.lo.search_ext_s(user_dn, ldap.SCOPE_BASE, timeout=10) except: return None primaryGroupID = res[0][1]['primaryGroupID'][0] res = self.lo.search_ext_s(self.adldapbase, ldap.SCOPE_SUBTREE, 'objectClass=group'.encode ('utf8'), timeout=10) import re regex = '^(.*?)-%s$' % primaryGroupID for r in res: if r[0] == None or r[0] == 'None': continue # Referral if re.search (regex, s4.decode_sid(r[1]['objectSid'][0])): return r[0] def setprimarygroup(self, user_dn, group_dn): res = self.lo.search_ext_s(group_dn, ldap.SCOPE_BASE, timeout=10) import re groupid = (re.search ('^(.*)-(.*?)$', s4.decode_sid (res[0][1]['objectSid'][0]))).group (2) self.set_attribute (user_dn, 'primaryGroupID', groupid) def container_create(self, name, position=None, description=None): if not position: position = self.adldapbase attrs = {} attrs['objectClass'] = ['top', 'container'] attrs['cn'] = name if description: attrs['description'] = description self.create('cn=%s,%s' % (name, position), attrs) def createou(self, name, position=None, description=None): if not position: position = self.adldapbase attrs = {} attrs['objectClass'] = ['top', 'organizationalUnit'] attrs['ou'] = name if description: attrs['description'] = description self.create('ou=%s,%s' % (name, position), attrs)
[ "kartik@debian.org" ]
kartik@debian.org
b5c44cbbab50c96d3ed02f99623993dae708a4fa
fce280d1a9ef78784d28409c47865ec92402fad4
/019Echarts/Demo_Geo.py
b5e92a127be827c15759193c16ca3deb9aa35c9c
[]
no_license
angus138/---
204fa9f5713fc3cee1ec814b0d600e5e4f413ab1
39ea3e51f32e093c01afae6984363afaaa5e120f
refs/heads/master
2020-12-12T13:39:56.871807
2020-01-15T11:06:20
2020-01-15T11:06:20
234,139,575
0
0
null
null
null
null
UTF-8
Python
false
false
1,126
py
# coding:utf-8 """ create on Jan 2, 2020 By Wayne Yu Function: 基于Pyecharts的Geo图 """ from pyecharts.faker import Faker from pyecharts import options as opts from pyecharts.charts import Geo from pyecharts.globals import ChartType, SymbolType from pyecharts.charts import Map def geo_base() -> Geo: c = ( Geo() .add_schema(maptype="china") .add("geo", [list(z) for z in zip(Faker.provinces, Faker.values())]) .set_series_opts(label_opts=opts.LabelOpts(is_show=False)) .set_global_opts( visualmap_opts=opts.VisualMapOpts(), title_opts=opts.TitleOpts(title="Geo-基本示例"), ) ) return c def map_world() -> Map: c = ( Map() .add("商家A", [list(z) for z in zip(Faker.country, Faker.values())], "world") .set_series_opts(label_opts=opts.LabelOpts(is_show=False)) .set_global_opts( title_opts=opts.TitleOpts(title="Map-世界地图"), visualmap_opts=opts.VisualMapOpts(max_=200), ) ) return c map_world().render("world_2D_render.html")
[ "ieeflsyu@outlook.com" ]
ieeflsyu@outlook.com
4f5f46a2c9ca7140338f82554c8064b407e1d2d1
3d7039903da398ae128e43c7d8c9662fda77fbdf
/database/CSS/juejin_1727.py
f64f660ab9993897acb4bd4196895de5b9c70bcc
[]
no_license
ChenYongChang1/spider_study
a9aa22e6ed986193bf546bb567712876c7be5e15
fe5fbc1a5562ff19c70351303997d3df3af690db
refs/heads/master
2023-08-05T10:43:11.019178
2021-09-18T01:30:22
2021-09-18T01:30:22
406,727,214
0
0
null
null
null
null
UTF-8
Python
false
false
69,429
py
{"err_no": 0, "err_msg": "success", "data": [{"article_id": "6897739815920500743", "article_info": {"article_id": "6897739815920500743", "user_id": "3790771822799240", "category_id": "6809637767543259144", "tag_ids": [6809640394175971342], "visible_level": 0, "link_url": "", "cover_image": "", "is_gfw": 0, "title": "一篇文章带你了解CSS3按钮知识", "brief_content": "在实际开发中,按钮的应用是必不可少。使用CSS来制作按钮,可以更有新意,更有趣,也可以自定义自己想要的样式。一、平面样式CSS按钮平面样式按钮的使用现在非常流行,并且符合无处不在的平面设计趋势。,这些", "is_english": 0, "is_original": 1, "user_index": 3.710916192250951, "original_type": 0, "original_author": "", "content": "", "ctime": "1606005864", "mtime": "1606014147", "rtime": "1606014147", "draft_id": "6897739468162203656", "view_count": 270, "collect_count": 1, "digg_count": 5, "comment_count": 0, "hot_index": 18, "is_hot": 0, "rank_index": 0.00021284, "status": 2, "verify_status": 1, "audit_status": 2, "mark_content": ""}, "author_user_info": {"user_id": "3790771822799240", "user_name": "Python进阶者", "company": "无", "job_title": "学生", "avatar_large": "https://sf1-ttcdn-tos.pstatp.com/img/user-avatar/0f000487090220f237b487a04f681748~300x300.image", "level": 3, "description": "喜欢网络爬虫、数据处理、数据清洗、数据加工、数据展示、数据挖掘等,", "followee_count": 1, "follower_count": 118, "post_article_count": 246, "digg_article_count": 198, "got_digg_count": 455, "got_view_count": 80644, "post_shortmsg_count": 0, "digg_shortmsg_count": 0, "isfollowed": false, "favorable_author": 0, "power": 1340, "study_point": 0, "university": {"university_id": "0", "name": "", "logo": ""}, "major": {"major_id": "0", "parent_id": "0", "name": ""}, "student_status": 0, "select_event_count": 0, "select_online_course_count": 0, "identity": 0, "is_select_annual": false, "select_annual_rank": 0, "annual_list_type": 0, "extraMap": {}, "is_logout": 0}, "category": {"category_id": "6809637767543259144", "category_name": "前端", "category_url": "frontend", "rank": 2, "back_ground": "https://lc-mhke0kuv.cn-n1.lcfile.com/8c95587526f346c0.png", "icon": "https://lc-mhke0kuv.cn-n1.lcfile.com/1c40f5eaba561e32.png", "ctime": 1457483942, "mtime": 1432503190, "show_type": 3, "item_type": 2, "promote_tag_cap": 4, "promote_priority": 2}, "tags": [{"id": 2546516, "tag_id": "6809640394175971342", "tag_name": "CSS", "color": "#244DE4", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/leancloud-assets/66de0c4eb9d10130d5bf.png~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 0, "ctime": 1432239426, "mtime": 1631688735, "id_type": 9, "tag_alias": "", "post_article_count": 14981, "concern_user_count": 297034}], "user_interact": {"id": 6897739815920500743, "omitempty": 2, "user_id": 0, "is_digg": false, "is_follow": false, "is_collect": false}, "org": {"org_info": null, "org_user": null, "is_followed": false}, "req_id": "202109151604300102121660811B004064"}, {"article_id": "6844904004770594829", "article_info": {"article_id": "6844904004770594829", "user_id": "2963939077920542", "category_id": "6809637767543259144", "tag_ids": [6809640394175971342], "visible_level": 0, "link_url": "https://juejin.im/post/6844904004770594829", "cover_image": "", "is_gfw": 0, "title": "彻底搞懂CSS伪类选择器:is、not", "brief_content": "1dds", "is_english": 0, "is_original": 1, "user_index": 0.13696495143458, "original_type": 0, "original_author": "", "content": "", "ctime": "1574732377", "mtime": "1598535918", "rtime": "1574734577", "draft_id": "6845076546529542158", "view_count": 996, "collect_count": 13, "digg_count": 12, "comment_count": 0, "hot_index": 61, "is_hot": 0, "rank_index": 0.0002126, "status": 2, "verify_status": 1, "audit_status": 2, "mark_content": ""}, "author_user_info": {"user_id": "2963939077920542", "user_name": "木法传", "company": "", "job_title": "前端开发工程师", "avatar_large": "https://sf1-ttcdn-tos.pstatp.com/img/user-avatar/e86cfa1f74dadfa543acd7da836c10e0~300x300.image", "level": 3, "description": "搞点不一样的", "followee_count": 15, "follower_count": 117, "post_article_count": 13, "digg_article_count": 28, "got_digg_count": 703, "got_view_count": 60897, "post_shortmsg_count": 16, "digg_shortmsg_count": 6, "isfollowed": false, "favorable_author": 0, "power": 1307, "study_point": 0, "university": {"university_id": "0", "name": "", "logo": ""}, "major": {"major_id": "0", "parent_id": "0", "name": ""}, "student_status": 0, "select_event_count": 0, "select_online_course_count": 0, "identity": 0, "is_select_annual": false, "select_annual_rank": 0, "annual_list_type": 0, "extraMap": {}, "is_logout": 0}, "category": {"category_id": "6809637767543259144", "category_name": "前端", "category_url": "frontend", "rank": 2, "back_ground": "https://lc-mhke0kuv.cn-n1.lcfile.com/8c95587526f346c0.png", "icon": "https://lc-mhke0kuv.cn-n1.lcfile.com/1c40f5eaba561e32.png", "ctime": 1457483942, "mtime": 1432503190, "show_type": 3, "item_type": 2, "promote_tag_cap": 4, "promote_priority": 2}, "tags": [{"id": 2546516, "tag_id": "6809640394175971342", "tag_name": "CSS", "color": "#244DE4", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/leancloud-assets/66de0c4eb9d10130d5bf.png~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 0, "ctime": 1432239426, "mtime": 1631688735, "id_type": 9, "tag_alias": "", "post_article_count": 14981, "concern_user_count": 297034}], "user_interact": {"id": 6844904004770594829, "omitempty": 2, "user_id": 0, "is_digg": false, "is_follow": false, "is_collect": false}, "org": {"org_info": null, "org_user": null, "is_followed": false}, "req_id": "202109151604300102121660811B004064"}, {"article_id": "6844903620991811592", "article_info": {"article_id": "6844903620991811592", "user_id": "3843548380668829", "category_id": "6809637767543259144", "tag_ids": [6809640394175971342, 6809640398105870343, 6809640407484334093, 6809640528267706382], "visible_level": 0, "link_url": "https://juejin.im/post/6844903620991811592", "cover_image": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/gold-user-assets/2018/6/15/16401f5da74a6c09~tplv-t2oaga2asx-image.image", "is_gfw": 0, "title": "【CSS模块化之路2】webpack中的Local Scope", "brief_content": "CSS是一门几十分钟就能入门,但是却需要很长的时间才能掌握好的语言。它有着它自身的一些复杂性与局限性。其中非常重要的一点就是,本身不具备真正的模块化能力。 1. 面临的问题 你可能会说,CSS有@import功能。然而,我们都知道,这里的@import仅仅是表示引入相应的CSS…", "is_english": 0, "is_original": 1, "user_index": 0, "original_type": 0, "original_author": "", "content": "", "ctime": "1529041264", "mtime": "1598456423", "rtime": "1529374361", "draft_id": "6845075539238092814", "view_count": 2227, "collect_count": 13, "digg_count": 20, "comment_count": 0, "hot_index": 131, "is_hot": 0, "rank_index": 0.0002126, "status": 2, "verify_status": 1, "audit_status": 2, "mark_content": ""}, "author_user_info": {"user_id": "3843548380668829", "user_name": "AlienZHOU", "company": "Kwai Inc.", "job_title": "前端工程师", "avatar_large": "https://sf1-ttcdn-tos.pstatp.com/img/user-avatar/6279b543742240e66a169cf6adc80573~300x300.image", "level": 4, "description": "前端工程化、Node.js与Serverless", "followee_count": 27, "follower_count": 10054, "post_article_count": 56, "digg_article_count": 151, "got_digg_count": 5746, "got_view_count": 258514, "post_shortmsg_count": 12, "digg_shortmsg_count": 60, "isfollowed": false, "favorable_author": 1, "power": 8297, "study_point": 0, "university": {"university_id": "0", "name": "", "logo": ""}, "major": {"major_id": "0", "parent_id": "0", "name": ""}, "student_status": 0, "select_event_count": 0, "select_online_course_count": 0, "identity": 0, "is_select_annual": false, "select_annual_rank": 0, "annual_list_type": 0, "extraMap": {}, "is_logout": 0}, "category": {"category_id": "6809637767543259144", "category_name": "前端", "category_url": "frontend", "rank": 2, "back_ground": "https://lc-mhke0kuv.cn-n1.lcfile.com/8c95587526f346c0.png", "icon": "https://lc-mhke0kuv.cn-n1.lcfile.com/1c40f5eaba561e32.png", "ctime": 1457483942, "mtime": 1432503190, "show_type": 3, "item_type": 2, "promote_tag_cap": 4, "promote_priority": 2}, "tags": [{"id": 2546516, "tag_id": "6809640394175971342", "tag_name": "CSS", "color": "#244DE4", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/leancloud-assets/66de0c4eb9d10130d5bf.png~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 0, "ctime": 1432239426, "mtime": 1631688735, "id_type": 9, "tag_alias": "", "post_article_count": 14981, "concern_user_count": 297034}, {"id": 2546519, "tag_id": "6809640398105870343", "tag_name": "JavaScript", "color": "#616161", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/leancloud-assets/5d70fd6af940df373834.png~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 0, "ctime": 1435884803, "mtime": 1631692583, "id_type": 9, "tag_alias": "", "post_article_count": 67405, "concern_user_count": 398956}, {"id": 2546526, "tag_id": "6809640407484334093", "tag_name": "前端", "color": "#60ADFF", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/leancloud-assets/bac28828a49181c34110.png~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 1, "ctime": 1435971546, "mtime": 1631692835, "id_type": 9, "tag_alias": "", "post_article_count": 88828, "concern_user_count": 527704}, {"id": 2546614, "tag_id": "6809640528267706382", "tag_name": "Webpack", "color": "#6F94DB", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/leancloud-assets/73e856b07f83b4231c1e.png~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 0, "ctime": 1440920866, "mtime": 1631692726, "id_type": 9, "tag_alias": "", "post_article_count": 6704, "concern_user_count": 204077}], "user_interact": {"id": 6844903620991811592, "omitempty": 2, "user_id": 0, "is_digg": false, "is_follow": false, "is_collect": false}, "org": {"org_info": null, "org_user": null, "is_followed": false}, "req_id": "202109151604300102121660811B004064"}, {"article_id": "6844903583247253511", "article_info": {"article_id": "6844903583247253511", "user_id": "4160207729203517", "category_id": "6809637767543259144", "tag_ids": [6809640407484334093, 6809640394175971342], "visible_level": 0, "link_url": "https://juejin.im/post/6844903583247253511", "cover_image": "", "is_gfw": 0, "title": "两列自适应布局方案整理", "brief_content": "本文讨论的是两列自适应布局:左列定宽/不定宽,右列自适应。 虽然分这两种情况,但实际上不定宽的方案同样适用于定宽的场景,因此不定宽的方案泛用度更高。 再者,这个方案由于.right-fix的margin-left和.left的width高度耦合,因此无法实现自适应,只能应用在左…", "is_english": 0, "is_original": 1, "user_index": 0, "original_type": 0, "original_author": "", "content": "", "ctime": "1522111082", "mtime": "1598449827", "rtime": "1522206624", "draft_id": "6845075400461123597", "view_count": 2115, "collect_count": 22, "digg_count": 37, "comment_count": 1, "hot_index": 143, "is_hot": 0, "rank_index": 0.00021252, "status": 2, "verify_status": 1, "audit_status": 2, "mark_content": ""}, "author_user_info": {"user_id": "4160207729203517", "user_name": "array_huang", "company": "腾讯", "job_title": "前端开发高级工程师", "avatar_large": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/gold-user-assets/2018/2/26/161d17582d6c9a4f~tplv-t2oaga2asx-image.image", "level": 3, "description": "全栈开发者,追求实用至上", "followee_count": 5, "follower_count": 216, "post_article_count": 13, "digg_article_count": 18, "got_digg_count": 844, "got_view_count": 43911, "post_shortmsg_count": 0, "digg_shortmsg_count": 0, "isfollowed": false, "favorable_author": 0, "power": 1283, "study_point": 0, "university": {"university_id": "0", "name": "", "logo": ""}, "major": {"major_id": "0", "parent_id": "0", "name": ""}, "student_status": 0, "select_event_count": 0, "select_online_course_count": 0, "identity": 0, "is_select_annual": false, "select_annual_rank": 0, "annual_list_type": 0, "extraMap": {}, "is_logout": 0}, "category": {"category_id": "6809637767543259144", "category_name": "前端", "category_url": "frontend", "rank": 2, "back_ground": "https://lc-mhke0kuv.cn-n1.lcfile.com/8c95587526f346c0.png", "icon": "https://lc-mhke0kuv.cn-n1.lcfile.com/1c40f5eaba561e32.png", "ctime": 1457483942, "mtime": 1432503190, "show_type": 3, "item_type": 2, "promote_tag_cap": 4, "promote_priority": 2}, "tags": [{"id": 2546526, "tag_id": "6809640407484334093", "tag_name": "前端", "color": "#60ADFF", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/leancloud-assets/bac28828a49181c34110.png~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 1, "ctime": 1435971546, "mtime": 1631692835, "id_type": 9, "tag_alias": "", "post_article_count": 88828, "concern_user_count": 527704}, {"id": 2546516, "tag_id": "6809640394175971342", "tag_name": "CSS", "color": "#244DE4", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/leancloud-assets/66de0c4eb9d10130d5bf.png~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 0, "ctime": 1432239426, "mtime": 1631688735, "id_type": 9, "tag_alias": "", "post_article_count": 14981, "concern_user_count": 297034}], "user_interact": {"id": 6844903583247253511, "omitempty": 2, "user_id": 0, "is_digg": false, "is_follow": false, "is_collect": false}, "org": {"org_info": null, "org_user": null, "is_followed": false}, "req_id": "202109151604300102121660811B004064"}, {"article_id": "6844903618059960333", "article_info": {"article_id": "6844903618059960333", "user_id": "958429868601117", "category_id": "6809637767543259144", "tag_ids": [6809640383690047502, 6809640388723212296, 6809640394175971342], "visible_level": 0, "link_url": "https://juejin.im/post/6844903618059960333", "cover_image": "", "is_gfw": 0, "title": "【前端Talkking】CSS系列——CSS深入理解之line-height", "brief_content": "行高,顾名思义指的就是一行文字的高度。按照定义来解释,就是两行文字之间基线之间的距离。那么问题来了,什么是基线呢?大家回想下我们刚开始学习汉语拼音的时候,使用四线格本子的四条线,其中倒数第二条线就是基线,如果你说,抱歉,我已经全部还给老师了,没有任何印象。呵呵,别急呢,我已经给…", "is_english": 0, "is_original": 1, "user_index": 0, "original_type": 0, "original_author": "", "content": "", "ctime": "1528418208", "mtime": "1598455807", "rtime": "1528683228", "draft_id": "6845075534892761101", "view_count": 1840, "collect_count": 23, "digg_count": 35, "comment_count": 6, "hot_index": 132, "is_hot": 0, "rank_index": 0.00021235, "status": 2, "verify_status": 1, "audit_status": 2, "mark_content": ""}, "author_user_info": {"user_id": "958429868601117", "user_name": "micstone", "company": "", "job_title": "前端工程师", "avatar_large": "https://sf1-ttcdn-tos.pstatp.com/img/user-avatar/d38a1911eeb141a4525bd8219e57ba81~300x300.image", "level": 2, "description": "", "followee_count": 63, "follower_count": 38, "post_article_count": 14, "digg_article_count": 42, "got_digg_count": 242, "got_view_count": 8691, "post_shortmsg_count": 1, "digg_shortmsg_count": 0, "isfollowed": false, "favorable_author": 0, "power": 257, "study_point": 0, "university": {"university_id": "0", "name": "", "logo": ""}, "major": {"major_id": "0", "parent_id": "0", "name": ""}, "student_status": 0, "select_event_count": 0, "select_online_course_count": 0, "identity": 0, "is_select_annual": false, "select_annual_rank": 0, "annual_list_type": 0, "extraMap": {}, "is_logout": 0}, "category": {"category_id": "6809637767543259144", "category_name": "前端", "category_url": "frontend", "rank": 2, "back_ground": "https://lc-mhke0kuv.cn-n1.lcfile.com/8c95587526f346c0.png", "icon": "https://lc-mhke0kuv.cn-n1.lcfile.com/1c40f5eaba561e32.png", "ctime": 1457483942, "mtime": 1432503190, "show_type": 3, "item_type": 2, "promote_tag_cap": 4, "promote_priority": 2}, "tags": [{"id": 2546508, "tag_id": "6809640383690047502", "tag_name": "Firefox", "color": "#D54101", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/leancloud-assets/d9b7ca13420fb40a2a78.png~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 0, "ctime": 1432234596, "mtime": 1631608254, "id_type": 9, "tag_alias": "", "post_article_count": 591, "concern_user_count": 23806}, {"id": 2546512, "tag_id": "6809640388723212296", "tag_name": "Microsoft", "color": "#737373", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/leancloud-assets/0fbb12f5279a25632d6f.png~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 0, "ctime": 1432234620, "mtime": 1631609610, "id_type": 9, "tag_alias": "", "post_article_count": 1226, "concern_user_count": 26586}, {"id": 2546516, "tag_id": "6809640394175971342", "tag_name": "CSS", "color": "#244DE4", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/leancloud-assets/66de0c4eb9d10130d5bf.png~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 0, "ctime": 1432239426, "mtime": 1631688735, "id_type": 9, "tag_alias": "", "post_article_count": 14981, "concern_user_count": 297034}], "user_interact": {"id": 6844903618059960333, "omitempty": 2, "user_id": 0, "is_digg": false, "is_follow": false, "is_collect": false}, "org": {"org_info": null, "org_user": null, "is_followed": false}, "req_id": "202109151604300102121660811B004064"}, {"article_id": "6844904191685558279", "article_info": {"article_id": "6844904191685558279", "user_id": "4371313964096926", "category_id": "6809637767543259144", "tag_ids": [6809640394175971342], "visible_level": 0, "link_url": "https://juejin.im/post/6844904191685558279", "cover_image": "", "is_gfw": 0, "title": "2020 祝安,缝隙中寻找机遇:面试题第一波:css", "brief_content": "非常感谢,前同事行长@onlyadaydreamer分享的面经。 话说,写了这么长时间的项目,很多基础都快忘没了。 我们程序员就是这样,默默无闻的当着键盘侠,明明都懂,却说不出来,就像我对你的爱。 来达到水平居中的效果。 可以在父容器的尾部添加i标签,当然也可以是其他的,我一般…", "is_english": 0, "is_original": 1, "user_index": 0.88895793873848, "original_type": 0, "original_author": "", "content": "", "ctime": "1592208853", "mtime": "1599033085", "rtime": "1592210227", "draft_id": "6845076833000652808", "view_count": 656, "collect_count": 6, "digg_count": 5, "comment_count": 0, "hot_index": 37, "is_hot": 0, "rank_index": 0.00021222, "status": 2, "verify_status": 1, "audit_status": 2, "mark_content": ""}, "author_user_info": {"user_id": "4371313964096926", "user_name": "Awen_Panda", "company": "某不知名教育机构", "job_title": "前端美食工程师", "avatar_large": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/gold-user-assets/2020/7/6/17322009096cd6eb~tplv-t2oaga2asx-image.image", "level": 2, "description": "想说一句喜欢你,却把希望寄予天空。", "followee_count": 5, "follower_count": 35, "post_article_count": 54, "digg_article_count": 29, "got_digg_count": 72, "got_view_count": 36331, "post_shortmsg_count": 9, "digg_shortmsg_count": 0, "isfollowed": false, "favorable_author": 0, "power": 435, "study_point": 0, "university": {"university_id": "0", "name": "", "logo": ""}, "major": {"major_id": "0", "parent_id": "0", "name": ""}, "student_status": 0, "select_event_count": 0, "select_online_course_count": 0, "identity": 0, "is_select_annual": false, "select_annual_rank": 0, "annual_list_type": 0, "extraMap": {}, "is_logout": 0}, "category": {"category_id": "6809637767543259144", "category_name": "前端", "category_url": "frontend", "rank": 2, "back_ground": "https://lc-mhke0kuv.cn-n1.lcfile.com/8c95587526f346c0.png", "icon": "https://lc-mhke0kuv.cn-n1.lcfile.com/1c40f5eaba561e32.png", "ctime": 1457483942, "mtime": 1432503190, "show_type": 3, "item_type": 2, "promote_tag_cap": 4, "promote_priority": 2}, "tags": [{"id": 2546516, "tag_id": "6809640394175971342", "tag_name": "CSS", "color": "#244DE4", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/leancloud-assets/66de0c4eb9d10130d5bf.png~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 0, "ctime": 1432239426, "mtime": 1631688735, "id_type": 9, "tag_alias": "", "post_article_count": 14981, "concern_user_count": 297034}], "user_interact": {"id": 6844904191685558279, "omitempty": 2, "user_id": 0, "is_digg": false, "is_follow": false, "is_collect": false}, "org": {"org_info": null, "org_user": null, "is_followed": false}, "req_id": "202109151604300102121660811B004064"}, {"article_id": "6912086688340639752", "article_info": {"article_id": "6912086688340639752", "user_id": "1530166414418605", "category_id": "6809637767543259144", "tag_ids": [6809640394175971342], "visible_level": 0, "link_url": "", "cover_image": "", "is_gfw": 0, "title": "CSS入门笔记3", "brief_content": "i. CSS布局有三种方式: ii. 布局的两种思路 iii. 布局需要用到哪些属性 iv. 用什么CSS布局方式呢? 1. float布局 在父元素上加 .clearfix ,用来包裹住里面的浮动元素。 如果设置为0,则不考虑内容周围的多余空间。如果设置为auto,则多余空间…", "is_english": 0, "is_original": 1, "user_index": 0, "original_type": 0, "original_author": "", "content": "", "ctime": "1609345615", "mtime": "1610107096", "rtime": "1609383469", "draft_id": "6911557757908811789", "view_count": 216, "collect_count": 1, "digg_count": 5, "comment_count": 3, "hot_index": 18, "is_hot": 0, "rank_index": 0.00021191, "status": 2, "verify_status": 1, "audit_status": 2, "mark_content": ""}, "author_user_info": {"user_id": "1530166414418605", "user_name": "一言沙雕", "company": "", "job_title": "前端工程师", "avatar_large": "https://sf6-ttcdn-tos.pstatp.com/img/user-avatar/62b440bca70b73a60b859214c6daf2ed~300x300.image", "level": 2, "description": "从入门到入土,一个前端小白的学习之旅", "followee_count": 45, "follower_count": 36, "post_article_count": 20, "digg_article_count": 147, "got_digg_count": 156, "got_view_count": 9389, "post_shortmsg_count": 0, "digg_shortmsg_count": 0, "isfollowed": false, "favorable_author": 0, "power": 249, "study_point": 145, "university": {"university_id": "6888594354433835015", "name": "成都文理学院", "logo": ""}, "major": {"major_id": "0", "parent_id": "0", "name": ""}, "student_status": 3, "select_event_count": 0, "select_online_course_count": 0, "identity": 0, "is_select_annual": false, "select_annual_rank": 0, "annual_list_type": 0, "extraMap": {}, "is_logout": 0}, "category": {"category_id": "6809637767543259144", "category_name": "前端", "category_url": "frontend", "rank": 2, "back_ground": "https://lc-mhke0kuv.cn-n1.lcfile.com/8c95587526f346c0.png", "icon": "https://lc-mhke0kuv.cn-n1.lcfile.com/1c40f5eaba561e32.png", "ctime": 1457483942, "mtime": 1432503190, "show_type": 3, "item_type": 2, "promote_tag_cap": 4, "promote_priority": 2}, "tags": [{"id": 2546516, "tag_id": "6809640394175971342", "tag_name": "CSS", "color": "#244DE4", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/leancloud-assets/66de0c4eb9d10130d5bf.png~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 0, "ctime": 1432239426, "mtime": 1631688735, "id_type": 9, "tag_alias": "", "post_article_count": 14981, "concern_user_count": 297034}], "user_interact": {"id": 6912086688340639752, "omitempty": 2, "user_id": 0, "is_digg": false, "is_follow": false, "is_collect": false}, "org": {"org_info": null, "org_user": null, "is_followed": false}, "req_id": "202109151604300102121660811B004064"}, {"article_id": "6844903983383838733", "article_info": {"article_id": "6844903983383838733", "user_id": "3386151546939421", "category_id": "6809637767543259144", "tag_ids": [6809640394175971342], "visible_level": 0, "link_url": "https://juejin.im/post/6844903983383838733", "cover_image": "", "is_gfw": 0, "title": "CSS编写策略之BEM", "brief_content": "项目开发过程中,一套合适的开发风格指南能够有效提高实际开发速度,降低维护成本。然而在有些项目开发过程中,CSS并没有完善的结构或者遵循命名约定,这导致在项目迭代的过程中,CSS结构变得越来越冗余,既降低了开发效率也影响性能。 现有的CSS编写策略有很多,如OOCSS,SMACS…", "is_english": 0, "is_original": 1, "user_index": 0, "original_type": 0, "original_author": "", "content": "", "ctime": "1572358004", "mtime": "1598531491", "rtime": "1572448498", "draft_id": "6845076513214169095", "view_count": 1101, "collect_count": 11, "digg_count": 8, "comment_count": 1, "hot_index": 64, "is_hot": 0, "rank_index": 0.00021138, "status": 2, "verify_status": 1, "audit_status": 2, "mark_content": ""}, "author_user_info": {"user_id": "3386151546939421", "user_name": "山雨林深", "company": "", "job_title": "", "avatar_large": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/gold-user-assets/2019/10/29/16e17dc5428b1e8c~tplv-t2oaga2asx-image.image", "level": 1, "description": "", "followee_count": 0, "follower_count": 1, "post_article_count": 2, "digg_article_count": 2, "got_digg_count": 8, "got_view_count": 2521, "post_shortmsg_count": 0, "digg_shortmsg_count": 0, "isfollowed": false, "favorable_author": 0, "power": 33, "study_point": 0, "university": {"university_id": "0", "name": "", "logo": ""}, "major": {"major_id": "0", "parent_id": "0", "name": ""}, "student_status": 0, "select_event_count": 0, "select_online_course_count": 0, "identity": 0, "is_select_annual": false, "select_annual_rank": 0, "annual_list_type": 0, "extraMap": {}, "is_logout": 0}, "category": {"category_id": "6809637767543259144", "category_name": "前端", "category_url": "frontend", "rank": 2, "back_ground": "https://lc-mhke0kuv.cn-n1.lcfile.com/8c95587526f346c0.png", "icon": "https://lc-mhke0kuv.cn-n1.lcfile.com/1c40f5eaba561e32.png", "ctime": 1457483942, "mtime": 1432503190, "show_type": 3, "item_type": 2, "promote_tag_cap": 4, "promote_priority": 2}, "tags": [{"id": 2546516, "tag_id": "6809640394175971342", "tag_name": "CSS", "color": "#244DE4", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/leancloud-assets/66de0c4eb9d10130d5bf.png~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 0, "ctime": 1432239426, "mtime": 1631688735, "id_type": 9, "tag_alias": "", "post_article_count": 14981, "concern_user_count": 297034}], "user_interact": {"id": 6844903983383838733, "omitempty": 2, "user_id": 0, "is_digg": false, "is_follow": false, "is_collect": false}, "org": {"org_info": null, "org_user": null, "is_followed": false}, "req_id": "202109151604300102121660811B004064"}, {"article_id": "6951642080737230862", "article_info": {"article_id": "6951642080737230862", "user_id": "1248693511259070", "category_id": "6809637767543259144", "tag_ids": [6809640394175971342], "visible_level": 0, "link_url": "", "cover_image": "", "is_gfw": 0, "title": "CSS系列 -- CSS 样式的四种使用方式", "brief_content": "CSS三种引入方式有内联样式内部样式表外部样式表内联样式实际在写页面时不提倡使用,在测试的时候可以使用页面渲染过程中,遍历 DOM 节点时要是遇到内联样式可能会引起重绘回流,而且内联样式的优先级较高内", "is_english": 0, "is_original": 1, "user_index": 0, "original_type": 0, "original_author": "", "content": "", "ctime": "1618555387", "mtime": "1626937848", "rtime": "1618557155", "draft_id": "6951634986252369950", "view_count": 167, "collect_count": 2, "digg_count": 1, "comment_count": 0, "hot_index": 9, "is_hot": 0, "rank_index": 0.00021119, "status": 2, "verify_status": 1, "audit_status": 2, "mark_content": ""}, "author_user_info": {"user_id": "1248693511259070", "user_name": "ALKAOUA", "company": "深圳大学 | 鹅厂实习生", "job_title": "大四学生", "avatar_large": "https://sf3-ttcdn-tos.pstatp.com/img/user-avatar/5f5db01d993c0569beee0f8124771363~300x300.image", "level": 2, "description": "前端开发", "followee_count": 3, "follower_count": 21, "post_article_count": 100, "digg_article_count": 81, "got_digg_count": 134, "got_view_count": 17766, "post_shortmsg_count": 1, "digg_shortmsg_count": 2, "isfollowed": false, "favorable_author": 0, "power": 311, "study_point": 0, "university": {"university_id": "0", "name": "", "logo": ""}, "major": {"major_id": "0", "parent_id": "0", "name": ""}, "student_status": 0, "select_event_count": 0, "select_online_course_count": 0, "identity": 0, "is_select_annual": false, "select_annual_rank": 0, "annual_list_type": 0, "extraMap": {}, "is_logout": 0}, "category": {"category_id": "6809637767543259144", "category_name": "前端", "category_url": "frontend", "rank": 2, "back_ground": "https://lc-mhke0kuv.cn-n1.lcfile.com/8c95587526f346c0.png", "icon": "https://lc-mhke0kuv.cn-n1.lcfile.com/1c40f5eaba561e32.png", "ctime": 1457483942, "mtime": 1432503190, "show_type": 3, "item_type": 2, "promote_tag_cap": 4, "promote_priority": 2}, "tags": [{"id": 2546516, "tag_id": "6809640394175971342", "tag_name": "CSS", "color": "#244DE4", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/leancloud-assets/66de0c4eb9d10130d5bf.png~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 0, "ctime": 1432239426, "mtime": 1631688735, "id_type": 9, "tag_alias": "", "post_article_count": 14981, "concern_user_count": 297034}], "user_interact": {"id": 6951642080737230862, "omitempty": 2, "user_id": 0, "is_digg": false, "is_follow": false, "is_collect": false}, "org": {"org_info": null, "org_user": null, "is_followed": false}, "req_id": "202109151604300102121660811B004064"}, {"article_id": "6844903497033318414", "article_info": {"article_id": "6844903497033318414", "user_id": "3896324936186007", "category_id": "6809637767543259144", "tag_ids": [6809640625856577549, 6809640394175971342, 6809640392770715656, 6809640398105870343], "visible_level": 0, "link_url": "http://www.zcfy.cc/article/building-the-dom-faster-speculative-parsing-async-defer-and-preload-x2605-mozilla-hacks-8211-the-web-developer-blog-4224.html?t=new", "cover_image": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/gold-user-assets/2017/9/21/a6d2e0ff7bb3e4a2b093ef30b592e28d~tplv-t2oaga2asx-image.image", "is_gfw": 0, "title": "更快地构建 DOM: 使用预解析, async, defer 以及 preload - 众成翻译", "brief_content": "在 2017年,保证我们的页面能够快速加载的手段包括压缩,资源优化到缓存,CDN,代码分割以及 tree shaking 等。 原文地址:https://hacks.mozilla.org/2017/09/building-the-dom-faster-speculative-p", "is_english": 0, "is_original": 0, "user_index": 0, "original_type": 1, "original_author": "", "content": "", "ctime": "1505994854", "mtime": "1599314041", "rtime": "1505994854", "draft_id": "0", "view_count": 1683, "collect_count": 39, "digg_count": 83, "comment_count": 3, "hot_index": 170, "is_hot": 0, "rank_index": 0.00021112, "status": 2, "verify_status": 1, "audit_status": 2, "mark_content": ""}, "author_user_info": {"user_id": "3896324936186007", "user_name": "AleCC", "company": "Null", "job_title": "前端美食工程师", "avatar_large": "https://sf6-ttcdn-tos.pstatp.com/img/user-avatar/75c79beb6d71343df8f213f6d56c9d1a~300x300.image", "level": 2, "description": "爱做饭的男人运气不会太差😉", "followee_count": 36, "follower_count": 20575, "post_article_count": 516, "digg_article_count": 1300, "got_digg_count": 37890, "got_view_count": 917741, "post_shortmsg_count": 61, "digg_shortmsg_count": 299, "isfollowed": false, "favorable_author": 0, "power": 141, "study_point": 0, "university": {"university_id": "0", "name": "", "logo": ""}, "major": {"major_id": "0", "parent_id": "0", "name": ""}, "student_status": 0, "select_event_count": 0, "select_online_course_count": 0, "identity": 0, "is_select_annual": false, "select_annual_rank": 0, "annual_list_type": 0, "extraMap": {}, "is_logout": 0}, "category": {"category_id": "6809637767543259144", "category_name": "前端", "category_url": "frontend", "rank": 2, "back_ground": "https://lc-mhke0kuv.cn-n1.lcfile.com/8c95587526f346c0.png", "icon": "https://lc-mhke0kuv.cn-n1.lcfile.com/1c40f5eaba561e32.png", "ctime": 1457483942, "mtime": 1432503190, "show_type": 3, "item_type": 2, "promote_tag_cap": 4, "promote_priority": 2}, "tags": [{"id": 2546683, "tag_id": "6809640625856577549", "tag_name": "浏览器", "color": "#47ebc7", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/leancloud-assets/baf3558e2acdfa623201.png~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 0, "ctime": 1460153459, "mtime": 1631677186, "id_type": 9, "tag_alias": "", "post_article_count": 3341, "concern_user_count": 28324}, {"id": 2546516, "tag_id": "6809640394175971342", "tag_name": "CSS", "color": "#244DE4", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/leancloud-assets/66de0c4eb9d10130d5bf.png~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 0, "ctime": 1432239426, "mtime": 1631688735, "id_type": 9, "tag_alias": "", "post_article_count": 14981, "concern_user_count": 297034}, {"id": 2546515, "tag_id": "6809640392770715656", "tag_name": "HTML", "color": "#E44D25", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/leancloud-assets/f18965b2a0ef9cac862e.png~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 0, "ctime": 1432239419, "mtime": 1631683077, "id_type": 9, "tag_alias": "", "post_article_count": 6109, "concern_user_count": 240134}, {"id": 2546519, "tag_id": "6809640398105870343", "tag_name": "JavaScript", "color": "#616161", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/leancloud-assets/5d70fd6af940df373834.png~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 0, "ctime": 1435884803, "mtime": 1631692583, "id_type": 9, "tag_alias": "", "post_article_count": 67405, "concern_user_count": 398956}], "user_interact": {"id": 6844903497033318414, "omitempty": 2, "user_id": 0, "is_digg": false, "is_follow": false, "is_collect": false}, "org": {"org_info": null, "org_user": null, "is_followed": false}, "req_id": "202109151604300102121660811B004064"}, {"article_id": "6844903625353854989", "article_info": {"article_id": "6844903625353854989", "user_id": "3298190613550462", "category_id": "6809637767543259144", "tag_ids": [6809640394175971342], "visible_level": 0, "link_url": "https://lisongfeng.cn/post/why-there-is-no-CSS4.html", "cover_image": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/gold-user-assets/2018/6/26/1643ad3faef496cc~tplv-t2oaga2asx-image.image", "is_gfw": 0, "title": "为什么不会有CSS4?", "brief_content": "为什么不会有CSS4了? 简单地说,就是从CSS3开始,CSS规范就被拆成众多模块(module)单独进行升级,或者将新需求作为一个新模块来立项并进行标准化。因此今后不会再有CSS4、CSS5这种所谓大版本号的变更,有的只是CSS某个模块级别的跃迁。 按照CSS工作组的说法,C…", "is_english": 0, "is_original": 0, "user_index": 0, "original_type": 1, "original_author": "", "content": "", "ctime": "1529995328", "mtime": "1598696974", "rtime": "1529995328", "draft_id": "0", "view_count": 2054, "collect_count": 9, "digg_count": 27, "comment_count": 0, "hot_index": 129, "is_hot": 0, "rank_index": 0.00021108, "status": 2, "verify_status": 1, "audit_status": 2, "mark_content": ""}, "author_user_info": {"user_id": "3298190613550462", "user_name": "众成翻译", "company": "", "job_title": "翻译,求知的另一种表达", "avatar_large": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/gold-user-assets/2018/3/30/16275a86e4bb52a2~tplv-t2oaga2asx-image.image", "level": 2, "description": "众成翻译官方账号", "followee_count": 35, "follower_count": 7819, "post_article_count": 567, "digg_article_count": 235, "got_digg_count": 8123, "got_view_count": 268377, "post_shortmsg_count": 1, "digg_shortmsg_count": 6, "isfollowed": false, "favorable_author": 0, "power": 416, "study_point": 0, "university": {"university_id": "0", "name": "", "logo": ""}, "major": {"major_id": "0", "parent_id": "0", "name": ""}, "student_status": 0, "select_event_count": 0, "select_online_course_count": 0, "identity": 0, "is_select_annual": false, "select_annual_rank": 0, "annual_list_type": 0, "extraMap": {}, "is_logout": 0}, "category": {"category_id": "6809637767543259144", "category_name": "前端", "category_url": "frontend", "rank": 2, "back_ground": "https://lc-mhke0kuv.cn-n1.lcfile.com/8c95587526f346c0.png", "icon": "https://lc-mhke0kuv.cn-n1.lcfile.com/1c40f5eaba561e32.png", "ctime": 1457483942, "mtime": 1432503190, "show_type": 3, "item_type": 2, "promote_tag_cap": 4, "promote_priority": 2}, "tags": [{"id": 2546516, "tag_id": "6809640394175971342", "tag_name": "CSS", "color": "#244DE4", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/leancloud-assets/66de0c4eb9d10130d5bf.png~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 0, "ctime": 1432239426, "mtime": 1631688735, "id_type": 9, "tag_alias": "", "post_article_count": 14981, "concern_user_count": 297034}], "user_interact": {"id": 6844903625353854989, "omitempty": 2, "user_id": 0, "is_digg": false, "is_follow": false, "is_collect": false}, "org": {"org_info": null, "org_user": null, "is_followed": false}, "req_id": "202109151604300102121660811B004064"}, {"article_id": "6844903673345081358", "article_info": {"article_id": "6844903673345081358", "user_id": "3210229682274766", "category_id": "6809637767543259144", "tag_ids": [6809640357354012685, 6809640394175971342, 6809640398105870343, 6809640614175604744], "visible_level": 0, "link_url": "https://juejin.im/post/6844903673345081358", "cover_image": "", "is_gfw": 0, "title": "[译] CSS 变量和 JavaScript 让应用支持动态主题", "brief_content": "大家好!在这篇文章中我准备讲一讲我在 Web 应用中创建动态主题加载器的方法。我会讲一点关于 React、Create-React-App、Portals、Sass、CSS 变量还有其它有意思的东西。如果你对此感兴趣,请继续阅读! 我正在开发的应用是一个音乐应用程序,它是 Sp…", "is_english": 0, "is_original": 1, "user_index": 0, "original_type": 0, "original_author": "", "content": "", "ctime": "1536502372", "mtime": "1599616410", "rtime": "1536558005", "draft_id": "6845075610969063431", "view_count": 1700, "collect_count": 19, "digg_count": 34, "comment_count": 0, "hot_index": 119, "is_hot": 0, "rank_index": 0.00021227, "status": 2, "verify_status": 1, "audit_status": 2, "mark_content": ""}, "author_user_info": {"user_id": "3210229682274766", "user_name": "子非", "company": "", "job_title": "前端开发工程师", "avatar_large": "https://sf3-ttcdn-tos.pstatp.com/img/user-avatar/520629266438ab7a54f1aee44a2b8f43~300x300.image", "level": 3, "description": "", "followee_count": 16, "follower_count": 2355, "post_article_count": 19, "digg_article_count": 23, "got_digg_count": 2490, "got_view_count": 163901, "post_shortmsg_count": 0, "digg_shortmsg_count": 0, "isfollowed": false, "favorable_author": 1, "power": 4129, "study_point": 0, "university": {"university_id": "0", "name": "", "logo": ""}, "major": {"major_id": "0", "parent_id": "0", "name": ""}, "student_status": 0, "select_event_count": 0, "select_online_course_count": 0, "identity": 0, "is_select_annual": false, "select_annual_rank": 0, "annual_list_type": 0, "extraMap": {}, "is_logout": 0}, "category": {"category_id": "6809637767543259144", "category_name": "前端", "category_url": "frontend", "rank": 2, "back_ground": "https://lc-mhke0kuv.cn-n1.lcfile.com/8c95587526f346c0.png", "icon": "https://lc-mhke0kuv.cn-n1.lcfile.com/1c40f5eaba561e32.png", "ctime": 1457483942, "mtime": 1432503190, "show_type": 3, "item_type": 2, "promote_tag_cap": 4, "promote_priority": 2}, "tags": [{"id": 2546490, "tag_id": "6809640357354012685", "tag_name": "React.js", "color": "#61DAFB", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/leancloud-assets/f655215074250f10f8d4.png~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 0, "ctime": 1432234367, "mtime": 1631692935, "id_type": 9, "tag_alias": "", "post_article_count": 16999, "concern_user_count": 226420}, {"id": 2546516, "tag_id": "6809640394175971342", "tag_name": "CSS", "color": "#244DE4", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/leancloud-assets/66de0c4eb9d10130d5bf.png~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 0, "ctime": 1432239426, "mtime": 1631688735, "id_type": 9, "tag_alias": "", "post_article_count": 14981, "concern_user_count": 297034}, {"id": 2546519, "tag_id": "6809640398105870343", "tag_name": "JavaScript", "color": "#616161", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/leancloud-assets/5d70fd6af940df373834.png~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 0, "ctime": 1435884803, "mtime": 1631692583, "id_type": 9, "tag_alias": "", "post_article_count": 67405, "concern_user_count": 398956}, {"id": 2546676, "tag_id": "6809640614175604744", "tag_name": "掘金翻译计划", "color": "#0081ff", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/leancloud-assets/95f7e8be776556ab8d82.png~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 0, "ctime": 1454716787, "mtime": 1631689800, "id_type": 9, "tag_alias": "", "post_article_count": 2502, "concern_user_count": 42848}], "user_interact": {"id": 6844903673345081358, "omitempty": 2, "user_id": 0, "is_digg": false, "is_follow": false, "is_collect": false}, "org": {"org_info": null, "org_user": null, "is_followed": false}, "req_id": "202109151604300102121660811B004064"}, {"article_id": "6844903713081917453", "article_info": {"article_id": "6844903713081917453", "user_id": "1521379824110743", "category_id": "6809637767543259144", "tag_ids": [6809640497393434632, 6809640407484334093, 6809640398105870343, 6809640394175971342], "visible_level": 0, "link_url": "https://juejin.im/post/6844903713081917453", "cover_image": "", "is_gfw": 0, "title": "Canvas环形倒计时组件", "brief_content": "1. html代码 2. 引入process.js文件 3. 初始化参数 canvas本身没有任何的绘图能力,所有的绘图工作都是通过js来实现的。通常我们在js通过getElementById来获取要操作的canvas(这意味着得给canvas设个id): 1.准备好画笔之后就…", "is_english": 0, "is_original": 1, "user_index": 0, "original_type": 0, "original_author": "", "content": "", "ctime": "1542110735", "mtime": "1598477675", "rtime": "1542162229", "draft_id": "6845075650647162887", "view_count": 1618, "collect_count": 29, "digg_count": 29, "comment_count": 0, "hot_index": 109, "is_hot": 0, "rank_index": 0.0002104, "status": 2, "verify_status": 1, "audit_status": 2, "mark_content": ""}, "author_user_info": {"user_id": "1521379824110743", "user_name": "RikaXia", "company": "前端开发 | 四三九九", "job_title": "", "avatar_large": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/mirror-assets/168e095b207a54471ed~tplv-t2oaga2asx-image.image", "level": 2, "description": "you can call me 仙女小", "followee_count": 35, "follower_count": 16, "post_article_count": 8, "digg_article_count": 28, "got_digg_count": 72, "got_view_count": 10529, "post_shortmsg_count": 0, "digg_shortmsg_count": 2, "isfollowed": false, "favorable_author": 0, "power": 177, "study_point": 0, "university": {"university_id": "0", "name": "", "logo": ""}, "major": {"major_id": "0", "parent_id": "0", "name": ""}, "student_status": 0, "select_event_count": 0, "select_online_course_count": 0, "identity": 0, "is_select_annual": false, "select_annual_rank": 0, "annual_list_type": 0, "extraMap": {}, "is_logout": 0}, "category": {"category_id": "6809637767543259144", "category_name": "前端", "category_url": "frontend", "rank": 2, "back_ground": "https://lc-mhke0kuv.cn-n1.lcfile.com/8c95587526f346c0.png", "icon": "https://lc-mhke0kuv.cn-n1.lcfile.com/1c40f5eaba561e32.png", "ctime": 1457483942, "mtime": 1432503190, "show_type": 3, "item_type": 2, "promote_tag_cap": 4, "promote_priority": 2}, "tags": [{"id": 2546591, "tag_id": "6809640497393434632", "tag_name": "Canvas", "color": "#F51A00", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/leancloud-assets/d21230e1c079d7706713.png~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 0, "ctime": 1439500018, "mtime": 1631692166, "id_type": 9, "tag_alias": "", "post_article_count": 2046, "concern_user_count": 60618}, {"id": 2546526, "tag_id": "6809640407484334093", "tag_name": "前端", "color": "#60ADFF", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/leancloud-assets/bac28828a49181c34110.png~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 1, "ctime": 1435971546, "mtime": 1631692835, "id_type": 9, "tag_alias": "", "post_article_count": 88828, "concern_user_count": 527704}, {"id": 2546519, "tag_id": "6809640398105870343", "tag_name": "JavaScript", "color": "#616161", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/leancloud-assets/5d70fd6af940df373834.png~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 0, "ctime": 1435884803, "mtime": 1631692583, "id_type": 9, "tag_alias": "", "post_article_count": 67405, "concern_user_count": 398956}, {"id": 2546516, "tag_id": "6809640394175971342", "tag_name": "CSS", "color": "#244DE4", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/leancloud-assets/66de0c4eb9d10130d5bf.png~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 0, "ctime": 1432239426, "mtime": 1631688735, "id_type": 9, "tag_alias": "", "post_article_count": 14981, "concern_user_count": 297034}], "user_interact": {"id": 6844903713081917453, "omitempty": 2, "user_id": 0, "is_digg": false, "is_follow": false, "is_collect": false}, "org": {"org_info": null, "org_user": null, "is_followed": false}, "req_id": "202109151604300102121660811B004064"}, {"article_id": "6844903537390911495", "article_info": {"article_id": "6844903537390911495", "user_id": "3562073404224301", "category_id": "6809637767543259144", "tag_ids": [6809640394175971342, 6809640407484334093], "visible_level": 0, "link_url": "https://zhuanlan.zhihu.com/p/32119908", "cover_image": "", "is_gfw": 0, "title": "css sprites精灵图、css图片整合、css贴图定位案例教程", "brief_content": "CSS Sprites通常被称为css精灵图,在国内也被意译为css图片整合和css贴图定位,也有人称他为雪碧图。就是将导航的背景图,按钮的背景图等有规则的合并成一张背景图,即多张图合并为一张整图,然后再利用background-position进行背景图定位的一种技术。 二、…", "is_english": 0, "is_original": 0, "user_index": 0, "original_type": 1, "original_author": "", "content": "", "ctime": "1513667829", "mtime": "1599384517", "rtime": "1513667829", "draft_id": "0", "view_count": 1879, "collect_count": 23, "digg_count": 59, "comment_count": 4, "hot_index": 156, "is_hot": 0, "rank_index": 0.00021032, "status": 2, "verify_status": 1, "audit_status": 2, "mark_content": ""}, "author_user_info": {"user_id": "3562073404224301", "user_name": "已禁用", "company": "", "job_title": "", "avatar_large": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/gold-user-assets/2019/1/7/168241351ef02be9~tplv-t2oaga2asx-image.image", "level": 3, "description": "我在这里挖掘最优质的互联网技术", "followee_count": 145, "follower_count": 15014, "post_article_count": 393, "digg_article_count": 1136, "got_digg_count": 21200, "got_view_count": 771736, "post_shortmsg_count": 250, "digg_shortmsg_count": 355, "isfollowed": false, "favorable_author": 0, "power": 2440, "study_point": 0, "university": {"university_id": "0", "name": "", "logo": ""}, "major": {"major_id": "0", "parent_id": "0", "name": ""}, "student_status": 0, "select_event_count": 0, "select_online_course_count": 0, "identity": 0, "is_select_annual": false, "select_annual_rank": 0, "annual_list_type": 0, "extraMap": {}, "is_logout": 0}, "category": {"category_id": "6809637767543259144", "category_name": "前端", "category_url": "frontend", "rank": 2, "back_ground": "https://lc-mhke0kuv.cn-n1.lcfile.com/8c95587526f346c0.png", "icon": "https://lc-mhke0kuv.cn-n1.lcfile.com/1c40f5eaba561e32.png", "ctime": 1457483942, "mtime": 1432503190, "show_type": 3, "item_type": 2, "promote_tag_cap": 4, "promote_priority": 2}, "tags": [{"id": 2546516, "tag_id": "6809640394175971342", "tag_name": "CSS", "color": "#244DE4", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/leancloud-assets/66de0c4eb9d10130d5bf.png~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 0, "ctime": 1432239426, "mtime": 1631688735, "id_type": 9, "tag_alias": "", "post_article_count": 14981, "concern_user_count": 297034}, {"id": 2546526, "tag_id": "6809640407484334093", "tag_name": "前端", "color": "#60ADFF", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/leancloud-assets/bac28828a49181c34110.png~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 1, "ctime": 1435971546, "mtime": 1631692835, "id_type": 9, "tag_alias": "", "post_article_count": 88828, "concern_user_count": 527704}], "user_interact": {"id": 6844903537390911495, "omitempty": 2, "user_id": 0, "is_digg": false, "is_follow": false, "is_collect": false}, "org": {"org_info": null, "org_user": null, "is_followed": false}, "req_id": "202109151604300102121660811B004064"}, {"article_id": "6924178754163982343", "article_info": {"article_id": "6924178754163982343", "user_id": "1935556603303512", "category_id": "6809637767543259144", "tag_ids": [6809640394175971342], "visible_level": 0, "link_url": "", "cover_image": "", "is_gfw": 0, "title": "缓动函数", "brief_content": "首先我们来认识一个缓动函数的核心。先以一个匀速运动的函数为例子 返回值是点a对应的y轴坐标,(当前运动时间,当前移动距离).", "is_english": 0, "is_original": 1, "user_index": 0, "original_type": 0, "original_author": "", "content": "", "ctime": "1612161051", "mtime": "1622537669", "rtime": "1612164133", "draft_id": "6924178568574402574", "view_count": 270, "collect_count": 1, "digg_count": 2, "comment_count": 0, "hot_index": 15, "is_hot": 0, "rank_index": 0.00021001, "status": 2, "verify_status": 1, "audit_status": 2, "mark_content": ""}, "author_user_info": {"user_id": "1935556603303512", "user_name": "一个大冰球", "company": "咖喱吨", "job_title": "地下室保安", "avatar_large": "https://sf3-ttcdn-tos.pstatp.com/img/user-avatar/2a990c2e08b69efb8e4f25e8daa290fa~300x300.image", "level": 2, "description": "睡觉", "followee_count": 4, "follower_count": 2, "post_article_count": 33, "digg_article_count": 17, "got_digg_count": 49, "got_view_count": 4932, "post_shortmsg_count": 0, "digg_shortmsg_count": 0, "isfollowed": false, "favorable_author": 0, "power": 100, "study_point": 0, "university": {"university_id": "0", "name": "", "logo": ""}, "major": {"major_id": "0", "parent_id": "0", "name": ""}, "student_status": 0, "select_event_count": 0, "select_online_course_count": 0, "identity": 0, "is_select_annual": false, "select_annual_rank": 0, "annual_list_type": 0, "extraMap": {}, "is_logout": 0}, "category": {"category_id": "6809637767543259144", "category_name": "前端", "category_url": "frontend", "rank": 2, "back_ground": "https://lc-mhke0kuv.cn-n1.lcfile.com/8c95587526f346c0.png", "icon": "https://lc-mhke0kuv.cn-n1.lcfile.com/1c40f5eaba561e32.png", "ctime": 1457483942, "mtime": 1432503190, "show_type": 3, "item_type": 2, "promote_tag_cap": 4, "promote_priority": 2}, "tags": [{"id": 2546516, "tag_id": "6809640394175971342", "tag_name": "CSS", "color": "#244DE4", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/leancloud-assets/66de0c4eb9d10130d5bf.png~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 0, "ctime": 1432239426, "mtime": 1631688735, "id_type": 9, "tag_alias": "", "post_article_count": 14981, "concern_user_count": 297034}], "user_interact": {"id": 6924178754163982343, "omitempty": 2, "user_id": 0, "is_digg": false, "is_follow": false, "is_collect": false}, "org": {"org_info": null, "org_user": null, "is_followed": false}, "req_id": "202109151604300102121660811B004064"}, {"article_id": "6981814438802243592", "article_info": {"article_id": "6981814438802243592", "user_id": "1794043877266509", "category_id": "6809637767543259144", "tag_ids": [6809640407484334093, 6809640394175971342], "visible_level": 0, "link_url": "", "cover_image": "", "is_gfw": 0, "title": "CSS3 新增属性:背景", "brief_content": "background-image CSS3 中可以通过 background-image 属性添加背景图片。", "is_english": 0, "is_original": 1, "user_index": 0.278187917751123, "original_type": 0, "original_author": "", "content": "", "ctime": "1625580459", "mtime": "1625634195", "rtime": "1625634195", "draft_id": "6981813515250040846", "view_count": 72, "collect_count": 0, "digg_count": 0, "comment_count": 0, "hot_index": 3, "is_hot": 0, "rank_index": 0.00020979, "status": 2, "verify_status": 1, "audit_status": 2, "mark_content": ""}, "author_user_info": {"user_id": "1794043877266509", "user_name": "前小小", "company": "", "job_title": "", "avatar_large": "https://sf3-ttcdn-tos.pstatp.com/img/user-avatar/59bb214c9345c23b213f410dabe64517~300x300.image", "level": 2, "description": "", "followee_count": 1, "follower_count": 6, "post_article_count": 80, "digg_article_count": 29, "got_digg_count": 62, "got_view_count": 5534, "post_shortmsg_count": 0, "digg_shortmsg_count": 0, "isfollowed": false, "favorable_author": 0, "power": 117, "study_point": 0, "university": {"university_id": "0", "name": "", "logo": ""}, "major": {"major_id": "0", "parent_id": "0", "name": ""}, "student_status": 0, "select_event_count": 0, "select_online_course_count": 0, "identity": 0, "is_select_annual": false, "select_annual_rank": 0, "annual_list_type": 0, "extraMap": {}, "is_logout": 0}, "category": {"category_id": "6809637767543259144", "category_name": "前端", "category_url": "frontend", "rank": 2, "back_ground": "https://lc-mhke0kuv.cn-n1.lcfile.com/8c95587526f346c0.png", "icon": "https://lc-mhke0kuv.cn-n1.lcfile.com/1c40f5eaba561e32.png", "ctime": 1457483942, "mtime": 1432503190, "show_type": 3, "item_type": 2, "promote_tag_cap": 4, "promote_priority": 2}, "tags": [{"id": 2546526, "tag_id": "6809640407484334093", "tag_name": "前端", "color": "#60ADFF", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/leancloud-assets/bac28828a49181c34110.png~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 1, "ctime": 1435971546, "mtime": 1631692835, "id_type": 9, "tag_alias": "", "post_article_count": 88828, "concern_user_count": 527704}, {"id": 2546516, "tag_id": "6809640394175971342", "tag_name": "CSS", "color": "#244DE4", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/leancloud-assets/66de0c4eb9d10130d5bf.png~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 0, "ctime": 1432239426, "mtime": 1631688735, "id_type": 9, "tag_alias": "", "post_article_count": 14981, "concern_user_count": 297034}], "user_interact": {"id": 6981814438802243592, "omitempty": 2, "user_id": 0, "is_digg": false, "is_follow": false, "is_collect": false}, "org": {"org_info": null, "org_user": null, "is_followed": false}, "req_id": "202109151604300102121660811B004064"}, {"article_id": "6977325366515859492", "article_info": {"article_id": "6977325366515859492", "user_id": "1918010987388829", "category_id": "6809637767543259144", "tag_ids": [6809640394175971342, 6809640407484334093], "visible_level": 0, "link_url": "", "cover_image": "https://p1-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/8e6ebb3ba24447908318deb2f0b7a164~tplv-k3u1fbpfcp-watermark.image", "is_gfw": 0, "title": "CSS基础知识要点(Y1)", "brief_content": "一、什么是CSS? 二、为什么要使用CSS? 三、CSS语法 四、CSS的三种用法 五、元素的三大类型", "is_english": 0, "is_original": 1, "user_index": 0, "original_type": 0, "original_author": "", "content": "", "ctime": "1624535166", "mtime": "1624602356", "rtime": "1624602356", "draft_id": "6977317809235689479", "view_count": 77, "collect_count": 0, "digg_count": 1, "comment_count": 0, "hot_index": 4, "is_hot": 0, "rank_index": 0.00020973, "status": 2, "verify_status": 1, "audit_status": 2, "mark_content": ""}, "author_user_info": {"user_id": "1918010987388829", "user_name": "Web程序贵", "company": "南京巅峰数据服务有限公司", "job_title": "前端开发实习生", "avatar_large": "https://sf3-ttcdn-tos.pstatp.com/img/user-avatar/6790a317242054936b8b900663fa6fc5~300x300.image", "level": 1, "description": "前端小白,只会基础知识。", "followee_count": 5, "follower_count": 6, "post_article_count": 25, "digg_article_count": 8, "got_digg_count": 17, "got_view_count": 1455, "post_shortmsg_count": 1, "digg_shortmsg_count": 0, "isfollowed": false, "favorable_author": 0, "power": 31, "study_point": 0, "university": {"university_id": "0", "name": "", "logo": ""}, "major": {"major_id": "0", "parent_id": "0", "name": ""}, "student_status": 0, "select_event_count": 0, "select_online_course_count": 0, "identity": 0, "is_select_annual": false, "select_annual_rank": 0, "annual_list_type": 0, "extraMap": {}, "is_logout": 0}, "category": {"category_id": "6809637767543259144", "category_name": "前端", "category_url": "frontend", "rank": 2, "back_ground": "https://lc-mhke0kuv.cn-n1.lcfile.com/8c95587526f346c0.png", "icon": "https://lc-mhke0kuv.cn-n1.lcfile.com/1c40f5eaba561e32.png", "ctime": 1457483942, "mtime": 1432503190, "show_type": 3, "item_type": 2, "promote_tag_cap": 4, "promote_priority": 2}, "tags": [{"id": 2546516, "tag_id": "6809640394175971342", "tag_name": "CSS", "color": "#244DE4", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/leancloud-assets/66de0c4eb9d10130d5bf.png~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 0, "ctime": 1432239426, "mtime": 1631688735, "id_type": 9, "tag_alias": "", "post_article_count": 14981, "concern_user_count": 297034}, {"id": 2546526, "tag_id": "6809640407484334093", "tag_name": "前端", "color": "#60ADFF", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/leancloud-assets/bac28828a49181c34110.png~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 1, "ctime": 1435971546, "mtime": 1631692835, "id_type": 9, "tag_alias": "", "post_article_count": 88828, "concern_user_count": 527704}], "user_interact": {"id": 6977325366515859492, "omitempty": 2, "user_id": 0, "is_digg": false, "is_follow": false, "is_collect": false}, "org": {"org_info": null, "org_user": null, "is_followed": false}, "req_id": "202109151604300102121660811B004064"}, {"article_id": "6966480459492491271", "article_info": {"article_id": "6966480459492491271", "user_id": "3922654381483533", "category_id": "6809637767543259144", "tag_ids": [6809640394175971342], "visible_level": 0, "link_url": "", "cover_image": "", "is_gfw": 0, "title": "day11 CSS BFC", "brief_content": "BFC 常见定位方法 普通流 浮动 绝对定位 BFC的概念 Formatting context(格式化上下文) 是 W3C CSS2.1 规范中的一个概念。它是页面中的一块渲染区域,并且有一套渲染规", "is_english": 0, "is_original": 1, "user_index": 0, "original_type": 0, "original_author": "", "content": "", "ctime": "1622010182", "mtime": "1622016708", "rtime": "1622016708", "draft_id": "6966135224577032205", "view_count": 129, "collect_count": 0, "digg_count": 0, "comment_count": 0, "hot_index": 6, "is_hot": 0, "rank_index": 0.0002097, "status": 2, "verify_status": 1, "audit_status": 2, "mark_content": ""}, "author_user_info": {"user_id": "3922654381483533", "user_name": "刘大拿吃橘子", "company": "", "job_title": "前端", "avatar_large": "https://sf1-ttcdn-tos.pstatp.com/img/user-avatar/fb23a39d7190f565fc74381722b35d94~300x300.image", "level": 1, "description": "一个前端", "followee_count": 2, "follower_count": 2, "post_article_count": 18, "digg_article_count": 2, "got_digg_count": 8, "got_view_count": 1087, "post_shortmsg_count": 0, "digg_shortmsg_count": 0, "isfollowed": false, "favorable_author": 0, "power": 18, "study_point": 0, "university": {"university_id": "0", "name": "", "logo": ""}, "major": {"major_id": "0", "parent_id": "0", "name": ""}, "student_status": 0, "select_event_count": 0, "select_online_course_count": 0, "identity": 0, "is_select_annual": false, "select_annual_rank": 0, "annual_list_type": 0, "extraMap": {}, "is_logout": 0}, "category": {"category_id": "6809637767543259144", "category_name": "前端", "category_url": "frontend", "rank": 2, "back_ground": "https://lc-mhke0kuv.cn-n1.lcfile.com/8c95587526f346c0.png", "icon": "https://lc-mhke0kuv.cn-n1.lcfile.com/1c40f5eaba561e32.png", "ctime": 1457483942, "mtime": 1432503190, "show_type": 3, "item_type": 2, "promote_tag_cap": 4, "promote_priority": 2}, "tags": [{"id": 2546516, "tag_id": "6809640394175971342", "tag_name": "CSS", "color": "#244DE4", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/leancloud-assets/66de0c4eb9d10130d5bf.png~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 0, "ctime": 1432239426, "mtime": 1631688735, "id_type": 9, "tag_alias": "", "post_article_count": 14981, "concern_user_count": 297034}], "user_interact": {"id": 6966480459492491271, "omitempty": 2, "user_id": 0, "is_digg": false, "is_follow": false, "is_collect": false}, "org": {"org_info": null, "org_user": null, "is_followed": false}, "req_id": "202109151604300102121660811B004064"}, {"article_id": "6844903685147852808", "article_info": {"article_id": "6844903685147852808", "user_id": "114004938731069", "category_id": "6809637767543259144", "tag_ids": [6809640394175971342, 6809640398105870343, 6809640407484334093, 6809640450249457671], "visible_level": 0, "link_url": "https://juejin.im/post/6844903685147852808", "cover_image": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/gold-user-assets/2018/9/28/1661e16c4494838b~tplv-t2oaga2asx-image.image", "is_gfw": 0, "title": "提高网页设计里文本的易读性", "brief_content": "网页设计中,文本是最常用的元素之一,文本易读性非常重要,我们都希望页面更加清晰易读,而颜色在文本易读性中起到了至关重要的作用。 文本和背景颜色有一个“对比度”,了解并能正确调整这个对比度,将会让你的页面更加清晰易读,进而提高阅读效率和阅读体验。 上面的两个案例,本质上都是文本色…", "is_english": 0, "is_original": 1, "user_index": 0, "original_type": 0, "original_author": "", "content": "", "ctime": "1538103108", "mtime": "1599624866", "rtime": "1538115437", "draft_id": "6845075622654394376", "view_count": 1719, "collect_count": 20, "digg_count": 30, "comment_count": 0, "hot_index": 115, "is_hot": 0, "rank_index": 0.00020967, "status": 2, "verify_status": 1, "audit_status": 2, "mark_content": ""}, "author_user_info": {"user_id": "114004938731069", "user_name": "dwb", "company": "香格里拉", "job_title": "前端工程师", "avatar_large": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/gold-user-assets/2018/9/28/1661e196804bdf03~tplv-t2oaga2asx-image.image", "level": 1, "description": "web development / design", "followee_count": 3, "follower_count": 7, "post_article_count": 3, "digg_article_count": 3, "got_digg_count": 61, "got_view_count": 2826, "post_shortmsg_count": 0, "digg_shortmsg_count": 2, "isfollowed": false, "favorable_author": 0, "power": 89, "study_point": 0, "university": {"university_id": "0", "name": "", "logo": ""}, "major": {"major_id": "0", "parent_id": "0", "name": ""}, "student_status": 0, "select_event_count": 0, "select_online_course_count": 0, "identity": 0, "is_select_annual": false, "select_annual_rank": 0, "annual_list_type": 0, "extraMap": {}, "is_logout": 0}, "category": {"category_id": "6809637767543259144", "category_name": "前端", "category_url": "frontend", "rank": 2, "back_ground": "https://lc-mhke0kuv.cn-n1.lcfile.com/8c95587526f346c0.png", "icon": "https://lc-mhke0kuv.cn-n1.lcfile.com/1c40f5eaba561e32.png", "ctime": 1457483942, "mtime": 1432503190, "show_type": 3, "item_type": 2, "promote_tag_cap": 4, "promote_priority": 2}, "tags": [{"id": 2546516, "tag_id": "6809640394175971342", "tag_name": "CSS", "color": "#244DE4", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/leancloud-assets/66de0c4eb9d10130d5bf.png~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 0, "ctime": 1432239426, "mtime": 1631688735, "id_type": 9, "tag_alias": "", "post_article_count": 14981, "concern_user_count": 297034}, {"id": 2546519, "tag_id": "6809640398105870343", "tag_name": "JavaScript", "color": "#616161", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/leancloud-assets/5d70fd6af940df373834.png~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 0, "ctime": 1435884803, "mtime": 1631692583, "id_type": 9, "tag_alias": "", "post_article_count": 67405, "concern_user_count": 398956}, {"id": 2546526, "tag_id": "6809640407484334093", "tag_name": "前端", "color": "#60ADFF", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/leancloud-assets/bac28828a49181c34110.png~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 1, "ctime": 1435971546, "mtime": 1631692835, "id_type": 9, "tag_alias": "", "post_article_count": 88828, "concern_user_count": 527704}, {"id": 2546557, "tag_id": "6809640450249457671", "tag_name": "Material Design", "color": "#00BCD6", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/leancloud-assets/aed9805dc6109e304f1d.png~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 0, "ctime": 1436204668, "mtime": 1631638506, "id_type": 9, "tag_alias": "", "post_article_count": 436, "concern_user_count": 72761}], "user_interact": {"id": 6844903685147852808, "omitempty": 2, "user_id": 0, "is_digg": false, "is_follow": false, "is_collect": false}, "org": {"org_info": null, "org_user": null, "is_followed": false}, "req_id": "202109151604300102121660811B004064"}, {"article_id": "6919744194428796941", "article_info": {"article_id": "6919744194428796941", "user_id": "2928754709772872", "category_id": "6809637767543259144", "tag_ids": [6809640394175971342], "visible_level": 0, "link_url": "", "cover_image": "", "is_gfw": 0, "title": "BFC 块级格式化上下文(较完善版)", "brief_content": "理论来讲,包裹在父元素里的元素,不会影响父元素旁边的元素,但实际上并不总是如此,那有没有什么办法可以让里面的元素与外部真正隔离开来呢?可以试试BFC。 BFC Block Formating Context 块级格式化上下文,是一个独立渲染区域,主要是隔离保护作用。也就是说BF…", "is_english": 0, "is_original": 1, "user_index": 0, "original_type": 0, "original_author": "", "content": "", "ctime": "1611128527", "mtime": "1611140514", "rtime": "1611128752", "draft_id": "6919741170843123726", "view_count": 274, "collect_count": 3, "digg_count": 2, "comment_count": 1, "hot_index": 16, "is_hot": 0, "rank_index": 0.00020944, "status": 2, "verify_status": 1, "audit_status": 2, "mark_content": ""}, "author_user_info": {"user_id": "2928754709772872", "user_name": "Pennie", "company": "", "job_title": "", "avatar_large": "https://sf1-ttcdn-tos.pstatp.com/img/user-avatar/959bb66b4d7e6c28e4eeddee3617c9ea~300x300.image", "level": 1, "description": "", "followee_count": 1, "follower_count": 1, "post_article_count": 1, "digg_article_count": 0, "got_digg_count": 2, "got_view_count": 274, "post_shortmsg_count": 0, "digg_shortmsg_count": 0, "isfollowed": false, "favorable_author": 0, "power": 4, "study_point": 0, "university": {"university_id": "0", "name": "", "logo": ""}, "major": {"major_id": "0", "parent_id": "0", "name": ""}, "student_status": 0, "select_event_count": 0, "select_online_course_count": 0, "identity": 0, "is_select_annual": false, "select_annual_rank": 0, "annual_list_type": 0, "extraMap": {}, "is_logout": 0}, "category": {"category_id": "6809637767543259144", "category_name": "前端", "category_url": "frontend", "rank": 2, "back_ground": "https://lc-mhke0kuv.cn-n1.lcfile.com/8c95587526f346c0.png", "icon": "https://lc-mhke0kuv.cn-n1.lcfile.com/1c40f5eaba561e32.png", "ctime": 1457483942, "mtime": 1432503190, "show_type": 3, "item_type": 2, "promote_tag_cap": 4, "promote_priority": 2}, "tags": [{"id": 2546516, "tag_id": "6809640394175971342", "tag_name": "CSS", "color": "#244DE4", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/leancloud-assets/66de0c4eb9d10130d5bf.png~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 0, "ctime": 1432239426, "mtime": 1631688735, "id_type": 9, "tag_alias": "", "post_article_count": 14981, "concern_user_count": 297034}], "user_interact": {"id": 6919744194428796941, "omitempty": 2, "user_id": 0, "is_digg": false, "is_follow": false, "is_collect": false}, "org": {"org_info": null, "org_user": null, "is_followed": false}, "req_id": "202109151604300102121660811B004064"}], "cursor": "eyJ2IjoiNzAwNzgwMzIxNDc1ODE1MDE3NSIsImkiOjM0ODB9", "count": 4601, "has_more": true}
[ "www.1759633997@qq.com" ]
www.1759633997@qq.com
305c1d5c727d5961cbda6d9218376a6e0b1f7e8c
7944d2fd5d885a034347a986f3114f0b81166447
/facebookads/adobjects/transactioncurrencyamount.py
a8258dea5f141931966835b4349ea71a84f93500
[]
no_license
it-devros/django-facebook-api
4fd94d1bbbff664f0314e046f50d91ee959f5664
ee2d91af49bc2be116bd10bd079c321bbf6af721
refs/heads/master
2021-06-23T06:29:07.664905
2019-06-25T07:47:50
2019-06-25T07:47:50
191,458,626
2
0
null
2021-06-10T21:33:08
2019-06-11T22:22:47
Python
UTF-8
Python
false
false
1,864
py
# Copyright 2014 Facebook, Inc. # You are hereby granted a non-exclusive, worldwide, royalty-free license to # use, copy, modify, and distribute this software in source code or binary # form for use in connection with the web services and APIs provided by # Facebook. # As with any software that integrates with the Facebook platform, your use # of this software is subject to the Facebook Developer Principles and # Policies [http://developers.facebook.com/policy/]. This copyright notice # shall be included in all copies or substantial portions of the software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. from facebookads.adobjects.abstractobject import AbstractObject """ This class is auto-generated. For any issues or feature requests related to this class, please let us know on github and we'll fix in our codegen framework. We'll not be able to accept pull request for this class. """ class TransactionCurrencyAmount( AbstractObject, ): def __init__(self, api=None): super(TransactionCurrencyAmount, self).__init__() self._isTransactionCurrencyAmount = True self._api = api class Field(AbstractObject.Field): amount = 'amount' currency = 'currency' total_amount = 'total_amount' _field_types = { 'amount': 'string', 'currency': 'string', 'total_amount': 'string', } @classmethod def _get_field_enum_info(cls): field_enum_info = {} return field_enum_info
[ "it-devros@outlook.com" ]
it-devros@outlook.com
1fbaf1949e4010bbf72b7c8c23c1bcba96b43012
0b9e588b3d6ddf95d87a0a0f02d10ef6efcccf51
/eduapi/analytics/models.py
d9d7a52d0e60648209033a8328d81b20c002dbb3
[]
no_license
omni360/inspiration-edu-api
b5d07a7fe3a473689d5323e60e6f88dd3d6fb4cb
6e1bbf8d895082d4c44af4ae35b9f5aa5cc9addc
refs/heads/master
2022-01-22T23:30:09.879433
2016-04-28T02:02:46
2016-04-28T02:02:46
57,559,736
0
0
null
2022-01-06T22:24:03
2016-05-01T06:35:12
Python
UTF-8
Python
false
false
30
py
from api.models import Project
[ "frida.cai@autodesk.com" ]
frida.cai@autodesk.com
ff93921ebd8c703b4a92793b7feac4e91c7c11f6
b05761d771bb5a85d39d370c649567c1ff3eb089
/venv/lib/python3.10/site-packages/google/protobuf/unknown_fields.py
172028c1fce1769a75be9b83aa83ec41ca749cf7
[]
no_license
JawshyJ/Coding_Practice
88c49cab955eab04609ec1003b6b8c20f103fc06
eb6b229d41aa49b1545af2120e6bee8e982adb41
refs/heads/master
2023-02-19T10:18:04.818542
2023-02-06T21:22:58
2023-02-06T21:22:58
247,788,631
4
0
null
null
null
null
UTF-8
Python
false
false
96
py
/home/runner/.cache/pip/pool/b0/c6/91/ac8a4d83d0130a6cf50b629b1194b74f0949be3b5bca5aa9b102cfcf97
[ "37465112+JawshyJ@users.noreply.github.com" ]
37465112+JawshyJ@users.noreply.github.com
6306d40d8de8fa5309662dd4786bb511bd60a1f6
4182f5c371c15b8f79bc744b8bed0965ffd13c79
/backend/pytx/views.py
fc5d4aa8a7a85c01fd20e630902f9ff9259702e4
[]
no_license
pytexas/PyTexas2015
f4db37a7d43ee523272311139f480189ecba02cd
f4648581a197e2f9387f61c2b94a8f178298becc
refs/heads/master
2021-05-30T18:47:47.431250
2015-11-21T20:52:43
2015-11-21T20:52:43
17,159,683
2
0
null
null
null
null
UTF-8
Python
false
false
914
py
import os import subprocess from django import http from django.views import static from django.conf import settings from pytx.utils import index_generator def favicon(request): return static.serve(request, 'favicon.ico', settings.FRONT_ROOT) def default_conf(request): return http.HttpResponseRedirect(settings.DEFAULT_CONF + '/') def index(request, conf_slug): conf_slug = conf_slug.split('/')[0] html = index_generator(conf_slug, dev=True) return http.HttpResponse(html) def less_view(request): less = os.path.join(settings.BASE_DIR, '..', 'frontend', 'css', 'pytx.less') pipe = subprocess.Popen( "lessc {}".format(less), shell=True, stdout=subprocess.PIPE) return http.HttpResponse(pipe.stdout, content_type="text/css") def frontend(request, *args, **kwargs): return http.HttpResponse( "Front-End Should Serve This URL", content_type="text/plain")
[ "paul.m.bailey@gmail.com" ]
paul.m.bailey@gmail.com
a6faf47fb558554f6674362748930f2d99227172
83de24182a7af33c43ee340b57755e73275149ae
/aliyun-python-sdk-sae/aliyunsdksae/request/v20190506/UpdateNamespaceRequest.py
dccc5256a59542e159be6e9d83c4f970cab07b3c
[ "Apache-2.0" ]
permissive
aliyun/aliyun-openapi-python-sdk
4436ca6c57190ceadbc80f0b1c35b1ab13c00c7f
83fd547946fd6772cf26f338d9653f4316c81d3c
refs/heads/master
2023-08-04T12:32:57.028821
2023-08-04T06:00:29
2023-08-04T06:00:29
39,558,861
1,080
721
NOASSERTION
2023-09-14T08:51:06
2015-07-23T09:39:45
Python
UTF-8
Python
false
false
2,483
py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # # http://www.apache.org/licenses/LICENSE-2.0 # # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from aliyunsdkcore.request import RoaRequest from aliyunsdksae.endpoint import endpoint_data class UpdateNamespaceRequest(RoaRequest): def __init__(self): RoaRequest.__init__(self, 'sae', '2019-05-06', 'UpdateNamespace','serverless') self.set_uri_pattern('/pop/v1/paas/namespace') self.set_method('PUT') if hasattr(self, "endpoint_map"): setattr(self, "endpoint_map", endpoint_data.getEndpointMap()) if hasattr(self, "endpoint_regional"): setattr(self, "endpoint_regional", endpoint_data.getEndpointRegional()) def get_NamespaceName(self): # String return self.get_query_params().get('NamespaceName') def set_NamespaceName(self, NamespaceName): # String self.add_query_param('NamespaceName', NamespaceName) def get_NamespaceDescription(self): # String return self.get_query_params().get('NamespaceDescription') def set_NamespaceDescription(self, NamespaceDescription): # String self.add_query_param('NamespaceDescription', NamespaceDescription) def get_EnableMicroRegistration(self): # Boolean return self.get_query_params().get('EnableMicroRegistration') def set_EnableMicroRegistration(self, EnableMicroRegistration): # Boolean self.add_query_param('EnableMicroRegistration', EnableMicroRegistration) def get_NamespaceId(self): # String return self.get_query_params().get('NamespaceId') def set_NamespaceId(self, NamespaceId): # String self.add_query_param('NamespaceId', NamespaceId) def get_NameSpaceShortId(self): # String return self.get_query_params().get('NameSpaceShortId') def set_NameSpaceShortId(self, NameSpaceShortId): # String self.add_query_param('NameSpaceShortId', NameSpaceShortId)
[ "sdk-team@alibabacloud.com" ]
sdk-team@alibabacloud.com
ed26c4174c273e492eba64f98d9537ec1ad20864
f3d38d0e1d50234ce5f17948361a50090ea8cddf
/CodeUp/파이썬 풀이/1230번 ; 터널 통과하기 2.py
3d02cf7a4fd78a7e1ee60df5860d0451ae9e76c7
[]
no_license
bright-night-sky/algorithm_study
967c512040c183d56c5cd923912a5e8f1c584546
8fd46644129e92137a62db657187b9b707d06985
refs/heads/main
2023-08-01T10:27:33.857897
2021-10-04T14:36:21
2021-10-04T14:36:21
323,322,211
0
0
null
null
null
null
UTF-8
Python
false
false
1,574
py
# https://codeup.kr/problem.php?id=1230 # readline을 사용하기 위해 import합니다. from sys import stdin # 세 터널의 높이 a, b, c를 공백으로 구분해 입력합니다. # 각각 int형으로 변환합니다. a, b, c = map(int, stdin.readline().split()) # 세 터널의 높이 a, b, c를 차례대로 170 보다 큰 지 검사해봅니다. # 첫 번째 터널의 높이가 170 초과라면 if a > 170: # 두 번째 터널의 높이가 170 초과라면 if b > 170: # 세 번째 터널의 높이가 170 초과라면 if c > 170: # 세 터널 모두 170 초과이므로 차가 잘 통과합니다. # 문자열 'PASS'를 출력합니다. print('PASS') # 첫 번째, 두 번째 터널은 통과했는데 # 세 번째 터널의 높이가 170 이하라면 else: # 세 번째 터널에서 사고가 나므로 문자열 'CRASH'와 # 세 번째 터널의 높이 c값을 공백으로 구분해 출력합니다. print('CRASH', c) # 첫 번째 터널은 통과했는데 # 두 번째 터널의 높이가 170 이하라면 else: # 두 번째 터널에서 사고가 나므로 문자열 'CRASH'와 # 두 번째 터널의 높이 b값을 공백으로 구분해 출력합니다. print('CRASH', b) # 첫 번째 터널의 높이가 170 이하라면 else: # 첫 번째 터널에서 사고가 나므로 문자열 'CRASH'와 # 첫 번째 터널의 높이 a값을 공백으로 구분해 출력합니다. print('CRASH', a)
[ "bright_night_sky@naver.com" ]
bright_night_sky@naver.com
a19e8ca6e4d0aacdea80fd56b4f663d4369843c5
9795dda526b3436de26c73353021a0651a6762f9
/pyefun/typeConv.py
6d16e72c8caf0defa6bb38fc430f6bf3af2868de
[ "Apache-2.0" ]
permissive
brucekk4/pyefun
891fc08897e4662823cf9016a680c07b31a8d5be
1b4d8e13ee2c59574fded792e3f2a77e0b5e11a2
refs/heads/master
2023-07-10T03:54:11.437283
2021-08-23T17:46:19
2021-08-23T17:46:19
null
0
0
null
null
null
null
UTF-8
Python
false
false
566
py
""" .. Hint:: 类型转换 .. literalinclude:: ../../../pyefun/typeConv_test.py :language: python :caption: 代码示例 :linenos: """ from .timeBase import * import json def 到文本(bytes): return str(bytes, encoding="utf-8") def 到字节集(str): return bytes(str, encoding='utf-8') def 到数值(val): return float(val) def 到整数(val): return int(float(val)) def 到时间(str): return 创建日期时间(str) def json到文本(obj): return json.dumps(obj) def json解析(obj): return json.loads(obj)
[ "ll@163.com" ]
ll@163.com
41017bba584e3df78520c70725466e1e02d28e2d
ad0e853db635edc578d58891b90f8e45a72a724f
/python/ray/train/lightning/__init__.py
a827dcd064ab3cc2b3b8ce362535db6e20395342
[ "BSD-3-Clause", "MIT", "Apache-2.0" ]
permissive
ericl/ray
8c93fc713af3b753215d4fe6221278700936e2db
e9a1c6d814fb1a81033809f56695030d651388f5
refs/heads/master
2023-08-31T11:53:23.584855
2023-06-07T21:04:28
2023-06-07T21:04:28
91,077,004
2
4
Apache-2.0
2023-01-11T17:19:10
2017-05-12T09:51:04
Python
UTF-8
Python
false
false
638
py
# isort: off try: import pytorch_lightning # noqa: F401 except ModuleNotFoundError: raise ModuleNotFoundError( "PyTorch Lightning isn't installed. To install PyTorch Lightning, " "please run 'pip install pytorch-lightning'" ) # isort: on from ray.train.lightning.lightning_checkpoint import LightningCheckpoint from ray.train.lightning.lightning_predictor import LightningPredictor from ray.train.lightning.lightning_trainer import ( LightningTrainer, LightningConfigBuilder, ) __all__ = [ "LightningTrainer", "LightningConfigBuilder", "LightningCheckpoint", "LightningPredictor", ]
[ "noreply@github.com" ]
ericl.noreply@github.com
b73ea34e6add92014bf1249f36194a4bccd11194
6921b29c09905e910c97c799fdb1c5249dff0274
/pyocd/coresight/gpr.py
b0ecaff545f1a43b824d27b15bc33ad403f98186
[ "Apache-2.0" ]
permissive
huaqli/pyOCD
b476a0d58cf55cc4855bea33b2c7a3afc37f7f35
ee8324de9e0219a0e6e28e686c81fa5af3637479
refs/heads/master
2022-04-16T17:22:33.861865
2020-04-20T16:44:07
2020-04-20T16:44:07
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,215
py
# pyOCD debugger # Copyright (c) 2018 Arm Limited # SPDX-License-Identifier: Apache-2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from .component import CoreSightComponent from ..utility.timeout import Timeout ACK_TIMEOUT = 5.0 class GPR(CoreSightComponent): """! @brief Granular Power Requestor. Currently only supports enabling power domains. """ CPWRUPREQ = 0x0 CPWRUPACK = 0x0 CPWRUPM_COUNT_MASK = 0x3f @classmethod def factory(cls, ap, cmpid, address): # Attempt to return the same instance that was created during ROM table scanning. if cmpid.parent_rom_table is not None: rom_gpr = cmpid.parent_rom_table.gpr if rom_gpr is not None and rom_gpr.address == address: return rom_gpr # No luck, create a new instance. gpr = cls(ap, cmpid, address) return gpr def __init__(self, ap, cmpid=None, addr=None): super(GPR, self).__init__(ap, cmpid, addr) def init(self): """! @brief Inits the GPR.""" self.domain_count = self.cmpid.devid[2] & self.CPWRUPM_COUNT_MASK def _power_up(self, mask): """! @brief Enable power to a power domaind by mask. @param self @param mask Bitmask of the domains to power up. @retval True Requested domains were successfully powered on. @return False Timeout waiting for power ack bit(s) to set. """ # Enable power up request bits. self.ap.write32(self.address + self.CPWRUPREQ, mask) # Wait for ack bits to set. with Timeout(ACK_TIMEOUT) as t_o: while t_o.check(): value = self.ap.read32(self.address + self.CPWRUPACK) if (value & mask) == mask: return True else: return False def power_up_all(self): """! @brief Enable power to all available power domains. @param self @retval True All domains were successfully powered on. @return False Timeout waiting for power ack bit(s) to set. """ mask = (1 << self.domain_count) - 1 return self._power_up(mask) def power_up_one(self, domain_id): """! @brief Power up a single power domain by domain ID. @param self @param domain_id Integer power domain ID. @retval True Requested domain was powered on successfully. @return False Timeout waiting for power ack bit to set. """ mask = 1 << domain_id return self._power_up(mask) def __repr__(self): return "<GPR @ %x: count=%d>" % (id(self), self.domain_count)
[ "flit@me.com" ]
flit@me.com
69c02c736463a9b65e274fce99476ca679810c4f
2603f28e3dc17ae2409554ee6e1cbd315a28b732
/ABC181/prob_d.py
4907374640a893c516218398622363e984976b2f
[]
no_license
steinstadt/AtCoder
69f172280e89f4249e673cae9beab9428e2a4369
cd6c7f577fcf0cb4c57ff184afdc163f7501acf5
refs/heads/master
2020-12-23T12:03:29.124134
2020-11-22T10:47:40
2020-11-22T10:47:40
237,144,420
0
0
null
null
null
null
UTF-8
Python
false
false
1,389
py
# Problem D - Hachi from itertools import permutations # input S = list(input()) # initialization ans = False def conv_nums(nums): num_list = [0] * 10 conv_result = [] for n in nums: num_list[n] += 1 for i in range(1, 10): if num_list[i]==0: continue if num_list[i]>3: num_list[i] = 3 for j in range(num_list[i]): conv_result.append(str(i)) return conv_result def check_eight(num): if not num%2==0: return False tmp_1 = num // 2 tmp_1 = str(tmp_1) tmp_1 = int(tmp_1[-2] + tmp_1[-1]) if not tmp_1%4==0: return False return True # check if len(S)==1: tmp = int(S[0]) if tmp%8==0: ans = True elif len(S)==2: tmp = int(S[0] + S[1]) if tmp%8==0: ans = True tmp = int(S[1] + S[0]) if tmp%8==0: ans = True else: T = list(map(int, S)) T = conv_nums(T) # 数字の集合をまとめる T_len = len(T) for i in range(T_len-2): for j in range(i+1, T_len-1): for k in range(j+1, T_len): tmp_list = [T[i], T[j], T[k]] for tmp_p in permutations(tmp_list): check_result = check_eight(int("".join(tmp_p))) if check_result: ans = True # output if ans: print("Yes") else: print("No")
[ "steinstadt@keio.jp" ]
steinstadt@keio.jp
a5e75047a5d44c391ab9fe5a3c6909b31a774f11
0f54a2a03fba8e231bfd2a14785a7f091b4b88ac
/WeeklyProcessor/3. Analysing & Cleaning Content/column_cleaners/business_cleaner.py
6d08b30c9eb7d94fa33c09233a891de80532a431
[]
no_license
LukaszMalucha/WeeklyProcessor
ced08869397e54fb7c0a26a53a760c74868942c8
b9c787248f41f6a30e34c4c13db08ce4d0834f52
refs/heads/master
2022-06-01T08:40:25.377037
2020-05-03T18:13:21
2020-05-03T18:13:21
243,991,681
0
0
null
null
null
null
UTF-8
Python
false
false
637
py
# -*- coding: utf-8 -*- """ Created on Wed Feb 19 17:55:52 2020 @author: jmalucl """ def business_cleaner(dataset): dataset['Business'].fillna("Not Specified") # REMOVE (OTHER CHOICES AVAILABLE) dataset['Business'] = dataset['Business'].str.replace("other choices available", "") dataset['Business'] = dataset['Business'].str.replace("\(", "") dataset['Business'] = dataset['Business'].str.replace("\)", "") dataset['Business'] = dataset['Business'].str.strip() dataset['business'] = dataset['Business'] dataset = dataset.drop(['Business'], axis=1) return dataset
[ "lucasmalucha@gmail.com" ]
lucasmalucha@gmail.com
1a15250cb5546c6b48ee83829dba429154c20d41
c9bb8998bde76bf88117a5d8f710621cd824df14
/tests/cupy_tests/cuda_tests/test_driver.py
fbc1e33d94198e127f8636923c068e6bf7df5cd6
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
hephaex/cupy
4a0d8198b889a26d9b958ec9c31346ec58598e49
5cf50a93bbdebe825337ed7996c464e84b1495ba
refs/heads/master
2020-06-06T18:55:49.827170
2019-06-19T21:00:21
2019-06-19T21:00:21
192,827,521
1
0
MIT
2019-06-20T01:28:56
2019-06-20T01:28:56
null
UTF-8
Python
false
false
990
py
import threading import unittest import cupy from cupy.cuda import driver class TestDriver(unittest.TestCase): def test_ctxGetCurrent(self): # Make sure to create context. cupy.arange(1) self.assertNotEqual(0, driver.ctxGetCurrent()) def test_ctxGetCurrent_thread(self): # Make sure to create context in main thread. cupy.arange(1) def f(self): self._result0 = driver.ctxGetCurrent() cupy.arange(1) self._result1 = driver.ctxGetCurrent() self._result0 = None self._result1 = None t = threading.Thread(target=f, args=(self,)) t.daemon = True t.start() t.join() # The returned context pointer must be NULL on sub thread # without valid context. self.assertEqual(0, self._result0) # After the context is created, it should return the valid # context pointer. self.assertNotEqual(0, self._result1)
[ "webmaster@kenichimaehashi.com" ]
webmaster@kenichimaehashi.com
6c3187ec0a176e1dda16a1d8fa32a1350f49b595
e1c14c3b3ed552f1af97f427c342be70d8e3b27f
/src/yMaths/print-combinations-integers-sum-given-number.py
d21539fee7022d456e69899e5a0e5284fbccefa3
[ "MIT" ]
permissive
mohitsaroha03/The-Py-Algorithms
4ab7285b6ea2ce0a008203b425ec3f459995664b
b5ba58602c0ef02c7664ea0be8bf272a8bd5239c
refs/heads/master
2023-01-28T09:25:33.317439
2020-12-05T06:17:00
2020-12-05T06:17:00
280,189,627
0
0
null
null
null
null
UTF-8
Python
false
false
962
py
# Link: https://www.techiedelight.com/print-combinations-integers-sum-given-number/ # IsDone: 1 # Recursive function to print all combination of positive integers # in increasing order that sum to a given number def printCombinations(A, i, sum, sum_left): # To maintain the increasing order, start the loop from # previous number stored in A prev_num = A[i - 1] if (i > 0) else 1 for k in range(prev_num, sum + 1): # set next element of the list to k A[i] = k # recur with the sum left and next location in the list if sum_left > k: printCombinations(A, i + 1, sum, sum_left - k) # if sum is found if sum_left == k: print(A[:i+1]) # Wrapper over printCombinations() function def findCombinations(sum): # create a temporary list for storing the combinations A = [0] * sum # recur for all combinations starting_index = 0 printCombinations(A, starting_index, sum, sum) if __name__ == '__main__': sum = 5 findCombinations(sum)
[ "MohitSaroha@Etechaces.com" ]
MohitSaroha@Etechaces.com
0b2fd01ae9041f32ba9b913c03009fd5954e14ec
ca7aa979e7059467e158830b76673f5b77a0f5a3
/Python_codes/p02574/s478211086.py
e348f33b7bcd5b939cd80827f0dd178d0a30ffa6
[]
no_license
Aasthaengg/IBMdataset
7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901
f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8
refs/heads/main
2023-04-22T10:22:44.763102
2021-05-13T17:27:22
2021-05-13T17:27:22
367,112,348
0
0
null
null
null
null
UTF-8
Python
false
false
2,119
py
from math import gcd from functools import reduce from collections import defaultdict n=int(input()) a=list(map(int,input().split())) g=reduce(gcd,a) if g!=1: print("not coprime") exit() def isPrimeMR(n): d = n - 1 d = d // (d & -d) L = [2] for a in L: t = d y = pow(a, t, n) if y == 1: continue while y != n - 1: y = (y * y) % n if y == 1 or t == n - 1: return 0 t <<= 1 return 1 def findFactorRho(n): m = 1 << n.bit_length() // 8 for c in range(1, 99): f = lambda x: (x * x + c) % n y, r, q, g = 2, 1, 1, 1 while g == 1: x = y for i in range(r): y = f(y) k = 0 while k < r and g == 1: ys = y for i in range(min(m, r - k)): y = f(y) q = q * abs(x - y) % n g = gcd(q, n) k += m r <<= 1 if g == n: g = 1 while g == 1: ys = f(ys) g = gcd(abs(x - ys), n) if g < n: if isPrimeMR(g): return g elif isPrimeMR(n // g): return n // g return findFactorRho(g) def primeFactor(n): i = 2 ret = {} rhoFlg = 0 while i*i <= n: k = 0 while n % i == 0: n //= i k += 1 if k: ret[i] = k i += 1 + i % 2 if i == 101 and n >= 2 ** 20: while n > 1: if isPrimeMR(n): ret[n], n = 1, 1 else: rhoFlg = 1 j = findFactorRho(n) k = 0 while n % j == 0: n //= j k += 1 ret[j] = k if n > 1: ret[n] = 1 if rhoFlg: ret = {x: ret[x] for x in sorted(ret)} return ret #d=defaultdict(int) s=set() for q in a: p=primeFactor(q) for j in p: if j in s: print("setwise coprime") exit() s.add(j) print("pairwise coprime")
[ "66529651+Aastha2104@users.noreply.github.com" ]
66529651+Aastha2104@users.noreply.github.com
dfbdf95b718951deb80f412553aeecbbadee397d
7ba05e73515c14fb8d2f3d056b51102131171a11
/000_mid_exam_retake/test.py
9f34a58afac2898aea41cae6d451743ed3c488e6
[]
no_license
gyurel/SoftUni-Basics-and-Fundamentals
bd6d5fa8c9d0cc51f241393afd418633a66c65dc
184fc5dfab2fdd410aa8593f4c562fd56211c727
refs/heads/main
2023-07-05T11:16:58.966841
2021-08-31T19:25:40
2021-08-31T19:25:40
401,485,125
0
0
null
null
null
null
UTF-8
Python
false
false
68
py
d = {} for x in range(1, 10): d["string{0}".format(x)] = "Hello"
[ "gyurel@yahoo.com" ]
gyurel@yahoo.com
f0595be963dc4b4499181013831a9970ba963495
180e1e947f3f824cb2c466f51900aa12a9428e1c
/pattern4/hamburg_store_v5/src/SichuanIngredientsFactory.py
db6d7e34726ae46ecf5b21659ff3352834e2f368
[ "MIT" ]
permissive
icexmoon/design-pattern-with-python
216f43a63dc87ef28a12d5a9a915bf0df3b64f50
bb897e886fe52bb620db0edc6ad9d2e5ecb067af
refs/heads/main
2023-06-15T11:54:19.357798
2021-07-21T08:46:16
2021-07-21T08:46:16
376,543,552
0
0
null
null
null
null
UTF-8
Python
false
false
709
py
####################################################### # # SichuanIngredientsFactory.py # Python implementation of the Class SichuanIngredientsFactory # Generated by Enterprise Architect # Created on: 19-6��-2021 21:34:31 # Original author: 70748 # ####################################################### from .Chicken import Chicken from .Pepper import Pepper from .SichuanPepper import SichuanPepper from .ThreeYellowChicken import ThreeYellowChicken from .IngredientsFactory import IngredientsFactory class SichuanIngredientsFactory(IngredientsFactory): def getChicken(self) -> Chicken: return ThreeYellowChicken() def getPepper(self) -> Pepper: return SichuanPepper()
[ "icexmoon@qq.com" ]
icexmoon@qq.com
fdd539cdf1889df24696c662f74796e12e6ae49e
b8ed6b49f25d08a0a313d749f3e40d7a5b59dfc9
/torch/fx/experimental/fx_acc/acc_op_properties.py
e2f53d7c48194b54b5f9ff834e1f73c13267da68
[ "BSD-2-Clause", "BSD-3-Clause", "LicenseRef-scancode-generic-cla", "BSL-1.0", "Apache-2.0" ]
permissive
yinchimaoliang/pytorch
191f154ede241d6c61f3600f2987f2a9ec637c92
ecf7e96969dec08f5e0091f1584557f13c290c18
refs/heads/master
2023-08-22T07:05:37.055667
2021-10-26T00:42:38
2021-10-26T00:44:05
null
0
0
null
null
null
null
UTF-8
Python
false
false
990
py
from collections import defaultdict from enum import Flag, auto from typing import Callable, DefaultDict, Set import torch import torch.fx class AccOpProperty(Flag): pointwise = auto() quantized = auto() acc_op_properties: DefaultDict[Callable, Set[AccOpProperty]] = defaultdict(set) acc_ops_with_property: DefaultDict[AccOpProperty, Set[Callable]] = defaultdict(set) def register_acc_op_properties(*properties: AccOpProperty): """ Attach properties to acc_op to inform optimization """ def decorator(acc_op: Callable): acc_op_properties[acc_op] |= set(properties) for prop in properties: acc_ops_with_property[prop].add(acc_op) return acc_op return decorator def add_optimization_properties_to_meta(mod: torch.fx.GraphModule) -> None: """ Add acc_op properties to Node.meta to inform optimization """ for node in mod.graph.nodes: node.meta['acc_op_properties'] = acc_op_properties[node.target]
[ "facebook-github-bot@users.noreply.github.com" ]
facebook-github-bot@users.noreply.github.com