def getVersion(cls) -> _uuid.UUID: return _uuid.UUID("be068f84-2627-4f53-87a9-9a1f4fd1c529")
#!/usr/bin/python3 # 다음 코드를 실행하기 위해서는 별도 모듈이 필요하지 않습니다. import base64 import uuid my_uuid = uuid.uuid4() print('원본 UUID={0}, 바이트 길이={1}'.format(str(my_uuid), len(my_uuid.bytes))) b64_encoded_str = base64.b64encode(my_uuid.bytes) print('base64 인코딩 문자열=\'{0}\', 바이트 길이={1}'.format( b64_encoded_str.decode('utf-8'), len(b64_encoded_str))) decoded_uuid = uuid.UUID(bytes=base64.b64decode(b64_encoded_str)) print('base64 디코딩 된 UUID={0}'.format(decoded_uuid))
HAS_PASSLIB = True except: HAS_PASSLIB = False from ansible import errors from ansible.module_utils.six import iteritems, string_types, integer_types from ansible.module_utils.six.moves import reduce, shlex_quote from ansible.module_utils._text import to_bytes, to_text from ansible.parsing.yaml.dumper import AnsibleDumper from ansible.utils.hashing import md5s, checksum_s from ansible.utils.unicode import unicode_wrap from ansible.utils.vars import merge_hash from ansible.vars.hostvars import HostVars UUID_NAMESPACE_ANSIBLE = uuid.UUID('361E6D51-FAEC-444A-9079-341386DA8E2E') class AnsibleJSONEncoder(json.JSONEncoder): ''' Simple encoder class to deal with JSON encoding of internal types like HostVars ''' def default(self, o): if isinstance(o, HostVars): return dict(o) else: return super(AnsibleJSONEncoder, self).default(o) def to_yaml(a, *args, **kw):
def process_result_value(self, value, dialect): if value is None: return value else: return uuid.UUID(value)
def uuid5_substitutions(dynamic_guids): for key, value in dynamic_guids.items(): if value.startswith("uuid5:"): name = value.split("uuid5:", 1)[1] assert name dynamic_guids[key] = str(uuid.uuid5(uuid.UUID(key), name)).upper()
def is_uuid_like(value): try: uuid.UUID(value) return True except Exception: return False
def to_python(self, value): if not isinstance(value, basestring): value = unicode(value) return uuid.UUID(value)
def uuid(self): return uuid.UUID(bytes_le=bytes(self.uuid_bytes))
def process_unmerge( message: Mapping[str, Any], all_columns: Sequence[FlattenedColumn], state_name: ReplacerState, ) -> Optional[Replacement]: hashes = message["hashes"] if not hashes: return None assert all(isinstance(h, str) for h in hashes) timestamp = datetime.strptime(message["datetime"], settings.PAYLOAD_DATETIME_FORMAT) all_column_names = [c.escaped for c in all_columns] select_columns = map( lambda i: i if i != "group_id" else str(message["new_group_id"]), all_column_names, ) where = """\ PREWHERE group_id = %(previous_group_id)s WHERE project_id = %(project_id)s AND primary_hash IN (%(hashes)s) AND received <= CAST('%(timestamp)s' AS DateTime) AND NOT deleted """ count_query_template = ( """\ SELECT count() FROM %(table_name)s FINAL """ + where ) insert_query_template = ( """\ INSERT INTO %(table_name)s (%(all_columns)s) SELECT %(select_columns)s FROM %(table_name)s FINAL """ + where ) query_args = { "all_columns": ", ".join(all_column_names), "select_columns": ", ".join(select_columns), "previous_group_id": message["previous_group_id"], "project_id": message["project_id"], "timestamp": timestamp.strftime(DATETIME_FORMAT), } if state_name == ReplacerState.ERRORS: query_args["hashes"] = ", ".join( ["'%s'" % str(uuid.UUID(_hashify(h))) for h in hashes] ) else: query_args["hashes"] = ", ".join("'%s'" % _hashify(h) for h in hashes) query_time_flags = (NEEDS_FINAL, message["project_id"]) return Replacement( count_query_template, insert_query_template, query_args, query_time_flags )
def create_new(self): random_uuid = str(uuid.UUID(int=random.getrandbits(128), version=4)) self._collection_name = '{}-{}'.format(self._service_name, random_uuid) return self._collection_name
def parse(data): assert type(data) == dict, 'data parsed must have type dict, but was "{}"'.format(type(data)) obj = MasterNodeUsage() timestamp = data.get('timestamp', None) assert timestamp is None or type( timestamp) == int, '"timestamp" must have type int, but was "{}"'.format(type(timestamp)) if timestamp is None: # set current time as default obj._timestamp = np.datetime64(time_ns(), 'ns') else: # set the value contained in the parsed data obj._timestamp = np.datetime64(timestamp, 'ns') timestamp_from = data.get('timestamp_from', None) assert timestamp_from is None or type( timestamp_from) == int, '"timestamp_from" must have type int, but was "{}"'.format( type(timestamp_from)) obj._timestamp_from = np.datetime64(timestamp_from, 'ns') if timestamp_from is not None else None mrealm_id = data.get('mrealm_id', None) assert mrealm_id is None or type( mrealm_id) == str, '"mrealm_id" must have type str, but was "{}"'.format(type(mrealm_id)) if mrealm_id: obj._mrealm_id = uuid.UUID(mrealm_id) metering_id = data.get('metering_id', None) assert metering_id is None or type( metering_id) == str, '"metering_id" must have type str, but was "{}"'.format(type(metering_id)) if metering_id: obj._metering_id = uuid.UUID(metering_id) pubkey = data.get('pubkey', None) assert pubkey is None or type(pubkey) == bytes and len( pubkey) == 32, '"pubkey" must have type bytes of length 32, but was "{}" of length {}'.format( type(pubkey), len(pubkey) if type(pubkey) == bytes else None) obj._pubkey = pubkey client_ip_address = data.get('client_ip_address', None) assert client_ip_address is None or type(client_ip_address) == bytes and len(client_ip_address) in [ 4, 16 ], '"client_ip_address" must have type bytes of length 4 or 16, but was "{}" of length {}'.format( type(client_ip_address), len(client_ip_address) if type(client_ip_address) == bytes else None) obj._client_ip_address = client_ip_address client_ip_version = data.get('client_ip_version', None) assert client_ip_version is None or client_ip_version == 0 or ( type(client_ip_version) == int and client_ip_version in [4, 6] ), '"client_ip_version" must have value [4, 6], but was "{}"'.format(client_ip_version) obj._client_ip_version = client_ip_version client_ip_port = data.get('client_ip_port', None) assert client_ip_port is None or client_ip_port == 0 or ( type(client_ip_port) == int and client_ip_port in range( 2**16)), '"client_ip_port" must have value [0, 2**16[, but was "{}"'.format(client_ip_port) obj._client_ip_port = client_ip_port seq = data.get('seq', None) assert seq is None or type(seq) == int, '"seq" must have type int, but was "{}"'.format(type(seq)) obj._seq = seq sent = data.get('sent', None) assert sent is None or type(sent) == int, '"sent" must have type int, but was "{}"'.format(type(sent)) if sent is not None: obj._sent = np.datetime64(sent, 'ns') if sent else None processed = data.get('processed', None) assert processed is None or type( processed) == int, '"processed" must have type int, but was "{}"'.format(type(processed)) obj._processed = np.datetime64(processed, 'ns') if processed else None status = data.get('status', 0) assert status is None or (type(status) == int and status in range(4)), '"status" must have type int, but was "{}"'.format( type(status)) obj._status = status status_message = data.get('status_message', None) assert status_message is None or type( status_message) == str, '"status_message" must have type str, but was "{}"'.format( type(status_message)) obj._status_message = status_message # metering data: count = data.get('count', None) assert count is None or type(count) == int obj._count = count total = data.get('total', None) assert total is None or type(total) == int obj._total = total nodes = data.get('nodes', None) assert nodes is None or type(nodes) == int obj._nodes = nodes controllers = data.get('controllers', None) assert controllers is None or type(controllers) == int obj._controllers = controllers hostmonitors = data.get('hostmonitors', None) assert hostmonitors is None or type(hostmonitors) == int obj._hostmonitors = hostmonitors routers = data.get('routers', None) assert routers is None or type(routers) == int obj._routers = routers containers = data.get('containers', None) assert containers is None or type(containers) == int obj._containers = containers guests = data.get('guests', None) assert guests is None or type(guests) == int obj._guests = guests proxies = data.get('proxies', None) assert proxies is None or type(proxies) == int obj._proxies = proxies marketmakers = data.get('marketmakers', None) assert marketmakers is None or type(marketmakers) == int obj._marketmakers = marketmakers sessions = data.get('sessions', None) assert sessions is None or type(sessions) == int obj._sessions = sessions msgs_call = data.get('msgs_call', None) assert msgs_call is None or type(msgs_call) == int obj._msgs_call = msgs_call msgs_yield = data.get('msgs_yield', None) assert msgs_yield is None or type(msgs_yield) == int obj._msgs_yield = msgs_yield msgs_invocation = data.get('msgs_invocation', None) assert msgs_invocation is None or type(msgs_invocation) == int obj._msgs_invocation = msgs_invocation msgs_result = data.get('msgs_result', None) assert msgs_result is None or type(msgs_result) == int obj._msgs_result = msgs_result msgs_error = data.get('msgs_error', None) assert msgs_error is None or type(msgs_error) == int obj._msgs_error = msgs_error msgs_publish = data.get('msgs_publish', None) assert msgs_publish is None or type(msgs_publish) == int obj._msgs_publish = msgs_publish msgs_published = data.get('msgs_published', None) assert msgs_published is None or type(msgs_published) == int obj._msgs_published = msgs_published msgs_event = data.get('msgs_event', None) assert msgs_event is None or type(msgs_event) == int obj._msgs_event = msgs_event msgs_register = data.get('msgs_register', None) assert msgs_register is None or type(msgs_register) == int obj._msgs_register = msgs_register msgs_registered = data.get('msgs_registered', None) assert msgs_registered is None or type(msgs_registered) == int obj._msgs_registered = msgs_registered msgs_subscribe = data.get('msgs_subscribe', None) assert msgs_subscribe is None or type(msgs_subscribe) == int obj._msgs_subscribe = msgs_subscribe msgs_subscribed = data.get('msgs_subscribed', None) assert msgs_subscribed is None or type(msgs_subscribed) == int obj._msgs_subscribed = msgs_subscribed return obj
def test_update_UUIDField_using_Value(self): UUID.objects.create() UUID.objects.update(uuid=Value(uuid.UUID('12345678901234567890123456789012'), output_field=UUIDField())) self.assertEqual(UUID.objects.get().uuid, uuid.UUID('12345678901234567890123456789012'))
def getVersion(cls) -> _uuid.UUID: return _uuid.UUID("67aaee05-7d09-40e1-a6e2-d367c7196832")
def getVersion(cls) -> _uuid.UUID: return _uuid.UUID("2629b768-3cfe-4bff-b28d-658ab6154202")
def validatePayloadList(self, val): return str(uuid.UUID(val, version=4))
from writehat.settings import * from writehat.lib.figure import * from writehat.lib.report import * fixed_reportparents = [] cleaned_components = [] cleaned_engagementreports = [] cleaned_figures = [] ### FIX REPORTPARENTS ### client = MONGO_DB.report_components for r in list(Report.objects.all()) + list(SavedReport.objects.all()): for c in r.flattened_components: current_reportParent = uuid.UUID(str(c.reportParent)) new_reportParent = uuid.UUID(str(r.id)) if current_reportParent != new_reportParent: client.update_one({'_id': uuid.UUID(str(c.id))}, {'$set': {'reportParent': uuid.UUID(str(r.id))}}) fixed_reportparents.append(c) ### REMOVE ORPHANED COMPONENTS ### # make a list of all components all_components = set() for c in client.find({}): all_components.add(uuid.UUID(str(c['_id']))) # make a list of all the components that are attached to reports valid_components = set()
'dtfield': '2015-11-26T09:00:00.000000', 'utcfield': '2015-11-26T07:00:00.000000Z', 'modelfield': { 'floatfield': 1.0, 'uuidfield': '54020382-291e-4192-b370-4850493ac5bc' } } natives = { 'intfield': 3, 'stringfield': 'foobar', 'dtfield': datetime.datetime(2015, 11, 26, 9), 'utcfield': datetime.datetime(2015, 11, 26, 7), 'modelfield': { 'floatfield': 1.0, 'uuidfield': uuid.UUID('54020382-291e-4192-b370-4850493ac5bc') } } def test_to_native(): m = M(primitives) output = m.to_native() assert type(output) is dict assert output == natives assert to_native(M, natives) == natives def test_to_primitive():
def resource_list(self, tenant_id=None): if tenant_id: parent_id = str(uuid.UUID(tenant_id)) else: parent_id = None return self._api.loadbalancers_list(parent_id=parent_id)
def convert_uuidfield_value(self, value, expression, connection): if value is not None: value = uuid.UUID(value) return value
def handle_vm_vc_uuid(self, socket, writer, data): peer = socket.getpeername() vm_vc_uuid = data.decode('ascii').replace(" ", "").replace("-", "") self.logger.debug("<< %s GET_VM_VC_UUID %s", peer, vm_vc_uuid) vm_client = self.sock_to_client.get(socket) vm_client.vm_vc_uuid = uuid.UUID(vm_vc_uuid)
def convert_uuidfield_value(self, value, field): if value is not None: value = uuid.UUID(value) return value
def test_depends_on_adls2_resource_file_manager(storage_account, file_system): bar_bytes = b"bar" @solid(output_defs=[OutputDefinition(ADLS2FileHandle)], required_resource_keys={"file_manager"}) def emit_file(context): return context.resources.file_manager.write_data(bar_bytes) @solid( input_defs=[InputDefinition("file_handle", ADLS2FileHandle)], required_resource_keys={"file_manager"}, ) def accept_file(context, file_handle): local_path = context.resources.file_manager.copy_handle_to_local_temp( file_handle) assert isinstance(local_path, str) assert open(local_path, "rb").read() == bar_bytes adls2_fake_resource = FakeADLS2Resource(storage_account) adls2_fake_file_manager = ADLS2FileManager( adls2_client=adls2_fake_resource.adls2_client, file_system=file_system, prefix="some-prefix", ) @pipeline(mode_defs=[ ModeDefinition(resource_defs={ "adls2": ResourceDefinition.hardcoded_resource(adls2_fake_resource), "file_manager": ResourceDefinition.hardcoded_resource(adls2_fake_file_manager), }, ) ]) def adls2_file_manager_test(): accept_file(emit_file()) result = execute_pipeline( adls2_file_manager_test, run_config={ "resources": { "file_manager": { "config": { "adls2_file_system": file_system } } } }, ) assert result.success keys_in_bucket = set( adls2_fake_resource.adls2_client.file_systems[file_system].keys()) assert len(keys_in_bucket) == 1 file_key = list(keys_in_bucket)[0] comps = file_key.split("/") assert "/".join(comps[:-1]) == "some-prefix" assert uuid.UUID(comps[-1])
def setguid(contents, offset, guid): guid = uuid.UUID(guid) struct.pack_into('<IHH8s', contents, offset, *(guid.fields[0:3] + (guid.bytes[8:], )))
# 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 uuid from jsonmodels import fields from neutron_lib import constants as n_const import dragonflow.db.field_types as df_fields import dragonflow.db.model_framework as mf from dragonflow.db.models import l2 from dragonflow.db.models import mixins SUPPORTED_SEGMENTATION_TYPES = (n_const.TYPE_VLAN, ) UUID_NAMESPACE = uuid.UUID('a11fee2a-d833-4e22-be31-f915b55f1f77') @mf.register_model @mf.construct_nb_db_model(indexes={ 'lport_id': 'port.id', 'parent_id': 'parent.id', }) class ChildPortSegmentation(mf.ModelBase, mixins.Topic, mixins.BasicEvents): table_name = 'child_port_segmentation' parent = df_fields.ReferenceField(l2.LogicalPort, required=True) port = df_fields.ReferenceField(l2.LogicalPort, required=True) segmentation_type = df_fields.EnumField(SUPPORTED_SEGMENTATION_TYPES, required=True) segmentation_id = fields.IntField(required=True)
def from_binary(data): g = Guid() g.uuid = uuid.UUID(bytes=data.read(16)) return g
def _is_uuid_like(self, val): try: return str(uuid.UUID(val)).replace( '-', '') == self._format_uuid_string(val) except (TypeError, ValueError, AttributeError): return False
def get_mac_address(): mac = uuid.UUID(int=uuid.getnode()).hex[-12:].upper() print '本机的mac地址: ' + '0x' + mac # 将str转换成16进制的int类型 return int('0x' + mac, 16)
class Migration(migrations.Migration): initial = True dependencies = [] operations = [ migrations.CreateModel( name='Contest', fields=[ ('id', models.CharField( default=uuid.UUID('952ad01f-9f18-4589-8861-1ac5ab711df1'), max_length=256, primary_key=True, serialize=False)), ('description', models.TextField(max_length=1000)), ('rounds', models.PositiveSmallIntegerField()), ('date', models.DateField()), ('start_time', models.TimeField()), ('money_at_start', models.PositiveBigIntegerField()), ], ), migrations.CreateModel( name='Question', fields=[ ('id', models.CharField( default=uuid.UUID('b76a45eb-389e-4cc7-8ea9-2be904d00498'), max_length=256, primary_key=True, serialize=False)), ('title', models.CharField(max_length=256)), ('description', models.TextField(max_length=5000)), ('input', models.TextField(max_length=256)), ('output', models.TextField(max_length=256)), ('test_input', models.TextField(blank=True, max_length=256, null=True)), ('test_output', models.TextField(blank=True, max_length=256, null=True)), ('points', models.PositiveBigIntegerField(default=2500)), ], ), migrations.CreateModel( name='Submission', fields=[ ('id', models.CharField( default=uuid.UUID('d4d266db-767b-4036-b2f9-c4cc99416af3'), max_length=256, primary_key=True, serialize=False)), ('fileUrl', models.URLField(max_length=256)), ('languageUsed', models.CharField(max_length=256)), ('timeOfSubmission', models.DateTimeField(auto_now_add=True)), ('questionId', models.ForeignKey( on_delete=django.db.models.deletion.DO_NOTHING, to='adminpanel.question')), ], ), migrations.CreateModel( name='Round', fields=[ ('id', models.CharField( default=uuid.UUID('58d8b051-f249-4180-89aa-81acb4f5a49c'), max_length=256, primary_key=True, serialize=False)), ('roundNumber', models.PositiveSmallIntegerField()), ('roundName', models.CharField(max_length=256)), ('startTime', models.DateTimeField()), ('contestId', models.ForeignKey( on_delete=django.db.models.deletion.DO_NOTHING, to='adminpanel.contest')), ], ), migrations.AddField( model_name='question', name='roundId', field=models.ForeignKey( on_delete=django.db.models.deletion.DO_NOTHING, to='adminpanel.round'), ), migrations.CreateModel( name='Components', fields=[ ('id', models.CharField( default=uuid.UUID('5ff8e23c-9dc1-4638-8903-57acc656b6b0'), max_length=256, primary_key=True, serialize=False)), ('componentName', models.CharField(max_length=256)), ('componentDescription', models.TextField(max_length=256)), ('componentPrice', models.PositiveBigIntegerField(default=100)), ('contestId', models.ForeignKey( on_delete=django.db.models.deletion.DO_NOTHING, to='adminpanel.contest')), ], ), ]
def reset_password(request, _form_class=ResetPasswordForm): if request.authenticated_userid is not None: return HTTPSeeOther(request.route_path("index")) user_service = request.find_service(IUserService, context=None) breach_service = request.find_service(IPasswordBreachedService, context=None) token_service = request.find_service(ITokenService, name="password") def _error(message): request.session.flash(message, queue="error") return HTTPSeeOther( request.route_path("accounts.request-password-reset")) try: token = request.params.get("token") data = token_service.loads(token) except TokenExpired: return _error(_("Expired token: request a new password reset link")) except TokenInvalid: return _error(_("Invalid token: request a new password reset link")) except TokenMissing: return _error(_("Invalid token: no token supplied")) # Check whether this token is being used correctly if data.get("action") != "password-reset": return _error(_("Invalid token: not a password reset token")) # Check whether a user with the given user ID exists user = user_service.get_user(uuid.UUID(data.get("user.id"))) if user is None: return _error(_("Invalid token: user not found")) # Check whether the user has logged in since the token was created last_login = data.get("user.last_login") if str(user.last_login) > last_login: # TODO: track and audit this, seems alertable return _error( _("Invalid token: user has logged in since " "this token was requested")) # Check whether the password has been changed since the token was created password_date = data.get("user.password_date") if str(user.password_date) > password_date: return _error( _("Invalid token: password has already been changed since this " "token was requested")) form = _form_class( **request.params, username=user.username, full_name=user.name, email=user.email, user_service=user_service, breach_service=breach_service, ) if request.method == "POST" and form.validate(): # Update password. user_service.update_user(user.id, password=form.new_password.data) user_service.record_event(user.id, tag="account:password:reset", ip_address=request.remote_addr) # Send password change email send_password_change_email(request, user) # Flash a success message request.session.flash(_("You have reset your password"), queue="success") # Redirect to account login. return HTTPSeeOther(request.route_path("accounts.login")) return {"form": form}
def getVersion(cls) -> _uuid.UUID: return _uuid.UUID("68c5cebb-0c47-4dec-8c85-8872b7f6c238")