hexsha
stringlengths
40
40
size
int64
5
1.05M
ext
stringclasses
98 values
lang
stringclasses
21 values
max_stars_repo_path
stringlengths
3
945
max_stars_repo_name
stringlengths
4
118
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
sequencelengths
1
10
max_stars_count
int64
1
368k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
945
max_issues_repo_name
stringlengths
4
118
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
sequencelengths
1
10
max_issues_count
int64
1
134k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
945
max_forks_repo_name
stringlengths
4
135
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
sequencelengths
1
10
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
5
1.05M
avg_line_length
float64
1
1.03M
max_line_length
int64
2
1.03M
alphanum_fraction
float64
0
1
123a2f48941c40045169cdd80a53cef08b9e8d53
2,500
h
C
sdk/rmsauth_sdk/rmsauth/rmsauth/Authenticator.h
AzureAD/rms-sdk-for-cpp
0e5d54a030008c5c0f70d8d3d0695fa0722b6ab6
[ "MIT" ]
30
2015-06-22T23:59:02.000Z
2021-09-12T05:51:34.000Z
sdk/rmsauth_sdk/rmsauth/rmsauth/Authenticator.h
AnthonyCSheehy/rms-sdk-for-cpp
42985c0b5d93da5bef6bd6c847ddced4be008843
[ "MIT" ]
115
2015-06-22T18:26:34.000Z
2022-03-24T16:57:46.000Z
sdk/rmsauth_sdk/rmsauth/rmsauth/Authenticator.h
AnthonyCSheehy/rms-sdk-for-cpp
42985c0b5d93da5bef6bd6c847ddced4be008843
[ "MIT" ]
32
2015-06-22T08:39:29.000Z
2022-03-24T16:49:20.000Z
/* * ====================================================================== * Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. * Licensed under the MIT License. * See LICENSE.md in the project root for license information. * ====================================================================== */ #ifndef AUTHENTICATOR_H #define AUTHENTICATOR_H #include "types.h" #include "AuthorityType.h" #include "Guid.h" #include "CallState.h" #include "Exceptions.h" #include "AuthenticatorTemplateList.h" #include "Constants.h" #include "utils.h" #include "Url.h" namespace rmsauth { class Authenticator { static const String& Tag() {static const String tag="Authenticator"; return tag;} static const String tenantlessTenantName(); static AuthenticatorTemplateList authenticatorTemplateList; bool updatedFromTemplate_ = false; bool validateAuthority_; bool default_ = true; String authority_; AuthorityType authorityType_; bool isTenantless_; String authorizationUri_; String tokenUri_; String userRealmUri_; String selfSignedJwtAudience_; Guid correlationId_; public: Authenticator():default_(true){} Authenticator(const String& authority, bool validateAuthority); const String& authority() const {return authority_;} const AuthorityType& authorityType() const {return authorityType_;} bool validateAuthority() const {return validateAuthority_;} bool isTenantless() const {return isTenantless_;} const String& authorizationUri() const {return authorizationUri_;} const String& tokenUri() const {return tokenUri_;} const String& userRealmUri() const {return userRealmUri_;} const String& selfSignedJwtAudience() const {return selfSignedJwtAudience_;} const Guid& correlationId() const {return correlationId_;} void correlationId(const Guid& val) {correlationId_ = val;} void updateFromTemplateAsync(CallStatePtr callState); void updateTenantId(const String& tenantId); private: static AuthorityType detectAuthorityType(const String& authority); static String canonicalizeUri(const String& uri); static String replaceTenantlessTenant(const String& authority, const String& tenantId); static bool isAdfsAuthority(const String& firstPath); }; using AuthenticatorPtr = ptr<Authenticator>; } // namespace rmsauth { #endif // AUTHENTICATOR_H
33.333333
91
0.68
0bae78fa6080de85a0feb221980172f577f30cf7
42,674
py
Python
packstack/plugins/neutron_350.py
melroyr/havana-packstack
72cdb0e5e29df4cccb81844ec8b365dfededf4f7
[ "Apache-2.0" ]
null
null
null
packstack/plugins/neutron_350.py
melroyr/havana-packstack
72cdb0e5e29df4cccb81844ec8b365dfededf4f7
[ "Apache-2.0" ]
null
null
null
packstack/plugins/neutron_350.py
melroyr/havana-packstack
72cdb0e5e29df4cccb81844ec8b365dfededf4f7
[ "Apache-2.0" ]
null
null
null
""" Installs and configures neutron """ import logging import os import re import uuid from packstack.installer import utils from packstack.installer import validators from packstack.installer.utils import split_hosts from packstack.modules.ospluginutils import getManifestTemplate, appendManifestFile # Controller object will be initialized from main flow controller = None # Plugin name PLUGIN_NAME = "OS-NEUTRON" logging.debug("plugin %s loaded", __name__) def initConfig(controllerObject): global controller controller = controllerObject logging.debug("Adding OpenStack Neutron configuration") conf_params = { "NEUTRON" : [ {"CMD_OPTION" : "neutron-server-host", "USAGE" : "The IP addresses of the server on which to install the Neutron server", "PROMPT" : "Enter the IP address of the Neutron server", "OPTION_LIST" : [], "VALIDATORS" : [validators.validate_ip, validators.validate_ssh], "DEFAULT_VALUE" : utils.get_localhost_ip(), "MASK_INPUT" : False, "LOOSE_VALIDATION": True, "CONF_NAME" : "CONFIG_NEUTRON_SERVER_HOST", "USE_DEFAULT" : False, "NEED_CONFIRM" : False, "CONDITION" : False }, {"CMD_OPTION" : "neutron-ks-password", "USAGE" : "The password to use for Neutron to authenticate with Keystone", "PROMPT" : "Enter the password for Neutron Keystone access", "OPTION_LIST" : [], "VALIDATORS" : [validators.validate_not_empty], "DEFAULT_VALUE" : uuid.uuid4().hex[:16], "MASK_INPUT" : True, "LOOSE_VALIDATION": False, "CONF_NAME" : "CONFIG_NEUTRON_KS_PW", "USE_DEFAULT" : True, "NEED_CONFIRM" : True, "CONDITION" : False }, {"CMD_OPTION" : "neutron-db-password", "USAGE" : "The password to use for Neutron to access DB", "PROMPT" : "Enter the password for Neutron DB access", "OPTION_LIST" : [], "VALIDATORS" : [validators.validate_not_empty], "DEFAULT_VALUE" : uuid.uuid4().hex[:16], "MASK_INPUT" : True, "LOOSE_VALIDATION": False, "CONF_NAME" : "CONFIG_NEUTRON_DB_PW", "USE_DEFAULT" : True, "NEED_CONFIRM" : True, "CONDITION" : False }, {"CMD_OPTION" : "neutron-l3-hosts", "USAGE" : "A comma separated list of IP addresses on which to install Neutron L3 agent", "PROMPT" : "Enter a comma separated list of IP addresses on which to install the Neutron L3 agent", "OPTION_LIST" : [], "VALIDATORS" : [validators.validate_multi_ssh], "DEFAULT_VALUE" : utils.get_localhost_ip(), "MASK_INPUT" : False, "LOOSE_VALIDATION": True, "CONF_NAME" : "CONFIG_NEUTRON_L3_HOSTS", "USE_DEFAULT" : False, "NEED_CONFIRM" : False, "CONDITION" : False }, {"CMD_OPTION" : "neutron-l3-ext-bridge", "USAGE" : "The name of the bridge that the Neutron L3 agent will use for external traffic, or 'provider' if using provider networks", "PROMPT" : "Enter the bridge the Neutron L3 agent will use for external traffic, or 'provider' if using provider networks", "OPTION_LIST" : [], "VALIDATORS" : [validators.validate_not_empty], "DEFAULT_VALUE" : "br-ex", "MASK_INPUT" : False, "LOOSE_VALIDATION": True, "CONF_NAME" : "CONFIG_NEUTRON_L3_EXT_BRIDGE", "USE_DEFAULT" : False, "NEED_CONFIRM" : False, "CONDITION" : False }, {"CMD_OPTION" : "neutron-dhcp-hosts", "USAGE" : "A comma separated list of IP addresses on which to install Neutron DHCP agent", "PROMPT" : "Enter a comma separated list of IP addresses on which to install Neutron DHCP agent", "OPTION_LIST" : [], "VALIDATORS" : [validators.validate_multi_ssh], "DEFAULT_VALUE" : utils.get_localhost_ip(), "MASK_INPUT" : False, "LOOSE_VALIDATION": True, "CONF_NAME" : "CONFIG_NEUTRON_DHCP_HOSTS", "USE_DEFAULT" : False, "NEED_CONFIRM" : False, "CONDITION" : False }, {"CMD_OPTION" : "neutron-lbaas-hosts", "USAGE" : "A comma separated list of IP addresses on which to install Neutron LBaaS agent", "PROMPT" : "Enter a comma separated list of IP addresses on which to install Neutron LBaaS agent", "OPTION_LIST" : [], "VALIDATORS" : [validators.validate_multi_ssh], "DEFAULT_VALUE" : "", "MASK_INPUT" : False, "LOOSE_VALIDATION": True, "CONF_NAME" : "CONFIG_NEUTRON_LBAAS_HOSTS", "USE_DEFAULT" : False, "NEED_CONFIRM" : False, "CONDITION" : False }, {"CMD_OPTION" : "neutron-l2-plugin", "USAGE" : "The name of the L2 plugin to be used with Neutron", "PROMPT" : "Enter the name of the L2 plugin to be used with Neutron", "OPTION_LIST" : ["linuxbridge", "openvswitch", "ml2"], "VALIDATORS" : [validators.validate_options], "DEFAULT_VALUE" : "openvswitch", "MASK_INPUT" : False, "LOOSE_VALIDATION": False, "CONF_NAME" : "CONFIG_NEUTRON_L2_PLUGIN", "USE_DEFAULT" : False, "NEED_CONFIRM" : False, "CONDITION" : False }, {"CMD_OPTION" : "neutron-metadata-hosts", "USAGE" : "A comma separated list of IP addresses on which to install Neutron metadata agent", "PROMPT" : "Enter a comma separated list of IP addresses on which to install the Neutron metadata agent", "OPTION_LIST" : [], "VALIDATORS" : [validators.validate_multi_ssh], "DEFAULT_VALUE" : utils.get_localhost_ip(), "MASK_INPUT" : False, "LOOSE_VALIDATION": True, "CONF_NAME" : "CONFIG_NEUTRON_METADATA_HOSTS", "USE_DEFAULT" : False, "NEED_CONFIRM" : False, "CONDITION" : False }, {"CMD_OPTION" : "neutron-metadata-pw", "USAGE" : "A comma separated list of IP addresses on which to install Neutron metadata agent", "PROMPT" : "Enter a comma separated list of IP addresses on which to install the Neutron metadata agent", "OPTION_LIST" : [], "VALIDATORS" : [validators.validate_not_empty], "DEFAULT_VALUE" : uuid.uuid4().hex[:16], "MASK_INPUT" : True, "LOOSE_VALIDATION": False, "CONF_NAME" : "CONFIG_NEUTRON_METADATA_PW", "USE_DEFAULT" : True, "NEED_CONFIRM" : True, "CONDITION" : False }, ], "NEUTRON_LB_PLUGIN" : [ {"CMD_OPTION" : "neutron-lb-tenant-network-type", "USAGE" : "The type of network to allocate for tenant networks (eg. vlan, local)", "PROMPT" : "Enter the type of network to allocate for tenant networks", "OPTION_LIST" : ["local", "vlan"], "VALIDATORS" : [validators.validate_options], "DEFAULT_VALUE" : "local", "MASK_INPUT" : False, "LOOSE_VALIDATION": False, "CONF_NAME" : "CONFIG_NEUTRON_LB_TENANT_NETWORK_TYPE", "USE_DEFAULT" : False, "NEED_CONFIRM" : False, "CONDITION" : False }, {"CMD_OPTION" : "neutron-lb-vlan-ranges", "USAGE" : "A comma separated list of VLAN ranges for the Neutron linuxbridge plugin (eg. physnet1:1:4094,physnet2,physnet3:3000:3999)", "PROMPT" : "Enter a comma separated list of VLAN ranges for the Neutron linuxbridge plugin", "OPTION_LIST" : [], "VALIDATORS" : [], "DEFAULT_VALUE" : "", "MASK_INPUT" : False, "LOOSE_VALIDATION": True, "CONF_NAME" : "CONFIG_NEUTRON_LB_VLAN_RANGES", "USE_DEFAULT" : False, "NEED_CONFIRM" : False, "CONDITION" : False }, ], "NEUTRON_LB_PLUGIN_AND_AGENT" : [ {"CMD_OPTION" : "neutron-lb-interface-mappings", "USAGE" : "A comma separated list of interface mappings for the Neutron linuxbridge plugin (eg. physnet1:br-eth1,physnet2:br-eth2,physnet3:br-eth3)", "PROMPT" : "Enter a comma separated list of interface mappings for the Neutron linuxbridge plugin", "OPTION_LIST" : [], "VALIDATORS" : [], "DEFAULT_VALUE" : "", "MASK_INPUT" : False, "LOOSE_VALIDATION": True, "CONF_NAME" : "CONFIG_NEUTRON_LB_INTERFACE_MAPPINGS", "USE_DEFAULT" : False, "NEED_CONFIRM" : False, "CONDITION" : False }, ], "NEUTRON_OVS_PLUGIN" : [ {"CMD_OPTION" : "neutron-ovs-tenant-network-type", "USAGE" : "Type of network to allocate for tenant networks (eg. vlan, local, gre, vxlan)", "PROMPT" : "Enter the type of network to allocate for tenant networks", "OPTION_LIST" : ["local", "vlan", "gre", "vxlan"], "VALIDATORS" : [validators.validate_options], "DEFAULT_VALUE" : "local", "MASK_INPUT" : False, "LOOSE_VALIDATION": False, "CONF_NAME" : "CONFIG_NEUTRON_OVS_TENANT_NETWORK_TYPE", "USE_DEFAULT" : False, "NEED_CONFIRM" : False, "CONDITION" : False }, {"CMD_OPTION" : "neutron-ovs-vlan-ranges", "USAGE" : "A comma separated list of VLAN ranges for the Neutron openvswitch plugin (eg. physnet1:1:4094,physnet2,physnet3:3000:3999)", "PROMPT" : "Enter a comma separated list of VLAN ranges for the Neutron openvswitch plugin", "OPTION_LIST" : [], "VALIDATORS" : [], "DEFAULT_VALUE" : "", "MASK_INPUT" : False, "LOOSE_VALIDATION": True, "CONF_NAME" : "CONFIG_NEUTRON_OVS_VLAN_RANGES", "USE_DEFAULT" : False, "NEED_CONFIRM" : False, "CONDITION" : False }, ], "NEUTRON_OVS_PLUGIN_AND_AGENT" : [ {"CMD_OPTION" : "neutron-ovs-bridge-mappings", "USAGE" : "A comma separated list of bridge mappings for the Neutron openvswitch plugin (eg. physnet1:br-eth1,physnet2:br-eth2,physnet3:br-eth3)", "PROMPT" : "Enter a comma separated list of bridge mappings for the Neutron openvswitch plugin", "OPTION_LIST" : [], "VALIDATORS" : [], "DEFAULT_VALUE" : "", "MASK_INPUT" : False, "LOOSE_VALIDATION": True, "CONF_NAME" : "CONFIG_NEUTRON_OVS_BRIDGE_MAPPINGS", "USE_DEFAULT" : False, "NEED_CONFIRM" : False, "CONDITION" : False }, {"CMD_OPTION" : "neutron-ovs-bridge-interfaces", "USAGE" : "A comma separated list of colon-separated OVS bridge:interface pairs. The interface will be added to the associated bridge.", "PROMPT" : "Enter a comma separated list of OVS bridge:interface pairs for the Neutron openvswitch plugin", "OPTION_LIST" : [], "VALIDATORS" : [], "DEFAULT_VALUE" : "", "MASK_INPUT" : False, "LOOSE_VALIDATION": True, "CONF_NAME" : "CONFIG_NEUTRON_OVS_BRIDGE_IFACES", "USE_DEFAULT" : False, "NEED_CONFIRM" : False, "CONDITION" : False }, ], "NEUTRON_OVS_PLUGIN_TUNNEL" : [ {"CMD_OPTION" : "neutron-ovs-tunnel-ranges", "USAGE" : "A comma separated list of tunnel ranges for the Neutron openvswitch plugin (eg. 1:1000)", "PROMPT" : "Enter a comma separated list of tunnel ranges for the Neutron openvswitch plugin", "OPTION_LIST" : [], "VALIDATORS" : [], "DEFAULT_VALUE" : "", "MASK_INPUT" : False, "LOOSE_VALIDATION": True, "CONF_NAME" : "CONFIG_NEUTRON_OVS_TUNNEL_RANGES", "USE_DEFAULT" : False, "NEED_CONFIRM" : False, "CONDITION" : False }, ], "NEUTRON_OVS_PLUGIN_AND_AGENT_TUNNEL" : [ {"CMD_OPTION" : "neutron-ovs-tunnel-if", "USAGE" : "The interface for the OVS tunnel. Packstack will override the IP address used for tunnels on this hypervisor to the IP found on the specified interface. (eg. eth1) ", "PROMPT" : "Enter interface with IP to override the default tunnel local_ip", "OPTION_LIST" : [], "VALIDATORS" : [], "DEFAULT_VALUE" : "", "MASK_INPUT" : False, "LOOSE_VALIDATION": True, "CONF_NAME" : "CONFIG_NEUTRON_OVS_TUNNEL_IF", "USE_DEFAULT" : False, "NEED_CONFIRM" : False, "CONDITION" : False }, ], "NEUTRON_OVS_PLUGIN_AND_AGENT_VXLAN" : [ {"CMD_OPTION" : "neutron-ovs-vxlan-udp-port", "CONF_NAME" : "CONFIG_NEUTRON_OVS_VXLAN_UDP_PORT", "USAGE" : "VXLAN UDP port", "PROMPT" : "Enter VXLAN UDP port number", "OPTION_LIST" : [], "VALIDATORS" : [validators.validate_port], "DEFAULT_VALUE" : 4789, "MASK_INPUT" : False, "LOOSE_VALIDATION": True, "USE_DEFAULT" : False, "NEED_CONFIRM" : False, "CONDITION" : False }, ], "NEUTRON_ML2_PLUGIN" : [ {"CMD_OPTION" : "neutron-ml2-type-drivers", "CONF_NAME" : "CONFIG_NEUTRON_ML2_TYPE_DRIVERS", "USAGE" : ("A comma separated list of network type " "driver entrypoints to be loaded from the " "neutron.ml2.type_drivers namespace."), "PROMPT" : ("Enter a comma separated list of network " "type driver entrypoints"), "OPTION_LIST" : ["local", "flat", "vlan", "gre", "vxlan"], "VALIDATORS" : [validators.validate_multi_options], "DEFAULT_VALUE" : "local", "MASK_INPUT" : False, "LOOSE_VALIDATION": False, "USE_DEFAULT" : False, "NEED_CONFIRM" : False, "CONDITION" : False }, {"CMD_OPTION" : "neutron-ml2-tenant-network-types", "CONF_NAME" : "CONFIG_NEUTRON_ML2_TENANT_NETWORK_TYPES", "USAGE" : ("A comma separated ordered list of " "network_types to allocate as tenant " "networks. The value 'local' is only useful " "for single-box testing but provides no " "connectivity between hosts."), "PROMPT" : ("Enter a comma separated ordered list of " "network_types to allocate as tenant " "networks"), "OPTION_LIST" : ["local", "vlan", "gre", "vxlan"], "VALIDATORS" : [validators.validate_multi_options], "DEFAULT_VALUE" : "local", "MASK_INPUT" : False, "LOOSE_VALIDATION": False, "USE_DEFAULT" : False, "NEED_CONFIRM" : False, "CONDITION" : False }, {"CMD_OPTION" : "neutron-ml2-mechanism-drivers", "CONF_NAME" : "CONFIG_NEUTRON_ML2_MECHANISM_DRIVERS", "USAGE" : ("A comma separated ordered list of " "networking mechanism driver entrypoints " "to be loaded from the " "neutron.ml2.mechanism_drivers namespace."), "PROMPT" : ("Enter a comma separated ordered list of " "networking mechanism driver entrypoints"), "OPTION_LIST" : ["logger", "test", "linuxbridge", "openvswitch", "hyperv", "ncs", "arista", "cisco_nexus", "l2population"], "VALIDATORS" : [validators.validate_multi_options], "DEFAULT_VALUE" : "openvswitch", "MASK_INPUT" : False, "LOOSE_VALIDATION": False, "USE_DEFAULT" : False, "NEED_CONFIRM" : False, "CONDITION" : False }, {"CMD_OPTION" : "neutron-ml2-flat-networks", "CONF_NAME" : "CONFIG_NEUTRON_ML2_FLAT_NETWORKS", "USAGE" : ("A comma separated list of physical_network" " names with which flat networks can be " "created. Use * to allow flat networks with " "arbitrary physical_network names."), "PROMPT" : ("Enter a comma separated list of " "physical_network names with which flat " "networks can be created"), "OPTION_LIST" : [], "VALIDATORS" : [], "DEFAULT_VALUE" : "*", "MASK_INPUT" : False, "LOOSE_VALIDATION": False, "USE_DEFAULT" : False, "NEED_CONFIRM" : False, "CONDITION" : False }, {"CMD_OPTION" : "neutron-ml2-vlan-ranges", "CONF_NAME" : "CONFIG_NEUTRON_ML2_VLAN_RANGES", "USAGE" : ("A comma separated list of " "<physical_network>:<vlan_min>:<vlan_max> " "or <physical_network> specifying " "physical_network names usable for VLAN " "provider and tenant networks, as well as " "ranges of VLAN tags on each available for " "allocation to tenant networks."), "PROMPT" : ("Enter a comma separated list of " "physical_network names usable for VLAN"), "OPTION_LIST" : [], "VALIDATORS" : [], "DEFAULT_VALUE" : "", "MASK_INPUT" : False, "LOOSE_VALIDATION": False, "USE_DEFAULT" : False, "NEED_CONFIRM" : False, "CONDITION" : False }, {"CMD_OPTION" : "neutron-ml2-tunnel-id-ranges", "CONF_NAME" : "CONFIG_NEUTRON_ML2_TUNNEL_ID_RANGES", "USAGE" : ("A comma separated list of <tun_min>:" "<tun_max> tuples enumerating ranges of GRE " "tunnel IDs that are available for tenant " "network allocation. Should be an array with" " tun_max +1 - tun_min > 1000000"), "PROMPT" : ("Enter a comma separated list of <tun_min>:" "<tun_max> tuples enumerating ranges of GRE " "tunnel IDs that are available for tenant " "network allocation"), "OPTION_LIST" : [], "VALIDATORS" : [], "DEFAULT_VALUE" : "", "MASK_INPUT" : False, "LOOSE_VALIDATION": False, "USE_DEFAULT" : False, "NEED_CONFIRM" : False, "CONDITION" : False }, {"CMD_OPTION" : "neutron-ml2-vxlan-group", "CONF_NAME" : "CONFIG_NEUTRON_ML2_VXLAN_GROUP", "USAGE" : ("Multicast group for VXLAN. If unset, " "disables VXLAN enable sending allocate " "broadcast traffic to this multicast group. " "When left unconfigured, will disable " "multicast VXLAN mode. Should be an " "Multicast IP (v4 or v6) address."), "PROMPT" : "Enter a multicast group for VXLAN", "OPTION_LIST" : [], "VALIDATORS" : [], "DEFAULT_VALUE" : "", "MASK_INPUT" : False, "LOOSE_VALIDATION": False, "USE_DEFAULT" : False, "NEED_CONFIRM" : False, "CONDITION" : False }, {"CMD_OPTION" : "neutron-ml2-vni-ranges", "CONF_NAME" : "CONFIG_NEUTRON_ML2_VNI_RANGES", "USAGE" : ("A comma separated list of <vni_min>:" "<vni_max> tuples enumerating ranges of " "VXLAN VNI IDs that are available for tenant" " network allocation. Min value is 0 and Max" " value is 16777215."), "PROMPT" : ("Enter a comma separated list of <vni_min>:" "<vni_max> tuples enumerating ranges of " "VXLAN VNI IDs that are available for tenant" " network allocation"), "OPTION_LIST" : [], "VALIDATORS" : [], "DEFAULT_VALUE" : "", "MASK_INPUT" : False, "LOOSE_VALIDATION": False, "USE_DEFAULT" : False, "NEED_CONFIRM" : False, "CONDITION" : False }, {"CMD_OPTION" : "neutron-l2-agent", # We need to ask for this only in case of ML2 plugins "USAGE" : "The name of the L2 agent to be used with Neutron", "PROMPT" : "Enter the name of the L2 agent to be used with Neutron", "OPTION_LIST" : ["linuxbridge", "openvswitch"], "VALIDATORS" : [validators.validate_options], "DEFAULT_VALUE" : "openvswitch", "MASK_INPUT" : False, "LOOSE_VALIDATION": False, "CONF_NAME" : "CONFIG_NEUTRON_L2_AGENT", "USE_DEFAULT" : False, "NEED_CONFIRM" : False, "CONDITION" : False }, ], } conf_groups = [ { "GROUP_NAME" : "NEUTRON", "DESCRIPTION" : "Neutron config", "PRE_CONDITION" : "CONFIG_NEUTRON_INSTALL", "PRE_CONDITION_MATCH" : "y", "POST_CONDITION" : False, "POST_CONDITION_MATCH" : True }, { "GROUP_NAME" : "NEUTRON_ML2_PLUGIN", "DESCRIPTION" : "Neutron ML2 plugin config", "PRE_CONDITION" : use_ml2_plugin, "PRE_CONDITION_MATCH" : True, "POST_CONDITION" : False, "POST_CONDITION_MATCH" : True }, { "GROUP_NAME" : "NEUTRON_LB_PLUGIN", "DESCRIPTION" : "Neutron LB plugin config", "PRE_CONDITION" : use_linuxbridge_plugin, "PRE_CONDITION_MATCH" : True, "POST_CONDITION" : False, "POST_CONDITION_MATCH" : True }, { "GROUP_NAME" : "NEUTRON_LB_PLUGIN_AND_AGENT", "DESCRIPTION" : "Neutron LB agent config", "PRE_CONDITION" : use_linuxbridge_agent, "PRE_CONDITION_MATCH" : True, "POST_CONDITION" : False, "POST_CONDITION_MATCH" : True }, { "GROUP_NAME" : "NEUTRON_OVS_PLUGIN", "DESCRIPTION" : "Neutron OVS plugin config", "PRE_CONDITION" : use_openvswitch_plugin, "PRE_CONDITION_MATCH" : True, "POST_CONDITION" : False, "POST_CONDITION_MATCH" : True }, { "GROUP_NAME" : "NEUTRON_OVS_PLUGIN_AND_AGENT", "DESCRIPTION" : "Neutron OVS agent config", "PRE_CONDITION" : use_openvswitch_agent, "PRE_CONDITION_MATCH" : True, "POST_CONDITION" : False, "POST_CONDITION_MATCH" : True }, { "GROUP_NAME" : "NEUTRON_OVS_PLUGIN_TUNNEL", "DESCRIPTION" : "Neutron OVS plugin config for tunnels", "PRE_CONDITION" : use_openvswitch_plugin_tunnel, "PRE_CONDITION_MATCH" : True, "POST_CONDITION" : False, "POST_CONDITION_MATCH" : True }, { "GROUP_NAME" : "NEUTRON_OVS_PLUGIN_AND_AGENT_TUNNEL", "DESCRIPTION" : "Neutron OVS agent config for tunnels", "PRE_CONDITION" : use_openvswitch_agent_tunnel, "PRE_CONDITION_MATCH" : True, "POST_CONDITION" : False, "POST_CONDITION_MATCH" : True }, { "GROUP_NAME" : "NEUTRON_OVS_PLUGIN_AND_AGENT_VXLAN", "DESCRIPTION" : "Neutron OVS agent config for VXLAN", "PRE_CONDITION" : use_openvswitch_vxlan, "PRE_CONDITION_MATCH" : True, "POST_CONDITION" : False, "POST_CONDITION_MATCH" : True }, ] for group in conf_groups: paramList = conf_params[group["GROUP_NAME"]] controller.addGroup(group, paramList) def use_ml2_plugin(config): return (config['CONFIG_NEUTRON_INSTALL'] == 'y' and config['CONFIG_NEUTRON_L2_PLUGIN'] == 'ml2') def use_linuxbridge_plugin(config): result = (config['CONFIG_NEUTRON_INSTALL'] == 'y' and config['CONFIG_NEUTRON_L2_PLUGIN'] == 'linuxbridge') if result: config["CONFIG_NEUTRON_L2_AGENT"] = 'linuxbridge' return result def use_linuxbridge_agent(config): ml2_used = (use_ml2_plugin(config) and config["CONFIG_NEUTRON_L2_AGENT"] == 'linuxbridge') return use_linuxbridge_plugin(config) or ml2_used def use_openvswitch_plugin(config): result = (config['CONFIG_NEUTRON_INSTALL'] == 'y' and config['CONFIG_NEUTRON_L2_PLUGIN'] == 'openvswitch') if result: config["CONFIG_NEUTRON_L2_AGENT"] = 'openvswitch' return result def use_openvswitch_plugin_tunnel(config): tun_types = ('gre', 'vxlan') return (use_openvswitch_plugin(config) and config['CONFIG_NEUTRON_OVS_TENANT_NETWORK_TYPE'] in tun_types) def use_ml2_with_ovs(config): return (use_ml2_plugin(config) and config["CONFIG_NEUTRON_L2_AGENT"] == 'openvswitch') def use_openvswitch_agent(config): return use_openvswitch_plugin(config) or use_ml2_with_ovs(config) def use_openvswitch_agent_tunnel(config): return use_openvswitch_plugin_tunnel(config) or use_ml2_with_ovs(config) def use_openvswitch_vxlan(config): return ((use_openvswitch_plugin_tunnel(config) and config['CONFIG_NEUTRON_OVS_TENANT_NETWORK_TYPE'] == 'vxlan') or (use_ml2_with_ovs(config) and 'vxlan' in config['CONFIG_NEUTRON_ML2_TYPE_DRIVERS'])) def use_openvswitch_gre(config): ovs_vxlan = ( use_openvswitch_plugin_tunnel(config) and config['CONFIG_NEUTRON_OVS_TENANT_NETWORK_TYPE'] == 'gre' ) ml2_vxlan = ( use_ml2_with_ovs(config) and 'gre' in config['CONFIG_NEUTRON_ML2_TENANT_NETWORK_TYPES'] ) return ovs_vxlan or ml2_vxlan def get_if_driver(config): agent = config['CONFIG_NEUTRON_L2_AGENT'] if agent == "openvswitch": return 'neutron.agent.linux.interface.OVSInterfaceDriver' elif agent == 'linuxbridge': return 'neutron.agent.linux.interface.BridgeInterfaceDriver' def initSequences(controller): config = controller.CONF if config['CONFIG_NEUTRON_INSTALL'] != 'y': return if config['CONFIG_NEUTRON_L2_PLUGIN'] == 'openvswitch': plugin_db = 'ovs_neutron' plugin_path = ('neutron.plugins.openvswitch.ovs_neutron_plugin.' 'OVSNeutronPluginV2') elif config['CONFIG_NEUTRON_L2_PLUGIN'] == 'linuxbridge': plugin_db = 'neutron_linux_bridge' plugin_path = ('neutron.plugins.linuxbridge.lb_neutron_plugin.' 'LinuxBridgePluginV2') elif config['CONFIG_NEUTRON_L2_PLUGIN'] == 'ml2': plugin_db = 'neutron' plugin_path = 'neutron.plugins.ml2.plugin.Ml2Plugin' # values modification for key in ('CONFIG_NEUTRON_ML2_TYPE_DRIVERS', 'CONFIG_NEUTRON_ML2_TENANT_NETWORK_TYPES', 'CONFIG_NEUTRON_ML2_MECHANISM_DRIVERS', 'CONFIG_NEUTRON_ML2_FLAT_NETWORKS', 'CONFIG_NEUTRON_ML2_VLAN_RANGES', 'CONFIG_NEUTRON_ML2_TUNNEL_ID_RANGES', 'CONFIG_NEUTRON_ML2_VNI_RANGES'): config[key] = str([i.strip() for i in config[key].split(',') if i]) key = 'CONFIG_NEUTRON_ML2_VXLAN_GROUP' config[key] = "'%s'" % config[key] if config[key] else 'undef' config['CONFIG_NEUTRON_L2_DBNAME'] = plugin_db config['CONFIG_NEUTRON_CORE_PLUGIN'] = plugin_path global api_hosts, l3_hosts, dhcp_hosts, lbaas_hosts, compute_hosts, meta_hosts, q_hosts api_hosts = split_hosts(config['CONFIG_NEUTRON_SERVER_HOST']) l3_hosts = split_hosts(config['CONFIG_NEUTRON_L3_HOSTS']) dhcp_hosts = split_hosts(config['CONFIG_NEUTRON_DHCP_HOSTS']) lbaas_hosts = split_hosts(config['CONFIG_NEUTRON_LBAAS_HOSTS']) meta_hosts = split_hosts(config['CONFIG_NEUTRON_METADATA_HOSTS']) compute_hosts = set() if config['CONFIG_NOVA_INSTALL'] == 'y': compute_hosts = split_hosts(config['CONFIG_NOVA_COMPUTE_HOSTS']) q_hosts = api_hosts | l3_hosts | dhcp_hosts | lbaas_hosts | compute_hosts | meta_hosts neutron_steps = [ {'title': 'Adding Neutron API manifest entries', 'functions': [create_manifests]}, {'title': 'Adding Neutron Keystone manifest entries', 'functions': [create_keystone_manifest]}, {'title': 'Adding Neutron L3 manifest entries', 'functions': [create_l3_manifests]}, {'title': 'Adding Neutron L2 Agent manifest entries', 'functions': [create_l2_agent_manifests]}, {'title': 'Adding Neutron DHCP Agent manifest entries', 'functions': [create_dhcp_manifests]}, {'title': 'Adding Neutron LBaaS Agent manifest entries', 'functions': [create_lbaas_manifests]}, {'title': 'Adding Neutron Metadata Agent manifest entries', 'functions': [create_metadata_manifests]}, ] controller.addSequence("Installing OpenStack Neutron", [], [], neutron_steps) def create_manifests(config): global q_hosts service_plugins = [] if config['CONFIG_NEUTRON_LBAAS_HOSTS']: service_plugins.append( 'neutron.services.loadbalancer.plugin.LoadBalancerPlugin' ) if config['CONFIG_NEUTRON_L2_PLUGIN'] == 'ml2': # ML2 uses the L3 Router service plugin to implement l3 agent service_plugins.append( 'neutron.services.l3_router.l3_router_plugin.L3RouterPlugin' ) config['SERVICE_PLUGINS'] = (str(service_plugins) if service_plugins else 'undef') if config['CONFIG_NEUTRON_L2_PLUGIN'] == 'openvswitch': nettype = config.get("CONFIG_NEUTRON_OVS_TENANT_NETWORK_TYPE", "local") plugin_manifest = 'neutron_ovs_plugin_%s.pp' % nettype elif config['CONFIG_NEUTRON_L2_PLUGIN'] == 'linuxbridge': plugin_manifest = 'neutron_lb_plugin.pp' elif config['CONFIG_NEUTRON_L2_PLUGIN'] == 'ml2': plugin_manifest = 'neutron_ml2_plugin.pp' # host to which allow neutron server allowed_hosts = set(q_hosts) if config['CONFIG_CLIENT_INSTALL'] == 'y': allowed_hosts.add(config['CONFIG_OSCLIENT_HOST']) if config['CONFIG_HORIZON_INSTALL'] == 'y': allowed_hosts.add(config['CONFIG_HORIZON_HOST']) if config['CONFIG_NOVA_INSTALL'] == 'y': allowed_hosts.add(config['CONFIG_NOVA_API_HOST']) for host in q_hosts: manifest_file = "%s_neutron.pp" % (host,) manifest_data = getManifestTemplate("neutron.pp") appendManifestFile(manifest_file, manifest_data, 'neutron') if host in api_hosts: manifest_file = "%s_neutron.pp" % (host,) manifest_data = getManifestTemplate("neutron_api.pp") # Firewall Rules for f_host in allowed_hosts: config['FIREWALL_SERVICE_NAME'] = "neutron server" config['FIREWALL_PORTS'] = "'9696'" config['FIREWALL_CHAIN'] = "INPUT" config['FIREWALL_PROTOCOL'] = 'tcp' config['FIREWALL_ALLOWED'] = "'%s'" % f_host config['FIREWALL_SERVICE_ID'] = "neutron_server_%s_%s" % (host, f_host) manifest_data += getManifestTemplate("firewall.pp") appendManifestFile(manifest_file, manifest_data, 'neutron') # Set up any l2 plugin configs we need anywhere we install neutron # XXX I am not completely sure about this, but it seems necessary: manifest_data = getManifestTemplate(plugin_manifest) # We also need to open VXLAN/GRE port for agent if use_openvswitch_vxlan(config) or use_openvswitch_gre(config): if use_openvswitch_vxlan(config): config['FIREWALL_PROTOCOL'] = 'udp' tunnel_port = ("'%s'" % config['CONFIG_NEUTRON_OVS_VXLAN_UDP_PORT']) else: config['FIREWALL_PROTOCOL'] = 'gre' tunnel_port = 'undef' config['FIREWALL_ALLOWED'] = "'ALL'" config['FIREWALL_SERVICE_NAME'] = "neutron tunnel port" config['FIREWALL_SERVICE_ID'] = ("neutron_tunnel") config['FIREWALL_PORTS'] = tunnel_port config['FIREWALL_CHAIN'] = "INPUT" manifest_data += getManifestTemplate('firewall.pp') appendManifestFile(manifest_file, manifest_data, 'neutron') def create_keystone_manifest(config): manifestfile = "%s_keystone.pp" % config['CONFIG_KEYSTONE_HOST'] manifestdata = getManifestTemplate("keystone_neutron.pp") appendManifestFile(manifestfile, manifestdata) def find_mapping(haystack, needle): return needle in [x.split(':')[1].strip() for x in get_values(haystack)] def create_l3_manifests(config): global l3_hosts plugin = config['CONFIG_NEUTRON_L2_PLUGIN'] if config['CONFIG_NEUTRON_L3_EXT_BRIDGE'] == 'provider': config['CONFIG_NEUTRON_L3_EXT_BRIDGE'] = '' for host in l3_hosts: config['CONFIG_NEUTRON_L3_HOST'] = host config['CONFIG_NEUTRON_L3_INTERFACE_DRIVER'] = get_if_driver(config) manifestdata = getManifestTemplate("neutron_l3.pp") manifestfile = "%s_neutron.pp" % (host,) appendManifestFile(manifestfile, manifestdata + '\n') if (config['CONFIG_NEUTRON_L2_PLUGIN'] == 'openvswitch' and config['CONFIG_NEUTRON_L3_EXT_BRIDGE'] and not find_mapping(config['CONFIG_NEUTRON_OVS_BRIDGE_MAPPINGS'], config['CONFIG_NEUTRON_L3_EXT_BRIDGE'])): config['CONFIG_NEUTRON_OVS_BRIDGE'] = config['CONFIG_NEUTRON_L3_EXT_BRIDGE'] manifestdata = getManifestTemplate('neutron_ovs_bridge.pp') appendManifestFile(manifestfile, manifestdata + '\n') def create_dhcp_manifests(config): global dhcp_hosts plugin = config['CONFIG_NEUTRON_L2_PLUGIN'] for host in dhcp_hosts: config["CONFIG_NEUTRON_DHCP_HOST"] = host config['CONFIG_NEUTRON_DHCP_INTERFACE_DRIVER'] = get_if_driver(config) manifest_data = getManifestTemplate("neutron_dhcp.pp") manifest_file = "%s_neutron.pp" % (host,) # Firewall Rules config['FIREWALL_PROTOCOL'] = 'tcp' for f_host in q_hosts: config['FIREWALL_ALLOWED'] = "'%s'" % f_host config['FIREWALL_SERVICE_NAME'] = "neutron dhcp in" config['FIREWALL_SERVICE_ID'] = "neutron_dhcp_in_%s_%s" % (host, f_host) config['FIREWALL_PORTS'] = "'67'" config['FIREWALL_CHAIN'] = "INPUT" manifest_data += getManifestTemplate("firewall.pp") config['FIREWALL_SERVICE_NAME'] = "neutron dhcp out" config['FIREWALL_SERVICE_ID'] = "neutron_dhcp_out_%s_%s" % (host, f_host) config['FIREWALL_PORTS'] = "'68'" config['FIREWALL_CHAIN'] = "OUTPUT" manifest_data += getManifestTemplate("firewall.pp") appendManifestFile(manifest_file, manifest_data, 'neutron') def create_lbaas_manifests(config): global lbaas_hosts for host in lbaas_hosts: controller.CONF['CONFIG_NEUTRON_LBAAS_INTERFACE_DRIVER'] = get_if_driver(config) manifestdata = getManifestTemplate("neutron_lbaas.pp") manifestfile = "%s_neutron.pp" % (host,) appendManifestFile(manifestfile, manifestdata + "\n") def get_values(val): return [x.strip() for x in val.split(',')] if val else [] def get_agent_type(config): # The only real use case I can think of for multiples right now is to list # "vlan,gre" or "vlan,vxlan" so that VLANs are used if available, # but tunnels are used if not. tenant_types = config.get('CONFIG_NEUTRON_ML2_TENANT_NETWORK_TYPES', "['local']").strip('[]') tenant_types = [i.strip('"\'') for i in tenant_types.split(',')] for i in ['gre', 'vxlan', 'vlan']: if i in tenant_types: return i return tenant_types[0] def create_l2_agent_manifests(config): global api_hosts, compute_hosts, dhcp_host, l3_hosts plugin = config['CONFIG_NEUTRON_L2_PLUGIN'] agent = config["CONFIG_NEUTRON_L2_AGENT"] if agent == "openvswitch": host_var = 'CONFIG_NEUTRON_OVS_HOST' if plugin == agent: # monolithic plugin installation ovs_type = 'CONFIG_NEUTRON_OVS_TENANT_NETWORK_TYPE' ovs_type = config.get(ovs_type, 'local') elif plugin == 'ml2': ovs_type = get_agent_type(config) else: raise RuntimeError('Invalid combination of plugin and agent.') template_name = "neutron_ovs_agent_%s.pp" % ovs_type bm_arr = get_values(config["CONFIG_NEUTRON_OVS_BRIDGE_MAPPINGS"]) iface_arr = get_values(config["CONFIG_NEUTRON_OVS_BRIDGE_IFACES"]) # The CONFIG_NEUTRON_OVS_BRIDGE_MAPPINGS parameter contains a # comma-separated list of bridge mappings. Since the puppet module # expects this parameter to be an array, this parameter must be properly # formatted by packstack, then consumed by the puppet module. # For example, the input string 'A, B, C' should formatted as '['A','B','C']'. config["CONFIG_NEUTRON_OVS_BRIDGE_MAPPINGS"] = str(bm_arr) elif agent == "linuxbridge": host_var = 'CONFIG_NEUTRON_LB_HOST' template_name = 'neutron_lb_agent.pp' else: raise KeyError("Unknown layer2 agent") # Install l2 agents on every compute host in addition to any hosts listed # specifically for the l2 agent for host in api_hosts | compute_hosts | dhcp_hosts | l3_hosts: config[host_var] = host manifestfile = "%s_neutron.pp" % (host,) manifestdata = getManifestTemplate(template_name) appendManifestFile(manifestfile, manifestdata + "\n") # neutron ovs port only on network hosts if ( agent == "openvswitch" and ( (host in l3_hosts and ovs_type in ['vxlan', 'gre']) or ovs_type == 'vlan') ): bridge_key = 'CONFIG_NEUTRON_OVS_BRIDGE' iface_key = 'CONFIG_NEUTRON_OVS_IFACE' for if_map in iface_arr: config[bridge_key], config[iface_key] = if_map.split(':') manifestdata = getManifestTemplate("neutron_ovs_port.pp") appendManifestFile(manifestfile, manifestdata + "\n") # Additional configurations required for compute hosts and # network hosts. manifestdata = getManifestTemplate('neutron_bridge_module.pp') appendManifestFile(manifestfile, manifestdata + '\n') def create_metadata_manifests(config): global meta_hosts if config.get('CONFIG_NOVA_INSTALL') == 'n': return for host in meta_hosts: controller.CONF['CONFIG_NEUTRON_METADATA_HOST'] = host manifestdata = getManifestTemplate('neutron_metadata.pp') manifestfile = "%s_neutron.pp" % (host,) appendManifestFile(manifestfile, manifestdata + "\n")
49.334104
200
0.552819
b1d80ab7be63babb5d736539f972647c426e6b2f
5,003
h
C
device/EFM32GG11B/Include/efm32gg11b_perpriv_register.h
Bucknalla/coprocessor-sdk
1e70d54a77d8c342580189f0e34ebf1e86d030fd
[ "Apache-2.0" ]
8
2019-04-15T08:56:49.000Z
2020-08-19T10:50:55.000Z
device/EFM32GG11B/Include/efm32gg11b_perpriv_register.h
Bucknalla/coprocessor-sdk
1e70d54a77d8c342580189f0e34ebf1e86d030fd
[ "Apache-2.0" ]
21
2019-03-05T21:04:22.000Z
2021-02-04T11:47:43.000Z
device/EFM32GG11B/Include/efm32gg11b_perpriv_register.h
Bucknalla/coprocessor-sdk
1e70d54a77d8c342580189f0e34ebf1e86d030fd
[ "Apache-2.0" ]
7
2019-03-14T15:09:01.000Z
2021-03-11T19:00:14.000Z
/**************************************************************************//** * @file efm32gg11b_perpriv_register.h * @brief EFM32GG11B_PERPRIV_REGISTER register and bit field definitions * @version 5.2.1 ****************************************************************************** * # License * <b>Copyright 2017 Silicon Laboratories, Inc. http://www.silabs.com</b> ****************************************************************************** * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software.@n * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software.@n * 3. This notice may not be removed or altered from any source distribution. * * DISCLAIMER OF WARRANTY/LIMITATION OF REMEDIES: Silicon Laboratories, Inc. * has no obligation to support this Software. Silicon Laboratories, Inc. is * providing the Software "AS IS", with no express or implied warranties of any * kind, including, but not limited to, any implied warranties of * merchantability or fitness for any particular purpose or warranties against * infringement of any proprietary rights of a third party. * * Silicon Laboratories, Inc. will not be liable for any consequential, * incidental, or special damages, or any other relief, or for any claim by * any third party, arising from your use of this Software. * *****************************************************************************/ #if defined(__ICCARM__) #pragma system_include /* Treat file as system include file. */ #elif defined(__ARMCC_VERSION) && (__ARMCC_VERSION >= 6010050) #pragma clang system_header /* Treat file as system include file. */ #endif /**************************************************************************//** * @addtogroup Parts * @{ ******************************************************************************/ /**************************************************************************//** * @defgroup EFM32GG11B_PERPRIV_REGISTER Peripheral Privilege Register * @{ *****************************************************************************/ /** PERPRIV_REGISTER Register Declaration */ typedef struct { /* Note! Use of double __IOM (volatile) qualifier to ensure that both */ /* pointer and referenced memory are declared volatile. */ __IOM int TIMER0 : 1; __IOM int TIMER1 : 1; __IOM int TIMER2 : 1; __IOM int TIMER3 : 1; __IOM int TIMER4 : 1; __IOM int TIMER5 : 1; __IOM int TIMER6 : 1; __IOM int WTIMER0 : 1; __IOM int WTIMER1 : 1; __IOM int WTIMER2 : 1; __IOM int WTIMER3 : 1; __IOM int USART0 : 1; __IOM int USART1 : 1; __IOM int USART2 : 1; __IOM int USART3 : 1; __IOM int USART4 : 1; __IOM int USART5 : 1; __IOM int UART0 : 1; __IOM int UART1 : 1; __IOM int CAN0 : 1; __IOM int CAN1 : 1; __IOM int RESERVED0 : 1; /**< Reserved for future use **/ __IOM int RESERVED1 : 1; /**< Reserved for future use **/ __IOM int TRNG0 : 1; __IOM int MSC : 1; __IOM int EBI : 1; __IOM int ETH : 1; __IOM int LDMA : 1; __IOM int FPUEH : 1; __IOM int GPCRC : 1; __IOM int QSPI0 : 1; __IOM int USB : 1; __IOM int SMU : 1; __IOM int ACMP0 : 1; __IOM int ACMP1 : 1; __IOM int ACMP2 : 1; __IOM int ACMP3 : 1; __IOM int I2C0 : 1; __IOM int I2C1 : 1; __IOM int I2C2 : 1; __IOM int ADC0 : 1; __IOM int ADC1 : 1; __IOM int CRYOTIMER : 1; __IOM int VDAC0 : 1; __IOM int IDAC0 : 1; __IOM int CSEN : 1; __IOM int RESERVED2 : 1; /**< Reserved for future use **/ __IOM int APB_RSYNC_COMB : 1; __IOM int GPIO : 1; __IOM int PRS : 1; __IOM int EMU : 1; __IOM int RMU : 1; __IOM int CMU : 1; __IOM int PCNT0 : 1; __IOM int PCNT1 : 1; __IOM int PCNT2 : 1; __IOM int LEUART0 : 1; __IOM int LEUART1 : 1; __IOM int LETIMER0 : 1; __IOM int LETIMER1 : 1; __IOM int WDOG0 : 1; __IOM int WDOG1 : 1; __IOM int LESENSE : 1; __IOM int LCD : 1; __IOM int RTC : 1; __IOM int RTCC : 1; } PERPRIV_REGISTER_TypeDef; /**< @} */ /** @} End of group Parts */
40.024
80
0.503898
e3f151b351ec317694b6731310ca6beff746b40a
789
go
Go
services/autoscaling/put_scheduled_update_group_action_request.go
lee-yongtak/ncloud-sdk-go-v2
36bb842331ba5a144dfa7a477501bc4980f44a5e
[ "MIT" ]
null
null
null
services/autoscaling/put_scheduled_update_group_action_request.go
lee-yongtak/ncloud-sdk-go-v2
36bb842331ba5a144dfa7a477501bc4980f44a5e
[ "MIT" ]
null
null
null
services/autoscaling/put_scheduled_update_group_action_request.go
lee-yongtak/ncloud-sdk-go-v2
36bb842331ba5a144dfa7a477501bc4980f44a5e
[ "MIT" ]
null
null
null
/* * autoscaling * * <br/>https://ncloud.apigw.ntruss.com/autoscaling/v2 * * API version: 2018-08-07T06:47:31Z * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) */ package autoscaling type PutScheduledUpdateGroupActionRequest struct { // 오토스케일링그룹명 AutoScalingGroupName *string `json:"autoScalingGroupName"` // 기대용량치 DesiredCapacity *int32 `json:"desiredCapacity,omitempty"` // 반복스케쥴종료시간 EndTime *string `json:"endTime,omitempty"` // 최대사이즈 MaxSize *int32 `json:"maxSize,omitempty"` // 최소사이즈 MinSize *int32 `json:"minSize,omitempty"` // 반복스케줄설정 RecurrenceInKST *string `json:"recurrenceInKST,omitempty"` // 스케쥴액션명 ScheduledActionName *string `json:"scheduledActionName"` // 스케쥴시작시간 StartTime *string `json:"startTime,omitempty"` }
20.763158
85
0.746515
0c865092d1b024900a20974bf4805c2c027168ad
1,337
asm
Assembly
src/primes.asm
rprouse/8088
7cba221d5dd515144afa0d7bdd875f914e0e8c9a
[ "MIT" ]
null
null
null
src/primes.asm
rprouse/8088
7cba221d5dd515144afa0d7bdd875f914e0e8c9a
[ "MIT" ]
null
null
null
src/primes.asm
rprouse/8088
7cba221d5dd515144afa0d7bdd875f914e0e8c9a
[ "MIT" ]
null
null
null
; Calculate primes using the Sieve of Eratosthenes cpu 8086 bits 16 org 0x0100 table: equ 0x8000 table_size: equ 1000 jmp start %include 'library.inc' start: mov bx,table mov cx,table_size mov al,0 ; Initialize the memory in the table to zero .zero_loop: mov [bx],al ; Write AL to the address pointed to by BX inc bx loop .zero_loop ; Decrease CX and jump if non-zero mov ax,2 ; Start at first prime, 2. AX is the prime we are testing .check_prime: mov bx,table ; Set BX to the table address add bx,ax ; Add the last prime to BX cmp byte [bx],0 ; Is it a prime? If it is still 0, we haven't marked it as a multiple jne .next push ax ; This is a prime, display it call display_number mov al,',' call chout pop ax mov bx,table add bx,ax .mark_multiples: add bx,ax ; Next multiple of AX cmp bx,table+table_size jg .next ; Make sure we're not at the end of the table mov byte [bx],1 ; Set the value as not-prime in the table jmp .mark_multiples ; Back and multiply again .next: inc ax ; Increment AX to the next number to check cmp ax,table_size ; Make sure we are not at the end jne .check_prime jmp exit
25.711538
93
0.615557
284b2688717d354ae6e7444f223b3fae0698eee2
1,513
rb
Ruby
lib/cute_print/formatter.rb
wconrad/cute_print
9df8f056579324d329030ef0bd6621b3f0fa2aa8
[ "MIT" ]
2
2015-06-19T17:31:24.000Z
2017-09-27T19:44:50.000Z
lib/cute_print/formatter.rb
wconrad/cute_print
9df8f056579324d329030ef0bd6621b3f0fa2aa8
[ "MIT" ]
5
2015-02-25T20:51:57.000Z
2018-03-13T19:29:21.000Z
lib/cute_print/formatter.rb
wconrad/cute_print
9df8f056579324d329030ef0bd6621b3f0fa2aa8
[ "MIT" ]
null
null
null
require "pp" require "stringio" require_relative "format" require_relative "labeler" require_relative "location" require_relative "location_label" require_relative "source_label" require_relative "values" module CutePrint # @api private class Formatter def initialize(opts = {}) @method = opts.fetch(:method) @out = opts.fetch(:out) @block = opts.fetch(:block, nil) @args = opts.fetch(:values, []) @values = Values.new(@args, @block) @width = opts.fetch(:width) @location_label = nil end def write if @values.empty? && !label.empty? write_line label.chomp(": ") else @values.each do |value| labeler = Labeler.new(@format, @width, label, value) write_lines labeler.labeled end end end def with_location(format_key) location = Location.find @location_label = LocationLabel.make(format_key, location) end def inspect @format = Format::Inspect.new end def pretty_print @format = Format::PrettyPrint.new end private def write_lines(lines) lines.each do |line| write_line line end end def write_line(line) line += "\n" unless line =~ /\n\Z/ @out.print line end def label @label ||= make_label end def make_label [ (@location_label.to_s if @location_label), (SourceLabel.new(@block, @method) if @block), ].compact.join end end end
20.173333
64
0.611368
85e1c083470ceaa2b265d2be23bb03565c65d78c
8,569
c
C
src/Setup/ExpressionSetup.c
ScrimpyCat/CommonGameK
47ad7a22140bfac86f36d6e426cb105f21df4277
[ "BSD-2-Clause" ]
9
2016-11-07T14:54:17.000Z
2021-11-14T20:37:22.000Z
src/Setup/ExpressionSetup.c
ScrimpyCat/CommonGameK
47ad7a22140bfac86f36d6e426cb105f21df4277
[ "BSD-2-Clause" ]
8
2017-03-18T23:55:09.000Z
2018-03-18T13:46:57.000Z
src/Setup/ExpressionSetup.c
ScrimpyCat/CommonGameK
47ad7a22140bfac86f36d6e426cb105f21df4277
[ "BSD-2-Clause" ]
2
2018-04-13T00:59:50.000Z
2020-06-07T16:03:25.000Z
//This file is automatically generated, modifications will be lost! #define CC_QUICK_COMPILE #include "ExpressionSetup.h" #include "ExpressionEvaluator.h" #include "MacroExpressions.h" #include "EntityExpressions.h" #include "TypeExpressions.h" #include "IOExpressions.h" #include "MessageExpressions.h" #include "MathExpressions.h" #include "StringExpressions.h" #include "EqualityExpressions.h" #include "ColourExpressions.h" #include "AssetExpressions.h" #include "DebugExpressions.h" #include "StateExpressions.h" #include "GraphicsExpressions.h" #include "BitwiseExpressions.h" #include "WindowExpressions.h" #include "ControlFlowExpressions.h" #include "FontExpressions.h" #include "ListExpressions.h" #include "ComponentExpressions.h" #include "TextExpressions.h" #include "GUIExpression.h" void CCExpressionSetup(void) { CCExpressionEvaluatorRegister(CC_STRING("quote"), CCMacroExpressionQuote); CCExpressionEvaluatorRegister(CC_STRING("unquote"), CCMacroExpressionUnquote); CCExpressionEvaluatorRegister(CC_STRING("entity"), CCEntityExpressionEntity); CCExpressionEvaluatorRegister(CC_STRING("entity-lookup"), CCEntityExpressionEntityLookup); CCExpressionEvaluatorRegister(CC_STRING("type"), CCTypeExpressionGetType); CCExpressionEvaluatorRegister(CC_STRING("integer->float"), CCTypeExpressionIntegerToFloat); CCExpressionEvaluatorRegister(CC_STRING("float->integer"), CCTypeExpressionFloatToInteger); CCExpressionEvaluatorRegister(CC_STRING("print"), CCIOExpressionPrint); CCExpressionEvaluatorRegister(CC_STRING("search"), CCIOExpressionSearch); CCExpressionEvaluatorRegister(CC_STRING("eval"), CCIOExpressionEval); CCExpressionEvaluatorRegister(CC_STRING("component-router"), CCMessageExpressionComponentRouter); CCExpressionEvaluatorRegister(CC_STRING("entity-component-router"), CCMessageExpressionEntityComponentRouter); CCExpressionEvaluatorRegister(CC_STRING("message"), CCMessageExpressionMessage); CCExpressionEvaluatorRegister(CC_STRING("+"), CCMathExpressionAddition); CCExpressionEvaluatorRegister(CC_STRING("-"), CCMathExpressionSubtract); CCExpressionEvaluatorRegister(CC_STRING("*"), CCMathExpressionMultiply); CCExpressionEvaluatorRegister(CC_STRING("/"), CCMathExpressionDivide); CCExpressionEvaluatorRegister(CC_STRING("min"), CCMathExpressionMinimum); CCExpressionEvaluatorRegister(CC_STRING("max"), CCMathExpressionMaximum); CCExpressionEvaluatorRegister(CC_STRING("random"), CCMathExpressionRandom); CCExpressionEvaluatorRegister(CC_STRING("round"), CCMathExpressionRound); CCExpressionEvaluatorRegister(CC_STRING("prefix"), CCStringExpressionPrefix); CCExpressionEvaluatorRegister(CC_STRING("suffix"), CCStringExpressionSuffix); CCExpressionEvaluatorRegister(CC_STRING("filename"), CCStringExpressionFilename); CCExpressionEvaluatorRegister(CC_STRING("replace"), CCStringExpressionReplace); CCExpressionEvaluatorRegister(CC_STRING("cat"), CCStringExpressionConcatenate); CCExpressionEvaluatorRegister(CC_STRING("length"), CCStringExpressionLength); CCExpressionEvaluatorRegister(CC_STRING("insert"), CCStringExpressionInsert); CCExpressionEvaluatorRegister(CC_STRING("remove"), CCStringExpressionRemove); CCExpressionEvaluatorRegister(CC_STRING("chop"), CCStringExpressionChop); CCExpressionEvaluatorRegister(CC_STRING("format"), CCStringExpressionFormat); CCExpressionEvaluatorRegister(CC_STRING("separate"), CCStringExpressionSeparate); CCExpressionEvaluatorRegister(CC_STRING("="), CCEqualityExpressionEqual); CCExpressionEvaluatorRegister(CC_STRING("!="), CCEqualityExpressionNotEqual); CCExpressionEvaluatorRegister(CC_STRING("<="), CCEqualityExpressionLessThanEqual); CCExpressionEvaluatorRegister(CC_STRING(">="), CCEqualityExpressionGreaterThanEqual); CCExpressionEvaluatorRegister(CC_STRING("<"), CCEqualityExpressionLessThan); CCExpressionEvaluatorRegister(CC_STRING(">"), CCEqualityExpressionGreaterThan); CCExpressionEvaluatorRegister(CC_STRING("not"), CCEqualityExpressionNot); CCExpressionEvaluatorRegister(CC_STRING("lighten"), CCColourExpressionLighten); CCExpressionEvaluatorRegister(CC_STRING("darken"), CCColourExpressionDarken); CCExpressionEvaluatorRegister(CC_STRING("shader"), CCAssetExpressionShader); CCExpressionEvaluatorRegister(CC_STRING("texture"), CCAssetExpressionTexture); CCExpressionEvaluatorRegister(CC_STRING("font"), CCAssetExpressionFont); CCExpressionEvaluatorRegister(CC_STRING("library"), CCAssetExpressionLibrary); CCExpressionEvaluatorRegister(CC_STRING("source"), CCAssetExpressionLibrarySource); CCExpressionEvaluatorRegister(CC_STRING("asset"), CCAssetExpressionAsset); CCExpressionEvaluatorRegister(CC_STRING("inspect"), CCDebugExpressionInspect); CCExpressionEvaluatorRegister(CC_STRING("break"), CCDebugExpressionBreak); CCExpressionEvaluatorRegister(CC_STRING("measure"), CCDebugExpressionMeasure); CCExpressionEvaluatorRegister(CC_STRING("state!"), CCStateExpressionCreateState); CCExpressionEvaluatorRegister(CC_STRING("namespace!"), CCStateExpressionCreateNamespace); CCExpressionEvaluatorRegister(CC_STRING("enum!"), CCStateExpressionCreateEnum); CCExpressionEvaluatorRegister(CC_STRING("super"), CCStateExpressionSuper); CCExpressionEvaluatorRegister(CC_STRING("strict-super"), CCStateExpressionStrictSuper); CCExpressionEvaluatorRegister(CC_STRING("render-rect"), CCGraphicsExpressionRenderRect); CCExpressionEvaluatorRegister(CC_STRING("render-text"), CCGraphicsExpressionRenderText); CCExpressionEvaluatorRegister(CC_STRING("and"), CCBitwiseExpressionAnd); CCExpressionEvaluatorRegister(CC_STRING("or"), CCBitwiseExpressionOr); CCExpressionEvaluatorRegister(CC_STRING("xor"), CCBitwiseExpressionXor); CCExpressionEvaluatorRegister(CC_STRING("window-percent-width"), CCWindowExpressionPercentageWidth); CCExpressionEvaluatorRegister(CC_STRING("window-percent-height"), CCWindowExpressionPercentageHeight); CCExpressionEvaluatorRegister(CC_STRING("window-width"), CCWindowExpressionWidth); CCExpressionEvaluatorRegister(CC_STRING("window-height"), CCWindowExpressionHeight); CCExpressionEvaluatorRegister(CC_STRING("window-resized?"), CCWindowExpressionWindowResized); CCExpressionEvaluatorRegister(CC_STRING("frame-changed?"), CCWindowExpressionFrameChanged); CCExpressionEvaluatorRegister(CC_STRING("begin"), CCControlFlowExpressionBegin); CCExpressionEvaluatorRegister(CC_STRING("if"), CCControlFlowExpressionBranch); CCExpressionEvaluatorRegister(CC_STRING("cond"), CCControlFlowExpressionCond); CCExpressionEvaluatorRegister(CC_STRING("loop"), CCControlFlowExpressionLoop); CCExpressionEvaluatorRegister(CC_STRING("repeat"), CCControlFlowExpressionRepeat); CCExpressionEvaluatorRegister(CC_STRING("loop!"), CCControlFlowExpressionLoopPersist); CCExpressionEvaluatorRegister(CC_STRING("repeat!"), CCControlFlowExpressionRepeatPersist); CCExpressionEvaluatorRegister(CC_STRING("any?"), CCControlFlowExpressionAny); CCExpressionEvaluatorRegister(CC_STRING("all?"), CCControlFlowExpressionAll); CCExpressionEvaluatorRegister(CC_STRING("font-line-height"), CCFontExpressionGetLineHeight); CCExpressionEvaluatorRegister(CC_STRING("get"), CCListExpressionGetter); CCExpressionEvaluatorRegister(CC_STRING("set"), CCListExpressionSetter); CCExpressionEvaluatorRegister(CC_STRING("drop"), CCListExpressionDrop); CCExpressionEvaluatorRegister(CC_STRING("flatten"), CCListExpressionFlatten); CCExpressionEvaluatorRegister(CC_STRING("parts"), CCListExpressionParts); CCExpressionEvaluatorRegister(CC_STRING("split"), CCListExpressionSplit); CCExpressionEvaluatorRegister(CC_STRING("count"), CCListExpressionCount); CCExpressionEvaluatorRegister(CC_STRING("component"), CCComponentExpressionComponent); CCExpressionEvaluatorRegister(CC_STRING("text-visible-length"), CCTextExpressionGetVisibleLength); CCExpressionEvaluatorRegister(CC_STRING("text-cursor-position"), CCTextExpressionGetCursorPosition); CCExpressionEvaluatorRegister(CC_STRING("text-cursor-offset"), CCTextExpressionGetCursorOffset); CCExpressionEvaluatorRegister(CC_STRING("gui"), GUIExpressionRegisterObject); CCExpressionEvaluatorRegister(CC_STRING("percent-width"), GUIExpressionPercentWidth); CCExpressionEvaluatorRegister(CC_STRING("percent-height"), GUIExpressionPercentHeight); CCExpressionEvaluatorRegister(CC_STRING("on"), GUIExpressionOnEvent); }
70.237705
114
0.826234
1a645c19448d1b78ea29333b1560e2b45f19d31e
2,406
lua
Lua
Code/['World']['Global']['Xls']['BowInfoXlsModule'].ModuleScript.lua
lilith-avatar/Social-island
009e43118a112c03dea77ec3e43899da9fbde32e
[ "MIT" ]
3
2021-04-20T09:39:11.000Z
2021-05-06T06:46:22.000Z
Code/['World']['Global']['Xls']['BowInfoXlsModule'].ModuleScript.lua
lilith-avatar/Social-island
009e43118a112c03dea77ec3e43899da9fbde32e
[ "MIT" ]
1
2021-04-12T13:00:53.000Z
2021-04-12T13:00:53.000Z
Code/['World']['Global']['Xls']['BowInfoXlsModule'].ModuleScript.lua
lilith-avatar/Social-island
009e43118a112c03dea77ec3e43899da9fbde32e
[ "MIT" ]
1
2021-05-12T09:51:41.000Z
2021-05-12T09:51:41.000Z
--- This file is generated by ava-x2l.exe, --- Don't change it manaully. --- @copyright Lilith Games, Project Da Vinci(Avatar Team) --- @see https://www.projectdavinci.com/ --- @see https://github.com/endaye/avatar-ava-xls2lua --- source file: .//GameHunting.xlsx local BowInfoXls = { [1] = { Id = 1, Ico = 'Ico_Bow_01', Modle = 'M_Bow_01', Offset = Vector3(0, 0, 0), AniSpeed = 1, Bullet = 'M_Arrow_01', HitEffect = 'bulinbulin', CanCharge = true, MinSpeed = 5.0, MaxSpeed = 10.0, Range = 0.0, AfterEffect = 'onfire', AfterEffectKeep = 3.0, Huntable = true, HitAni = 'Hit' }, [2] = { Id = 2, Ico = 'Ico_Bow_02', Modle = 'M_Bow_02', Offset = Vector3(0, 0, 0), AniSpeed = 1, Bullet = 'M_Arrow_02', HitEffect = 'bulinbulin', CanCharge = true, MinSpeed = 5.0, MaxSpeed = 10.0, Range = 0.0, AfterEffect = 'onfire', AfterEffectKeep = 3.0, Huntable = true, HitAni = 'Hit' }, [3] = { Id = 3, Ico = 'Ico_Bow_03', Modle = 'M_Bow_03', Offset = Vector3(0, 0, 0), AniSpeed = 1, Bullet = 'M_Arrow_03', HitEffect = 'bulinbulin', CanCharge = true, MinSpeed = 5.0, MaxSpeed = 10.0, Range = 0.0, AfterEffect = 'onfire', AfterEffectKeep = 3.0, Huntable = true, HitAni = 'Hit' }, [4] = { Id = 4, Ico = 'Ico_Bow_04', Modle = 'M_Bow_04', Offset = Vector3(0, 0, 0), AniSpeed = 1, Bullet = 'M_Arrow_04', HitEffect = 'bulinbulin', CanCharge = true, MinSpeed = 5.0, MaxSpeed = 10.0, Range = 0.0, AfterEffect = 'onfire', AfterEffectKeep = 3.0, Huntable = true, HitAni = 'Hit' }, [5] = { Id = 5, Ico = 'Ico_Bow_05', Modle = 'M_Bow_05', Offset = Vector3(0, 0, 0), AniSpeed = 3, Bullet = 'M_Arrow_05', HitEffect = 'bulinbulin', CanCharge = true, MinSpeed = 5.0, MaxSpeed = 10.0, Range = 0.0, AfterEffect = 'onfire', AfterEffectKeep = 3.0, Huntable = true, HitAni = 'Hit' } } return BowInfoXls
24.804124
58
0.476725
9c3480bb3d3bf65d3d1391fe49f56590ba6a6c37
1,312
js
JavaScript
src/utils/getEmblems.js
FabriSilve/bookclub
2fab40cd83a34b319bcc0ba0ceeb6361e0f3ac09
[ "MIT" ]
null
null
null
src/utils/getEmblems.js
FabriSilve/bookclub
2fab40cd83a34b319bcc0ba0ceeb6361e0f3ac09
[ "MIT" ]
null
null
null
src/utils/getEmblems.js
FabriSilve/bookclub
2fab40cd83a34b319bcc0ba0ceeb6361e0f3ac09
[ "MIT" ]
null
null
null
import none from '../images/emblems/none.png'; import ajax from '../images/emblems/ajax.png'; import arsenal from '../images/emblems/arsenal.png'; import madrid from '../images/emblems/madrid.png'; import leverkusen from '../images/emblems/leverkusen.png'; import chelsea from '../images/emblems/chelsea.png'; import everton from '../images/emblems/everton.png'; import inter from '../images/emblems/inter.png'; import lazio from '../images/emblems/lazio.png'; import manchester from '../images/emblems/manchester.png'; import milan from '../images/emblems/milan.png'; import napoli from '../images/emblems/napoli.png'; import lyonnaise from '../images/emblems/lyonnais.png'; import roma from '../images/emblems/roma.png'; import tottenham from '../images/emblems/tottenham.png'; import valencia from '../images/emblems/valencia.png'; const emblems = { 'ajax': ajax, 'arsenal': arsenal, 'madrid': madrid, 'leverkusen': leverkusen, 'chelsea': chelsea, 'everton': everton, 'inter': inter, 'lazio': lazio, 'manchester': manchester, 'milan': milan, 'napoli': napoli, 'lyonnais': lyonnaise, 'roma': roma, 'tottenham': tottenham, 'valencia': valencia, }; const getEmblem = (team) => { const logo = emblems[team]; if (logo) return logo; return none; }; export default getEmblem;
29.818182
58
0.707317
12af8e6739106beee60537c14f2e92b431b2e9ca
672
h
C
CustomerSystem-ios/HelpDeskUI/HDUIKit/3rdparty/HDMJRefresh/Base/HDMJRefreshFooter.h
dujiepeng/kefu-ios-demo
3e43fd76d0ea51ba53da0ca5ca2e699da1be86d4
[ "MIT" ]
null
null
null
CustomerSystem-ios/HelpDeskUI/HDUIKit/3rdparty/HDMJRefresh/Base/HDMJRefreshFooter.h
dujiepeng/kefu-ios-demo
3e43fd76d0ea51ba53da0ca5ca2e699da1be86d4
[ "MIT" ]
null
null
null
CustomerSystem-ios/HelpDeskUI/HDUIKit/3rdparty/HDMJRefresh/Base/HDMJRefreshFooter.h
dujiepeng/kefu-ios-demo
3e43fd76d0ea51ba53da0ca5ca2e699da1be86d4
[ "MIT" ]
null
null
null
// HDMJRefreshFooter.h // HDMJRefreshExample // // Created by MJ Lee on 15/3/5. #import "HDMJRefreshComponent.h" @interface HDMJRefreshFooter : HDMJRefreshComponent + (instancetype)footerWithRefreshingBlock:(HDMJRefreshComponentRefreshingBlock)refreshingBlock; + (instancetype)footerWithRefreshingTarget:(id)target refreshingAction:(SEL)action; - (void)endRefreshingWithNoMoreData; - (void)noticeNoMoreData HDMJRefreshDeprecated("Please use endRefreshingWithNoMoreData"); - (void)resetNoMoreData; @property (assign, nonatomic) CGFloat ignoredScrollViewContentInsetBottom; @property (assign, nonatomic, getter=isAutomaticallyHidden) BOOL automaticallyHidden; @end
32
95
0.825893
f40b33f0f7b0ecfdde0645cd9570314811b4f8d9
4,855
sql
SQL
database/demo/demo_script/03_demo_utl_xml_parsequery.sql
bjtp/plscope-utils
4d62d54701dc35eca7b7c4941a0205936484f797
[ "Apache-2.0" ]
null
null
null
database/demo/demo_script/03_demo_utl_xml_parsequery.sql
bjtp/plscope-utils
4d62d54701dc35eca7b7c4941a0205936484f797
[ "Apache-2.0" ]
null
null
null
database/demo/demo_script/03_demo_utl_xml_parsequery.sql
bjtp/plscope-utils
4d62d54701dc35eca7b7c4941a0205936484f797
[ "Apache-2.0" ]
null
null
null
-- 1. parse a select statement using sys.utl_xml.parsequery SELECT parse_util.parse_query( in_parse_user => user, in_query => q'[ SELECT /*+ordered */ d.deptno, d.dname, SUM(e.sal + NVL(e.comm, 0)) AS sal FROM dept d LEFT JOIN (SELECT * FROM emp WHERE hiredate > DATE '1980-01-01') e ON e.deptno = d.deptno GROUP BY d.deptno, d.dname ]' ) FROM dual; -- 2. parse an insert statement using sys.utl_xml.parsequery SELECT parse_util.parse_query( in_parse_user => user, in_query => q'[ INSERT INTO deptsal (dept_no, dept_name, salary) SELECT /*+ordered */ d.deptno, d.dname, SUM(e.sal + NVL(e.comm, 0)) AS sal FROM dept d LEFT JOIN (SELECT * FROM emp WHERE hiredate > DATE '1980-01-01') e ON e.deptno = d.deptno GROUP BY d.deptno, d.dname ]' ) FROM dual; -- 3. parse an update statement using sys.utl_xml.parsequery SELECT parse_util.parse_query( in_parse_user => user, in_query => q'[ UPDATE deptsal SET salary = salary + 10 WHERE dept_no = (SELECT deptno FROM dept WHERE dname = 'SALES') ]' ) FROM dual; -- 4. parse a delete statement using sys.util_xml_parsequery SELECT parse_util.parse_query( in_parse_user => user, in_parse_query => q'[ DELETE deptsal WHERE dept_no = (SELECT deptno FROM dept WHERE dname = 'SALES') ]' ) FROM dual; -- 5. parse a merge statement using sys.util_xml_parsequery SELECT parse_util.parse_query( in_parse_user => user, in_query => q'[ MERGE INTO deptsal t USING ( SELECT /*+ordered */ d.deptno, d.dname, SUM(e.sal + NVL(e.comm, 0)) AS sal FROM dept d LEFT JOIN (SELECT * FROM emp WHERE hiredate > DATE '1980-01-01') e ON e.deptno = d.deptno GROUP BY d.deptno, d.dname ) s ON (t.dept_no = s.deptno) WHEN MATCHED THEN UPDATE SET t.salary = s.sal * 0.1 WHEN NOT MATCHED THEN INSERT (t.dept_no, t.dept_name, t.salary) VALUES (s.deptno, s.dname, s.sal * 0.1) ]' ) FROM dual; -- 6. parse an anonymous PL/SQL block using sys.util_xml_parsequery - empty! SELECT parse_util.parse_query( in_parse_user => user, in_parse_query => q'[ BEGIN INSERT INTO deptsal (dept_no, dept_name, salary) SELECT /*+ordered */ d.deptno, d.dname, SUM(e.sal + NVL(e.comm, 0)) AS sal FROM dept d LEFT JOIN (SELECT * FROM emp WHERE hiredate > DATE '1980-01-01') e ON e.deptno = d.deptno GROUP BY d.deptno, d.dname; -- avoid premature statement termination in SQL*Plus et al. END; -- avoid premature statement termination in SQL*Plus et al. ]' ) FROM dual; -- 7. parse a select statement with a function using sys.utl_xml.parsequery - empty! SELECT parse_util.parse_query( in_parse_user => user, in_query => q'[ WITH FUNCTION my_add(in_a IN NUMBER, in_b IN NUMBER) RETURN NUMBER IS BEGIN RETURN NVL(in_a, 0) + NVL(in_b, 0); -- avoid premature statement termination in SQL*Plus et al. END my_add; -- avoid premature statement termination in SQL*Plus et al. SELECT /*+ordered */ d.deptno, d.dname, SUM(my_add(e.sal, e.comm)) AS sal FROM dept d LEFT JOIN (SELECT * FROM emp WHERE hiredate > DATE '1980-01-01') e ON e.deptno = d.deptno GROUP BY d.deptno, d.dname ]' ) FROM dual; -- 8. parse a select statement with a 12.2 features using sys.utl_xml.parsequer SELECT parse_util.parse_query( in_parse_user => user, in_query => q'[ SELECT CAST('x' AS NUMBER DEFAULT 0 ON CONVERSION ERROR) AS cast_col, VALIDATE_CONVERSION('$29.99' AS BINARY_FLOAT, '$99D99') AS validate_col, LISTAGG( ename || ' (' || job || ')', ', ' ON OVERFLOW TRUNCATE '...' WITH COUNT ) WITHIN GROUP (ORDER BY deptno) AS enames FROM emp ]' ) FROM dual;
39.471545
114
0.508342
d86919b31fe48ca967fedadbefafa62b35da669e
96
sql
SQL
popx/stub/migrations/transactional/20200831110752000018_identity_verifiable_address_remove_code.sqlite3.down.sql
svrakitin/x
37110c95b9fb5e9b007a6b4369aaefb2d612bd02
[ "Apache-2.0" ]
33
2018-10-08T12:12:00.000Z
2022-03-29T11:40:24.000Z
popx/stub/migrations/transactional/20200831110752000018_identity_verifiable_address_remove_code.sqlite3.down.sql
svrakitin/x
37110c95b9fb5e9b007a6b4369aaefb2d612bd02
[ "Apache-2.0" ]
118
2018-10-20T16:00:42.000Z
2022-03-24T17:54:17.000Z
popx/stub/migrations/transactional/20200831110752000018_identity_verifiable_address_remove_code.sqlite3.down.sql
svrakitin/x
37110c95b9fb5e9b007a6b4369aaefb2d612bd02
[ "Apache-2.0" ]
64
2018-10-14T03:00:10.000Z
2022-03-11T07:19:21.000Z
UPDATE identity_verifiable_addresses SET expires_at = CURRENT_TIMESTAMP WHERE expires_at IS NULL
96
96
0.895833
d0a08b690b245a58617ea8e5fa62c2e25b9c2a55
118
lua
Lua
apps/vmq_diversity/test/bcrypt_test.lua
joskwanten/vernemq
67640325ce3321d035ed9191e3d313d0def43507
[ "Apache-2.0" ]
1,588
2015-05-27T19:13:50.000Z
2018-11-02T08:07:56.000Z
apps/vmq_diversity/test/bcrypt_test.lua
joskwanten/vernemq
67640325ce3321d035ed9191e3d313d0def43507
[ "Apache-2.0" ]
900
2018-11-02T09:20:24.000Z
2022-03-31T17:13:58.000Z
apps/vmq_diversity/test/bcrypt_test.lua
joskwanten/vernemq
67640325ce3321d035ed9191e3d313d0def43507
[ "Apache-2.0" ]
212
2018-11-14T09:12:42.000Z
2022-03-24T05:10:17.000Z
salt = bcrypt.gen_salt() hash = bcrypt.hashpw("my-password", salt) assert(bcrypt.hashpw("my-password", hash) == hash)
29.5
50
0.711864
0ce5d95f10a05417cb3b6fc154c24d7adc27cf45
1,877
py
Python
scripts/baxter_find_tf.py
mkrizmancic/qlearn_baxter
0498315212cacb40334cbb97a858c6ba317f52a3
[ "MIT" ]
4
2017-11-11T18:16:22.000Z
2018-11-08T13:31:09.000Z
scripts/baxter_find_tf.py
mkrizmancic/qlearn_baxter
0498315212cacb40334cbb97a858c6ba317f52a3
[ "MIT" ]
null
null
null
scripts/baxter_find_tf.py
mkrizmancic/qlearn_baxter
0498315212cacb40334cbb97a858c6ba317f52a3
[ "MIT" ]
2
2019-09-04T12:28:58.000Z
2021-09-27T13:02:48.000Z
#!/usr/bin/env python """Calculate transformation matrices and broadcast transform from robot's base to head markers.""" import rospy import tf import math from PyKDL import Vector, Frame, Rotation if __name__ == '__main__': rospy.init_node('baxter_find_transformation') listener = tf.TransformListener() br = tf.TransformBroadcaster() rate = rospy.Rate(50) while not rospy.is_shutdown(): try: (trans_OH, rot_OH) = listener.lookupTransform('/optitrack', '/bax_head', rospy.Time(0)) (trans_OA, rot_OA) = listener.lookupTransform('/optitrack', '/bax_arm', rospy.Time(0)) (trans_BG, rot_BG) = listener.lookupTransform('/base', '/left_gripper_base', rospy.Time(0)) except (tf.LookupException, tf.ConnectivityException, tf.ExtrapolationException): continue # Rotations rot_OH = Rotation.Quaternion(*rot_OH) rot_OA = Rotation.Quaternion(*rot_OA) rot_BG = Rotation.Quaternion(*rot_BG) rot_AG = Rotation.RPY(math.pi / 2, -math.pi, math.pi / 2) # Creating Frames T_OH = Frame(rot_OH, Vector(*trans_OH)) T_OA = Frame(rot_OA, Vector(*trans_OA)) T_BG = Frame(rot_BG, Vector(*trans_BG)) T_AG = Frame(rot_AG, Vector(0, 0, 0)) # Finding right transformation T_HB = T_OH.Inverse() * T_OA * T_AG * T_BG.Inverse() T_empty_p = Vector(0, 0, 0) T_empty_Q = Rotation.Quaternion(0, 0, 0, 1) T_empty = Frame(T_empty_Q, T_empty_p) # Broadcast new transformations br.sendTransform(T_HB.p, T_HB.M.GetQuaternion(), rospy.Time.now(), 'base', 'bax_head') br.sendTransform(T_HB.p, T_HB.M.GetQuaternion(), rospy.Time.now(), 'reference/base', 'bax_head') br.sendTransform(T_empty.p, T_empty.M.GetQuaternion(), rospy.Time.now(), 'world', 'base') rate.sleep()
39.93617
104
0.64731
ade1192e66419a4f1a0f70babfae972e654e2cc0
13,712
lua
Lua
3DreamEngine/loader/dae.lua
sewbacca/3DreamEngine
d688b7d04fd7ffdbedaa55b0d26785e78304bbca
[ "MIT" ]
209
2019-04-01T20:58:05.000Z
2022-03-30T20:02:26.000Z
3DreamEngine/loader/dae.lua
sewbacca/3DreamEngine
d688b7d04fd7ffdbedaa55b0d26785e78304bbca
[ "MIT" ]
54
2019-03-30T23:58:34.000Z
2022-02-01T14:20:57.000Z
3DreamEngine/loader/dae.lua
sewbacca/3DreamEngine
d688b7d04fd7ffdbedaa55b0d26785e78304bbca
[ "MIT" ]
12
2019-03-31T09:50:25.000Z
2022-03-03T09:52:04.000Z
--[[ #dae - COLLADA --]] --load space seperated arrays as floats or as strings local function loadFloatArray(arr) local t = { } for w in arr:gmatch("%S+") do t[#t+1] = tonumber(w) end return t end local function loadArray(arr) local t = { } for w in arr:gmatch("%S+") do t[#t+1] = w end return t end --load entire tree and index all IDs local indices local localToGlobal local function indexTree(node) for key,child in pairs(node) do if type(child) == "table" and key ~= "_attr" then indexTree(child) end end if node._attr and node._attr.id then indices[node._attr.id] = node indices["#" .. node._attr.id] = node if node._attr.sid then localToGlobal[node._attr.sid] = node._attr.id end end end return function(self, obj, path) local xml2lua = require(self.root .. "/libs/xml2lua/xml2lua") local handler = require(self.root .. "/libs/xml2lua/tree"):new() --parse local file = love.filesystem.read(path) xml2lua.parser(handler):parse(file) local correction = mat4:getRotateX(-math.pi/2) local root = handler.root.COLLADA[1] --get id indices indices = { } localToGlobal = { } indexTree(root) --load armatures and vertex weights local armatures = { } local controllers = { } if root.library_controllers then for d,s in ipairs(root.library_controllers[1].controller) do if s.skin then local name = s.skin[1]._attr.source:sub(2) local a = { weights = { }, joints = { }, jointIDs = { }, } armatures[name] = a controllers[s._attr.id] = name --load sources local weights = { } for i,v in ipairs(s.skin[1].source) do local typ = v.technique_common[1].accessor[1].param[1]._attr.name if typ == "JOINT" then a.jointIDs = loadArray(v.Name_array[1][1]) for d,s in ipairs(a.jointIDs) do a.jointIDs[d] = localToGlobal[s] or s end elseif typ == "WEIGHT" then weights = loadFloatArray(v.float_array[1][1]) end end --load weights local vw = s.skin[1].vertex_weights[1] local vcount = vw.vcount and loadFloatArray(vw.vcount[1][1]) or { } local ids = loadFloatArray(vw.v[1][1]) local count = tonumber(vw._attr.count) local fields = #vw.input for _,input in ipairs(vw.input) do local typ = input._attr.semantic local offset = 1 + tonumber(input._attr.offset) if typ == "JOINT" then local ci = 1 for i = 1, count do local verts = vcount[i] or 1 a.joints[i] = { } for v = 1, verts do local id = ids[(ci-1)*fields+offset] a.joints[i][v] = id+1 ci = ci + 1 end end elseif typ == "WEIGHT" then local ci = 1 for i = 1, count do local verts = vcount[i] or 1 a.weights[i] = { } for v = 1, verts do local id = ids[(ci-1)*fields+offset] a.weights[i][v] = weights[id+1] ci = ci + 1 end end end end --normalize weights and limit to 4 (GPU limit) for i = 1, #a.weights do while #a.weights[i] > 4 do local min, best = math.huge, 1 for d,s in ipairs(a.weights[i]) do if s < min then min = s best = d end end table.remove(a.joints[i], best) table.remove(a.weights[i], best) end --normalize local sum = 0 for d,s in ipairs(a.weights[i]) do sum = sum + s end if sum > 0 then for d,s in ipairs(a.weights[i]) do a.weights[i][d] = s / sum end end end end end end --load materials if root.library_materials then for _,mat in ipairs(root.library_materials[1].material) do local name = mat._attr.name local material = self:newMaterial(name) obj.materials[name] = material indices[mat._attr.id] = material --load if mat.instance_effect then local effect = indices[mat.instance_effect[1]._attr.url] --get first profile local profile for d,s in pairs(effect) do profile = s[1] end --parse data if profile then for step, dataArr in pairs(profile.technique[1]) do if step ~= "_attr" then local data = dataArr[1] if data.emission then local e = data.emission[1] if e.color then local color = loadFloatArray( e.color[1][1] ) material.emission = {color[1] * color[4], color[2] * color[4], color[3] * color[4]} end end if data.diffuse then local d = data.diffuse[1] if d.color then local color = loadFloatArray( d.color[1][1] ) material.color = color end end if data.specular then local s = data.specular[1] if s.color then local color = loadFloatArray( s.color[1][1] ) material.specular = math.sqrt(color[1]^2 + color[2]^2 + color[3]^2) end end if data.shininess then material.glossiness = tonumber( data.shininess[1].float[1][1] ) end if data.index_of_refraction then material.ior = tonumber( data.index_of_refraction[1].float[1][1] ) end end end end end end end --load main geometry local meshData = { } for d,geo in ipairs(root.library_geometries[1].geometry) do local mesh = geo.mesh[1] local id = geo._attr.id meshData[id] = meshData[id] or { } --translation table local translate = { ["VERTEX"] = "vertices", ["NORMAL"] = "normals", ["TEXCOORD"] = "texCoords", ["COLOR"] = "colors", } --parse vertices local o local lastMaterial local index = 0 local edges = { } for typ = 1, 3 do local list if typ == 1 then list = mesh.triangles elseif typ == 2 then list = mesh.polylist else list = mesh.polygons end if list then for _,l in ipairs(list) do local mat = indices[l._attr.material] or obj.materials.None local material = self.materialLibrary[mat.name] or mat if obj.args.splitMaterials then o = self:newSubObject(geo._attr.id, obj, material) meshData[id][#meshData[id]+1] = o index = 0 elseif not o then o = self:newSubObject(geo._attr.id, obj, material) meshData[id][#meshData[id]+1] = o end --connect with armature if armatures[o.name] and not o.weights then o.weights = { } o.joints = { } o.jointIDs = armatures[o.name].jointIDs end --ids of source components per vertex local ids local vcount if typ == 3 then ids = { } vcount = { } --combine polygons for _,p in ipairs(l.p) do local a = loadFloatArray(p[1]) for _,v in ipairs(a) do ids[#ids+1] = v end vcount[#vcount+1] = #a end else ids = loadFloatArray(l.p[1][1]) vcount = l.vcount and loadFloatArray(l.vcount[1][1]) or { } end --get max offset local fields = 0 for d,input in ipairs(l.input) do fields = tonumber(input._attr.offset) + 1 end --parse data arrays local verticeIndex = { } for d,input in ipairs(l.input) do local f = translate[input._attr.semantic] if f then local s = loadFloatArray( (indices[input._attr.source].input and indices[ indices[input._attr.source].input[1]._attr.source ] or indices[input._attr.source]).float_array[1][1] ) for i = 1, #ids / fields do local id = ids[(i-1)*fields + tonumber(input._attr.offset) + 1] if f == "texCoords" then --xy vector o[f][index+i] = { s[id*2+1], 1.0-s[id*2+2], } elseif f == "colors" then --rgba vector o[f][index+i] = { s[id*4+1], s[id*4+2], s[id*4+3], s[id*4+4], } else --xyz vectors o[f][index+i] = { s[id*3+1], s[id*3+2], s[id*3+3] } if f == "vertices" then verticeIndex[index+i] = id end --also connect weight and joints if f == "vertices" and o.weights then o.weights[index+i] = armatures[o.name].weights[id+1] o.joints[index+i] = armatures[o.name].joints[id+1] o.materials[index+i] = material end end end end end --parse polygons local count = l._attr.count local i = index+1 for face = 1, count do local verts = vcount[face] or 3 --store edges for v = 1, verts do local a, b = i + v - 1, v == verts and i or (i + v) local min = math.min(verticeIndex[a], verticeIndex[b]) local max = math.max(verticeIndex[a], verticeIndex[b]) local id = min * 65536 + max if not edges[id] then edges[id] = true o.edges[#o.edges+1] = {a, b} end end if verts == 3 then --tris o.faces[#o.faces+1] = {i, i+1, i+2} else --triangulates, fan style for f = 1, verts-2 do o.faces[#o.faces+1] = {i, i+f, i+f+1} end end i = i + verts end index = #o.vertices end end end end --load light local lightIDs = { } if root.library_lights then for d,light in ipairs(root.library_lights[1].light) do local l = self:newLight() lightIDs[light._attr.id] = l if light.extra and light.extra[1] and light.extra[1].technique and light.extra[1].technique[1] then local dat = light.extra[1].technique[1] l:setColor(dat.red and tonumber(dat.red[1][1]) or 1.0, dat.green and tonumber(dat.green[1][1]) or 1.0, dat.blue and tonumber(dat.blue[1][1]) or 1.0) l:setBrightness(dat.energy and tonumber(dat.energy[1][1]) or 1.0) end table.insert(obj.lights, l) end end local function addObject(name, mesh, transform) for _,subObject in ipairs(meshData[mesh]) do local id = name if obj.args.splitMaterials then id = id .. "_" .. subObject.material.name end obj.objects[id] = subObject:clone() obj.objects[id].name = name obj.objects[id].transform = correction * transform end end --load scene for d,s in ipairs(root.library_visual_scenes[1].visual_scene[1].node) do obj.joints = { } if s.instance_geometry then --object local id = s.instance_geometry[1]._attr.url:sub(2) local name = s._attr.name or s._attr.id local transform = mat4(loadFloatArray(s.matrix[1][1])) addObject(name, id, transform) elseif s.instance_light then local transform = correction * mat4(loadFloatArray(s.matrix[1][1])) local l = lightIDs[s.instance_light[1]._attr.url:sub(2)] l:setPosition(transform[4], transform[8], transform[12]) elseif s._attr.name == "Armature" then --propably an armature --TODO: not a proper way to identify armature nodes local function skeletonLoader(nodes, parentTransform) local skel = { } for d,s in ipairs(nodes) do if s.instance_controller then --object associated with skeleton local id = s.instance_controller[1]._attr.url:sub(2) local mesh = controllers[id] local name = s._attr.name or s._attr.id local transform = mat4(loadFloatArray(s.matrix[1][1])) addObject(name, mesh, transform) end if s._attr.type == "JOINT" then local name = s._attr.id local m = mat4(loadFloatArray(s.matrix[1][1])) local bindTransform = parentTransform and parentTransform * m or m skel[name] = { name = name, bindTransform = m, inverseBindTransform = bindTransform:invert(), } obj.joints[name] = skel[name] if s.node then skel[name].children = skeletonLoader(s.node, bindTransform) end end end return skel end obj.skeleton = skeletonLoader(s.node) break end end --load animations if root.library_animations then local animations = { } local function loadAnimation(anim) for _,a in ipairs(anim) do if a.animation then loadAnimation(a.animation) else local keyframes = { } local name = a.channel[1]._attr.target:sub(1, -11) --parse sources local sources = { } for d,s in ipairs(a.source) do sources[s._attr.id] = s.float_array and loadFloatArray(s.float_array[1][1]) or s.Name_array and loadArray(s.Name_array[1][1]) end for d,s in ipairs(a.sampler[1].input) do sources[s._attr.semantic] = sources[s._attr.source:sub(2)] end --get matrices local frames = { } local positions = { } for i = 1, #sources.OUTPUT / 16 do local m = mat4(unpack(sources.OUTPUT, i*16-15, i*16)) frames[#frames+1] = { time = sources.INPUT[i], --interpolation = sources.INTERPOLATION[i], rotation = quat.fromMatrix(m:subm()), position = vec3(m[4], m[8], m[12]), } end --pack animations[name] = frames end end end loadAnimation(root.library_animations[1].animation) --split animations if obj.args.animations then obj.animations = { } obj.animationLengths = { } for anim, time in pairs(obj.args.animations) do obj.animations[anim] = { } obj.animationLengths[anim] = time[2] - time[1] for joint, frames in pairs(animations) do local newFrames = { } for i, frame in ipairs(frames) do if frame.time >= time[1] and frame.time <= time[2] then table.insert(newFrames, frame) end end obj.animations[anim][joint] = newFrames end end else obj.animations = { default = animations, } obj.animationLengths = { default = animations[#animations].time, } end end end
26.573643
184
0.589192
f051fa84986a7c9f1470f505282adadb784afefe
5,289
py
Python
ibmsecurity/isam/base/fips.py
zone-zero/ibmsecurity
7d3e38104b67e1b267e18a44845cb756a5302c3d
[ "Apache-2.0" ]
46
2017-03-21T21:08:59.000Z
2022-02-20T22:03:46.000Z
ibmsecurity/isam/base/fips.py
zone-zero/ibmsecurity
7d3e38104b67e1b267e18a44845cb756a5302c3d
[ "Apache-2.0" ]
201
2017-03-21T21:25:52.000Z
2022-03-30T21:38:20.000Z
ibmsecurity/isam/base/fips.py
zone-zero/ibmsecurity
7d3e38104b67e1b267e18a44845cb756a5302c3d
[ "Apache-2.0" ]
91
2017-03-22T16:25:36.000Z
2022-02-04T04:36:29.000Z
import logging import ibmsecurity.utilities.tools import time logger = logging.getLogger(__name__) requires_model = "Appliance" def get(isamAppliance, check_mode=False, force=False): """ Retrieving the current FIPS Mode configuration """ return isamAppliance.invoke_get("Retrieving the current FIPS Mode configuration", "/fips_cfg", requires_model=requires_model) def set(isamAppliance, fipsEnabled=True, tlsv10Enabled=True, tlsv11Enabled=False, check_mode=False, force=False): """ Updating the FIPS Mode configuration """ obj = _check(isamAppliance, fipsEnabled, tlsv10Enabled, tlsv11Enabled) if force is True or obj['value'] is False: if check_mode is True: return isamAppliance.create_return_object(changed=True, warnings=obj['warnings']) else: return isamAppliance.invoke_put( "Updating the FIPS Mode configuration", "/fips_cfg", { "fipsEnabled": fipsEnabled, "tlsv10Enabled": tlsv10Enabled, "tlsv11Enabled": tlsv11Enabled }, requires_model=requires_model ) return isamAppliance.create_return_object(warnings=obj['warnings']) def restart(isamAppliance, check_mode=False, force=False): """ Rebooting and enabling the FIPS Mode configuration :param isamAppliance: :param check_mode: :param force: :return: """ if check_mode is True: return isamAppliance.create_return_object(changed=True) else: return isamAppliance.invoke_put( "Rebooting and enabling the FIPS Mode configuration", "/fips_cfg/restart", {}, requires_model=requires_model ) def restart_and_wait(isamAppliance, wait_time=300, check_freq=5, check_mode=False, force=False): """ Restart after FIPS configuration changes :param isamAppliance: :param wait_time: :param check_freq: :param check_mode: :param force: :return: """ if isamAppliance.facts['model'] != "Appliance": return isamAppliance.create_return_object( warnings="API invoked requires model: {0}, appliance is of deployment model: {1}.".format( requires_model, isamAppliance.facts['model'])) warnings = [] if check_mode is True: return isamAppliance.create_return_object(changed=True) else: firmware = ibmsecurity.isam.base.firmware.get(isamAppliance, check_mode=check_mode, force=force) ret_obj = restart(isamAppliance) if ret_obj['rc'] == 0: sec = 0 # Now check if it is up and running while 1: ret_obj = ibmsecurity.isam.base.firmware.get(isamAppliance, check_mode=check_mode, force=force, ignore_error=True) # check partition last_boot time if ret_obj['rc'] == 0 and isinstance(ret_obj['data'], list) and len(ret_obj['data']) > 0 and \ (('last_boot' in ret_obj['data'][0] and ret_obj['data'][0]['last_boot'] != firmware['data'][0][ 'last_boot'] and ret_obj['data'][0]['active'] == True) or ( 'last_boot' in ret_obj['data'][1] and ret_obj['data'][1]['last_boot'] != firmware['data'][1]['last_boot'] and ret_obj['data'][1]['active'] == True)): logger.info("Server is responding and has a different boot time!") return isamAppliance.create_return_object(warnings=warnings) else: time.sleep(check_freq) sec += check_freq logger.debug( "Server is not responding yet. Waited for {0} secs, next check in {1} secs.".format(sec, check_freq)) if sec >= wait_time: warnings.append( "The FIPS restart not detected or completed, exiting... after {0} seconds".format(sec)) break return isamAppliance.create_return_object(warnings=warnings) def _check(isamAppliance, fipsEnabled, tlsv10Enabled, tlsv11Enabled): obj = {'value': True, 'warnings': ""} ret_obj = get(isamAppliance) obj['warnings'] = ret_obj['warnings'] if ret_obj['data']['fipsEnabled'] != fipsEnabled: logger.info("fipsEnabled change to {0}".format(fipsEnabled)) obj['value'] = False return obj if ret_obj['data']['tlsv10Enabled'] != tlsv10Enabled: logger.info("TLS v1.0 change to {0}".format(tlsv10Enabled)) obj['value'] = False return obj if ret_obj['data']['tlsv11Enabled'] != tlsv11Enabled: logger.info("TLS v1.1 change to {0}".format(tlsv11Enabled)) obj['value'] = False return obj return obj def compare(isamAppliance1, isamAppliance2): ret_obj1 = get(isamAppliance1) ret_obj2 = get(isamAppliance2) return ibmsecurity.utilities.tools.json_compare(ret_obj1, ret_obj2, deleted_keys=[])
36.729167
120
0.592362
ba03b0c7e0b235ff3e8bc748446df2c28c5457c7
551
sql
SQL
migrations/first.sql
andrewfromfly/rdo
30dd303c83ef11e758b4b548042920a3653a3ba7
[ "Unlicense" ]
2
2020-03-20T17:22:40.000Z
2020-04-14T02:26:04.000Z
migrations/first.sql
andrewarrow/feedback
ecdfe98eb179b7bcd6a531afd49da9ef42d6647f
[ "Unlicense" ]
null
null
null
migrations/first.sql
andrewarrow/feedback
ecdfe98eb179b7bcd6a531afd49da9ef42d6647f
[ "Unlicense" ]
null
null
null
CREATE TABLE users ( id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, email varchar(255), phrase varchar(255), flavor varchar(255), created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, UNIQUE KEY unique_email (email) ) ENGINE InnoDB; CREATE TABLE inboxes ( id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, sent_to varchar(255), sent_from varchar(255), subject varchar(255), is_spam int, spam_score float, body text, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, KEY sent_key (sent_to) ) ENGINE InnoDB;
25.045455
51
0.713249
74c131707b54dc87bc91c433708564a5e067e24e
5,628
js
JavaScript
docs/build/p-m5afxxug.entry.js
christian-fleckenstein/LernwortTrainer
417d4d5c09c040bb0f1fdbc6363d79c2f34b4f1f
[ "MIT" ]
null
null
null
docs/build/p-m5afxxug.entry.js
christian-fleckenstein/LernwortTrainer
417d4d5c09c040bb0f1fdbc6363d79c2f34b4f1f
[ "MIT" ]
1
2020-02-05T03:51:33.000Z
2020-02-05T03:51:33.000Z
docs/build/p-m5afxxug.entry.js
christian-fleckenstein/LernwortTrainer
417d4d5c09c040bb0f1fdbc6363d79c2f34b4f1f
[ "MIT" ]
null
null
null
import{r as t,h as i}from"./p-6da8d263.js";const e=class{constructor(i){t(this,i),this.zielWert=3,this.toggle=0,this.wortListe=[],this.abfrageListe=[],this.eingabeDavor="",this.loesungAnzeigen=!1,this.vorherigesloesungAnzeigen=!1,this.synth=window.speechSynthesis,this.voices=[],this.currentVoice=0}abfrageListeNeuAufbauen(){var t=this.zielWert;this.wortListe.map(i=>{i.richtig<t?(t=i.richtig,this.abfrageListe=[],this.abfrageListe.push(i)):i.richtig==t&&this.zielWert>i.richtig&&this.abfrageListe.push(i)});for(var i,e=this.abfrageListe.length;e>0;){i=Math.floor(Math.random()*e);var s=this.abfrageListe[e-=1];this.abfrageListe[e]=this.abfrageListe[i],this.abfrageListe[i]=s}}vorlesen(t,i){var e;if(0==this.voices.length)for(this.voices=this.synth.getVoices(),e=0;e<this.voices.length;e++)"de-DE"!=this.voices[e].lang&&(this.voices[e]=this.voices[this.voices.length-1],this.voices.pop(),e--);0==this.voices.length&&alert("Dieser Webbrowser kann nicht in Deutsch vorlesen - bitte einen anderen verwenden!"),i&&(this.currentVoice+=1,this.currentVoice>=this.voices.length&&(this.currentVoice=0));var s=new SpeechSynthesisUtterance(t);s.voice=this.voices[this.currentVoice],s.pitch=1,s.rate=1,this.synth.speak(s)}zielwertGeaendert(t){this.zielWert=t.target.value}woertListeGeaendert(t){this.eingabeWortliste=t.target.value}woerterUebernehmen(t){if(t.preventDefault(),void 0===this.eingabeWortliste)return-1;var i=this.eingabeWortliste.split("\n");this.wortListe=[];for(const[n,r]of i.entries()){var e=r.trim();if(-1!=e.indexOf('"')&&e.indexOf('"')+2<e.lastIndexOf('"'))e=e.substring(e.indexOf('"')+1,e.lastIndexOf('"'));else{var s=0;r.split(" ").forEach(t=>{t.length>s&&(s=t.length,e=t)})}var h={wort:r.trim(),richtig:0,index:n,antwort:e};r.trim().length>1&&this.wortListe.push(h)}this.abfrageListeNeuAufbauen(),this.vorlesen(this.abfrageListe[0].wort,!1)}eingabeAbgeben(t){t.preventDefault(),this.abfrageListe.length>0&&this.vorlesen(this.abfrageListe[0].wort,!1),""==this.eingabeDavor||this.eingabeDavor!=this.eingabeJetzt?this.eingabeDavor=this.eingabeJetzt:(this.loesungAnzeigen=!0,this.abfrageListe[0].richtig=0)}eingabeEingeben(t){return this.eingabeJetzt=t.target.value,this.loesungAnzeigen=!1,this.vorherigesloesungAnzeigen=!1,this.abfrageListe[0].antwort==this.eingabeJetzt&&(this.vorlesen("richtig!",!1),this.eingabeDavor=this.eingabeJetzt,this.eingabeJetzt="",this.abfrageListe[0].richtig++,this.abfrageListe.shift(),this.vorherigesloesungAnzeigen=!0,0==this.abfrageListe.length&&this.abfrageListeNeuAufbauen(),this.abfrageListe.length>0&&this.vorlesen(this.abfrageListe[0].wort,!1)),-1}render(){return this.toggle=1-this.toggle,0==this.wortListe.length?i("div",{class:"app-home"},i("header",null,i("h1",null,"Lernwort Quiz"),i("button",{onClick:()=>this.vorlesen("Hallo, verstehst Du mich gut?",!0)},"Stimme wechseln!")),i("p",null,"Bitte hier eine die abzufragenden Wörter eingeben.",i("br",null),"Werden mehrere Wörter pro Zeile eingegeben, so wird alles vorgelesen, aber nicht so genau geprüft.",i("br",null),"D.h. es reicht, das längste Wort richtig einzugeben."),i("datalist",{id:"1bis5"},i("option",{value:"1"}),i("option",{value:"2"}),i("option",{value:"3"}),i("option",{value:"4"}),i("option",{value:"5"})),i("form",{onSubmit:t=>this.woerterUebernehmen(t)},i("label",null,"Benötigte richtige Antworten:",i("input",{type:"number",width:1,min:1,max:5,value:this.zielWert,list:"1bis5",size:1,onInput:t=>this.zielwertGeaendert(t)})),i("br",null),i("textarea",{onInput:t=>this.woertListeGeaendert(t),cols:30,rows:10,minlength:5+this.toggle,spellcheck:!0,autoFocus:!0}),i("br",null),i("input",{type:"Submit",value:"Übernehmen"}))):this.abfrageListe.length>0?i("div",{class:"app-home"},i("header",null,i("h1",null,"Lernwort Quiz"),i("button",{onClick:()=>this.vorlesen(this.abfrageListe[0].wort,!0)},"Stimme wechseln!")),i("p",null,i("div",null,i("form",{onSubmit:t=>this.eingabeAbgeben(t)},i("p",null,"Antwort:",i("input",{type:"text",width:20,value:this.eingabeJetzt,autoFocus:!0,minLength:0*this.toggle,onInput:t=>this.eingabeEingeben(t)}),this.loesungAnzeigen||this.vorherigesloesungAnzeigen?this.loesungAnzeigen?this.abfrageListe[0].antwort:""+this.vorherigesloesungAnzeigen?this.eingabeDavor:"":""))))):(this.vorlesen("Du hast alle Lernwörter "+this.zielWert+" mal richtig gehabt. Super!",!1),i("div",{class:"app-home"},i("header",null,i("h1",null,"Lernwort Quiz")),i("div",null,i("p",{class:"richtig"},"Geschafft!"))))}static get style(){return".app-home{padding:10px}button,input{background:#3737b8}button,input,textarea{color:#fff;margin:8px;border:none;font-size:13px;font-weight:700;padding:16px 5px;border-radius:2px;-webkit-box-shadow:0 8px 16px rgba(0,0,0,.1),0 3px 6px rgba(0,0,0,.08);box-shadow:0 8px 16px rgba(0,0,0,.1),0 3px 6px rgba(0,0,0,.08);outline:0;letter-spacing:.04em;-webkit-transition:all .15s ease;transition:all .15s ease;cursor:pointer}textarea{background:#ffc}button:hover,input:focus{-webkit-box-shadow:0 3px 6px rgba(0,0,0,.1),0 1px 3px rgba(0,0,0,.1);box-shadow:0 3px 6px rgba(0,0,0,.1),0 1px 3px rgba(0,0,0,.1);-webkit-transform:translateY(1px);transform:translateY(1px)}header{background:#5851ff;color:#fff}.richtig,header{height:56px;display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center;-webkit-box-shadow:0 2px 5px 0 rgba(0,0,0,.26);box-shadow:0 2px 5px 0 rgba(0,0,0,.26)}.richtig{background:#ff2;color:#000}h1{color:#fff}h1,p{font-size:1.7rem;font-weight:500;padding:0 12px}p{color:#000}label,textarea{padding:16 12px}input,label,textarea{font-size:1.7rem;font-weight:500;color:#000}input{background:#ffa;padding:16 px;border:none}"}};export{e as app_home};
5,628
5,628
0.746624
c62c59722e177b9f46cc044c639a7d8328bba139
189
rb
Ruby
app/jobs/term_stat_update_job.rb
EOL/publishing
f0076291521a1b3dbeba2d565b2bbb653f504028
[ "MIT" ]
21
2016-10-05T03:52:57.000Z
2021-09-09T14:38:45.000Z
app/jobs/term_stat_update_job.rb
EOL/publishing
f0076291521a1b3dbeba2d565b2bbb653f504028
[ "MIT" ]
61
2016-12-22T18:02:25.000Z
2021-09-09T14:16:42.000Z
app/jobs/term_stat_update_job.rb
EOL/publishing
f0076291521a1b3dbeba2d565b2bbb653f504028
[ "MIT" ]
5
2018-03-06T18:34:34.000Z
2019-09-02T20:00:32.000Z
class TermStatUpdateJob < ApplicationJob def perform Rails.logger.info("START TermStatUpdater.run") TermStatUpdater.run Rails.logger.info("END TermStatUpdater.run") end end
23.625
50
0.761905
a1a1482378c71a2a2a06620d98f2d8b25e74906d
79
go
Go
models/usersettingapi.go
Romaindu35/PufferPanel
fd470944774fb251405ad5b9ff76eb1be4a03cd8
[ "Apache-2.0" ]
829
2015-01-01T11:20:52.000Z
2022-03-31T14:05:33.000Z
models/usersettingapi.go
noyzys/PufferPanel
f3e27033af509a639621de262685fcc4a3c69202
[ "Apache-2.0" ]
690
2015-01-01T01:15:47.000Z
2022-03-24T15:04:34.000Z
models/usersettingapi.go
noyzys/PufferPanel
f3e27033af509a639621de262685fcc4a3c69202
[ "Apache-2.0" ]
301
2015-01-03T07:42:02.000Z
2022-03-26T22:12:44.000Z
package models type ChangeUserSetting struct { Value string `json:"value"` }
13.166667
31
0.759494
b772f9360a770d0262c7f22d349b3bd48343ad40
384
sql
SQL
bemyndigelsesservice/src/main/resources/db/manual/metadata_update_ajourfoering_indlaeggelse_rollback.sql
trifork/bemyndigelsesregister
8d2b6e1981245da04ab68ae4b294017d83c2f288
[ "MIT" ]
null
null
null
bemyndigelsesservice/src/main/resources/db/manual/metadata_update_ajourfoering_indlaeggelse_rollback.sql
trifork/bemyndigelsesregister
8d2b6e1981245da04ab68ae4b294017d83c2f288
[ "MIT" ]
null
null
null
bemyndigelsesservice/src/main/resources/db/manual/metadata_update_ajourfoering_indlaeggelse_rollback.sql
trifork/bemyndigelsesregister
8d2b6e1981245da04ab68ae4b294017d83c2f288
[ "MIT" ]
null
null
null
UPDATE `bemyndigelse`.`rettighed` SET beskrivelse = 'Suspender/frigiv medicinkort' where kode = 'Suspendering'; UPDATE `bemyndigelse`.`rettighed` SET beskrivelse = 'Sæt markering for medicinafstemning' where kode = 'Afstemning'; UPDATE `bemyndigelse`.`rettighed` SET beskrivelse = 'Opretning tilknytning til en enhed (F.eks. tilknytning til hjemmepleje)' where kode = 'Tilknytning';
76.8
153
0.78125
10f8b1ccffda51eae61ac786487bbd04d6547580
9,367
kt
Kotlin
ui/src/main/java/ru/tinkoff/acquiring/sdk/ui/activities/ThreeDsActivity.kt
safchemist/AcquiringSdkAndroid
5a678c88d43bf120edb3444f159258b182189e77
[ "Apache-2.0" ]
null
null
null
ui/src/main/java/ru/tinkoff/acquiring/sdk/ui/activities/ThreeDsActivity.kt
safchemist/AcquiringSdkAndroid
5a678c88d43bf120edb3444f159258b182189e77
[ "Apache-2.0" ]
null
null
null
ui/src/main/java/ru/tinkoff/acquiring/sdk/ui/activities/ThreeDsActivity.kt
safchemist/AcquiringSdkAndroid
5a678c88d43bf120edb3444f159258b182189e77
[ "Apache-2.0" ]
null
null
null
/* * Copyright © 2020 Tinkoff Bank * * 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. */ package ru.tinkoff.acquiring.sdk.ui.activities import android.annotation.SuppressLint import android.app.Activity import android.content.Context import android.content.Intent import android.graphics.Bitmap import android.graphics.Point import android.os.Bundle import android.view.View import android.view.WindowManager import android.webkit.WebView import android.webkit.WebViewClient import androidx.lifecycle.Observer import org.json.JSONObject import ru.tinkoff.acquiring.sdk.R import ru.tinkoff.acquiring.sdk.exceptions.AcquiringSdkException import ru.tinkoff.acquiring.sdk.models.* import ru.tinkoff.acquiring.sdk.models.ScreenState import ru.tinkoff.acquiring.sdk.models.options.screen.BaseAcquiringOptions import ru.tinkoff.acquiring.sdk.models.result.AsdkResult import ru.tinkoff.acquiring.sdk.network.AcquiringApi import ru.tinkoff.acquiring.sdk.network.AcquiringApi.COMPLETE_3DS_METHOD_V2 import ru.tinkoff.acquiring.sdk.network.AcquiringApi.SUBMIT_3DS_AUTHORIZATION import ru.tinkoff.acquiring.sdk.network.AcquiringApi.SUBMIT_3DS_AUTHORIZATION_V2 import ru.tinkoff.acquiring.sdk.responses.Check3dsVersionResponse import ru.tinkoff.acquiring.sdk.utils.Base64 import ru.tinkoff.acquiring.sdk.utils.getTimeZoneOffsetInMinutes import ru.tinkoff.acquiring.sdk.viewmodel.* import java.lang.IllegalStateException import java.net.URLEncoder import java.util.* internal class ThreeDsActivity : BaseAcquiringActivity() { private lateinit var wvThreeDs: WebView private lateinit var viewModel: ThreeDsViewModel private lateinit var data: ThreeDsData private var termUrl: String? = null companion object { const val RESULT_DATA = "result_data" const val ERROR_DATA = "result_error" const val RESULT_ERROR = 564 const val THREE_DS_DATA = "three_ds_data" private const val OPTIONS = "options" private const val THREE_DS_CALLED_FLAG = "Y" private const val THREE_DS_NOT_CALLED_FLAG = "N" private const val WINDOW_SIZE_CODE = "05" private const val MESSAGE_TYPE = "CReq" private val TERM_URL = "${AcquiringApi.getUrl(SUBMIT_3DS_AUTHORIZATION)}/$SUBMIT_3DS_AUTHORIZATION" private val TERM_URL_V2 = "${AcquiringApi.getUrl(SUBMIT_3DS_AUTHORIZATION_V2)}/$SUBMIT_3DS_AUTHORIZATION_V2" private val NOTIFICATION_URL = "${AcquiringApi.getUrl(COMPLETE_3DS_METHOD_V2)}/$COMPLETE_3DS_METHOD_V2" private val cancelActions = arrayOf("cancel.do", "cancel=true") fun createIntent(context: Context, options: BaseAcquiringOptions, data: ThreeDsData): Intent { val intent = Intent(context, ThreeDsActivity::class.java) intent.putExtra(THREE_DS_DATA, data) intent.putExtra(OPTIONS, options) return intent } fun collectData(context: Context, response: Check3dsVersionResponse?): MutableMap<String, String> { var threeDSCompInd = THREE_DS_NOT_CALLED_FLAG if (response != null) { val hiddenWebView = WebView(context) val threeDsMethodData = JSONObject().apply { put("threeDSMethodNotificationURL", NOTIFICATION_URL) put("threeDSServerTransID", response.serverTransId) } val dataBase64 = Base64.encodeToString(threeDsMethodData.toString().toByteArray(), Base64.DEFAULT).trim() val params = "threeDSMethodData=${URLEncoder.encode(dataBase64, "UTF-8")}" hiddenWebView.postUrl(response.threeDsMethodUrl, params.toByteArray()) threeDSCompInd = THREE_DS_CALLED_FLAG } val display = (context.getSystemService(Context.WINDOW_SERVICE) as WindowManager).defaultDisplay val point = Point() display.getSize(point) return mutableMapOf<String, String>().apply { put("threeDSCompInd", threeDSCompInd) put("language", Locale.getDefault().toString().replace("_", "-")) put("timezone", getTimeZoneOffsetInMinutes()) put("screen_height", "${point.y}") put("screen_width", "${point.x}") put("cresCallbackUrl", TERM_URL_V2) } } } @SuppressLint("SetJavaScriptEnabled") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.acq_activity_3ds) wvThreeDs = findViewById(R.id.acq_3ds_wv) wvThreeDs.run { visibility = View.GONE webViewClient = ThreeDsWebViewClient() settings.domStorageEnabled = true settings.javaScriptEnabled = true settings.javaScriptCanOpenWindowsAutomatically = true } progressBar = findViewById(R.id.acq_progressbar) content = wvThreeDs data = intent.getSerializableExtra(THREE_DS_DATA) as ThreeDsData viewModel = provideViewModel(ThreeDsViewModel::class.java) as ThreeDsViewModel observeLiveData() start3Ds() } override fun setSuccessResult(result: AsdkResult) { val intent = Intent() intent.putExtra(RESULT_DATA, result) setResult(Activity.RESULT_OK, intent) } override fun setErrorResult(throwable: Throwable) { val intent = Intent() intent.putExtra(ERROR_DATA, throwable) setResult(RESULT_ERROR, intent) } override fun handleLoadState(loadState: LoadState) { when (loadState) { is LoadingState -> { progressBar?.visibility = View.VISIBLE content?.visibility = View.INVISIBLE } } } private fun observeLiveData() { viewModel.run { loadStateLiveData.observe(this@ThreeDsActivity, Observer { handleLoadState(it) }) screenStateLiveData.observe(this@ThreeDsActivity, Observer { handleScreenState(it) }) resultLiveData.observe(this@ThreeDsActivity, Observer { finishWithSuccess(it) }) } } private fun handleScreenState(screenState: ScreenState) { when (screenState) { is ErrorScreenState -> finishWithError(AcquiringSdkException(IllegalStateException(screenState.message))) is FinishWithErrorScreenState -> finishWithError(screenState.error) } } private fun start3Ds() { val url = data.acsUrl val params: String? if (data.is3DsVersion2) { termUrl = TERM_URL_V2 val base64Creq = prepareCreqParams() params = "creq=${URLEncoder.encode(base64Creq, "UTF-8")}" } else { termUrl = TERM_URL params = "PaReq=${URLEncoder.encode(data.paReq, "UTF-8")}" + "&MD=${URLEncoder.encode(data.md, "UTF-8")}" + "&TermUrl=${URLEncoder.encode(termUrl, "UTF-8")}" } wvThreeDs.postUrl(url, params.toByteArray()) } private fun prepareCreqParams(): String { val creqData = JSONObject().apply { put("threeDSServerTransID", data.tdsServerTransId) put("acsTransID", data.acsTransId) put("messageVersion", data.version) put("challengeWindowSize", WINDOW_SIZE_CODE) put("messageType", MESSAGE_TYPE) } return Base64.encodeToString(creqData.toString().toByteArray(), Base64.DEFAULT).trim() } private fun requestState() { if (data.isPayment) { viewModel.requestPaymentState(data.paymentId) } else if (data.isAttaching) { viewModel.requestAddCardState(data.requestKey) } } private inner class ThreeDsWebViewClient : WebViewClient() { private var canceled = false override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) { super.onPageStarted(view, url, favicon) content?.visibility = View.INVISIBLE progressBar?.visibility = View.VISIBLE } override fun onPageFinished(view: WebView, url: String) { super.onPageFinished(view, url) cancelActions.forEach { if (url.contains(it)) { canceled = true (view.context as Activity).run { setResult(Activity.RESULT_CANCELED) finish() } } } if (termUrl == url) { view.visibility = View.INVISIBLE if (!canceled) { requestState() } } else { progressBar?.visibility = View.GONE view.visibility = View.VISIBLE } } } }
37.468
121
0.654852
e78f6bb0b846cc332e66a7fac265da7ba17efcef
507
js
JavaScript
plugin/attributesCount.js
phuu/flight-static-analysis
a89e6acaa14b7635a334dc9ebfff6445cea95cb2
[ "MIT" ]
3
2015-02-21T12:23:17.000Z
2015-04-26T13:56:34.000Z
plugin/attributesCount.js
phuu/flight-static-analysis
a89e6acaa14b7635a334dc9ebfff6445cea95cb2
[ "MIT" ]
null
null
null
plugin/attributesCount.js
phuu/flight-static-analysis
a89e6acaa14b7635a334dc9ebfff6445cea95cb2
[ "MIT" ]
null
null
null
/** * Counting New Attributes Usage */ var u = require('../plugin-util'); module.exports = function (file, node, data, argv) { if (u.isCallTo(node, 'this', 'attributes')) { var attributes = data.for('attributes'); attributes.for('summary').inc('count'); if (argv.instances) { var instances = attributes.get('instances') || []; instances.push({ name: 'attributes', loc: node.loc }); attributes.set('instances', instances); } } };
26.684211
58
0.568047
6049fb9928ee15555928833d25111284eb369369
22
html
HTML
google/index.html
clstokes/instance-metadata-examples
c837237843ac6de4573fb42d1347039fec54550b
[ "Apache-2.0" ]
22
2016-08-08T09:54:46.000Z
2017-10-24T04:40:09.000Z
google/index.html
clstokes/instance-metadata-examples
c837237843ac6de4573fb42d1347039fec54550b
[ "Apache-2.0" ]
4
2016-08-09T05:20:06.000Z
2020-02-18T18:54:22.000Z
google/index.html
clstokes/instance-metadata-examples
c837237843ac6de4573fb42d1347039fec54550b
[ "Apache-2.0" ]
3
2016-08-08T13:56:01.000Z
2021-08-09T05:14:35.000Z
0.1/ computeMetadata/
7.333333
16
0.772727
f024f2d1468cd63a89d1e5336dc2508a4542b04f
1,476
py
Python
Stack/10-stack-special-design-and-implement.py
mahmutcankurt/DataStructures_Python
bfb81e3530b535c4e48c07548dc4a4f9a648bab2
[ "MIT" ]
1
2022-01-25T22:17:55.000Z
2022-01-25T22:17:55.000Z
Stack/10-stack-special-design-and-implement.py
mahmutcankurt/DataStructures_Python
bfb81e3530b535c4e48c07548dc4a4f9a648bab2
[ "MIT" ]
null
null
null
Stack/10-stack-special-design-and-implement.py
mahmutcankurt/DataStructures_Python
bfb81e3530b535c4e48c07548dc4a4f9a648bab2
[ "MIT" ]
null
null
null
class Stack: def __init__(self): self.array = [] self.top = -1 self.max = 100 def isEmpty(self): if(self.top == -1): return True else: return False def isFull(self): if(self.top == self.max -1): return True else: return False def push(self, data): if(self.isFull()): print("Stack Overflow") return else: self.top += 1 self.array.append(data) def pop(self): if(self.isEmpty()): print("Stack Underflow") return else: self.top -= 1 return(self.array.pop()) class SpecialStack(Stack): def __init__(self): super().__init__() self.Min = Stack() def push(self, x): if(self.isEmpty): super().push(x) self.Min.push(x) else: super().push(x) y = self.Min.pop() self.Min.push(y) if(x <= y): self.Min.push(x) else: self.Min.push(y) def pop(self): x = super().pop() self.Min.pop() return x def getMin(self): x = self.Min.pop() self.Min.push(x) return x if __name__ == "__main__": s = SpecialStack() s.push(10) s.push(20) s.push(30) print(s.getMin()) s.push(5) print(s.getMin())
20.219178
36
0.443767
5c67a13c25c05a800c9dc9a5a6d454d4ead9cd53
3,385
h
C
hns_data.h
handshake-org/libhns
5cc63093ac4832bcdf9bcb1d46f331c0746a93c1
[ "MIT" ]
18
2018-08-02T16:58:49.000Z
2022-03-05T22:34:51.000Z
hns_data.h
jilky/libhns
5cc63093ac4832bcdf9bcb1d46f331c0746a93c1
[ "MIT" ]
2
2018-10-04T23:09:50.000Z
2020-06-26T17:20:37.000Z
hns_data.h
jilky/libhns
5cc63093ac4832bcdf9bcb1d46f331c0746a93c1
[ "MIT" ]
4
2019-09-22T10:16:46.000Z
2022-03-05T22:34:51.000Z
/* Copyright (C) 2009-2013 by Daniel Stenberg * * Permission to use, copy, modify, and distribute this * software and its documentation for any purpose and without * fee is hereby granted, provided that the above copyright * notice appear in all copies and that both that copyright * notice and this permission notice appear in supporting * documentation, and that the name of M.I.T. not be used in * advertising or publicity pertaining to distribution of the * software without specific, written prior permission. * M.I.T. makes no representations about the suitability of * this software for any purpose. It is provided "as is" * without express or implied warranty. */ typedef enum { HNS_DATATYPE_UNKNOWN = 1, /* unknown data type - introduced in 1.7.0 */ HNS_DATATYPE_SRV_REPLY, /* struct hns_srv_reply - introduced in 1.7.0 */ HNS_DATATYPE_TXT_REPLY, /* struct hns_txt_reply - introduced in 1.7.0 */ HNS_DATATYPE_TXT_EXT, /* struct hns_txt_ext - introduced in 1.11.0 */ HNS_DATATYPE_ADDR_NODE, /* struct hns_addr_node - introduced in 1.7.1 */ HNS_DATATYPE_MX_REPLY, /* struct hns_mx_reply - introduced in 1.7.2 */ HNS_DATATYPE_NAPTR_REPLY, /* struct hns_naptr_reply - introduced in 1.7.6 */ HNS_DATATYPE_SOA_REPLY, /* struct hns_soa_reply - introduced in 1.9.0 */ HNS_DATATYPE_SSHFP_REPLY, /* struct hns_sshfp_reply */ HNS_DATATYPE_DANE_REPLY, /* struct hns_dane_reply */ HNS_DATATYPE_OPENPGPKEY_REPLY, /* struct hns_openpgpkey_reply */ #if 0 HNS_DATATYPE_ADDR6TTL, /* struct hns_addrttl */ HNS_DATATYPE_ADDRTTL, /* struct hns_addr6ttl */ HNS_DATATYPE_HOSTENT, /* struct hostent */ HNS_DATATYPE_OPTIONS, /* struct hns_options */ #endif HNS_DATATYPE_ADDR_PORT_NODE, /* struct hns_addr_port_node - introduced in 1.11.0 */ HNS_DATATYPE_LAST /* not used - introduced in 1.7.0 */ } hns_datatype; #define HNS_DATATYPE_MARK 0xbead /* * hns_data struct definition is internal to hns and shall not * be exposed by the public API in order to allow future changes * and extensions to it without breaking ABI. This will be used * internally by hns as the container of multiple types of data * dynamically allocated for which a reference will be returned * to the calling application. * * hns API functions returning a pointer to hns internally * allocated data will actually be returning an interior pointer * into this hns_data struct. * * All this is 'invisible' to the calling application, the only * requirement is that this kind of data must be free'ed by the * calling application using hns_free_data() with the pointer * it has received from a previous hns function call. */ struct hns_data { hns_datatype type; /* Actual data type identifier. */ unsigned int mark; /* Private hns_data signature. */ union { struct hns_txt_reply txt_reply; struct hns_txt_ext txt_ext; struct hns_srv_reply srv_reply; struct hns_addr_node addr_node; struct hns_addr_port_node addr_port_node; struct hns_mx_reply mx_reply; struct hns_naptr_reply naptr_reply; struct hns_soa_reply soa_reply; struct hns_sshfp_reply sshfp_reply; struct hns_dane_reply dane_reply; struct hns_openpgpkey_reply openpgpkey_reply; } data; }; void *hns_malloc_data(hns_datatype type);
42.848101
85
0.731758
4751be4c1616132b2718fc1e706dbc4399c3b26a
510
asm
Assembly
libsrc/_DEVELOPMENT/adt/p_forward_list_alt/c/sccz80/p_forward_list_alt_push_front.asm
jpoikela/z88dk
7108b2d7e3a98a77de99b30c9a7c9199da9c75cb
[ "ClArtistic" ]
640
2017-01-14T23:33:45.000Z
2022-03-30T11:28:42.000Z
libsrc/_DEVELOPMENT/adt/p_forward_list_alt/c/sccz80/p_forward_list_alt_push_front.asm
jpoikela/z88dk
7108b2d7e3a98a77de99b30c9a7c9199da9c75cb
[ "ClArtistic" ]
1,600
2017-01-15T16:12:02.000Z
2022-03-31T12:11:12.000Z
libsrc/_DEVELOPMENT/adt/p_forward_list_alt/c/sccz80/p_forward_list_alt_push_front.asm
jpoikela/z88dk
7108b2d7e3a98a77de99b30c9a7c9199da9c75cb
[ "ClArtistic" ]
215
2017-01-17T10:43:03.000Z
2022-03-23T17:25:02.000Z
; void p_forward_list_alt_push_front(p_forward_list_alt_t *list, void *item) SECTION code_clib SECTION code_adt_p_forward_list_alt PUBLIC p_forward_list_alt_push_front EXTERN asm_p_forward_list_alt_push_front p_forward_list_alt_push_front: pop af pop de pop bc push bc push de push af jp asm_p_forward_list_alt_push_front ; SDCC bridge for Classic IF __CLASSIC PUBLIC _p_forward_list_alt_push_front defc _p_forward_list_alt_push_front = p_forward_list_alt_push_front ENDIF
17.586207
76
0.82549
8eb23d312e8fd6d27c4535a62b69f37e29c74c63
1,285
rb
Ruby
lib/user.rb
darkhelmet/TinderizerApp
ead515a946b2556bf21574f3a2d0582696e4ad91
[ "Apache-2.0" ]
2
2015-11-05T08:55:45.000Z
2016-03-01T22:14:51.000Z
lib/user.rb
darkhelmet/TinderizerApp
ead515a946b2556bf21574f3a2d0582696e4ad91
[ "Apache-2.0" ]
null
null
null
lib/user.rb
darkhelmet/TinderizerApp
ead515a946b2556bf21574f3a2d0582696e4ad91
[ "Apache-2.0" ]
null
null
null
require 'redis' require 'mail' require 'json' require 'postmark' module User Config = JSON.parse(File.read('config/config.json')) Lua = <<-LUA local value = redis('get', KEYS[1]) if value ~= nil then return {err='limited'} end redis('set', KEYS[1], 'locked') redis('expire', KEYS[1], tonumber(ARGV[1])) return {ok='locked'} LUA class << self def mail(email, title, url, mobi) m = Mail.new m.delivery_method(Mail::Postmark, api_key: Config['postmark']) m.from(Config['email']['from']) m.to(email) m.subject('convert') m.body("Straight to your Kindle! #{title}: #{url}") m.postmark_attachments = [File.open(mobi)] m.deliver! end def notify(redis, key, message) failed = false redis.multi do redis.set(key, message) redis.expire(key, 30) end rescue SystemCallError => boom unless failed failed = true retry end end def limit(redis, email, time) redis.eval(Lua, 1, Digest::SHA1.hexdigest(email), time) rescue RuntimeError => limited { message: "Sorry, but there's a rate-limit, and you've hit it! Try again in a minute.", limited: true }.to_json else yield end end end
24.245283
94
0.592996
c542d3a9de0d2db46c50db8ba8650e0ec9ab04a2
7,118
sql
SQL
comuna11/agrupar_mzas_adys.sql
manureta/segmentacion
74f67dbd0f84189d620e95a9ba777f3aa6f65f4b
[ "MIT" ]
1
2019-06-05T12:21:43.000Z
2019-06-05T12:21:43.000Z
comuna11/agrupar_mzas_adys.sql
manureta/segmentacion
74f67dbd0f84189d620e95a9ba777f3aa6f65f4b
[ "MIT" ]
9
2019-06-05T18:20:10.000Z
2019-11-20T20:04:49.000Z
comuna11/agrupar_mzas_adys.sql
manureta/segmentacion
74f67dbd0f84189d620e95a9ba777f3aa6f65f4b
[ "MIT" ]
3
2016-12-06T21:07:41.000Z
2019-06-04T20:59:44.000Z
/* titulo: agrupar_mzas_adys.sql descripción genera una tabla o vista con grupos de mzas adys fecha: 2019-05-22 Mi autor: -h */ create view adyacencias_orden_1 as select frac, radio, mza, vivs_mza, mza || array_agg(distinct mza_ady order by mza_ady) as ady_ord_1 from adyacencias_mzas natural join conteos_manzanas group by frac, radio, mza, vivs_mza having vivs_mza < 30 order by frac, radio, mza ; /* select * from adyacencias_orden_1 order by frac, radio, mza limit 10; frac | radio | mza | vivs_mza | ady_ord_1 ------+-------+-----+----------+--------------------------- 1 | 1 | 11 | 15 | {11,8} 1 | 2 | 12 | 1 | {12,13} 1 | 2 | 14 | 19 | {14,13,15,17} 1 | 2 | 33 | 8 | {33,31,34} 1 | 10 | 74 | 21 | {74,73,84} 1 | 11 | 80 | 12 | {80,81,91} 1 | 11 | 86 | 1 | {86,87,88} 1 | 12 | 62 | 21 | {62,63,65} 1 | 12 | 64 | 1 | {64,65,78} 1 | 12 | 65 | 2 | {65,62,63,64,67,68,76,77} */ create or replace function costo(vivs bigint) returns float as $$ select abs($1 - 40)::float $$ language sql ; drop view desigualdad_triangular; create view desigualdad_triangular as select distinct l.frac, l.radio, array[m.mza] as mza, m.vivs_mza, costo(m.vivs_mza) as costo_mza, array[a.mza] as ady, a.vivs_mza as vivs_ady, costo(a.vivs_mza) as costo_ady, array[m.mza, a.mza] as par, m.vivs_mza + a.vivs_mza as vivs_par, costo(m.vivs_mza + a.vivs_mza) as costo_par from adyacencias_mzas l natural join conteos_manzanas m join conteos_manzanas a on m.frac = a.frac and m.radio=a.radio and l.mza_ady = a.mza where m.vivs_mza < 35 and a.vivs_mza < 35 and costo(m.vivs_mza + a.vivs_mza) < costo(m.vivs_mza) + costo(a.vivs_mza) order by l.frac, l.radio, array[m.mza], array[a.mza] ; /* select * from desigualdad_triangular limit 10; frac | radio | mza | vivs_mza | costo_mza | ady | vivs_ady | costo_ady | par | vivs_par | costo_par ------+-------+------+----------+-----------+------+----------+-----------+---------+----------+----------- 1 | 1 | {8} | 30 | 10 | {11} | 15 | 25 | {8,11} | 45 | 5 1 | 1 | {11} | 15 | 25 | {8} | 30 | 10 | {11,8} | 45 | 5 1 | 2 | {12} | 1 | 39 | {13} | 33 | 7 | {12,13} | 34 | 6 1 | 2 | {13} | 33 | 7 | {12} | 1 | 39 | {13,12} | 34 | 6 1 | 2 | {13} | 33 | 7 | {14} | 19 | 21 | {13,14} | 52 | 12 1 | 2 | {14} | 19 | 21 | {13} | 33 | 7 | {14,13} | 52 | 12 1 | 12 | {62} | 21 | 19 | {65} | 2 | 38 | {62,65} | 23 | 17 1 | 12 | {64} | 1 | 39 | {65} | 2 | 38 | {64,65} | 3 | 37 1 | 12 | {64} | 1 | 39 | {78} | 5 | 35 | {64,78} | 6 | 34 1 | 12 | {65} | 2 | 38 | {62} | 21 | 19 | {65,62} | 23 | 17 (10 rows) */ drop view conjunto_de_mzas; create view conjunto_de_mzas as select frac, radio, min(par) as par, vivs_par as vivs, costo_par as costo from desigualdad_triangular group by frac, radio, vivs_par, costo_par order by frac, radio ; /* select * from conjunto_de_mzas limit 10; frac | radio | min | vivs | costo ------+-------+---------+------+------- 1 | 1 | {8,11} | 45 | 5 1 | 2 | {12,13} | 34 | 6 1 | 2 | {13,14} | 52 | 12 1 | 12 | {64,65} | 3 | 37 1 | 12 | {64,78} | 6 | 34 1 | 12 | {65,68} | 20 | 20 1 | 12 | {62,65} | 23 | 17 2 | 1 | {7,8} | 33 | 7 2 | 7 | {61,61} | 38 | 2 2 | 9 | {87,96} | 31 | 9 (10 rows) */ create view conjuntos_a_iterar as select frac, radio, par from conjunto_de_mzas where (frac, radio) in ( select frac, radio from conjunto_de_mzas group by frac, radio having count(*) > 1) ; /* select * from conjuntos_a_iterar limit 10; frac | radio | par ------+-------+----------- 1 | 2 | {12,13} 1 | 2 | {13,14} 1 | 12 | {64,65} 1 | 12 | {64,78} 1 | 12 | {65,68} 1 | 12 | {62,65} 2 | 9 | {87,96} 2 | 9 | {87,88} 2 | 11 | {108,109} 2 | 11 | {109,111} (10 rows) */ select frac, radio, count(*) from conjuntos_a_iterar group by frac, radio having count(*) > 1 ; /* frac | radio | count ------+-------+------- 1 | 2 | 2 1 | 12 | 4 2 | 9 | 2 2 | 11 | 3 4 | 3 | 4 4 | 4 | 2 4 | 5 | 3 4 | 9 | 5 5 | 8 | 5 5 | 10 | 2 11 | 1 | 2 (11 rows) */ select count(*) as radios_de_muestra_comuna11 from (select distinct frac, radio from adyacencias_mzas) as radios ; /* radios_de_muestra_comuna11 ---------------------------- 223 se necesita iterar en 11 de 223 radios para esta muestra representa el 5% */ /* select frac, radio, count(*) from conjunto_de_mzas group by frac, radio ; frac | radio | count ------+-------+------- 1 | 1 | 1 1 | 2 | 2 1 | 12 | 4 2 | 1 | 1 2 | 7 | 1 2 | 9 | 2 2 | 10 | 1 2 | 11 | 3 4 | 3 | 4 4 | 4 | 2 4 | 5 | 3 4 | 6 | 1 4 | 8 | 1 4 | 9 | 5 5 | 4 | 1 5 | 8 | 5 5 | 9 | 1 5 | 10 | 2 10 | 10 | 1 11 | 1 | 2 (20 rows) */ ------------------------------ -- setear segmento en listado comuna11 --------------------------------------- create view mzas_a_agrupar as with radios_con_un_solo_par as ( select frac, radio from conjunto_de_mzas group by frac, radio having count(*) = 1 ), pares as ( select frac, radio, unnest(par) as mza from conjunto_de_mzas where (frac, radio) in (select * from radios_con_un_solo_par) ) select * from pares; ; alter table comuna11 add column sgm_grp_mzas integer default Null; update comuna11 set sgm_grp_mzas = 1 where (frac, radio, mza) in ( select frac, radio, mza from mzas_a_agrupar ) ; /* select frac, radio, mza, sgm_mza_grd, sgm_mza_eq, sgm_grp_mzas, sgm from comuna11 order by frac, radio, mza ; . . . 11 | 9 | 44 | | | | 3 11 | 9 | 47 | | | | 6 12 | 1 | 4 | 1 | 1 | | 3 12 | 1 | 5 | 4 | 3 | | 4 12 | 1 | 5 | 4 | 4 | | 4 . . . TODO: revisar secuencia de corrida para generar sgm_mza_grd y sgm_mza_eq no deberían dar resultados null, y de donde sale sgm? */ update comuna11 set sgm = 101 where sgm_grp_mzas is not Null ;
27.589147
113
0.445209
4379bf01e7ab20c82e823c6156654986ead3974f
2,090
go
Go
license/licpol/pdp.go
mariotoffia/gojwtlic
f7e36658a68a034b6bacb77d2f14ee1f9aa14b59
[ "Apache-2.0" ]
null
null
null
license/licpol/pdp.go
mariotoffia/gojwtlic
f7e36658a68a034b6bacb77d2f14ee1f9aa14b59
[ "Apache-2.0" ]
null
null
null
license/licpol/pdp.go
mariotoffia/gojwtlic
f7e36658a68a034b6bacb77d2f14ee1f9aa14b59
[ "Apache-2.0" ]
null
null
null
package licpol import ( "fmt" "reflect" "strconv" ) // PDPMessage is a standar PDP message. // // .Example Invocation // [source,json] // ---- // { // "type": "invoke", // <1> // "method": ["path","to","method-name"], // <2> // "sc": { // "oidc": { // <3> // "aud": "https://nordvestor.api.crossbreed.se", // "iss": "https://iss.crossbreed.se", // "sub": "[email protected]", // "exp": 1927735782, // "iat": 1612375782, // "nbf": 1612375782, // "jti": "fcd2174b-664a-11eb-afe1-1629c910062f", // "client_id": "my-client-id", // "scope": "oid::r::999 oid::rw::1234" // } // }, // "body": { // <4> // "name": "my-param", // "dir": "inbound" // } // } // ---- // <1> About to invoke function // <2> The action, i.e. path to method // <3> The security context, in this case the _OpenID Connect_ token // <4> Body do contain the function parameters marshalled to _JSON_ type PDPMessage struct { Type string `json:"type"` Method []string `json:"method"` SecurityContext map[string]interface{} `json:"sc,omitempty"` Body map[string]interface{} `json:"body,omitempty"` } // PDP is the Policy Decision Point implementation type PDP struct { } func (pdp *PDP) Register(f interface{}) { rf := reflect.TypeOf(f) if rf.Kind() != reflect.Func { panic("expects a function") } numIn := rf.NumIn() //Count inbound parameters numOut := rf.NumOut() //Count outbounding parameters fmt.Println("Method:", rf.String()) fmt.Println("Variadic:", rf.IsVariadic()) // Used (<type> ...) ? fmt.Println("Package:", rf.PkgPath()) for i := 0; i < numIn; i++ { inV := rf.In(i) in_Kind := inV.Kind() fmt.Println(inV) fmt.Printf("\nParameter IN: "+strconv.Itoa(i)+"\nKind: %v\nName: %v\n-----------", in_Kind, inV.Name()) } for o := 0; o < numOut; o++ { returnV := rf.Out(0) return_Kind := returnV.Kind() fmt.Printf("\nParameter OUT: "+strconv.Itoa(o)+"\nKind: %v\nName: %v\n", return_Kind, returnV.Name()) } }
25.802469
105
0.561244
a1a2300c1cce61195b9234156b446c0752339a3e
920
go
Go
main.go
afshin/sleuth-echo-client
24e9fe0e34d657b02fda126f9861b2f8f6e520f4
[ "MIT" ]
null
null
null
main.go
afshin/sleuth-echo-client
24e9fe0e34d657b02fda126f9861b2f8f6e520f4
[ "MIT" ]
null
null
null
main.go
afshin/sleuth-echo-client
24e9fe0e34d657b02fda126f9861b2f8f6e520f4
[ "MIT" ]
1
2020-09-02T07:25:35.000Z
2020-09-02T07:25:35.000Z
package main import ( "bytes" "fmt" "io/ioutil" "net/http" "time" "github.com/ursiform/sleuth" ) func main() { service := "echo-service" // In the real world, the Interface field of the sleuth.Config object // should be set so that all services are on the same subnet. config := &sleuth.Config{Interface: "en0", LogLevel: "debug"} client, err := sleuth.New(config) client.Timeout = time.Second * 5 if err != nil { panic(err.Error()) } defer client.Close() client.WaitFor(service) input := "This is the value I am inputting." body := bytes.NewBuffer([]byte(input)) request, _ := http.NewRequest("POST", "sleuth://"+service+"/", body) response, err := client.Do(request) if err != nil { print(err.(*sleuth.Error).Codes) panic(err.Error()) } output, _ := ioutil.ReadAll(response.Body) if string(output) == input { fmt.Println("It works.") } else { fmt.Println("It doesn't work.") } }
23
70
0.659783
0be80710e2e1cb0528efac3a214390ad4c82f2b5
559
js
JavaScript
es6-features/15-js-modules/app.js
vitorjsls30/spotify-wrapper-player
12f6a5bb03e577e25fb4e60712fa83ddfac80376
[ "MIT" ]
null
null
null
es6-features/15-js-modules/app.js
vitorjsls30/spotify-wrapper-player
12f6a5bb03e577e25fb4e60712fa83ddfac80376
[ "MIT" ]
null
null
null
es6-features/15-js-modules/app.js
vitorjsls30/spotify-wrapper-player
12f6a5bb03e577e25fb4e60712fa83ddfac80376
[ "MIT" ]
null
null
null
// import method from library // * loads all lib content // as => alias for the given method (a new name for it) import { union as gatherAll, uniq as exclusiveItems } from 'ramda'; import sum, { sub, multiply, div, PI } from './utils'; const arr1 = [1, 1, 1, 2, 2, 3, 4, 5, 6, 6]; const arr2 = [5, 6, 6, 6, 7, 7, 8, 9, 10, 1]; const arr3 = gatherAll(arr1, arr2); const arr4 = exclusiveItems(arr1); console.log(arr3); console.log(arr4); console.log(sum(3, 5)); console.log(sub(5, 3)); console.log(multiply(7, 2)); console.log(div(4, 2)); console.log(PI);
25.409091
67
0.644007
1271d813e97df08823fabe6f996d8dc8a2741893
2,300
h
C
IntactMiddleware/MembershipManagerConnection.h
intact-software-systems/cpp-software-patterns
e463fc7eeba4946b365b5f0b2eecf3da0f4c895b
[ "MIT" ]
1
2020-09-03T07:23:11.000Z
2020-09-03T07:23:11.000Z
IntactMiddleware/MembershipManagerConnection.h
intact-software-systems/cpp-software-patterns
e463fc7eeba4946b365b5f0b2eecf3da0f4c895b
[ "MIT" ]
null
null
null
IntactMiddleware/MembershipManagerConnection.h
intact-software-systems/cpp-software-patterns
e463fc7eeba4946b365b5f0b2eecf3da0f4c895b
[ "MIT" ]
null
null
null
#ifndef IntactMiddleware_MembershipManagerConnection_h_IsIncluded #define IntactMiddleware_MembershipManagerConnection_h_IsIncluded #include"IntactMiddleware/IncludeExtLibs.h" #include"IntactMiddleware/MembershipManagerBase.h" #include"IntactMiddleware/Export.h" namespace IntactMiddleware { // -------------------------------------------------------- // struct MembershipManagerConnectionConfig // -------------------------------------------------------- struct MembershipManagerConnectionConfig { static int membershipManagerPort; }; // -------------------------------------------------------- // class MembershipManagerConnection // -------------------------------------------------------- /** * Class MembershipManagerConnection logs in the component. */ class DLL_STATE MembershipManagerConnection : protected Thread { private: MembershipManagerConnection(const HostInformation &info, InterfaceHandle handle, bool autorStart = true); virtual ~MembershipManagerConnection(); public: static MembershipManagerConnection *GetOrCreate(InterfaceHandle *membershipHandle = NULL); public: bool Login(); void Logout(); HostInformation GetHostInformation() const; bool IsLoggedIn(); bool StopConnection(bool wait = true); bool WaitConnected(bool wait = true); void WaitForTermination() { Thread::wait(); } private: virtual void run(); bool login(); void logout(); private: inline bool runThread() const { MutexLocker lock(&classMutex_); return runThread_; } inline bool automaticLogin() const { MutexLocker lock(&classMutex_); return automaticLogin_; } inline void lock() { classMutex_.lock(); } inline void unlock() { classMutex_.unlock(); } inline void wakeAll() { classCondition_.wakeAll(); } inline bool lockedAndUnlockedWait(int64 ms) { lock(); bool wokenUp = classCondition_.wait(&classMutex_, ms); unlock(); return wokenUp; } private: MembershipManagerClient *membershipManagerProxy_; HostInformation myHostInformation_; InterfaceHandle membershipManagerHandle_; bool isLoggedIn_; bool automaticLogin_; bool runThread_; private: mutable Mutex classMutex_; WaitCondition classCondition_; private: static MembershipManagerConnection *membershipManagerConnection_; }; } // namespace IntactMiddleware #endif
26.436782
106
0.703043
cf6938aaefe4c86a359a2bf340ef28f94c665f6c
1,451
sql
SQL
assets/update_tabel/m_tindakan.sql
Dmenk123/odontogram
87996281ade92ef6f46103813c14871282dcaf5f
[ "MIT" ]
1
2022-01-28T11:31:56.000Z
2022-01-28T11:31:56.000Z
assets/update_tabel/m_tindakan.sql
Dmenk123/odontogram
87996281ade92ef6f46103813c14871282dcaf5f
[ "MIT" ]
null
null
null
assets/update_tabel/m_tindakan.sql
Dmenk123/odontogram
87996281ade92ef6f46103813c14871282dcaf5f
[ "MIT" ]
null
null
null
/* Navicat Premium Data Transfer Source Server : sql local Source Server Type : MySQL Source Server Version : 100414 Source Host : localhost:3306 Source Schema : odontogram Target Server Type : MySQL Target Server Version : 100414 File Encoding : 65001 Date: 09/09/2020 15:09:35 */ SET NAMES utf8mb4; SET FOREIGN_KEY_CHECKS = 0; -- ---------------------------- -- Table structure for m_tindakan -- ---------------------------- DROP TABLE IF EXISTS `m_tindakan`; CREATE TABLE `m_tindakan` ( `id_tindakan` int(32) NOT NULL AUTO_INCREMENT, `kode_tindakan` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, `nama_tindakan` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, `harga` int(255) NULL DEFAULT NULL, `created_at` datetime(0) NULL DEFAULT NULL, `updated_at` datetime(0) NULL DEFAULT NULL, `deleted_at` datetime(0) NULL DEFAULT NULL, PRIMARY KEY (`id_tindakan`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 3 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; -- ---------------------------- -- Records of m_tindakan -- ---------------------------- INSERT INTO `m_tindakan` VALUES (1, 'T001', 'Operasi', 100000, NULL, NULL, NULL); INSERT INTO `m_tindakan` VALUES (2, 'T002', 'Penambalan Gigi Cuy', 50000, '2020-09-09 14:35:45', '2020-09-09 15:05:11', NULL); SET FOREIGN_KEY_CHECKS = 1;
34.547619
126
0.661613
1fc6ca66cd41c7d3e05189bd6056fc0f8f33972b
2,614
html
HTML
public_goods_game/Test.html
chenyuyou/Behavior-template
ca3949a2765becd63992d2fbbd4f65ac1e5af8f0
[ "MIT" ]
null
null
null
public_goods_game/Test.html
chenyuyou/Behavior-template
ca3949a2765becd63992d2fbbd4f65ac1e5af8f0
[ "MIT" ]
null
null
null
public_goods_game/Test.html
chenyuyou/Behavior-template
ca3949a2765becd63992d2fbbd4f65ac1e5af8f0
[ "MIT" ]
null
null
null
{{ extends "global/Page.html" }} {{ block title }}问题测试{{ endblock }} {{ block content }} <script> // 获取输入框内容 window.onload = function() { var A_income_0 = document.getElementById("A_income_0"); var B_income_0 = document.getElementById("B_income_0"); var A_income_80 = document.getElementById("A_income_80"); var B_income_80 = document.getElementById("B_income_80"); // 获取提交按钮 var btn_submit = document.getElementById("btn_submit"); function check() { var A_income_0_value = A_income_0.value; var B_income_0_value = B_income_0.value; var A_income_80_value = A_income_80.value; var B_income_80_value = B_income_80.value; // 必填项验证 if (""==A_income_0_value) { alert("该输入项不能为空"); return false; } if (B_income_0_value == null || B_income_0_value=="") { alert("该输入项不能为空"); return false; } if (A_income_80_value == null || A_income_80_value=="") { alert("该输入项不能为空"); return false; } if (B_income_80_value == null || B_income_80_value =="") { alert("该输入项不能为空"); return false; } if (A_income_0_value != 80 ) { alert("第一个答案错误,请输入正确答案"); return false; } if (B_income_0_value != 80 ) { alert("第二个答案错误,请输入正确答案"); return false; } if (A_income_80_value != 128) { alert("第三个答案错误,请输入正确答案"); return false; } if (B_income_80_value != 128 ) { alert("第四个答案错误,请输入正确答案"); return false; } // 错误信息清空 msg.innerHTML = ""; return true; }; btn_submit.onclick = check; } </script> <p>以下是一些练习,可帮助您了解决策情况。</p> <form name="test" onsubmit="return validateForm()" method="post"> <ol> <li>两个人都往公共池中存入0点,那么A的收入是:<input type="text" class="form-control-sm" id="A_income_0" placeholder="请输入正确答案"><span id="msg"></span>,B的收入是:<input type="text" class="form-control-sm" id="B_income_0"placeholder="请输入正确答案"><span id="msg"></span>。</li> <li>两个人都往公共池中存了80点,那么A的收入是<input type="text" class="form-control-sm" id="A_income_80"placeholder="请输入正确答案"><span id="msg"></span>,B的收入是<input type="text" class="form-control-sm" id="B_income_80"placeholder="请输入正确答案"><span id="msg"></span>。</li> </ol> <input type="submit" class="btn btn-primary" value="验证答案" id="btn_submit"> </form> {{ endblock }}
29.370787
252
0.561209
3ee9849131059f92da08c50b09c21e8c45bfc3a1
9,169
h
C
src/dfm/protocol/TER.h
dfm-official/dfm
97f133aa87b17c760b90f2358d6ba10bc7ad9d1f
[ "ISC" ]
null
null
null
src/dfm/protocol/TER.h
dfm-official/dfm
97f133aa87b17c760b90f2358d6ba10bc7ad9d1f
[ "ISC" ]
null
null
null
src/dfm/protocol/TER.h
dfm-official/dfm
97f133aa87b17c760b90f2358d6ba10bc7ad9d1f
[ "ISC" ]
null
null
null
#ifndef RIPPLE_PROTOCOL_TER_H_INCLUDED #define RIPPLE_PROTOCOL_TER_H_INCLUDED #include <ripple/basics/safe_cast.h> #include <ripple/json/json_value.h> #include <boost/optional.hpp> #include <ostream> #include <string> namespace ripple { using TERUnderlyingType = int; enum TELcodes : TERUnderlyingType { telLOCAL_ERROR = -399, telBAD_DOMAIN, telBAD_PATH_COUNT, telBAD_PUBLIC_KEY, telFAILED_PROCESSING, telINSUF_FEE_P, telNO_DST_PARTIAL, telCAN_NOT_QUEUE, telCAN_NOT_QUEUE_BALANCE, telCAN_NOT_QUEUE_BLOCKS, telCAN_NOT_QUEUE_BLOCKED, telCAN_NOT_QUEUE_FEE, telCAN_NOT_QUEUE_FULL }; enum TEMcodes : TERUnderlyingType { temMALFORMED = -299, temBAD_AMOUNT, temBAD_CURRENCY, temBAD_EXPIRATION, temBAD_FEE, temBAD_ISSUER, temBAD_LIMIT, temBAD_OFFER, temBAD_PATH, temBAD_PATH_LOOP, temBAD_REGKEY, temBAD_SEND_XRP_LIMIT, temBAD_SEND_XRP_MAX, temBAD_SEND_XRP_NO_DIRECT, temBAD_SEND_XRP_PARTIAL, temBAD_SEND_XRP_PATHS, temBAD_SEQUENCE, temBAD_SIGNATURE, temBAD_SRC_ACCOUNT, temBAD_TRANSFER_RATE, temDST_IS_SRC, temDST_NEEDED, temINVALID, temINVALID_FLAG, temREDUNDANT, temRIPPLE_EMPTY, temDISABLED, temBAD_SIGNER, temBAD_QUORUM, temBAD_WEIGHT, temBAD_TICK_SIZE, temINVALID_ACCOUNT_ID, temCANNOT_PREAUTH_SELF, temUNCERTAIN, temUNKNOWN }; enum TEFcodes : TERUnderlyingType { tefFAILURE = -199, tefALREADY, tefBAD_ADD_AUTH, tefBAD_AUTH, tefBAD_LEDGER, tefCREATED, tefEXCEPTION, tefINTERNAL, tefNO_AUTH_REQUIRED, tefPAST_SEQ, tefWRONG_PRIOR, tefMASTER_DISABLED, tefMAX_LEDGER, tefBAD_SIGNATURE, tefBAD_QUORUM, tefNOT_MULTI_SIGNING, tefBAD_AUTH_MASTER, tefINVARIANT_FAILED, }; enum TERcodes : TERUnderlyingType { terRETRY = -99, terFUNDS_SPENT, terINSUF_FEE_B, terNO_ACCOUNT, terNO_AUTH, terNO_LINE, terOWNERS, terPRE_SEQ, terLAST, terNO_RIPPLE, terQUEUED }; enum TEScodes : TERUnderlyingType { tesSUCCESS = 0 }; enum TECcodes : TERUnderlyingType { tecCLAIM = 100, tecPATH_PARTIAL = 101, tecUNFUNDED_ADD = 102, tecUNFUNDED_OFFER = 103, tecUNFUNDED_PAYMENT = 104, tecFAILED_PROCESSING = 105, tecDIR_FULL = 121, tecINSUF_RESERVE_LINE = 122, tecINSUF_RESERVE_OFFER = 123, tecNO_DST = 124, tecNO_DST_INSUF_XRP = 125, tecNO_LINE_INSUF_RESERVE = 126, tecNO_LINE_REDUNDANT = 127, tecPATH_DRY = 128, tecUNFUNDED = 129, tecNO_ALTERNATIVE_KEY = 130, tecNO_REGULAR_KEY = 131, tecOWNERS = 132, tecNO_ISSUER = 133, tecNO_AUTH = 134, tecNO_LINE = 135, tecINSUFF_FEE = 136, tecFROZEN = 137, tecNO_TARGET = 138, tecNO_PERMISSION = 139, tecNO_ENTRY = 140, tecINSUFFICIENT_RESERVE = 141, tecNEED_MASTER_KEY = 142, tecDST_TAG_NEEDED = 143, tecINTERNAL = 144, tecOVERSIZE = 145, tecCRYPTOCONDITION_ERROR = 146, tecINVARIANT_FAILED = 147, tecEXPIRED = 148, tecDUPLICATE = 149, tecKILLED = 150, }; constexpr TERUnderlyingType TERtoInt (TELcodes v) { return safe_cast<TERUnderlyingType>(v); } constexpr TERUnderlyingType TERtoInt (TEMcodes v) { return safe_cast<TERUnderlyingType>(v); } constexpr TERUnderlyingType TERtoInt (TEFcodes v) { return safe_cast<TERUnderlyingType>(v); } constexpr TERUnderlyingType TERtoInt (TERcodes v) { return safe_cast<TERUnderlyingType>(v); } constexpr TERUnderlyingType TERtoInt (TEScodes v) { return safe_cast<TERUnderlyingType>(v); } constexpr TERUnderlyingType TERtoInt (TECcodes v) { return safe_cast<TERUnderlyingType>(v); } template <template<typename> class Trait> class TERSubset { TERUnderlyingType code_; public: constexpr TERSubset() : code_ (tesSUCCESS) { } constexpr TERSubset (TERSubset const& rhs) = default; constexpr TERSubset (TERSubset&& rhs) = default; private: constexpr explicit TERSubset (int rhs) : code_ (rhs) { } public: static constexpr TERSubset fromInt (int from) { return TERSubset (from); } template <typename T, typename = std::enable_if_t<Trait<T>::value>> constexpr TERSubset (T rhs) : code_ (TERtoInt (rhs)) { } constexpr TERSubset& operator=(TERSubset const& rhs) = default; constexpr TERSubset& operator=(TERSubset&& rhs) = default; template <typename T> constexpr auto operator= (T rhs) -> std::enable_if_t<Trait<T>::value, TERSubset&> { code_ = TERtoInt (rhs); return *this; } explicit operator bool() const { return code_ != tesSUCCESS; } operator Json::Value() const { return Json::Value {code_}; } friend std::ostream& operator<< (std::ostream& os, TERSubset const& rhs) { return os << rhs.code_; } friend constexpr TERUnderlyingType TERtoInt (TERSubset v) { return v.code_; } }; template <typename L, typename R> constexpr auto operator== (L const& lhs, R const& rhs) -> std::enable_if_t< std::is_same<decltype (TERtoInt(lhs)), int>::value && std::is_same<decltype (TERtoInt(rhs)), int>::value, bool> { return TERtoInt(lhs) == TERtoInt(rhs); } template <typename L, typename R> constexpr auto operator!= (L const& lhs, R const& rhs) -> std::enable_if_t< std::is_same<decltype (TERtoInt(lhs)), int>::value && std::is_same<decltype (TERtoInt(rhs)), int>::value, bool> { return TERtoInt(lhs) != TERtoInt(rhs); } template <typename L, typename R> constexpr auto operator< (L const& lhs, R const& rhs) -> std::enable_if_t< std::is_same<decltype (TERtoInt(lhs)), int>::value && std::is_same<decltype (TERtoInt(rhs)), int>::value, bool> { return TERtoInt(lhs) < TERtoInt(rhs); } template <typename L, typename R> constexpr auto operator<= (L const& lhs, R const& rhs) -> std::enable_if_t< std::is_same<decltype (TERtoInt(lhs)), int>::value && std::is_same<decltype (TERtoInt(rhs)), int>::value, bool> { return TERtoInt(lhs) <= TERtoInt(rhs); } template <typename L, typename R> constexpr auto operator> (L const& lhs, R const& rhs) -> std::enable_if_t< std::is_same<decltype (TERtoInt(lhs)), int>::value && std::is_same<decltype (TERtoInt(rhs)), int>::value, bool> { return TERtoInt(lhs) > TERtoInt(rhs); } template <typename L, typename R> constexpr auto operator>= (L const& lhs, R const& rhs) -> std::enable_if_t< std::is_same<decltype (TERtoInt(lhs)), int>::value && std::is_same<decltype (TERtoInt(rhs)), int>::value, bool> { return TERtoInt(lhs) >= TERtoInt(rhs); } template <typename FROM> class CanCvtToNotTEC : public std::false_type {}; template <> class CanCvtToNotTEC<TELcodes> : public std::true_type {}; template <> class CanCvtToNotTEC<TEMcodes> : public std::true_type {}; template <> class CanCvtToNotTEC<TEFcodes> : public std::true_type {}; template <> class CanCvtToNotTEC<TERcodes> : public std::true_type {}; template <> class CanCvtToNotTEC<TEScodes> : public std::true_type {}; using NotTEC = TERSubset<CanCvtToNotTEC>; template <typename FROM> class CanCvtToTER : public std::false_type {}; template <> class CanCvtToTER<TELcodes> : public std::true_type {}; template <> class CanCvtToTER<TEMcodes> : public std::true_type {}; template <> class CanCvtToTER<TEFcodes> : public std::true_type {}; template <> class CanCvtToTER<TERcodes> : public std::true_type {}; template <> class CanCvtToTER<TEScodes> : public std::true_type {}; template <> class CanCvtToTER<TECcodes> : public std::true_type {}; template <> class CanCvtToTER<NotTEC> : public std::true_type {}; using TER = TERSubset<CanCvtToTER>; inline bool isTelLocal(TER x) { return ((x) >= telLOCAL_ERROR && (x) < temMALFORMED); } inline bool isTemMalformed(TER x) { return ((x) >= temMALFORMED && (x) < tefFAILURE); } inline bool isTefFailure(TER x) { return ((x) >= tefFAILURE && (x) < terRETRY); } inline bool isTerRetry(TER x) { return ((x) >= terRETRY && (x) < tesSUCCESS); } inline bool isTesSuccess(TER x) { return ((x) == tesSUCCESS); } inline bool isTecClaim(TER x) { return ((x) >= tecCLAIM); } bool transResultInfo (TER code, std::string& token, std::string& text); std::string transToken (TER code); std::string transHuman (TER code); boost::optional<TER> transCode(std::string const& token); } #endif
24.581769
84
0.633548
283f1973a2a1befc48302cd673535ce3ba5f93a8
2,467
rb
Ruby
app/controllers/providers/used_multiple_delegated_functions_controller.rb
rowlando/apply-for-la
3254b45e39d45b820665883787a47bdcb28430b4
[ "MIT" ]
16
2018-11-26T10:54:26.000Z
2022-02-07T16:46:42.000Z
app/controllers/providers/used_multiple_delegated_functions_controller.rb
ministryofjustice/laa-apply-for-legal-aid
3bca22eb67031597101ebf9fca773d345b713750
[ "MIT" ]
697
2018-11-02T11:53:39.000Z
2022-03-31T07:36:17.000Z
app/controllers/providers/used_multiple_delegated_functions_controller.rb
rowlando/apply-for-la
3254b45e39d45b820665883787a47bdcb28430b4
[ "MIT" ]
10
2019-05-02T20:24:09.000Z
2021-09-17T16:23:41.000Z
module Providers class UsedMultipleDelegatedFunctionsController < ProviderBaseController include PreDWPCheckVisible def show form end def update render :show unless save_continue_and_update_scope_limitations end private def save_continue_and_update_scope_limitations form.draft = draft_selected? return unless form.save(form_params) update_scope_limitations DelegatedFunctionsDateService.call(legal_aid_application, draft_selected: draft_selected?) draft_selected? ? continue_or_draft : go_forward(delegated_functions_used_over_month_ago?) end def form @form ||= LegalAidApplications::UsedMultipleDelegatedFunctionsForm.call(application_proceedings_by_name) end def proceeding_types @proceeding_types ||= legal_aid_application.proceeding_types end def application_proceedings_by_name @application_proceedings_by_name ||= legal_aid_application.application_proceedings_by_name end def application_proceeding_types application_proceedings_by_name.map(&:application_proceeding_type) end def delegated_functions_used_over_month_ago? return false if earliest_delegated_functions_date.nil? earliest_delegated_functions_date < 1.month.ago end def earliest_delegated_functions_date @earliest_delegated_functions_date ||= legal_aid_application.earliest_delegated_functions_date end # def earliest_delegated_functions_reported_date # @earliest_delegated_functions_reported_date ||= legal_aid_application.earliest_delegated_functions_reported_date # end def update_scope_limitations earliest_delegated_functions_date ? add_delegated_scope_limitations : remove_delegated_scope_limitations end def add_delegated_scope_limitations proceeding_types.each do |proceeding_type| LegalFramework::AddAssignedScopeLimitationService.call(legal_aid_application, proceeding_type.id, :delegated) end end def remove_delegated_scope_limitations application_proceeding_types.each(&:remove_default_delegated_functions_scope_limitation) end def form_params merged_params = params.require(:legal_aid_applications_used_multiple_delegated_functions_form) .except(:delegated_functions) convert_date_params(merged_params) end def draft_selected? params.key?(:draft_button) end end end
30.8375
120
0.781516
f175e1dbdba4b3a4ad88090e55ae9492e92e764f
7,516
rb
Ruby
spec/octopolo/github_spec.rb
sportngin/octopolo
51c15e31b6737657a5581de70bb7328206b78181
[ "MIT" ]
13
2015-02-10T03:20:05.000Z
2020-09-24T16:27:58.000Z
spec/octopolo/github_spec.rb
sportngin/octopolo
51c15e31b6737657a5581de70bb7328206b78181
[ "MIT" ]
78
2015-01-27T23:23:56.000Z
2021-08-11T16:08:48.000Z
spec/octopolo/github_spec.rb
sportngin/octopolo
51c15e31b6737657a5581de70bb7328206b78181
[ "MIT" ]
4
2015-09-08T12:14:11.000Z
2016-05-13T19:20:16.000Z
require "spec_helper" require_relative "../../lib/octopolo/github" module Octopolo describe GitHub do context ".client" do let(:octokit_client) { stub(:github_client) } let(:user_config) { stub(:user_config, github_user: "foo", github_token: "bar") } before do GitHub.stub(user_config: user_config) end it "logs in with the configured authentication values" do Octokit::Client.should_receive(:new).with(login: user_config.github_user, access_token: user_config.github_token) { octokit_client } GitHub.client.should == octokit_client end it "uses additional given parameters" do Octokit::Client.should_receive(:new).with(login: user_config.github_user, access_token: user_config.github_token, auto_traversal: true) { octokit_client } GitHub.client(auto_traversal: true).should == octokit_client end it "properly handles if the github authentication isn't configured" do user_config.should_receive(:github_user).and_raise(UserConfig::MissingGitHubAuth) Scripts::GithubAuth.should_not_receive(:invoke) expect { GitHub.client }.to raise_error(GitHub::TryAgain, "No GitHub API token stored. Please run `op github-auth` to generate your token.") end end context ".crawling_client" do let(:client) { stub } it "instantiates a client with auto_traversal" do GitHub.should_receive(:client).with(auto_traversal: true) { client } GitHub.crawling_client.should == client end end context "having convenience methods" do let(:client) { stub(:github_client) } let(:crawling_client) { stub(:github_crawling_client) } let(:data) { stub } before do GitHub.stub(client: client, crawling_client: crawling_client) end context ".pull_request *args" do it "sends onto the client wrapper" do client.should_receive(:pull_request).with("a", "b") { data } result = GitHub.pull_request("a", "b") result.should == data end end context ".issue *args" do it "sends onto the client wrapper" do client.should_receive(:issue).with("a", "b") { data } result = GitHub.issue("a", "b") result.should == data end end context ".pull_request_commits *args" do it "sends onto the client wrapper" do client.should_receive(:pull_request_commits).with("a", "b") { data } result = GitHub.pull_request_commits("a", "b") result.should == data end end context ".issue_comments *args" do it "sends onto the client wrapper" do client.should_receive(:issue_comments).with("a", "b") { data } result = GitHub.issue_comments("a", "b") result.should == data end end context ".pull_requests *args" do it "sends onto the crawling client wrapper" do crawling_client.should_receive(:pull_requests).with("a", "b") { data } GitHub.pull_requests("a", "b").should == data end end context ".tst_repos" do it "fetches the sportngin organization repos" do crawling_client.should_receive(:organization_repositories).with("sportngin") { data } GitHub.org_repos.should == data end it "fetches another organization's repos if requested" do crawling_client.should_receive(:organization_repositories).with("foo") { data } GitHub.org_repos("foo").should == data end end context ".create_pull_request" do it "sends the pull request to the API" do client.should_receive(:create_pull_request).with("repo", "destination_branch", "source_branch", "title", "body") { data } GitHub.create_pull_request("repo", "destination_branch", "source_branch", "title", "body").should == data end end context ".create_issue" do it "sends the issue to the API" do client.should_receive(:create_issue).with("repo", "title", "body") { data } GitHub.create_issue("repo", "title", "body").should == data end end context ".add_comment" do it "sends the comment to the API" do client.should_receive(:add_comment).with("repo", 123, "contents of comment") GitHub.add_comment "repo", 123, "contents of comment" end end context ".user username" do let(:username) { "foo" } let(:valid_user) { stub(login: "foo", name: "Joe Foo")} it "fetches the user data from GitHub" do client.should_receive(:user).with(username) { valid_user } GitHub.user(username).should == valid_user end it "returns a generic Unknown user if none is found" do client.should_receive(:user).with(username).and_raise(Octokit::NotFound) GitHub.user(username).should == Hashie::Mash.new(name: GitHub::UNKNOWN_USER) end end context ".check_connection" do it "performs a request against the API which requires authentication" do client.should_receive(:user) GitHub.check_connection end it "raises BadCredentials if testing the connection raises Octokit::Unauthorized" do client.should_receive(:user).and_raise(Octokit::Unauthorized) expect { GitHub.check_connection }.to raise_error(GitHub::BadCredentials) end end context ".connect &block" do let(:thing) { stub } let(:try_again) { GitHub::TryAgain.new("try-again message") } let(:bad_credentials) { GitHub::BadCredentials.new("bad-credentials message") } it "performs the block if GitHub.check_connection does not raise an exception" do GitHub.should_receive(:check_connection) thing.should_receive(:foo) GitHub.connect do thing.foo end end it "does not perform the block if GitHub.check_connection raises TryAgain" do GitHub.should_receive(:check_connection).and_raise(try_again) thing.should_not_receive(:foo) CLI.should_receive(:say).with(try_again.message) GitHub.connect do thing.foo end end it "does not perform the block if GitHub.check_connection raises BadCredentials" do GitHub.should_receive(:check_connection).and_raise(bad_credentials) thing.should_not_receive(:foo) CLI.should_receive(:say).with(bad_credentials.message) GitHub.connect do thing.foo end end end context ".team_member? team" do let(:valid_team) { 2396228 } let(:invalid_team) { 2396227 } let(:user_config) { stub(:user_config, github_user: "foo", github_token: "bar") } before { GitHub.stub(user_config: user_config) } context "when valid team member" do it "returns true" do client.should_receive(:team_member?).with(valid_team, user_config.github_user) { true } GitHub.team_member?(valid_team).should == true end end context "when not a valid team member" do it "returns false" do client.should_receive(:team_member?).with(invalid_team, user_config.github_user) { false } GitHub.team_member?(invalid_team).should == false end end end end end end
36.309179
162
0.633183
1ff6f6bd506e88958e65ade42d195f3d1c46432b
2,529
css
CSS
public/css/cssmod.css
hanbragher/aziz
570ed108f486a15b2437a40bce2c93b297c15835
[ "MIT" ]
null
null
null
public/css/cssmod.css
hanbragher/aziz
570ed108f486a15b2437a40bce2c93b297c15835
[ "MIT" ]
null
null
null
public/css/cssmod.css
hanbragher/aziz
570ed108f486a15b2437a40bce2c93b297c15835
[ "MIT" ]
null
null
null
div.sidenav-item{ padding-left: 1rem; } div.card-second-part{ padding: 10px !important; } div.card-notes{ padding: 10px !important; } span.photo-header{ padding: 5px 10px; } span.place-header{ padding: 5px 10px; } img.notification-thumb{ width: 25px; height: 25px; border-radius: 50%; } div.notification{ padding: 10px !important; } div.comment{ padding: 10px !important; } p.sidenav-divader{ padding: 6px !important; background-color: ghostwhite !important; } a.set-fav-photo{ position: absolute; padding-top: 10px; padding-left: 10px; } a.set-fav-place{ position: absolute; padding-top: 10px; padding-left: 10px; } i.padded-left{ padding-left: 5px; } a.collection-item{ padding: 6px 10px !important; } i.sidenav-icon{ margin-right: 1rem; } .margin-bottom-0{ margin-bottom: 0px !important; } ul.msg-tabs { position: relative; overflow-x: auto; overflow-y: hidden; height: 48px; width: 100%; background-color: #fff; margin: 0 auto; white-space: nowrap; } li.inbox-col{ display: inline-block; text-align: center; line-height: 48px; height: 48px; padding: 0; margin: 0; text-transform: uppercase; background-color: rgba(246,178,181,0.2); } a.active-tab { color: #ee6e73; } /*img.announcement-card-image{ height: 190px; float: left; vertical-align: top; margin: 5px; } img.announcement-card-mob-image{ height: 80px; float: left; vertical-align: top; margin: 5px; }*/ @media only screen and (min-width : 601px) and (max-width : 1260px) { .toast { width: 100%; border-radius: 0; } #toast-container { min-width: 100%; bottom: 0%; top: 90%; right: 0%; left: 0%; } img.announcement-card-image{ height: 150px; float: left; vertical-align: top; margin: 5px; } } @media only screen and (min-width : 1261px) { .toast { width: 100%; border-radius: 0; } #toast-container { top: auto !important; right: auto !important; bottom: 50%; left:45%; } img.announcement-card-image{ height: 190px; float: left; vertical-align: top; margin: 5px; } } @media (max-width : 600px) { img.announcement-card-image{ height: 100px; float: left; vertical-align: top; margin: 5px; } }
14.964497
69
0.577699
6ba13971d148240133b0b0b2869240829e4f3b24
1,812
h
C
src/samples/rsxglgears2/texcube_frag.h
williamblair/RSXGL
ffe01772456aac795961a0ab3532580f9cea84bb
[ "BSD-2-Clause" ]
5
2021-06-05T19:30:07.000Z
2021-07-05T20:22:34.000Z
src/samples/rsxglgears2/texcube_frag.h
williamblair/RSXGL
ffe01772456aac795961a0ab3532580f9cea84bb
[ "BSD-2-Clause" ]
null
null
null
src/samples/rsxglgears2/texcube_frag.h
williamblair/RSXGL
ffe01772456aac795961a0ab3532580f9cea84bb
[ "BSD-2-Clause" ]
1
2021-08-14T23:47:49.000Z
2021-08-14T23:47:49.000Z
unsigned char texcube_frag[] = { 0x23, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x20, 0x31, 0x33, 0x30, 0x0a, 0x75, 0x6e, 0x69, 0x66, 0x6f, 0x72, 0x6d, 0x20, 0x73, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x72, 0x32, 0x44, 0x20, 0x69, 0x6d, 0x61, 0x67, 0x65, 0x2c, 0x20, 0x67, 0x72, 0x61, 0x64, 0x69, 0x65, 0x6e, 0x74, 0x3b, 0x0a, 0x2f, 0x2f, 0x75, 0x6e, 0x69, 0x66, 0x6f, 0x72, 0x6d, 0x20, 0x76, 0x65, 0x63, 0x34, 0x20, 0x66, 0x6f, 0x6f, 0x3b, 0x0a, 0x0a, 0x76, 0x61, 0x72, 0x79, 0x69, 0x6e, 0x67, 0x20, 0x76, 0x65, 0x63, 0x32, 0x20, 0x74, 0x63, 0x3b, 0x0a, 0x0a, 0x76, 0x6f, 0x69, 0x64, 0x0a, 0x6d, 0x61, 0x69, 0x6e, 0x28, 0x76, 0x6f, 0x69, 0x64, 0x29, 0x0a, 0x7b, 0x0a, 0x20, 0x20, 0x2f, 0x2f, 0x67, 0x6c, 0x5f, 0x46, 0x72, 0x61, 0x67, 0x43, 0x6f, 0x6c, 0x6f, 0x72, 0x20, 0x3d, 0x20, 0x76, 0x65, 0x63, 0x34, 0x28, 0x74, 0x63, 0x2e, 0x78, 0x2c, 0x74, 0x63, 0x2e, 0x79, 0x2c, 0x30, 0x2c, 0x31, 0x29, 0x3b, 0x0a, 0x20, 0x20, 0x67, 0x6c, 0x5f, 0x46, 0x72, 0x61, 0x67, 0x43, 0x6f, 0x6c, 0x6f, 0x72, 0x20, 0x3d, 0x20, 0x74, 0x65, 0x78, 0x74, 0x75, 0x72, 0x65, 0x32, 0x44, 0x28, 0x69, 0x6d, 0x61, 0x67, 0x65, 0x2c, 0x74, 0x63, 0x29, 0x20, 0x2a, 0x20, 0x74, 0x65, 0x78, 0x74, 0x75, 0x72, 0x65, 0x28, 0x67, 0x72, 0x61, 0x64, 0x69, 0x65, 0x6e, 0x74, 0x2c, 0x74, 0x63, 0x29, 0x3b, 0x0a, 0x20, 0x20, 0x2f, 0x2f, 0x67, 0x6c, 0x5f, 0x46, 0x72, 0x61, 0x67, 0x43, 0x6f, 0x6c, 0x6f, 0x72, 0x20, 0x3d, 0x20, 0x74, 0x65, 0x78, 0x74, 0x75, 0x72, 0x65, 0x32, 0x44, 0x28, 0x69, 0x6d, 0x61, 0x67, 0x65, 0x2c, 0x74, 0x63, 0x29, 0x3b, 0x0a, 0x20, 0x20, 0x2f, 0x2f, 0x67, 0x6c, 0x5f, 0x46, 0x72, 0x61, 0x67, 0x43, 0x6f, 0x6c, 0x6f, 0x72, 0x20, 0x3d, 0x20, 0x76, 0x65, 0x63, 0x34, 0x28, 0x31, 0x2c, 0x31, 0x2c, 0x31, 0x2c, 0x31, 0x29, 0x3b, 0x0a, 0x7d, 0x0a }; unsigned int texcube_frag_len = 282;
64.714286
73
0.652318
e7184b1b797bf90d5e37ca0d2942cb1412994826
2,158
js
JavaScript
node_modules/styled-icons/typicons/SocialGithub/SocialGithub.esm.js
venhrun-petro/oselya
8f0476105c0d08495661f2b7236b4af89f6e0b72
[ "MIT" ]
null
null
null
node_modules/styled-icons/typicons/SocialGithub/SocialGithub.esm.js
venhrun-petro/oselya
8f0476105c0d08495661f2b7236b4af89f6e0b72
[ "MIT" ]
null
null
null
node_modules/styled-icons/typicons/SocialGithub/SocialGithub.esm.js
venhrun-petro/oselya
8f0476105c0d08495661f2b7236b4af89f6e0b72
[ "MIT" ]
null
null
null
import * as tslib_1 from "tslib"; import * as React from 'react'; import { StyledIconBase } from '../../StyledIconBase'; export var SocialGithub = React.forwardRef(function (props, ref) { var attrs = { "fill": "currentColor", }; return (React.createElement(StyledIconBase, tslib_1.__assign({ iconAttrs: attrs, iconVerticalAlign: "middle", iconViewBox: "0 0 24 24" }, props, { ref: ref }), React.createElement("path", { d: "M14.435 12.973c.269 0 .492.133.686.396.192.265.294.588.294.975 0 .385-.102.711-.294.973-.193.265-.417.396-.686.396-.278 0-.522-.131-.715-.396-.192-.262-.294-.588-.294-.973 0-.387.102-.71.294-.975.192-.264.436-.396.715-.396m3.44-3.559c.746.811 1.125 1.795 1.125 2.953 0 .748-.086 1.423-.259 2.023-.175.597-.394 1.084-.654 1.459a4.268 4.268 0 0 1-.974.989 4.94 4.94 0 0 1-1.065.623 5.465 5.465 0 0 1-1.111.306 9 9 0 0 1-.943.123l-.685.014-.547.015a17.567 17.567 0 0 1-1.524 0l-.547-.015-.685-.014a8.966 8.966 0 0 1-.943-.123 5.28 5.28 0 0 1-1.111-.306 4.888 4.888 0 0 1-1.064-.623 4.253 4.253 0 0 1-.975-.989c-.261-.375-.479-.862-.654-1.459-.173-.6-.259-1.275-.259-2.023 0-1.158.379-2.143 1.125-2.953-.082-.041-.085-.447-.008-1.217a7.071 7.071 0 0 1 .495-2.132c.934.099 2.09.629 3.471 1.581.466-.119 1.101-.183 1.917-.183.852 0 1.491.064 1.918.184.629-.425 1.23-.771 1.805-1.034.584-.261 1.005-.416 1.269-.457l.396-.09c.27.649.434 1.36.496 2.132.076.769.073 1.175-.009 1.216m-5.845 7.82c1.688 0 2.954-.202 3.821-.607.855-.404 1.292-1.238 1.292-2.496 0-.73-.273-1.34-.822-1.828a1.845 1.845 0 0 0-.989-.486c-.375-.061-.949-.061-1.72 0-.769.062-1.298.09-1.582.09-.385 0-.8-.018-1.319-.059-.52-.04-.928-.065-1.223-.078a3.727 3.727 0 0 0-.958.108 1.913 1.913 0 0 0-.853.425c-.521.469-.79 1.077-.79 1.828 0 1.258.426 2.092 1.28 2.496.85.405 2.113.607 3.802.607h.061m-2.434-4.261c.268 0 .492.133.685.396.192.265.294.588.294.975 0 .385-.102.711-.294.973-.192.265-.417.396-.685.396-.279 0-.522-.131-.716-.396-.192-.262-.294-.588-.294-.973 0-.387.102-.71.294-.975.193-.264.436-.396.716-.396", key: "k0" }))); }); SocialGithub.displayName = 'SocialGithub'; export var SocialGithubDimensions = { height: 24, width: 24 };
166
1,638
0.65431
0cc6f68c50e68c364cd5514c50d107da2d606391
122
py
Python
api/crawller/admin.py
MahsaSeifikar/tweetphus
01b687f38365023cfaaa34739c50b0da79f0b510
[ "MIT" ]
null
null
null
api/crawller/admin.py
MahsaSeifikar/tweetphus
01b687f38365023cfaaa34739c50b0da79f0b510
[ "MIT" ]
1
2021-12-26T16:35:36.000Z
2021-12-29T15:07:01.000Z
api/crawller/admin.py
MahsaSeifikar/tweetphus
01b687f38365023cfaaa34739c50b0da79f0b510
[ "MIT" ]
null
null
null
from django.contrib import admin from crawller.models import User # Register your models here. admin.site.register(User)
20.333333
32
0.811475
2069a8783ef5257f23ae89a2c54877facee8a7e6
1,961
lua
Lua
lua/twilight/colors/init.lua
jzone1366/twilight.nvim
da72643da7b73745ce5b56dd79340446949acf7f
[ "MIT" ]
1
2022-03-14T23:15:29.000Z
2022-03-14T23:15:29.000Z
lua/twilight/colors/init.lua
jzone1366/twilight.nvim
da72643da7b73745ce5b56dd79340446949acf7f
[ "MIT" ]
1
2022-03-15T08:23:39.000Z
2022-03-15T14:31:22.000Z
lua/twilight/colors/init.lua
jzone1366/twilight.nvim
da72643da7b73745ce5b56dd79340446949acf7f
[ "MIT" ]
null
null
null
local M = {} M.styles = { "light", "dark", } -- Adds subtle and harsh colors depending if the colors are dark or light -- @param colors table -- @return table of colors local function construct(colors) colors.harsh = colors.meta.light and colors.black or colors.white colors.subtle = colors.meta.light and colors.white or colors.black return colors end -- Returns a color table based on the name provided -- This returns the initial colors defined by the colorscheme -- without overrides from the configuration -- If name is not found will default to light -- If the style is invalid the it will return light colors -- @param name string (optional) -- @return table of colors function M.init(name) name = name or require("twilight.config").options.style if name == "random" then local index = math.random(#M.styles) return construct(require("twilight.colors." .. M.styles[index]).init()) end for _, style in ipairs(M.styles) do if style == name then return construct(require("twilight.colors." .. name).init()) end end require("twilight.util").warn("colorscheme " .. name .. " was not found") return construct(require("twilight.colors.light").init()) end -- Return color table based on the name provided -- If no name is provided it will return the style set in the config -- If the style defined in the configuration is invalid the it will return light colors -- @param name string (optional) -- @return table of colors function M.load(name) name = name or require("twilight.config").options.style if name == "random" then local index = math.random(#M.styles) return construct(require("twilight.colors." .. M.styles[index]).load()) end for _, style in ipairs(M.styles) do if style == name then return construct(require("twilight.colors." .. name).load()) end end require("twilight.util").warn("colorscheme " .. name .. " was not found") return construct(require("twilight.colors.light").load()) end return M
29.712121
87
0.720551
bf7d99c5206704daef4fffb57d87520b9a59363d
682
kt
Kotlin
app/src/main/java/com/huanchengfly/tieba/post/Consts.kt
fly2marss/TiebaLite
34c341be0e706810febda54ea68cbd38955502d8
[ "Apache-2.0" ]
1,346
2020-04-16T02:23:22.000Z
2022-03-31T15:44:57.000Z
app/src/main/java/com/huanchengfly/tieba/post/Consts.kt
lz233/TiebaLite
62753d18bb83b03de767fbbd8d9468785478c982
[ "Apache-2.0" ]
85
2020-08-12T02:10:01.000Z
2022-03-29T08:34:11.000Z
app/src/main/java/com/huanchengfly/tieba/post/Consts.kt
lz233/TiebaLite
62753d18bb83b03de767fbbd8d9468785478c982
[ "Apache-2.0" ]
144
2020-04-16T15:38:12.000Z
2022-03-29T12:10:15.000Z
package com.huanchengfly.tieba.post object BundleConfig { const val MATCH_COMPONENT = "matchComponent" const val MATCH_ACTION = "matchAction" const val TARGET_URL = "targetUrl" const val TARGET_DATA = "targetData" const val TARGET_TITLE = "targetTitle" const val TARGET_IMAGE = "targetImage" const val TARGET_EXTRA = "targetExtra" } object IntentConfig { const val ACTION = "com.miui.personalassistant.action.FAVORITE" const val PACKAGE = "com.miui.personalassistant" //发送广播指定的包名 const val PERMISSION = "com.miui.personalassistant.permission.FAVORITE" //发送广播指定的权限 const val BUNDLES = "bundles" const val ACTION_FAV = "action_fav" }
34.1
87
0.737537
992c92958b330fe79a14a17c9e4bdcb921428732
2,605
h
C
System/Library/PrivateFrameworks/HealthDaemon.framework/HDSyncAnchorEntity.h
lechium/iPhoneOS_12.1.1_Headers
aac688b174273dfcbade13bab104461f463db772
[ "MIT" ]
12
2019-06-02T02:42:41.000Z
2021-04-13T07:22:20.000Z
System/Library/PrivateFrameworks/HealthDaemon.framework/HDSyncAnchorEntity.h
lechium/iPhoneOS_12.1.1_Headers
aac688b174273dfcbade13bab104461f463db772
[ "MIT" ]
null
null
null
System/Library/PrivateFrameworks/HealthDaemon.framework/HDSyncAnchorEntity.h
lechium/iPhoneOS_12.1.1_Headers
aac688b174273dfcbade13bab104461f463db772
[ "MIT" ]
3
2019-06-11T02:46:10.000Z
2019-12-21T14:58:16.000Z
/* * This header is generated by classdump-dyld 1.0 * on Saturday, June 1, 2019 at 6:49:36 PM Mountain Standard Time * Operating System: Version 12.1.1 (Build 16C5050a) * Image Source: /System/Library/PrivateFrameworks/HealthDaemon.framework/HealthDaemon * classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos. */ #import <HealthDaemon/HealthDaemon-Structs.h> #import <HealthDaemon/HDHealthEntity.h> @interface HDSyncAnchorEntity : HDHealthEntity +(id)databaseTable; +(const SCD_Struct_HD0*)columnDefinitionsWithCount:(unsigned long long*)arg1 ; +(id)uniquedColumns; +(long long)protectionClass; +(long long)nextSyncAnchorForEntityIdentifier:(id)arg1 store:(id)arg2 profile:(id)arg3 error:(id*)arg4 ; +(BOOL)setAcknowledgedAnchorsWithMap:(id)arg1 store:(id)arg2 resetNext:(BOOL)arg3 resetInvalid:(BOOL)arg4 profile:(id)arg5 error:(id*)arg6 ; +(BOOL)resetReceivedAnchorsForStore:(id)arg1 profile:(id)arg2 error:(id*)arg3 ; +(BOOL)getReceivedAnchorsWithMap:(id)arg1 store:(id)arg2 profile:(id)arg3 error:(id*)arg4 ; +(BOOL)resetSyncStore:(id)arg1 profile:(id)arg2 error:(id*)arg3 ; +(BOOL)getNextAnchorsWithMap:(id)arg1 store:(id)arg2 profile:(id)arg3 error:(id*)arg4 ; +(BOOL)resetNextSyncAnchor:(long long)arg1 entityIdentifier:(id)arg2 store:(id)arg3 profile:(id)arg4 error:(id*)arg5 ; +(BOOL)setNextSyncAnchor:(long long)arg1 entityIdentifier:(id)arg2 store:(id)arg3 profile:(id)arg4 error:(id*)arg5 ; +(BOOL)setReceivedAnchor:(long long)arg1 entityIdentifier:(id)arg2 store:(id)arg3 profile:(id)arg4 error:(id*)arg5 ; +(long long)receivedAnchorForEntityIdentifier:(id)arg1 store:(id)arg2 profile:(id)arg3 error:(id*)arg4 ; +(long long)_syncAnchorForProperty:(id)arg1 entityIdentifier:(id)arg2 store:(id)arg3 profile:(id)arg4 error:(id*)arg5 ; +(BOOL)_setSyncAnchor:(long long)arg1 options:(unsigned long long)arg2 updatePolicy:(long long)arg3 entityIdentifier:(id)arg4 store:(id)arg5 profile:(id)arg6 error:(id*)arg7 ; +(BOOL)_setSyncAnchor:(long long)arg1 options:(unsigned long long)arg2 updatePolicy:(long long)arg3 entityIdentifier:(id)arg4 store:(id)arg5 database:(id)arg6 error:(id*)arg7 ; +(BOOL)_getAnchorsForProperty:(id)arg1 anchorMap:(id)arg2 store:(id)arg3 profile:(id)arg4 error:(id*)arg5 ; +(id)_predicateForSyncStore:(id)arg1 ; +(id)_predicateForSyncEntityIdentifier:(id)arg1 syncStore:(id)arg2 ; +(id)_predicateForSyncEntityIdentifier:(id)arg1 ; +(BOOL)getAckedAnchorsWithMap:(id)arg1 store:(id)arg2 profile:(id)arg3 error:(id*)arg4 ; +(BOOL)enumerateSyncAnchorsForStoreID:(long long)arg1 database:(id)arg2 error:(id*)arg3 handler:(/*^block*/id)arg4 ; @end
68.552632
176
0.777351
92237db77ec93b3b6f2d198efe47abd249007f5e
2,515
sql
SQL
Projects/EastLondonGenesAndHealthPhase2/Queries/gh2execute11.sql
endeavourhealth-discovery/DiscoveryQueryLibrary
7f8573df1bf44e073b793aab69e32600161ba02d
[ "Apache-2.0" ]
null
null
null
Projects/EastLondonGenesAndHealthPhase2/Queries/gh2execute11.sql
endeavourhealth-discovery/DiscoveryQueryLibrary
7f8573df1bf44e073b793aab69e32600161ba02d
[ "Apache-2.0" ]
null
null
null
Projects/EastLondonGenesAndHealthPhase2/Queries/gh2execute11.sql
endeavourhealth-discovery/DiscoveryQueryLibrary
7f8573df1bf44e073b793aab69e32600161ba02d
[ "Apache-2.0" ]
null
null
null
USE data_extracts; -- ahui 10/2/2020 DROP PROCEDURE IF EXISTS gh2execute11; DELIMITER // CREATE PROCEDURE gh2execute11() BEGIN -- Medications (Asthma) DROP TABLE IF EXISTS gh2_MedAsthmaDataset; CREATE TABLE gh2_MedAsthmaDataset ( pseudo_id VARCHAR(255), pseudo_nhsnumber VARCHAR(255), category VARCHAR(100), subcategory VARCHAR(100), class VARCHAR(100), code VARCHAR(100), term VARCHAR(200), earliest_issue_date DATE, latest_issue_date DATE, discontinued_date DATE, binary_4month_ind VARCHAR(10), med_id BIGINT ); ALTER TABLE gh2_MedAsthmaDataset ADD INDEX gh2_mdast_pseduo_id (pseudo_id); CALL populateMedicationsV2('Asthma','Oral steroid','Oral steroid','gh2_MedAsthmaDataset','10312003,349354003',null,null,null); CALL populateMedicationsV2('Asthma','ICS','ICS','gh2_MedAsthmaDataset','1389007,108632003,75203002,416739001',null,'349361004,432681009,350386006,11880411000001105,13229101000001104,34855311000001107,20121811000001105,16072611000001102,22053511000001109,29731511000001103,350438003,350437008,13229401000001105,13229501000001109,21991211000001107,34955711000001102,407754007,407753001,13229701000001103,32695711000001104,32695811000001107,32695811000001107,18525411000001101,424048001',null); CALL populateMedicationsV2('Asthma','Beta2 agonist','Beta2 agonist','gh2_MedAsthmaDataset','91143003,45311002,108605008,386171009,349923005',null,'421685007,135640007,13159601000001109,35937011000001102,28279711000001100,35916011000001108,349928001,28367211000001102,34855311000001107,763710002',null); CALL populateMedicationsV2('Asthma','Other','Other','gh2_MedAsthmaDataset','66493003,55867006',null,null,null); CALL populateMedicationsV2('Asthma','Leukotriene antagonist','Leukotriene antagonist','gh2_MedAsthmaDataset','320883008',null,null,null); CALL populateMedicationsV2('Asthma','Mast cell stabilizer','Mast cell stabilizer','gh2_MedAsthmaDataset','108627004,4161311000001109,35926611000001105,35926711000001101,13801911000001104',null,'430684006',null); CALL populateMedicationsV2('Asthma','Monoclonal Ab','Monoclonal Ab','gh2_MedAsthmaDataset','763652003,406442003,31201911000001104,33999711000001105',null,null,null); CALL populateMedicationsV2('Asthma','Leukotriene antagonist','Leukotriene antagonist','gh2_MedAsthmaDataset','108614003,386180009',null,null,null); END // DELIMITER ;
49.313725
491
0.774155
43c9ae59a393ebfbeb768d3575fb36a4c0db3588
1,578
go
Go
storage/s3_func.go
OgreCase/kit
bebf00292e30262a2fc33b0c544e3e3de27194de
[ "Apache-2.0" ]
null
null
null
storage/s3_func.go
OgreCase/kit
bebf00292e30262a2fc33b0c544e3e3de27194de
[ "Apache-2.0" ]
null
null
null
storage/s3_func.go
OgreCase/kit
bebf00292e30262a2fc33b0c544e3e3de27194de
[ "Apache-2.0" ]
1
2022-01-10T09:13:38.000Z
2022-01-10T09:13:38.000Z
package storage import ( "bytes" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/s3" "github.com/globalsign/mgo/bson" "mime/multipart" "net/http" "path/filepath" ) func UploadFileToS3(s *session.Session, fileHeader *multipart.FileHeader) (string, error) { // get the file size and read // the file content into a buffer size := fileHeader.Size buffer := make([]byte, size) file, err := fileHeader.Open() if err != nil { return "", err } file.Read(buffer) // create a unique file name for the file // 此处文件名称即为上传到aws bucket的名称,也是文件url路径的一部分。也可以在此处拼接url全路径,把域名部分拼接在前边即可。 tempFileName := "pictures/" + bson.NewObjectId().Hex() + filepath.Ext(fileHeader.Filename) // config settings: this is where you choose the bucket, // filename, content-type and storage class of the file // you're uploading _, err = s3.New(s).PutObject(&s3.PutObjectInput{ Bucket: aws.String("test-bucket"), // bucket名称,把自己创建的bucket名称替换到此处即可 Key: aws.String(tempFileName), ACL: aws.String("public-read"), // could be private if you want it to be access by only authorized users Body: bytes.NewReader(buffer), ContentLength: aws.Int64(int64(size)), ContentType: aws.String(http.DetectContentType(buffer)), ContentDisposition: aws.String("attachment"), ServerSideEncryption: aws.String("AES256"), StorageClass: aws.String("INTELLIGENT_TIERING"), }) if err != nil { return "", err } return tempFileName, err }
32.204082
123
0.680608
6e291fb8660a195fa7277221bddf159ffe3e806b
6,623
html
HTML
blog/c3_thinking-style.html
fgv02009/fgv02009.github.io
402a29adb8736b8e78b3f9998cb9f764ed913d8b
[ "MIT" ]
null
null
null
blog/c3_thinking-style.html
fgv02009/fgv02009.github.io
402a29adb8736b8e78b3f9998cb9f764ed913d8b
[ "MIT" ]
null
null
null
blog/c3_thinking-style.html
fgv02009/fgv02009.github.io
402a29adb8736b8e78b3f9998cb9f764ed913d8b
[ "MIT" ]
null
null
null
<!DOCTYPE HTML> <HTML> <head> <link type = "text/css" rel = "stylesheet" href = "../stylesheets/blog-stylesheet.css" </head> <body> <header> <ul> <li><a href ="https://twitter.com/FloriGarcia1"/> <img src= "Twitter_logo.png"></a> </li> <li><a href ="https://www.facebook.com/flori.garcia.3"/> <img src= "fb_logo.png"></a> </li> <li><a href ="https://plus.google.com/u/0/102513395518148946200/posts?cfem=1"/> <img src= "GooglePlus_logo.png"></a> </li> <li><a href ="https://www.linkedin.com/profile/view?id=156562910&trk=nav_responsive_tab_profile_pic/>"/> <img src= "LinkedIn_logo.png"></a> </li> </ul> </header> <div id="DivBody"> <div class = "title">Thinking Styles </div> <div class = "subtitle">Adapting The Way We Learn </div> <h6>11/11/2014 </h6> <div id ="content"> <p>People are wired a certain way. In college, when I was often required to work in groups for projects or assignments, it became very clear to me that what works for some people is often the farthest thing from what works for others. For some people, just being in a group was enough to cause them anxiety. Others thrived in group settings by leading discussions and directing the flow of the project. Some seemed confused by the professor's teaching methods but for others, he could not be more coherent. </p> <p>I had faith in all my classmates and knew they were all very intelligent, but I often wondered why some thrived in certain situations and others (myself included) were stunted by the methods certain professors used. When I started reading about the Gregorc Thinking Style (named after Anthony Gregorc), it clicked. Often times the material we need to learn is not presented to us in the style that best fits our method of thinking. In these cases, if students are not able to adapt either themselves to a new form of learning, or the material into a new form of presentation, then they may fall behind. </p> <p>Gregorc describes two perceptual qualities: concrete and abstract. People with concrete qualities register information directly from their five senses, they are dealing with the obvious and not looking for hidden meaning. People with the abstract quality are able to visualize and conceive ideas. These people look beyond what is obvious and can use their imagination and intuition to see beyond what is right in front of them. He also describes two ordering qualities: sequential and random. Those with the ability to order sequentially organize information in a linear and logical manner, whereas those with the ability to order randomly, organize their information in chunks, but in no particular order. These people can often skip steps in a process and still end up with the desired results. Gregorc uses these four qualities/abilities to come up with the four strongest perceptual and ordering abilities found in each individual: concrete sequential, abstract random, abstract sequential and concrete random.</p> <p>I recently took the personal style thinking test and received my highest score in the concrete random section, and while I think a lot of the characteristics of a concrete random thinker are fitting for me, I don't agree with all of them. (Then again, Gregorc does say no one is a "pure" style, but a combination of the four styles.) My scores were very close all across the board and I think it is because as I've grown up my thinking method has changed, it has been molded by many different learning experiences.</p> <p>As a child I wanted to work by myself, I wanted directions and rules and only one right answer. I was all about getting the best grade, and the most conducive way for me to do that was when there were directions to follow and no one in my way preventing me from being efficient. </p> <p>Thankfully, I went to college. Pomona college, and many liberal arts colleges in general, pride themselves on teaching their students how to learn. My learning horizon expanded exponentially while I was at Pomona. I was often forced to work in groups and by the second or third year I actually preferred that to working alone. While there was still a decent amount of structure in my courses, professors weren't necessarily impressed by the student that got the highest grade in their class. They wanted students that were inquisitive and asked interesting questions and didn't just finish the homework and follow the formulas. I like to think that my time at Pomona slowly started to shape me into a more flexible learner. It is possible that I went from being a highly concrete sequential learner to a mix of any of the other three during my time in college.</p> <p>Since phase 0 has started, I find myself wishing I had more access to other students or staff. While I am very efficient working alone, often times I crave the group setting. It's not necessarily because I have a ton of questions (although sometimes I do), but it's because I've always learned more by being in a group and hearing other people ask questions</p> <p>I know that to get the most of DBC I need to be a flexible learner. I need to be open to the idea of being intently focused one minute and off on a tangent the next. While intense focus helps with efficiency, it is often the students that allow their brains to wander off the specified path for a bit that get the most from their experiences. This will be the first time that I will be going to school where I am not evaluated by grades, but truly by my ability to understand and implement certain concepts. I know that to fully capture everything DBC has to offer, I have to step up to the challenge of accessing all four thinking styles.</p> </div> <div id="DivTable"> <table> <tr> <td><img src="fgv02009.jpg"><td/> <td><h3>By Flori Garcia-Vicente </h3></td> </tr> </table> </div> <div class = "footer" <ul> <li><a href ="../index.html">Home</a></li> <li><a href ="../blog/index.html">Blogs</a></li> <li><a href ="#">About Me</a></li> <li><a href ="../Projects/index.html">Projects</a></li> </ul> </div> </div> </body> </HTML>
118.267857
1,037
0.694096
750b3cd558f06cfce6c0f1836c74fc7efbe100c1
4,341
c
C
templates/src/main.c
ghivert/ocarm
4935ec199f2eb853b49163c8914110bfc87ce7dc
[ "MIT" ]
7
2016-11-11T20:33:02.000Z
2021-04-25T05:04:02.000Z
templates/src/main.c
ghivert/ocarm
4935ec199f2eb853b49163c8914110bfc87ce7dc
[ "MIT" ]
null
null
null
templates/src/main.c
ghivert/ocarm
4935ec199f2eb853b49163c8914110bfc87ce7dc
[ "MIT" ]
1
2019-12-15T07:49:36.000Z
2019-12-15T07:49:36.000Z
#include "main.h" static void SystemClock_Config(void); static void Error_Handler(void); int main(void) { HAL_Init(); /* Configure the system clock to have a system clock = 72 Mhz */ SystemClock_Config(); BSP_LED_Init(LED3); BSP_LED_Init(LED4); BSP_LED_Init(LED5); BSP_LED_Init(LED6); BSP_LED_Init(LED7); BSP_LED_Init(LED8); BSP_LED_Init(LED9); BSP_LED_Init(LED10); BSP_PB_Init(BUTTON_USER, BUTTON_MODE_GPIO); int was_pressed = 0; int indic = 0; while (1) { if (BSP_PB_GetState(BUTTON_USER)) { was_pressed = !was_pressed; if (indic) { BSP_LED_Toggle(LED3); HAL_Delay(30); BSP_LED_Toggle(LED5); HAL_Delay(30); BSP_LED_Toggle(LED7); HAL_Delay(30); BSP_LED_Toggle(LED9); HAL_Delay(30); BSP_LED_Toggle(LED10); HAL_Delay(30); BSP_LED_Toggle(LED8); HAL_Delay(30); BSP_LED_Toggle(LED6); HAL_Delay(30); BSP_LED_Toggle(LED4); } if (!was_pressed) HAL_Delay(1000); } if (was_pressed) { indic = indic ? 0 : 1; BSP_LED_Toggle(LED3); HAL_Delay(30); BSP_LED_Toggle(LED5); HAL_Delay(30); BSP_LED_Toggle(LED7); HAL_Delay(30); BSP_LED_Toggle(LED9); HAL_Delay(30); BSP_LED_Toggle(LED10); HAL_Delay(30); BSP_LED_Toggle(LED8); HAL_Delay(30); BSP_LED_Toggle(LED6); HAL_Delay(30); BSP_LED_Toggle(LED4); HAL_Delay(30); } } } /** * @brief System Clock Configuration * The system Clock is configured as follow : * System Clock source = PLL (HSE) * SYSCLK(Hz) = 72000000 * HCLK(Hz) = 72000000 * AHB Prescaler = 1 * APB1 Prescaler = 2 * APB2 Prescaler = 1 * HSE Frequency(Hz) = 8000000 * HSE PREDIV = 1 * PLLMUL = RCC_PLL_MUL9 (9) * Flash Latency(WS) = 2 * @param None * @retval None */ static void SystemClock_Config(void) { RCC_ClkInitTypeDef RCC_ClkInitStruct; RCC_OscInitTypeDef RCC_OscInitStruct; /* Enable HSE Oscillator and activate PLL with HSE as source */ RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE; RCC_OscInitStruct.HSEState = RCC_HSE_ON; RCC_OscInitStruct.HSEPredivValue = RCC_HSE_PREDIV_DIV1; RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON; RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE; RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL9; if (HAL_RCC_OscConfig(&RCC_OscInitStruct)!= HAL_OK) { Error_Handler(); } /* Select PLL as system clock source and configure the HCLK, PCLK1 and PCLK2 clocks dividers */ RCC_ClkInitStruct.ClockType = (RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2); RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK; RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1; RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2; RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1; if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2)!= HAL_OK) { Error_Handler(); } } /** * @brief This function is executed in case of error occurrence. * @param None * @retval None */ static void Error_Handler(void) { /* User may add here some code to deal with this error */ //while(1) //{ //} } #ifdef USE_FULL_ASSERT /** * @brief Reports the name of the source file and the source line number * where the assert_param error has occurred. * @param file: pointer to the source file name * @param line: assert_param error line source number * @retval None */ void assert_failed(uint8_t* file, uint32_t line) { /* User can add his own implementation to report the file name and line number, ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */ /* Infinite loop */ //while (1) //{ //} } #endif
27.826923
121
0.592029
f002326f1a28c7e060443caad098a4b8ad312c0c
216
py
Python
src/myutils/__init__.py
yyHaker/TextClassification
dc3c5ffe0731609c8f0c7a18a4daa5f149f83e9f
[ "MIT" ]
3
2019-06-08T14:11:56.000Z
2020-05-26T15:08:23.000Z
src/myutils/__init__.py
yyHaker/TextClassification
dc3c5ffe0731609c8f0c7a18a4daa5f149f83e9f
[ "MIT" ]
null
null
null
src/myutils/__init__.py
yyHaker/TextClassification
dc3c5ffe0731609c8f0c7a18a4daa5f149f83e9f
[ "MIT" ]
null
null
null
#!/usr/bin/python # coding:utf-8 """ @author: yyhaker @contact: [email protected] @file: __init__.py @time: 2019/3/9 15:41 """ from .util import * from .functions import * from .nn import * from .attention import *
14.4
26
0.685185
0cdcd31b1d541c0b2fc7fa87f9fe6a1fb877291b
4,997
py
Python
rdsslib/kinesis/client.py
JiscSD/rdss-shared-libraries
cf07cad3f176ef8be1410fc29b240fb4791e607a
[ "Apache-2.0" ]
null
null
null
rdsslib/kinesis/client.py
JiscSD/rdss-shared-libraries
cf07cad3f176ef8be1410fc29b240fb4791e607a
[ "Apache-2.0" ]
4
2018-02-15T12:32:26.000Z
2018-03-06T16:33:34.000Z
rdsslib/kinesis/client.py
JiscSD/rdss-shared-libraries
cf07cad3f176ef8be1410fc29b240fb4791e607a
[ "Apache-2.0" ]
1
2018-03-13T19:38:54.000Z
2018-03-13T19:38:54.000Z
import json import logging from .errors import MaxRetriesExceededException, DecoratorApplyException MAX_ATTEMPTS = 6 class KinesisClient(object): def __init__(self, writer, reader): """ Writes and reads messages to and from Kinesis streams :param writer: handles writing of payloads to Kinesis stream :param reader: handles reading of payloads from Kinesis stream :type writer: writer.StreamWriter :type reader: reader.StreamReader """ self.logger = logging.getLogger(__name__) self.logger.setLevel(logging.INFO) self.writer = writer self.reader = reader def write_message(self, stream_names, payload, max_attempts=MAX_ATTEMPTS): """Write a payload into each stream in stream_names :param stream_names: Kinesis streams to write to :param payload: JSON payload :param max_attempts: maximum number of times to attempt writing :type stream_names: list of str :type payload: str """ for stream_name in stream_names: self.writer.put_stream(stream_name, payload, max_attempts) def read_messages(self, stream_name, seq_number=None): """Continuous loop that reads messages from stream_name :param stream_name: Name of Kinesis stream to read from :param seq_number: Optional seq number :type stream_name: str :return message_gen: Yields messages read from Kinesis stream :rtype message_gen: generator """ message_gen = self.reader.read_stream( stream_name, seq_number=seq_number) return message_gen class EnhancedKinesisClient(KinesisClient): def __init__(self, writer, reader, error_handler, decorators=None): """ Writes and reads messages to and from Kinesis streams with error handling and message decoration :param writer: Writes messages to Kinesis stream :param reader: Reads messages from Kinesis stream :param error_handler: Handles messages with errors :param decorators: Enhance messages with extra fields :type writer: writer.StreamWriter :type reader: reader.StreamReader :type error_handler: handlers.MessageErrorHandler :type decorators: list """ super().__init__(writer, reader) if decorators: self.decorators = decorators else: self.decorators = [] self.error_handler = error_handler def _apply_decorators(self, payload): """ Applies a sequence of decorators that enhance and modify the contents of a payload :param payload: Undecorated JSON payload :type payload: str :return payload: Decorated JSON payload :rtype payload: str """ decorated_payload = payload for decorator in self.decorators: try: decorated_payload = decorator.process(payload) except Exception: self.logger.warning( 'Failed to apply decorator {}'.format(decorator.name)) raise DecoratorApplyException() return decorated_payload def write_message(self, stream_names, payload, max_attempts=MAX_ATTEMPTS): """Write a payload into each stream in stream_names :param stream_names: Kinesis streams to write to :param payload: JSON payload :param max_attempts: Max number of times to attempt writing :type stream_names: list of str :type payload: str :type max_attempts: int """ try: json.loads(payload) except json.decoder.JSONDecodeError: self.error_handler.handle_invalid_json(payload) return decorated_payload = self._apply_decorators(payload) for stream_name in stream_names: try: super().write_message([stream_name], decorated_payload, max_attempts) except MaxRetriesExceededException as e: stream_name = e.args[0] error_code = 'GENERR005' error_description = 'Maximum retry attempts {0} exceed'\ 'for stream {1}'.format(max_attempts, stream_name) self.error_handler.handle_error(decorated_payload, error_code, error_description) def handle_error(self, payload, error_code, error_description): """ Allows errors to be posted to the stream occurring from activities like payload validation :param payload: JSON payload :param error_code: Error Code :param error_description: Description Of Error """ self.error_handler.handle_error(payload, error_code, error_description)
39.346457
79
0.626976
9c02d946c8f2edd003ed05df676f014d83067098
485
js
JavaScript
lib/cli.js
taylorc93/spawn
17a23b64360de0754598a2c4e02783596df6875c
[ "MIT" ]
2
2018-06-05T22:50:03.000Z
2020-04-24T16:34:54.000Z
lib/cli.js
taylorc93/spawn
17a23b64360de0754598a2c4e02783596df6875c
[ "MIT" ]
null
null
null
lib/cli.js
taylorc93/spawn
17a23b64360de0754598a2c4e02783596df6875c
[ "MIT" ]
null
null
null
import Compiler from './compiler'; import ArgHandler from './argHandler'; import fs from 'fs'; export function run() { const argHandler = new ArgHandler(); const compiler = new Compiler(); const settings = argHandler.processArgs(); if (__DEV__) { console.log("User settings:", JSON.stringify(settings)); } compiler.generateFiles(settings); fs.watch(settings.src, (event, filename) => { console.log(__filename); console.log(event); console.log(filename); }); }
23.095238
58
0.696907
b1130d7cdcb6b170a5f0302abc50ac96b23aca31
187
kt
Kotlin
src/main/kotlin/com/herokuapp/ourairports/repository/AirportsRepository.kt
alexmaryin/ourairports_json
0d2a86a2197fa2e289f42bdc54f36e865162a182
[ "Unlicense" ]
null
null
null
src/main/kotlin/com/herokuapp/ourairports/repository/AirportsRepository.kt
alexmaryin/ourairports_json
0d2a86a2197fa2e289f42bdc54f36e865162a182
[ "Unlicense" ]
null
null
null
src/main/kotlin/com/herokuapp/ourairports/repository/AirportsRepository.kt
alexmaryin/ourairports_json
0d2a86a2197fa2e289f42bdc54f36e865162a182
[ "Unlicense" ]
null
null
null
package com.herokuapp.ourairports.repository import com.herokuapp.ourairports.repository.model.Airport interface AirportsRepository { suspend fun getByICAO(code: String): Airport? }
26.714286
57
0.823529
7f03c1a3d423b9003132c57b83ddbce04ad9be78
105
go
Go
doc.go
SETTER2000/lengconv
0e11cdf6cf82cc60562d630e33b8c4612a1856e1
[ "MIT" ]
null
null
null
doc.go
SETTER2000/lengconv
0e11cdf6cf82cc60562d630e33b8c4612a1856e1
[ "MIT" ]
null
null
null
doc.go
SETTER2000/lengconv
0e11cdf6cf82cc60562d630e33b8c4612a1856e1
[ "MIT" ]
null
null
null
package lengconv /* Конвертер длинн 1. Открыть cmd в папке с программой cn 2. Помощь по флагам cn -h */
11.666667
38
0.733333
70b4a560218bd2b4ae7350c0aabd5d5072a724e9
2,089
go
Go
pkg/util/file/volatile_file/volatile_file.go
dizzy57/flow
cc1282eb8a54943686115a95468101835cdce481
[ "MIT" ]
null
null
null
pkg/util/file/volatile_file/volatile_file.go
dizzy57/flow
cc1282eb8a54943686115a95468101835cdce481
[ "MIT" ]
null
null
null
pkg/util/file/volatile_file/volatile_file.go
dizzy57/flow
cc1282eb8a54943686115a95468101835cdce481
[ "MIT" ]
null
null
null
package file import ( "fmt" "io/ioutil" "sync" log "github.com/sirupsen/logrus" event "github.com/awesome-flow/flow/pkg/util/file/event" "github.com/fsnotify/fsnotify" ) const ( VFPermDefault = 0644 ) type VolatileFile struct { path string once *sync.Once watcher *fsnotify.Watcher notify chan *event.Event } func New(path string) (*VolatileFile, error) { w, err := fsnotify.NewWatcher() if err != nil { return nil, err } vf := &VolatileFile{ path: path, once: &sync.Once{}, watcher: w, notify: make(chan *event.Event), } return vf, nil } func (vf *VolatileFile) Deploy() error { log.Infof("Deploying a watcher for path: %s", vf.path) vf.once.Do(func() { go func() { for ntf := range vf.watcher.Events { log.Infof("Received a new fsnotify notification: %s", ntf) switch ntf.Op { case fsnotify.Create: vf.notify <- event.New(event.Create) case fsnotify.Write: vf.notify <- event.New(event.Update) case fsnotify.Remove: vf.notify <- event.New(event.Delete) default: log.Infof("Ignored event: %s", ntf.String()) } } }() vf.watcher.Add(vf.path) }) return nil } func (vf *VolatileFile) TearDown() error { log.Infof("Removing the watcher for path: %s", vf.path) return vf.watcher.Remove(vf.path) } func (vf *VolatileFile) ReadRawData() ([]byte, error) { rawData, err := ioutil.ReadFile(vf.path) if err != nil { return nil, err } return rawData, nil } func (vf *VolatileFile) ReadData() (interface{}, error) { return vf.ReadRawData() } func (vf *VolatileFile) WriteData(data interface{}) error { rawData, err := vf.EncodeData(data) if err != nil { return err } return ioutil.WriteFile(vf.path, rawData, VFPermDefault) } func (vf *VolatileFile) GetPath() string { return vf.path } func (vf *VolatileFile) GetNotifyChan() chan *event.Event { return vf.notify } func (vf *VolatileFile) EncodeData(data interface{}) ([]byte, error) { if byteData, ok := data.([]byte); ok { return byteData, nil } return nil, fmt.Errorf("Failed to convert data to []byte") }
20.281553
70
0.662518
b93ad6f9bb276568052b2f77654cb3a0d8a8787c
10,515
kt
Kotlin
src/main/kotlin/bot/Bot.kt
0awawa0/CTF_Bot
2641a819253eaedf41689b4a415ee14bdc34ece7
[ "MIT" ]
null
null
null
src/main/kotlin/bot/Bot.kt
0awawa0/CTF_Bot
2641a819253eaedf41689b4a415ee14bdc34ece7
[ "MIT" ]
null
null
null
src/main/kotlin/bot/Bot.kt
0awawa0/CTF_Bot
2641a819253eaedf41689b4a415ee14bdc34ece7
[ "MIT" ]
null
null
null
package bot import database.CompetitionDTO import database.DbHelper import kotlinx.coroutines.* import org.telegram.telegrambots.bots.TelegramLongPollingBot import org.telegram.telegrambots.meta.api.methods.AnswerCallbackQuery import org.telegram.telegrambots.meta.api.objects.CallbackQuery import org.telegram.telegrambots.meta.api.objects.Message import org.telegram.telegrambots.meta.api.objects.Update import org.telegram.telegrambots.meta.exceptions.TelegramApiException import utils.Logger import java.lang.ref.WeakReference import java.util.concurrent.Executors class Bot( private val credentials: BotCredentials, val competition: CompetitionDTO, private val testing: Boolean = false, private val testingPassword: String = "" ): TelegramLongPollingBot() { companion object { const val MSG_START = "/start" const val MSG_FLAG = "/flag" const val MSG_TESTING_PASSWORD = "/testingPassword" const val MSG_CONVERT = "/convert" const val MSG_TO_HEX = "/toHex" const val MSG_TO_DEC = "/toDec" const val MSG_TO_BIN = "/toBin" const val MSG_TO_STRING = "/toString" const val MSG_ROT = "/rot" const val MSG_ROT_BRUTE = "/rotBruteForce" const val MSG_CHECK_MAGIC = "/checkMagic" const val MSG_CHANGE_NAME = "/changeName" const val MSG_DELETE = "/delete" const val MSG_COMMANDS_HELP = "/commandsHelp" const val DATA_MENU = "/menu" const val DATA_CURRENT_SCOREBOARD = "/current_scoreboard" const val DATA_GLOBAL_SCOREBOARD = "/global_scoreboard" const val DATA_TASKS = "/tasks" const val DATA_TASK = "/task" const val DATA_FILE = "/file" const val DATA_COMMANDS = "/commands" const val DATA_JPEG_SIGNATURE = "/jpegSignature" const val DATA_JPEG_TAIL = "/jpegTail" const val DATA_PNG_SIGNATURE = "/pngSignature" const val DATA_PNG_HEADER = "/pngHeader" const val DATA_PNG_DATA = "/pngData" const val DATA_PNG_TAIL = "/pngTail" const val DATA_ZIP_SIGNATURE = "/zipSignature" const val DATA_RAR_SIGNATURE = "/rarSignature" const val DATA_ELF_SIGNATURE = "/elfSignature" const val DATA_CLASS_SIGNATURE = "/classSignature" const val DATA_PDF_SIGNATURE = "/pdfSignature" const val DATA_PDF_TAIL = "/pdfTail" const val DATA_PSD_SIGNATURE = "/psdSignature" const val DATA_RIFF_SIGNATURE = "/wavAviSignature" const val DATA_WAVE_TAG = "/waveTag" const val DATA_AVI_TAG = "/aviTag" const val DATA_BMP_SIGNATURE = "/bmpSignature" const val DATA_DOC_SIGNATURE = "/docSignature" const val DATA_VMDK_SIGNATURE = "/vmdkSignature" const val DATA_TAR_SIGNATURE = "/tarSignature" const val DATA_7ZIP_SIGNATURE = "/7zSignature" const val DATA_GZ_SIGNATURE = "/gzSignature" } private val tag = "Bot" private val authorizedForTesting = HashSet<Long>() private val threadPool = Executors.newCachedThreadPool() private var botScope = CoroutineScope(threadPool.asCoroutineDispatcher()) private val messageMaker = MessageMaker(WeakReference(this)) override fun getBotToken(): String { return credentials.token } override fun getBotUsername(): String { return credentials.name } override fun onUpdateReceived(update: Update?) { if (update == null) return botScope.launch { if (update.hasMessage()) { if (update.message.hasText()) { val start = System.nanoTime() answerMessage(update.message) val end = System.nanoTime() Logger.debug(tag, "Message processed in ${(end - start) / 1000000} ms") } if (update.message.hasSticker()) Logger.info(tag, "Received sticker: ${update.message.sticker.fileId}") } if (update.hasCallbackQuery()) { val start = System.nanoTime() answerCallback(update.callbackQuery) val end = System.nanoTime() Logger.debug(tag, "Callback processed in ${(end - start) / 1000000} ms") } } } override fun onClosing() { super.onClosing() botScope.cancel() threadPool.shutdownNow() } override fun onRegister() { super.onRegister() botScope = CoroutineScope(threadPool.asCoroutineDispatcher()) } private suspend fun answerMessage(message: Message) { val msgText = message.text Logger.info( tag, "Received message from chat id: ${message.chatId} " + "Player name: ${message.from.userName ?: message.from.firstName}. " + "Message $msgText" ) if (!msgText.startsWith("/")) { // answer wrong message return } val command = msgText.split(" ").find { it.startsWith("/") }!! val content = msgText.replace(command, "").trim() if (testing && message.chatId !in authorizedForTesting) { try { if (command == MSG_TESTING_PASSWORD) { if (content == testingPassword) { authorizedForTesting.add(message.chatId) execute(messageMaker.getMenuMessage(message)) } else { execute(messageMaker.getPasswordWrongMessage(message)) } } else { execute(messageMaker.getPasswordRequestMessage(message.chatId)) } } catch (ex: TelegramApiException) { Logger.error(tag, "${ex.message}\n${ex.stackTraceToString()}") } return } if (!DbHelper.checkPlayerExists(message.chatId)) { execute(messageMaker.getStartMessage(message)) return } try { when (command) { MSG_START -> execute(messageMaker.getMenuMessage(message)) MSG_FLAG -> execute(messageMaker.getFlagSticker(message, content)) MSG_CONVERT -> execute(messageMaker.getConvertMessage(message ,content)) MSG_TO_HEX -> execute(messageMaker.getToHexMessage(message, content)) MSG_TO_BIN -> execute(messageMaker.getToBinMessage(message, content)) MSG_TO_DEC -> execute(messageMaker.getToDecMessage(message, content)) MSG_TO_STRING -> execute(messageMaker.getToStringMessage(message, content)) MSG_ROT -> execute(messageMaker.getRotMessage(message, content)) MSG_ROT_BRUTE -> execute(messageMaker.getRotBruteMessage(message, content)) MSG_CHECK_MAGIC -> execute(messageMaker.getCheckMagicMessage(message, content)) MSG_CHANGE_NAME -> execute(messageMaker.getChangeNameMessage(message, content)) MSG_DELETE -> execute(messageMaker.getDeleteMessage(message, content)) MSG_COMMANDS_HELP -> execute(messageMaker.getCommandsHelpMessage(message)) else -> execute(messageMaker.getUnknownMessage(message)) } } catch (ex: TelegramApiException) { Logger.error(tag, "${ex.message}\n${ex.stackTraceToString()}") } } private suspend fun answerCallback(callback: CallbackQuery) { try { val answerToCallback = AnswerCallbackQuery() answerToCallback.callbackQueryId = callback.id execute(answerToCallback) Logger.info( tag, "Received callback from chat id: ${callback.message.chatId} " + "Player name: ${callback.from.userName ?: callback.from.firstName}. " + "Data: ${callback.data}" ) if (testing && callback.message.chatId !in authorizedForTesting) { execute(messageMaker.getPasswordRequestMessage(callback.message.chatId)) return } if (!DbHelper.checkPlayerExists(callback.message.chatId)) { execute(messageMaker.getStartMessage(callback)) return } if (!callback.data.startsWith("/")) { execute(messageMaker.getErrorMessage(callback.message.chatId)) return } val command = callback.data.split(" ").find { it.startsWith("/") }!! val content = callback.data.replace(command, "").trim() when (command) { DATA_FILE -> execute(messageMaker.getFileMessage(callback, content.toLong())) DATA_CURRENT_SCOREBOARD -> execute(messageMaker.getCurrentScoreboard(callback)) DATA_GLOBAL_SCOREBOARD -> execute(messageMaker.getGlobalScoreboard(callback)) DATA_TASKS -> execute(messageMaker.getTasksMessage(callback)) DATA_TASK -> execute(messageMaker.getTaskMessage(callback, content.toLong())) DATA_MENU -> execute(messageMaker.getMenuMessage(callback)) DATA_COMMANDS -> execute(messageMaker.getCommandsHelpMessage(callback)) DATA_JPEG_SIGNATURE, DATA_JPEG_TAIL, DATA_PNG_SIGNATURE, DATA_PNG_HEADER, DATA_PNG_DATA, DATA_PNG_TAIL, DATA_ZIP_SIGNATURE, DATA_RAR_SIGNATURE, DATA_ELF_SIGNATURE, DATA_CLASS_SIGNATURE, DATA_PDF_SIGNATURE, DATA_PDF_TAIL, DATA_PSD_SIGNATURE, DATA_RIFF_SIGNATURE, DATA_WAVE_TAG, DATA_AVI_TAG, DATA_BMP_SIGNATURE, DATA_DOC_SIGNATURE, DATA_VMDK_SIGNATURE, DATA_TAR_SIGNATURE, DATA_7ZIP_SIGNATURE, DATA_GZ_SIGNATURE -> messageMaker.getMagicData(callback, callback.data) else -> messageMaker.getMenuMessage(callback) } } catch (ex: TelegramApiException) { Logger.error(tag, "${ex.message}\n${ex.stackTraceToString()}") } } fun sendMessageToPlayer(id: Long, text: String) { botScope.launch { execute(messageMaker.getMessageToPlayer(id, text)) } } fun broadcastMessage(text: String) { botScope.launch { for (player in DbHelper.getAllPlayers()) { sendMessageToPlayer(player.id, text) delay(100) } } } }
42.06
119
0.616358
5ecf8b11f9f9457e3f401b83e30a2cf5bad66df8
252
sql
SQL
TodoAmendoimApp/sql/CategoriaDelete.sql
VagnerAlcantara/todoAmendoimApp
054bacaf471f7de068aa9be1504bd8f072e33eaf
[ "MIT" ]
null
null
null
TodoAmendoimApp/sql/CategoriaDelete.sql
VagnerAlcantara/todoAmendoimApp
054bacaf471f7de068aa9be1504bd8f072e33eaf
[ "MIT" ]
null
null
null
TodoAmendoimApp/sql/CategoriaDelete.sql
VagnerAlcantara/todoAmendoimApp
054bacaf471f7de068aa9be1504bd8f072e33eaf
[ "MIT" ]
null
null
null
USE [DbTodo] GO SELECT * FROM Categoria SELECT * FROM Tarefa DELETE FROM [dbo].[Categoria] WHERE Id = 2 GO SELECT * FROM Categoria where Id = 2 SELECT * FROM Tarefa WHERE IdCategoria = 2 DELETE FROM [dbo].[Tarefa] Where IdCategoria = 2 GO
14
42
0.698413
f04b14b6017d3bc28465902ee2fb277e9af99099
1,468
js
JavaScript
packages/remark-comments/dist/index.js
Situphen/zmarkdown
1c667a7130f34f5a8d7e6a585db468e2471937a7
[ "MIT" ]
null
null
null
packages/remark-comments/dist/index.js
Situphen/zmarkdown
1c667a7130f34f5a8d7e6a585db468e2471937a7
[ "MIT" ]
null
null
null
packages/remark-comments/dist/index.js
Situphen/zmarkdown
1c667a7130f34f5a8d7e6a585db468e2471937a7
[ "MIT" ]
null
null
null
'use strict'; var beginMarkerFactory = function beginMarkerFactory() { var marker = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'COMMENTS'; return '<--' + marker; }; var endMarkerFactory = function endMarkerFactory() { var marker = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'COMMENTS'; return marker + '-->'; }; var SPACE = ' '; function plugin() { var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var beginMarker = beginMarkerFactory(opts.beginMarker); var endMarker = endMarkerFactory(opts.endMarker); function locator(value, fromIndex) { return value.indexOf(beginMarker, fromIndex); } function inlineTokenizer(eat, value, silent) { var keepBegin = value.indexOf(beginMarker); var keepEnd = value.indexOf(endMarker); if (keepBegin !== 0 || keepEnd === -1) return; /* istanbul ignore if - never used (yet) */ if (silent) return true; var comment = value.substring(beginMarker.length + 1, keepEnd - 1); return eat(beginMarker + SPACE + comment + SPACE + endMarker); } inlineTokenizer.locator = locator; var Parser = this.Parser; // Inject inlineTokenizer var inlineTokenizers = Parser.prototype.inlineTokenizers; var inlineMethods = Parser.prototype.inlineMethods; inlineTokenizers.comments = inlineTokenizer; inlineMethods.splice(inlineMethods.indexOf('text'), 0, 'comments'); } module.exports = plugin;
31.913043
94
0.694823
14992220885c7a8d417972337b8a383c2ae2eb5f
2,756
lua
Lua
Aetheri/aetheri/species/appearance.lua
cuteBoiButt/sb.StardustSuite
3c442c94192df257f46e08afc9f3ff8b5a6f2016
[ "MIT" ]
30
2016-09-17T21:28:00.000Z
2022-03-31T04:59:51.000Z
Aetheri/aetheri/species/appearance.lua
cuteBoiButt/sb.StardustSuite
3c442c94192df257f46e08afc9f3ff8b5a6f2016
[ "MIT" ]
22
2016-10-16T01:37:24.000Z
2021-11-29T20:47:52.000Z
Aetheri/aetheri/species/appearance.lua
cuteBoiButt/sb.StardustSuite
3c442c94192df257f46e08afc9f3ff8b5a6f2016
[ "MIT" ]
14
2016-12-17T18:59:03.000Z
2022-03-03T00:58:22.000Z
-- handles all appearance and animation apart from the HUD require "/lib/stardust/color.lua" appearance = { baseDirectives = "", } local bodyReplacePalette = { "dafafafa", "caeaeafa", "badadafa", "aacacafa" } local function generatePalette(tbl) local hue = tbl[1] local sat = tbl[2] local lumBright = tbl[3] local lumDark = tbl[4] return { color.toHex(color.fromHsl{ hue, sat, lumBright }), color.toHex(color.fromHsl{ hue, sat, util.lerp(1/3, lumBright, lumDark) }), color.toHex(color.fromHsl{ hue, sat, util.lerp(2/3, lumBright, lumDark) }), color.toHex(color.fromHsl{ hue, sat, lumDark }) } end local directives = "" local updateGlow function appearance.updateColors() appearance.settings = status.statusProperty("aetheri:appearance", { }) local a = appearance.settings if not a.coreHsl then local name = world.entityName(entity.id()) a.coreHsl = { -- start with a randomized core color based on your name! sb.staticRandomDoubleRange(0.0, 1.0, name, "core hue"), -- random hue 1.0 - sb.staticRandomDoubleRange(0.0, 1.0, name, "core saturation")^2, -- biased toward saturated math.min(1, sb.staticRandomI32Range(0, 4, name, "bright or dark?")), -- 1 in 5 chance to start dark sb.staticRandomDoubleRange(0.3, 0.7, name, "border brightness") } --playerext.message("generated values: " .. util.tableToString(a.coreHsl)) end a.palette = generatePalette(a.coreHsl) a.glowColor = color.fromHsl { a.coreHsl[1], a.coreHsl[2], 0.5 + (((a.coreHsl[3] + a.coreHsl[4]) / 2) - 0.5) * 0.5 -- average luma, pushed towards 0.5 (full vivid) } status.setStatusProperty("aetheri:appearance", a) local d = { "?replace;663b14fe=00000000;8d581cfe=00000000;c88b28fe=00000000;e7c474fe=00000000;404040fe=00000000;808080fe=00000000;6d0103fe=00000000;02da37fe=00000000;5786fffe=00000000", color.replaceDirective(bodyReplacePalette, a.palette, true), } appearance.baseDirectives = table.concat(d) tech.setParentDirectives(appearance.baseDirectives) playerext.setGlowColor(color.lightColor(a.glowColor, 0.8)) world.sendEntityMessage(entity.id(), "aetheri:paletteChanged") world.sendEntityMessage(entity.id(), "startech:refreshEnergyColor") updateGlow = true end function appearance.update(p) if updateGlow then updateGlow = false local a = appearance.settings playerext.setGlowColor(color.lightColor(a.glowColor, 0.8)) end end -- register these here since this is executed during techstub init message.setHandler("aetheri:refreshAppearance", appearance.updateColors) message.setHandler("startech:getEnergyColor", function() local p = appearance.settings.palette return { p[1], p[3], p[4] } -- somewhat cut down palette end)
35.333333
177
0.714078
754ede0866f00570e3fcddcbbe209fa86d15e7b5
738
h
C
Chapter_3_Intensity_Transformation_and_Spatial_Filtering/include/Section_3_3/Section_3_3.h
AlazzR/Digital-Image-Processing-Cpp
22573ff1aa2c8c8cc3dd6fb4ffaea07241aec47a
[ "CC0-1.0" ]
null
null
null
Chapter_3_Intensity_Transformation_and_Spatial_Filtering/include/Section_3_3/Section_3_3.h
AlazzR/Digital-Image-Processing-Cpp
22573ff1aa2c8c8cc3dd6fb4ffaea07241aec47a
[ "CC0-1.0" ]
null
null
null
Chapter_3_Intensity_Transformation_and_Spatial_Filtering/include/Section_3_3/Section_3_3.h
AlazzR/Digital-Image-Processing-Cpp
22573ff1aa2c8c8cc3dd6fb4ffaea07241aec47a
[ "CC0-1.0" ]
null
null
null
#ifndef _SECTION_3_3_H_ #define _SECTION_3_3_H_ #include <iostream> #include <opencv2/opencv.hpp> #include <memory> #include <string> #include<cmath> template<typename T>std::unique_ptr<float[]> calculating_histogram(const cv::Mat&); void histogram_equalization(const cv::Mat&, std::string); void local_histogram_processing(const cv::Mat&, int size=3); template<typename T> float calculating_mean_neighborhood(const cv::Mat&, const std::unique_ptr<T[]>&); template<typename T> float calculating_stdDeviation_neighborhood(const cv::Mat&, const std::unique_ptr<T[]>&, float); void statistical_local_enhancement(const cv::Mat&, float C=30.5F, float k0=0.0F, float k1=0.1F, float k2=0.0F, float k3=0.1F, int size = 3); #endif _SECTION_3_3_H_
52.714286
141
0.773713
6ee0b47e8b2a87f4801508974ffd7fe423c44f94
811
html
HTML
bootparts/one-column-content/one-column-content.html
yelluw/bootparts
7e04564704ad9bcb1d6a13cfd33d530fe7d3c420
[ "MIT" ]
16
2017-01-20T10:32:58.000Z
2017-10-27T23:33:33.000Z
bootparts/one-column-content/one-column-content.html
yelluw/Bootparts
7e04564704ad9bcb1d6a13cfd33d530fe7d3c420
[ "MIT" ]
6
2017-01-20T04:47:36.000Z
2017-07-18T22:11:18.000Z
bootparts/one-column-content/one-column-content.html
yelluw/bootparts
7e04564704ad9bcb1d6a13cfd33d530fe7d3c420
[ "MIT" ]
null
null
null
<!-- Bootparts Start --> <div class="one-column-content"> <div class="container"> <div class="row"> <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12"> <p> Bootparts by Yelluw. This project aims to simplify the process of building websites. It leverages the Bootstrap framework version 3 and provides a collection of ready to use components. You simply need to customize the colors, fonts, and content. Everything else is done for you. </p> </div> <!-- end row --> </div> <!-- end container--> </div> <!-- end one-column-content --> </div> <!-- Bootparts End -->
27.965517
100
0.484587
9ad2b96d91f5e14709857f2d037b378f7372d4a0
229
lua
Lua
MMOCoreORB/bin/scripts/object/custom_content/mobile/vf_Done/dressed_myyydril_refugee_m_03.lua
V-Fib/FlurryClone
40e0ca7245ec31b3815eb6459329fd9e70f88936
[ "Zlib", "OpenSSL" ]
18
2017-02-09T15:36:05.000Z
2021-12-21T04:22:15.000Z
MMOCoreORB/bin/scripts/object/custom_content/mobile/vf_Done/dressed_myyydril_refugee_m_03.lua
V-Fib/FlurryClone
40e0ca7245ec31b3815eb6459329fd9e70f88936
[ "Zlib", "OpenSSL" ]
61
2016-12-30T21:51:10.000Z
2021-12-10T20:25:56.000Z
MMOCoreORB/bin/scripts/object/custom_content/mobile/vf_Done/dressed_myyydril_refugee_m_03.lua
V-Fib/FlurryClone
40e0ca7245ec31b3815eb6459329fd9e70f88936
[ "Zlib", "OpenSSL" ]
71
2017-01-01T05:34:38.000Z
2022-03-29T01:04:00.000Z
object_mobile_dressed_myyydril_refugee_m_03 = object_mobile_shared_dressed_myyydril_refugee_m_03:new { } ObjectTemplates:addTemplate(object_mobile_dressed_myyydril_refugee_m_03, "object/mobile/dressed_myyydril_refugee_m_03.iff")
57.25
123
0.912664
5899b4071d52f9ff480c22f495bfa3aa599c9c3e
814
kt
Kotlin
app/src/main/java/com/codility/servicebackground/MainActivity.kt
meetdhaliwal1995/Service_Background
282bb0fa109e7be38ef6af0506859ac6d4fd772f
[ "MIT" ]
3
2018-06-02T21:06:12.000Z
2021-11-30T02:00:56.000Z
app/src/main/java/com/codility/servicebackground/MainActivity.kt
meetdhaliwal1995/Service_Background
282bb0fa109e7be38ef6af0506859ac6d4fd772f
[ "MIT" ]
null
null
null
app/src/main/java/com/codility/servicebackground/MainActivity.kt
meetdhaliwal1995/Service_Background
282bb0fa109e7be38ef6af0506859ac6d4fd772f
[ "MIT" ]
1
2020-05-16T06:54:10.000Z
2020-05-16T06:54:10.000Z
package com.codility.servicebackground import android.content.Intent import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.view.View import android.widget.Toast class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) } fun startServiceView(view: View) { startService(Intent(this, MyService::class.java)) showToast("Background Service Started..!!") } fun stopServiceView(view: View) { stopService(Intent(this, MyService::class.java)) showToast("Background Service Stopped..!!") } private fun showToast(msg: String) { Toast.makeText(this, msg, Toast.LENGTH_SHORT).show() } }
28.068966
60
0.710074
b130fa39a6b2d32eb23c99304f171c0c52be6c9d
47
tab
SQL
src/Tests/test_expect/csv-codec/csv_to_tab/three_x_three_unfinished_quote.tab
Upstream-Research/records.net
edcaad05b645ea460e7d649479e3e387ae9e5d1e
[ "MIT" ]
null
null
null
src/Tests/test_expect/csv-codec/csv_to_tab/three_x_three_unfinished_quote.tab
Upstream-Research/records.net
edcaad05b645ea460e7d649479e3e387ae9e5d1e
[ "MIT" ]
null
null
null
src/Tests/test_expect/csv-codec/csv_to_tab/three_x_three_unfinished_quote.tab
Upstream-Research/records.net
edcaad05b645ea460e7d649479e3e387ae9e5d1e
[ "MIT" ]
null
null
null
one two three four "five,six seven,eight,nine"
11.75
17
0.765957
9fa44a12f13faf86b7ffad6a1dcff044eea9c2df
319
asm
Assembly
src/shaders/post_processing/gen5_6/nv12_load_save_pl3.asm
digetx/intel-vaapi-driver
d87db2111a33b157d1913415f15d201cc5182850
[ "MIT" ]
192
2018-01-26T11:51:55.000Z
2022-03-25T20:04:19.000Z
src/shaders/post_processing/gen5_6/nv12_load_save_pl3.asm
digetx/intel-vaapi-driver
d87db2111a33b157d1913415f15d201cc5182850
[ "MIT" ]
256
2017-01-23T02:10:27.000Z
2018-01-23T10:00:05.000Z
src/shaders/post_processing/gen5_6/nv12_load_save_pl3.asm
digetx/intel-vaapi-driver
d87db2111a33b157d1913415f15d201cc5182850
[ "MIT" ]
64
2018-01-30T19:51:53.000Z
2021-11-24T01:26:14.000Z
// Module name: NV12_LOAD_SAVE_PL3 .kernel NV12_LOAD_SAVE_PL3 .code #include "SetupVPKernel.asm" #include "Multiple_Loop_Head.asm" #include "NV12_Load_8x4.asm" #include "PL8x4_Save_IMC3.asm" #include "Multiple_Loop.asm" END_THREAD // End of Thread .end_code .end_kernel // end of nv12_load_save_pl3.asm
17.722222
36
0.761755
53805b1279f7c2aca29730855ea88281317dbdcd
803
kt
Kotlin
dal/src/main/java/net/mieczkowski/dal/services/businessLookupService/BusinessContract.kt
jmiecz/YelpBusinessExample
2479a0b469641fd4c8fe530cfa23e077ac0e54be
[ "Apache-2.0" ]
null
null
null
dal/src/main/java/net/mieczkowski/dal/services/businessLookupService/BusinessContract.kt
jmiecz/YelpBusinessExample
2479a0b469641fd4c8fe530cfa23e077ac0e54be
[ "Apache-2.0" ]
null
null
null
dal/src/main/java/net/mieczkowski/dal/services/businessLookupService/BusinessContract.kt
jmiecz/YelpBusinessExample
2479a0b469641fd4c8fe530cfa23e077ac0e54be
[ "Apache-2.0" ]
null
null
null
package net.mieczkowski.dal.services.businessLookupService import io.reactivex.Single import net.mieczkowski.dal.services.businessLookupService.models.BusinessDetails import net.mieczkowski.dal.services.businessLookupService.models.YelpBusinessWrapper import retrofit2.http.GET import retrofit2.http.Path import retrofit2.http.Query /** * Created by Josh Mieczkowski on 9/12/2018. */ interface BusinessContract { @GET("businesses/search") abstract fun lookUpBusiness(@Query("term") search: String, @Query("latitude") latitude: Double, @Query("longitude") longitude: Double): Single<YelpBusinessWrapper> @GET("businesses/{id}") abstract fun getBusinessDetails(@Path("id") businessID: String): Single<BusinessDetails> }
36.5
99
0.729763
98a7de1e8269fb184580768ad07be35addefbe0e
1,727
html
HTML
B2G/gecko/layout/reftests/text-overflow/two-value-syntax-ref.html
wilebeast/FireFox-OS
43067f28711d78c429a1d6d58c77130f6899135f
[ "Apache-2.0" ]
3
2015-08-31T15:24:31.000Z
2020-04-24T20:31:29.000Z
B2G/gecko/layout/reftests/text-overflow/two-value-syntax-ref.html
wilebeast/FireFox-OS
43067f28711d78c429a1d6d58c77130f6899135f
[ "Apache-2.0" ]
null
null
null
B2G/gecko/layout/reftests/text-overflow/two-value-syntax-ref.html
wilebeast/FireFox-OS
43067f28711d78c429a1d6d58c77130f6899135f
[ "Apache-2.0" ]
3
2015-07-29T07:17:15.000Z
2020-11-04T06:55:37.000Z
<!DOCTYPE HTML> <!-- Any copyright is dedicated to the Public Domain. http://creativecommons.org/licenses/publicdomain/ Test: text-overflow:<left> <right> --> <html><head> <title>text-overflow: text-overflow:&lt;left&gt; &lt;right&gt;</title> <style type="text/css"> @font-face { font-family: DejaVuSansMono; src: url(../fonts/DejaVuSansMono.woff); } html,body { color:black; background-color:white; font-size:16px; padding:0; margin:0; font-family:DejaVuSansMono; } .test { overflow:hidden; width:100%; white-space:nowrap; } span { margin: 0 -2px; } .rlo { unicode-bidi: bidi-override; direction:rtl; } .lro { unicode-bidi: bidi-override; } .rtl { direction:rtl; } .ltr { direction:ltr; } </style> </head><body> <div style="float:left;"> ||||| <div class="test t1"><span>&nbsp;&#x2026;||&#x2026;</span></div> <div class="test rtl t1"><span>&nbsp;&#x2026;||&#x2026;</span></div> <div class="test t2"><span>&nbsp;&#x2026;||||</span></div> <div class="test rtl t2"><span>||||&#x2026;</span></div> <div class="test t3"><span>||||&#x2026;</span></div> <div class="test rtl t3"><span>&nbsp;&#x2026;||||</span></div> <div class="test t4"><span>||||.</span></div> <div class="test rtl t4"><span>&nbsp;.||||</span></div> <div class="test t5"><span>&nbsp;.||||</span></div> <div class="test rtl t5"><span>||||.</span></div> <div class="test t6"><span>&nbsp;.||,</span></div> <div class="test rtl t6"><span>&nbsp;,||.</span></div> <div class="test t7"><span>&nbsp;&#x2026;||,</span></div> <div class="test rtl t7"><span>&nbsp;,||&#x2026;</span></div> <div class="test t8"><span>&nbsp;.||&#x2026;</span></div> <div class="test rtl t8"><span>&nbsp;&#x2026;||.</span></div> </div> </body> </html>
25.776119
105
0.617255
d51562e0514ba723150504a16edafea415e774b7
109
kt
Kotlin
preisservice/src/main/kotlin/com/example/Application.kt
TheHandOfNOD/MyJourney2Kotlin
74cc60e34c79b08ba364b018568f0cf07bfaf953
[ "Apache-2.0" ]
null
null
null
preisservice/src/main/kotlin/com/example/Application.kt
TheHandOfNOD/MyJourney2Kotlin
74cc60e34c79b08ba364b018568f0cf07bfaf953
[ "Apache-2.0" ]
null
null
null
preisservice/src/main/kotlin/com/example/Application.kt
TheHandOfNOD/MyJourney2Kotlin
74cc60e34c79b08ba364b018568f0cf07bfaf953
[ "Apache-2.0" ]
null
null
null
package com.example import io.micronaut.runtime.Micronaut.* fun main(args: Array<String>) { run(*args) }
12.111111
39
0.724771
5b040296ddbd9f5247e9974e32850bd6c3e2379a
80
h
C
runtime/statements/break.h
hlooalklampc/tss
23856e1e8244a89ac1bc30ba56b417a4a1c1687f
[ "MIT" ]
2
2018-08-18T03:12:56.000Z
2019-12-10T05:21:09.000Z
runtime/statements/break.h
hlooalklampc/tss
23856e1e8244a89ac1bc30ba56b417a4a1c1687f
[ "MIT" ]
null
null
null
runtime/statements/break.h
hlooalklampc/tss
23856e1e8244a89ac1bc30ba56b417a4a1c1687f
[ "MIT" ]
null
null
null
int zephir_statement_break(zephir_context *context, zval *statement TSRMLS_DC);
40
79
0.85
50325a332db58ada7be099fbaaa94e73b9244525
3,715
go
Go
pkg/provider/gce/gce.go
uswitch/kube-lego
438bdadf157362661a842df50c26aa47a0c90e07
[ "Apache-2.0" ]
4
2016-12-11T21:45:42.000Z
2019-11-17T21:50:51.000Z
pkg/provider/gce/gce.go
uswitch/kube-lego
438bdadf157362661a842df50c26aa47a0c90e07
[ "Apache-2.0" ]
null
null
null
pkg/provider/gce/gce.go
uswitch/kube-lego
438bdadf157362661a842df50c26aa47a0c90e07
[ "Apache-2.0" ]
1
2021-02-10T11:03:09.000Z
2021-02-10T11:03:09.000Z
package gce import ( "errors" "fmt" "github.com/jetstack/kube-lego/pkg/kubelego_const" "github.com/jetstack/kube-lego/pkg/service" "github.com/Sirupsen/logrus" k8sExtensions "k8s.io/kubernetes/pkg/apis/extensions" ) const ClassName = "gce" var ErrorClassNotMatching = errors.New("Ingress class not matching") var challengePath = fmt.Sprintf("%s/*", kubelego.AcmeHttpChallengePath) var _ kubelego.IngressProvider = &Gce{} func getHostMap(ing kubelego.Ingress) map[string]bool { hostMap := map[string]bool{} for _, tls := range ing.Tls() { for _, host := range tls.Hosts() { hostMap[host] = true } } return hostMap } type Gce struct { kubelego kubelego.KubeLego service kubelego.Service usedByNamespace map[string]bool } func New(kl kubelego.KubeLego) *Gce { return &Gce{ kubelego: kl, usedByNamespace: map[string]bool{}, } } func (p *Gce) Log() (log *logrus.Entry) { return p.kubelego.Log().WithField("context", "provider").WithField("provider", "gce") } func (p *Gce) Reset() (err error) { p.Log().Debug("reset") p.usedByNamespace = map[string]bool{} p.service = nil return nil } func (p *Gce) Finalize() (err error) { p.Log().Debug("finialize") err = p.updateServices() if err != nil { return err } err = p.removeServices() return } func (p *Gce) removeServices() (err error) { // TODO implement me return nil } func (p *Gce) updateServices() (err error) { for namespace, enabled := range p.usedByNamespace { if enabled { err = p.updateService(namespace) if err != nil { return err } } } return nil } func (p *Gce) updateService(namespace string) (err error) { var svc kubelego.Service = service.New(p.kubelego, namespace, p.kubelego.LegoServiceNameGce()) svc.SetKubeLegoSpec() svc.Object().Spec.Type = "NodePort" svc.Object().Spec.Selector = map[string]string{} podIP := p.kubelego.LegoPodIP().String() p.Log().WithField("pod_ip", podIP).WithField("namespace", namespace).Debug("setting up svc endpoint") err = svc.SetEndpoints([]string{podIP}) if err != nil { return err } return svc.Save() } func (p *Gce) Process(ingObj kubelego.Ingress) (err error) { ingApi := ingObj.Object() hostsEnabled := getHostMap(ingObj) hostsNotConfigured := getHostMap(ingObj) var rulesNew []k8sExtensions.IngressRule for _, rule := range ingApi.Spec.Rules { pathsNew := []k8sExtensions.HTTPIngressPath{} // add challenge endpoints first, if needed if _, hostEnabled := hostsEnabled[rule.Host]; hostEnabled { delete(hostsNotConfigured, rule.Host) pathsNew = []k8sExtensions.HTTPIngressPath{ p.getHTTPIngressPath(), } } // remove existing challenge paths for _, path := range rule.HTTP.Paths { if path.Path == challengePath { continue } pathsNew = append(pathsNew, path) } // add rule if it contains at least one path if len(pathsNew) > 0 { rule.HTTP.Paths = pathsNew rulesNew = append(rulesNew, rule) } } // add missing hosts for host, _ := range hostsNotConfigured { rulesNew = append(rulesNew, k8sExtensions.IngressRule{ Host: host, IngressRuleValue: k8sExtensions.IngressRuleValue{ HTTP: &k8sExtensions.HTTPIngressRuleValue{ Paths: []k8sExtensions.HTTPIngressPath{ p.getHTTPIngressPath(), }, }, }, }) } ingApi.Spec.Rules = rulesNew if len(hostsEnabled) > 0 { p.usedByNamespace[ingApi.Namespace] = true } return ingObj.Save() } func (p *Gce) getHTTPIngressPath() k8sExtensions.HTTPIngressPath { return k8sExtensions.HTTPIngressPath{ Path: challengePath, Backend: k8sExtensions.IngressBackend{ ServiceName: p.kubelego.LegoServiceNameGce(), ServicePort: p.kubelego.LegoHTTPPort(), }, } }
22.245509
102
0.692328
b2e5f383923565aa615eda28c9950c8812f8c749
3,161
py
Python
luna/__init__.py
ktemkin/luna
661dc89f7f60ba8a51165f7f8037ad2d5854cf34
[ "BSD-3-Clause" ]
4
2020-02-11T18:40:02.000Z
2020-04-03T13:07:38.000Z
luna/__init__.py
ktemkin/luna
661dc89f7f60ba8a51165f7f8037ad2d5854cf34
[ "BSD-3-Clause" ]
null
null
null
luna/__init__.py
ktemkin/luna
661dc89f7f60ba8a51165f7f8037ad2d5854cf34
[ "BSD-3-Clause" ]
null
null
null
# # This file is part of LUNA. # import shutil import tempfile import argparse from nmigen import Elaboratable from .gateware.platform import get_appropriate_platform def top_level_cli(fragment, *pos_args, **kwargs): """ Runs a default CLI that assists in building and running gateware. If the user's options resulted in the board being programmed, this returns the fragment that was programmed onto the board. Otherwise, it returns None. """ parser = argparse.ArgumentParser(description="Gateware generation/upload script for '{}' gateware.".format(fragment.__class__.__name__)) parser.add_argument('--output', '-o', metavar='filename', help="Build and output a bitstream to the given file.") parser.add_argument('--erase', '-E', action='store_true', help="Clears the relevant FPGA's flash before performing other options.") parser.add_argument('--upload', '-U', action='store_true', help="Uploads the relevant design to the target hardware. Default if no options are provided.") parser.add_argument('--flash', '-F', action='store_true', help="Flashes the relevant design to the target hardware's configuration flash.") parser.add_argument('--dry-run', '-D', action='store_true', help="When provided as the only option; builds the relevant bitstream without uploading or flashing it.") parser.add_argument('--keep-files', action='store_true', help="Keeps the local files in the default `build` folder.") args = parser.parse_args() platform = get_appropriate_platform() # If this isn't a fragment directly, interpret it as an object that will build one. if callable(fragment): fragment = fragment(*pos_args, **kwargs) # If we have no other options set, build and upload the relevant file. if (args.output is None and not args.flash and not args.erase and not args.dry_run): args.upload = True # Once the device is flashed, it will self-reconfigure, so we # don't need an explicitly upload step; and it implicitly erases # the flash, so we don't need an erase step. if args.flash: args.erase = False args.upload = False # Build the relevant gateware, uploading if requested. build_dir = "build" if args.keep_files else tempfile.mkdtemp() # Build the relevant files. try: if args.erase: platform.toolchain_erase() products = platform.build(fragment, do_program=args.upload, build_dir=build_dir ) # If we're flashing the FPGA's flash, do so. if args.flash: platform.toolchain_flash(products) # If we're outputting a file, write it. if args.output: bitstream = products.get("top.bit") with open(args.output, "wb") as f: f.write(bitstream) # Return the fragment we're working with, for convenience. if args.upload or args.flash: return fragment # Clean up any directories we've created. finally: if not args.keep_files: shutil.rmtree(build_dir) return None
37.188235
140
0.669092
bcb1e23b7719466234ba84c9d7996f3a4601bd95
46,072
js
JavaScript
bundles/swimlane-ngx-graph.umd.min.js
magoox5/ngx-graph-dist
30e205675bb95ca02c861b85ff121ccd99d77526
[ "MIT" ]
null
null
null
bundles/swimlane-ngx-graph.umd.min.js
magoox5/ngx-graph-dist
30e205675bb95ca02c861b85ff121ccd99d77526
[ "MIT" ]
null
null
null
bundles/swimlane-ngx-graph.umd.min.js
magoox5/ngx-graph-dist
30e205675bb95ca02c861b85ff121ccd99d77526
[ "MIT" ]
null
null
null
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports,require("@angular/core"),require("@swimlane/ngx-charts"),require("d3-selection"),require("d3-shape"),require("d3-ease"),require("d3-transition"),require("rxjs"),require("rxjs/operators"),require("transformation-matrix"),require("dagre"),require("d3-force"),require("webcola"),require("d3-dispatch"),require("d3-timer")):"function"==typeof define&&define.amd?define("@swimlane/ngx-graph",["exports","@angular/core","@swimlane/ngx-charts","d3-selection","d3-shape","d3-ease","d3-transition","rxjs","rxjs/operators","transformation-matrix","dagre","d3-force","webcola","d3-dispatch","d3-timer"],e):e(((t="undefined"!=typeof globalThis?globalThis:t||self).swimlane=t.swimlane||{},t.swimlane["ngx-graph"]={}),t.ng.core,t.ngxCharts,t.d3Selection,t.shape,t.ease,null,t.rxjs,t.rxjs.operators,t.transformationMatrix,t.dagre,t.d3Force,t.webcola,t.d3Dispatch,t.d3Timer)}(this,(function(t,e,n,i,o,r,a,s,h,d,p,u,g,c,l){"use strict";function m(t){if(t&&t.__esModule)return t;var e=Object.create(null);return t&&Object.keys(t).forEach((function(n){if("default"!==n){var i=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(e,n,i.get?i:{enumerable:!0,get:function(){return t[n]}})}})),e.default=t,Object.freeze(e)}var f=m(u),y=m(c),v=m(l),x=function(t,e){return(x=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])})(t,e)};function b(t,e){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(t,e)}Object.create;function w(t){var e="function"==typeof Symbol&&Symbol.iterator,n=e&&t[e],i=0;if(n)return n.call(t);if(t&&"number"==typeof t.length)return{next:function(){return t&&i>=t.length&&(t=void 0),{value:t&&t[i++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function O(t,e){var n="function"==typeof Symbol&&t[Symbol.iterator];if(!n)return t;var i,o,r=n.call(t),a=[];try{for(;(void 0===e||e-- >0)&&!(i=r.next()).done;)a.push(i.value)}catch(t){o={error:t}}finally{try{i&&!i.done&&(n=r.return)&&n.call(r)}finally{if(o)throw o.error}}return a}function M(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(O(arguments[e]));return t}Object.create;var T,G,L={};function D(){var t=("0000"+(Math.random()*Math.pow(36,4)<<0).toString(36)).slice(-4);return L[t="a"+t]?D():(L[t]=!0,t)}(T=t.Orientation||(t.Orientation={})).LEFT_TO_RIGHT="LR",T.RIGHT_TO_LEFT="RL",T.TOP_TO_BOTTOM="TB",T.BOTTOM_TO_TOM="BT",(G=t.Alignment||(t.Alignment={})).CENTER="C",G.UP_LEFT="UL",G.UP_RIGHT="UR",G.DOWN_LEFT="DL",G.DOWN_RIGHT="DR";var k=function(){function e(){this.defaultSettings={orientation:t.Orientation.LEFT_TO_RIGHT,marginX:20,marginY:20,edgePadding:100,rankPadding:100,nodePadding:50,multigraph:!0,compound:!0},this.settings={}}return e.prototype.run=function(t){this.createDagreGraph(t),p.layout(this.dagreGraph),t.edgeLabels=this.dagreGraph._edgeLabels;var e=function(e){var i=n.dagreGraph._nodes[e],o=t.nodes.find((function(t){return t.id===i.id}));o.position={x:i.x,y:i.y},o.dimension={width:i.width,height:i.height}},n=this;for(var i in this.dagreGraph._nodes)e(i);return t},e.prototype.updateEdge=function(t,e){var n=t.nodes.find((function(t){return t.id===e.source})),i=t.nodes.find((function(t){return t.id===e.target})),o=n.position.y<=i.position.y?-1:1,r={x:n.position.x,y:n.position.y-o*(n.dimension.height/2)},a={x:i.position.x,y:i.position.y+o*(i.dimension.height/2)};return e.points=[r,a],t},e.prototype.createDagreGraph=function(t){var e,n,i,o,r=Object.assign({},this.defaultSettings,this.settings);this.dagreGraph=new p.graphlib.Graph({compound:r.compound,multigraph:r.multigraph}),this.dagreGraph.setGraph({rankdir:r.orientation,marginx:r.marginX,marginy:r.marginY,edgesep:r.edgePadding,ranksep:r.rankPadding,nodesep:r.nodePadding,align:r.align,acyclicer:r.acyclicer,ranker:r.ranker,multigraph:r.multigraph,compound:r.compound}),this.dagreGraph.setDefaultEdgeLabel((function(){return{}})),this.dagreNodes=t.nodes.map((function(t){var e=Object.assign({},t);return e.width=t.dimension.width,e.height=t.dimension.height,e.x=t.position.x,e.y=t.position.y,e})),this.dagreEdges=t.edges.map((function(t){var e=Object.assign({},t);return e.id||(e.id=D()),e}));try{for(var a=w(this.dagreNodes),s=a.next();!s.done;s=a.next()){var h=s.value;h.width||(h.width=20),h.height||(h.height=30),this.dagreGraph.setNode(h.id,h)}}catch(t){e={error:t}}finally{try{s&&!s.done&&(n=a.return)&&n.call(a)}finally{if(e)throw e.error}}try{for(var d=w(this.dagreEdges),u=d.next();!u.done;u=d.next()){var g=u.value;r.multigraph?this.dagreGraph.setEdge(g.source,g.target,g,g.id):this.dagreGraph.setEdge(g.source,g.target)}}catch(t){i={error:t}}finally{try{u&&!u.done&&(o=d.return)&&o.call(d)}finally{if(i)throw i.error}}return this.dagreGraph},e}(),E=function(){function e(){this.defaultSettings={orientation:t.Orientation.LEFT_TO_RIGHT,marginX:20,marginY:20,edgePadding:100,rankPadding:100,nodePadding:50,multigraph:!0,compound:!0},this.settings={}}return e.prototype.run=function(t){var e=this;this.createDagreGraph(t),p.layout(this.dagreGraph),t.edgeLabels=this.dagreGraph._edgeLabels;var n=function(t){var n=e.dagreGraph._nodes[t.id];return Object.assign(Object.assign({},t),{position:{x:n.x,y:n.y},dimension:{width:n.width,height:n.height}})};return t.clusters=(t.clusters||[]).map(n),t.nodes=t.nodes.map(n),t},e.prototype.updateEdge=function(t,e){var n=t.nodes.find((function(t){return t.id===e.source})),i=t.nodes.find((function(t){return t.id===e.target})),o=n.position.y<=i.position.y?-1:1,r={x:n.position.x,y:n.position.y-o*(n.dimension.height/2)},a={x:i.position.x,y:i.position.y+o*(i.dimension.height/2)};return e.points=[r,a],t},e.prototype.createDagreGraph=function(t){var e,n,i,o,r,a,s=this,h=Object.assign({},this.defaultSettings,this.settings);this.dagreGraph=new p.graphlib.Graph({compound:h.compound,multigraph:h.multigraph}),this.dagreGraph.setGraph({rankdir:h.orientation,marginx:h.marginX,marginy:h.marginY,edgesep:h.edgePadding,ranksep:h.rankPadding,nodesep:h.nodePadding,align:h.align,acyclicer:h.acyclicer,ranker:h.ranker,multigraph:h.multigraph,compound:h.compound}),this.dagreGraph.setDefaultEdgeLabel((function(){return{}})),this.dagreNodes=t.nodes.map((function(t){var e=Object.assign({},t);return e.width=t.dimension.width,e.height=t.dimension.height,e.x=t.position.x,e.y=t.position.y,e})),this.dagreClusters=t.clusters||[],this.dagreEdges=t.edges.map((function(t){var e=Object.assign({},t);return e.id||(e.id=D()),e}));try{for(var d=w(this.dagreNodes),u=d.next();!u.done;u=d.next()){var g=u.value;this.dagreGraph.setNode(g.id,g)}}catch(t){e={error:t}}finally{try{u&&!u.done&&(n=d.return)&&n.call(d)}finally{if(e)throw e.error}}var c=function(t){l.dagreGraph.setNode(t.id,t),t.childNodeIds.forEach((function(e){s.dagreGraph.setParent(e,t.id)}))},l=this;try{for(var m=w(this.dagreClusters),f=m.next();!f.done;f=m.next()){c(f.value)}}catch(t){i={error:t}}finally{try{f&&!f.done&&(o=m.return)&&o.call(m)}finally{if(i)throw i.error}}try{for(var y=w(this.dagreEdges),v=y.next();!v.done;v=y.next()){var x=v.value;h.multigraph?this.dagreGraph.setEdge(x.source,x.target,x,x.id):this.dagreGraph.setEdge(x.source,x.target)}}catch(t){r={error:t}}finally{try{v&&!v.done&&(a=y.return)&&a.call(y)}finally{if(r)throw r.error}}return this.dagreGraph},e}(),C=function(){function e(){this.defaultSettings={orientation:t.Orientation.LEFT_TO_RIGHT,marginX:20,marginY:20,edgePadding:100,rankPadding:100,nodePadding:50,curveDistance:20,multigraph:!0,compound:!0},this.settings={}}return e.prototype.run=function(t){var e,n;this.createDagreGraph(t),p.layout(this.dagreGraph),t.edgeLabels=this.dagreGraph._edgeLabels;var i=function(e){var n=o.dagreGraph._nodes[e],i=t.nodes.find((function(t){return t.id===n.id}));i.position={x:n.x,y:n.y},i.dimension={width:n.width,height:n.height}},o=this;for(var r in this.dagreGraph._nodes)i(r);try{for(var a=w(t.edges),s=a.next();!s.done;s=a.next()){var h=s.value;this.updateEdge(t,h)}}catch(t){e={error:t}}finally{try{s&&!s.done&&(n=a.return)&&n.call(a)}finally{if(e)throw e.error}}return t},e.prototype.updateEdge=function(t,e){var n,i,o,r,a=t.nodes.find((function(t){return t.id===e.source})),s=t.nodes.find((function(t){return t.id===e.target})),h="BT"===this.settings.orientation||"TB"===this.settings.orientation?"y":"x",d="y"===h?"x":"y",p="y"===h?"height":"width",u=a.position[h]<=s.position[h]?-1:1,g=((n={})[d]=a.position[d],n[h]=a.position[h]-u*(a.dimension[p]/2),n),c=((i={})[d]=s.position[d],i[h]=s.position[h]+u*(s.dimension[p]/2),i),l=this.settings.curveDistance||this.defaultSettings.curveDistance;e.points=[g,(o={},o[d]=g[d],o[h]=g[h]-u*l,o),(r={},r[d]=c[d],r[h]=c[h]+u*l,r),c];var m=e.source+""+e.target+"\0",f=t.edgeLabels[m];return f&&(f.points=e.points),t},e.prototype.createDagreGraph=function(t){var e,n,i,o,r=Object.assign({},this.defaultSettings,this.settings);this.dagreGraph=new p.graphlib.Graph({compound:r.compound,multigraph:r.multigraph}),this.dagreGraph.setGraph({rankdir:r.orientation,marginx:r.marginX,marginy:r.marginY,edgesep:r.edgePadding,ranksep:r.rankPadding,nodesep:r.nodePadding,align:r.align,acyclicer:r.acyclicer,ranker:r.ranker,multigraph:r.multigraph,compound:r.compound}),this.dagreGraph.setDefaultEdgeLabel((function(){return{}})),this.dagreNodes=t.nodes.map((function(t){var e=Object.assign({},t);return e.width=t.dimension.width,e.height=t.dimension.height,e.x=t.position.x,e.y=t.position.y,e})),this.dagreEdges=t.edges.map((function(t){var e=Object.assign({},t);return e.id||(e.id=D()),e}));try{for(var a=w(this.dagreNodes),s=a.next();!s.done;s=a.next()){var h=s.value;h.width||(h.width=20),h.height||(h.height=30),this.dagreGraph.setNode(h.id,h)}}catch(t){e={error:t}}finally{try{s&&!s.done&&(n=a.return)&&n.call(a)}finally{if(e)throw e.error}}try{for(var d=w(this.dagreEdges),u=d.next();!u.done;u=d.next()){var g=u.value;r.multigraph?this.dagreGraph.setEdge(g.source,g.target,g,g.id):this.dagreGraph.setEdge(g.source,g.target)}}catch(t){i={error:t}}finally{try{u&&!u.done&&(o=d.return)&&o.call(d)}finally{if(i)throw i.error}}return this.dagreGraph},e}();function S(t){return"string"==typeof t?{id:t,x:0,y:0}:t}var I=function(){function t(){this.defaultSettings={force:u.forceSimulation().force("charge",u.forceManyBody().strength(-150)).force("collide",u.forceCollide(5)),forceLink:u.forceLink().id((function(t){return t.id})).distance((function(){return 100}))},this.settings={},this.outputGraph$=new s.Subject}return t.prototype.run=function(t){var e=this;return this.inputGraph=t,this.d3Graph={nodes:M(this.inputGraph.nodes.map((function(t){return Object.assign({},t)}))),edges:M(this.inputGraph.edges.map((function(t){return Object.assign({},t)})))},this.outputGraph={nodes:[],edges:[],edgeLabels:[]},this.outputGraph$.next(this.outputGraph),this.settings=Object.assign({},this.defaultSettings,this.settings),this.settings.force&&this.settings.force.nodes(this.d3Graph.nodes).force("link",this.settings.forceLink.links(this.d3Graph.edges)).alpha(.5).restart().on("tick",(function(){e.outputGraph$.next(e.d3GraphToOutputGraph(e.d3Graph))})),this.outputGraph$.asObservable()},t.prototype.updateEdge=function(t,e){var n=this,i=Object.assign({},this.defaultSettings,this.settings);return i.force&&i.force.nodes(this.d3Graph.nodes).force("link",i.forceLink.links(this.d3Graph.edges)).alpha(.5).restart().on("tick",(function(){n.outputGraph$.next(n.d3GraphToOutputGraph(n.d3Graph))})),this.outputGraph$.asObservable()},t.prototype.d3GraphToOutputGraph=function(t){return this.outputGraph.nodes=this.d3Graph.nodes.map((function(t){return Object.assign(Object.assign({},t),{id:t.id||D(),position:{x:t.x,y:t.y},dimension:{width:t.dimension&&t.dimension.width||20,height:t.dimension&&t.dimension.height||20},transform:"translate("+(t.x-(t.dimension&&t.dimension.width||20)/2||0)+", "+(t.y-(t.dimension&&t.dimension.height||20)/2||0)+")"})})),this.outputGraph.edges=this.d3Graph.edges.map((function(t){return Object.assign(Object.assign({},t),{source:S(t.source).id,target:S(t.target).id,points:[{x:S(t.source).x,y:S(t.source).y},{x:S(t.target).x,y:S(t.target).y}]})})),this.outputGraph.edgeLabels=this.outputGraph.edges,this.outputGraph},t.prototype.onDragStart=function(t,e){this.settings.force.alphaTarget(.3).restart();var n=this.d3Graph.nodes.find((function(e){return e.id===t.id}));n&&(this.draggingStart={x:e.x-n.x,y:e.y-n.y},n.fx=e.x-this.draggingStart.x,n.fy=e.y-this.draggingStart.y)},t.prototype.onDrag=function(t,e){if(t){var n=this.d3Graph.nodes.find((function(e){return e.id===t.id}));n&&(n.fx=e.x-this.draggingStart.x,n.fy=e.y-this.draggingStart.y)}},t.prototype.onDragEnd=function(t,e){if(t){var n=this.d3Graph.nodes.find((function(e){return e.id===t.id}));n&&(this.settings.force.alphaTarget(0),n.fx=void 0,n.fy=void 0)}},t}();function P(t,e){return"number"==typeof e?t[e]:e}var N,j,z=function(){function t(){this.defaultSettings={force:g.d3adaptor(Object.assign(Object.assign(Object.assign({},y),f),v)).linkDistance(150).avoidOverlaps(!0),viewDimensions:{width:600,height:600,xOffset:0}},this.settings={},this.outputGraph$=new s.Subject}return t.prototype.run=function(t){var e=this;return this.inputGraph=t,this.inputGraph.clusters||(this.inputGraph.clusters=[]),this.internalGraph={nodes:M(this.inputGraph.nodes.map((function(t){return Object.assign(Object.assign({},t),{width:t.dimension?t.dimension.width:20,height:t.dimension?t.dimension.height:20})}))),groups:M(this.inputGraph.clusters.map((function(t){return{padding:5,groups:t.childNodeIds.map((function(t){return e.inputGraph.clusters.findIndex((function(e){return e.id===t}))})).filter((function(t){return t>=0})),leaves:t.childNodeIds.map((function(t){return e.inputGraph.nodes.findIndex((function(e){return e.id===t}))})).filter((function(t){return t>=0}))}}))),links:M(this.inputGraph.edges.map((function(t){var n=e.inputGraph.nodes.findIndex((function(e){return t.source===e.id})),i=e.inputGraph.nodes.findIndex((function(e){return t.target===e.id}));if(-1!==n&&-1!==i)return Object.assign(Object.assign({},t),{source:n,target:i})})).filter((function(t){return!!t}))),groupLinks:M(this.inputGraph.edges.map((function(t){var n=e.inputGraph.nodes.findIndex((function(e){return t.source===e.id})),i=e.inputGraph.nodes.findIndex((function(e){return t.target===e.id}));if(!(n>=0&&i>=0))return t})).filter((function(t){return!!t})))},this.outputGraph={nodes:[],clusters:[],edges:[],edgeLabels:[]},this.outputGraph$.next(this.outputGraph),this.settings=Object.assign({},this.defaultSettings,this.settings),this.settings.force&&(this.settings.force=this.settings.force.nodes(this.internalGraph.nodes).groups(this.internalGraph.groups).links(this.internalGraph.links).alpha(.5).on("tick",(function(){e.settings.onTickListener&&e.settings.onTickListener(e.internalGraph),e.outputGraph$.next(e.internalGraphToOutputGraph(e.internalGraph))})),this.settings.viewDimensions&&(this.settings.force=this.settings.force.size([this.settings.viewDimensions.width,this.settings.viewDimensions.height])),this.settings.forceModifierFn&&(this.settings.force=this.settings.forceModifierFn(this.settings.force)),this.settings.force.start()),this.outputGraph$.asObservable()},t.prototype.updateEdge=function(t,e){var n=Object.assign({},this.defaultSettings,this.settings);return n.force&&n.force.start(),this.outputGraph$.asObservable()},t.prototype.internalGraphToOutputGraph=function(t){var e=this;return this.outputGraph.nodes=t.nodes.map((function(t){return Object.assign(Object.assign({},t),{id:t.id||D(),position:{x:t.x,y:t.y},dimension:{width:t.dimension&&t.dimension.width||20,height:t.dimension&&t.dimension.height||20},transform:"translate("+(t.x-(t.dimension&&t.dimension.width||20)/2||0)+", "+(t.y-(t.dimension&&t.dimension.height||20)/2||0)+")"})})),this.outputGraph.edges=t.links.map((function(e){var n=P(t.nodes,e.source),i=P(t.nodes,e.target);return Object.assign(Object.assign({},e),{source:n.id,target:i.id,points:[n.bounds.rayIntersection(i.bounds.cx(),i.bounds.cy()),i.bounds.rayIntersection(n.bounds.cx(),n.bounds.cy())]})})).concat(t.groupLinks.map((function(e){var n=t.nodes.find((function(t){return t.id===e.source})),i=t.nodes.find((function(t){return t.id===e.target})),o=n||t.groups.find((function(t){return t.id===e.source})),r=i||t.groups.find((function(t){return t.id===e.target}));return Object.assign(Object.assign({},e),{source:o.id,target:r.id,points:[o.bounds.rayIntersection(r.bounds.cx(),r.bounds.cy()),r.bounds.rayIntersection(o.bounds.cx(),o.bounds.cy())]})}))),this.outputGraph.clusters=t.groups.map((function(t,n){var i=e.inputGraph.clusters[n];return Object.assign(Object.assign({},i),{dimension:{width:t.bounds?t.bounds.width():20,height:t.bounds?t.bounds.height():20},position:{x:t.bounds?t.bounds.x+t.bounds.width()/2:0,y:t.bounds?t.bounds.y+t.bounds.height()/2:0}})})),this.outputGraph.edgeLabels=this.outputGraph.edges,this.outputGraph},t.prototype.onDragStart=function(t,e){var n=this.outputGraph.nodes.findIndex((function(e){return e.id===t.id})),i=this.internalGraph.nodes[n];i&&(this.draggingStart={x:i.x-e.x,y:i.y-e.y},i.fixed=1,this.settings.force.start())},t.prototype.onDrag=function(t,e){if(t){var n=this.outputGraph.nodes.findIndex((function(e){return e.id===t.id})),i=this.internalGraph.nodes[n];i&&(i.x=this.draggingStart.x+e.x,i.y=this.draggingStart.y+e.y)}},t.prototype.onDragEnd=function(t,e){if(t){var n=this.outputGraph.nodes.findIndex((function(e){return e.id===t.id})),i=this.internalGraph.nodes[n];i&&(i.fixed=0)}},t}(),_={dagre:k,dagreCluster:E,dagreNodesOnly:C,d3ForceDirected:I,colaForceDirected:z},$=function(){function t(){}return t.prototype.getLayout=function(t){if(_[t])return new _[t];throw new Error("Unknown layout type '"+t+"'")},t}();function W(t,e,n){var i,o,r;n=n||{};var a=null,s=0;function h(){s=!1===n.leading?0:+new Date,a=null,r=t.apply(i,o)}return function(){var d=+new Date;s||!1!==n.leading||(s=d);var p=e-(d-s);return i=this,o=arguments,p<=0?(clearTimeout(a),a=null,s=d,r=t.apply(i,o)):a||!1===n.trailing||(a=setTimeout(h,p)),r}}function F(t,e){return function(n,i,o){return{configurable:!0,enumerable:o.enumerable,get:function(){return Object.defineProperty(this,i,{configurable:!0,enumerable:o.enumerable,value:W(o.value,t,e)}),this[i]}}}}$.decorators=[{type:e.Injectable}],(N=t.PanningAxis||(t.PanningAxis={})).Both="both",N.Horizontal="horizontal",N.Vertical="vertical",(j=t.MiniMapPosition||(t.MiniMapPosition={})).UpperLeft="UpperLeft",j.UpperRight="UpperRight";var B=function(a){function p(n,i,o,r){var h=a.call(this,n,i,o)||this;return h.el=n,h.zone=i,h.cd=o,h.layoutService=r,h.legend=!1,h.nodes=[],h.clusters=[],h.links=[],h.activeEntries=[],h.draggingEnabled=!0,h.panningEnabled=!0,h.panningAxis=t.PanningAxis.Both,h.enableZoom=!0,h.zoomSpeed=.1,h.minZoomLevel=.1,h.maxZoomLevel=4,h.autoZoom=!1,h.panOnZoom=!0,h.animate=!1,h.autoCenter=!1,h.enableTrackpadSupport=!1,h.showMiniMap=!1,h.miniMapMaxWidth=100,h.miniMapPosition=t.MiniMapPosition.UpperRight,h.activate=new e.EventEmitter,h.deactivate=new e.EventEmitter,h.zoomChange=new e.EventEmitter,h.clickHandler=new e.EventEmitter,h.isMouseMoveCalled=!1,h.graphSubscription=new s.Subscription,h.subscriptions=[],h.margin=[0,0,0,0],h.results=[],h.isPanning=!1,h.isDragging=!1,h.initialized=!1,h.graphDims={width:0,height:0},h._oldLinks=[],h.oldNodes=new Set,h.oldClusters=new Set,h.transformationMatrix=d.identity(),h._touchLastX=null,h._touchLastY=null,h.minimapScaleCoefficient=3,h.minimapOffsetX=0,h.minimapOffsetY=0,h.isMinimapPanning=!1,h.groupResultsBy=function(t){return t.label},h}return function(t,e){function n(){this.constructor=t}x(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)}(p,a),Object.defineProperty(p.prototype,"zoomLevel",{get:function(){return this.transformationMatrix.a},set:function(t){this.zoomTo(Number(t))},enumerable:!1,configurable:!0}),Object.defineProperty(p.prototype,"panOffsetX",{get:function(){return this.transformationMatrix.e},set:function(t){this.panTo(Number(t),null)},enumerable:!1,configurable:!0}),Object.defineProperty(p.prototype,"panOffsetY",{get:function(){return this.transformationMatrix.f},set:function(t){this.panTo(null,Number(t))},enumerable:!1,configurable:!0}),p.prototype.ngOnInit=function(){var t=this;this.update$&&this.subscriptions.push(this.update$.subscribe((function(){t.update()}))),this.center$&&this.subscriptions.push(this.center$.subscribe((function(){t.center()}))),this.zoomToFit$&&this.subscriptions.push(this.zoomToFit$.subscribe((function(){t.zoomToFit()}))),this.panToNode$&&this.subscriptions.push(this.panToNode$.subscribe((function(e){t.panToNodeId(e)}))),this.minimapClipPathId="minimapClip"+D()},p.prototype.ngOnChanges=function(t){t.layout;var e=t.layoutSettings;t.nodes,t.clusters,t.links;this.setLayout(this.layout),e&&this.setLayoutSettings(this.layoutSettings),this.update()},p.prototype.setLayout=function(t){this.initialized=!1,t||(t="dagre"),"string"==typeof t&&(this.layout=this.layoutService.getLayout(t),this.setLayoutSettings(this.layoutSettings))},p.prototype.setLayoutSettings=function(t){this.layout&&"string"!=typeof this.layout&&(this.layout.settings=t)},p.prototype.ngOnDestroy=function(){var t,e;a.prototype.ngOnDestroy.call(this);try{for(var n=w(this.subscriptions),i=n.next();!i.done;i=n.next()){i.value.unsubscribe()}}catch(e){t={error:e}}finally{try{i&&!i.done&&(e=n.return)&&e.call(n)}finally{if(t)throw t.error}}this.subscriptions=null},p.prototype.ngAfterViewInit=function(){var t=this;a.prototype.ngAfterViewInit.call(this),setTimeout((function(){return t.update()}))},p.prototype.update=function(){var t=this;a.prototype.update.call(this),this.curve||(this.curve=o.curveBundle.beta(1)),this.zone.run((function(){t.dims=n.calculateViewDimensions({width:t.width,height:t.height,margins:t.margin,showLegend:t.legend}),t.seriesDomain=t.getSeriesDomain(),t.setColors(),t.legendOptions=t.getLegendOptions(),t.createGraph(),t.updateTransform(),t.initialized=!0}))},p.prototype.createGraph=function(){var t=this;this.graphSubscription.unsubscribe(),this.graphSubscription=new s.Subscription;var e=function(e){return e.meta||(e.meta={}),e.id||(e.id=D()),e.dimension?e.meta.forceDimensions=void 0===e.meta.forceDimensions||e.meta.forceDimensions:(e.dimension={width:t.nodeWidth?t.nodeWidth:30,height:t.nodeHeight?t.nodeHeight:30},e.meta.forceDimensions=!1),e.position={x:0,y:0},e.data=e.data?e.data:{},e};this.graph={nodes:this.nodes.length>0?M(this.nodes).map(e):[],clusters:this.clusters&&this.clusters.length>0?M(this.clusters).map(e):[],edges:this.links.length>0?M(this.links).map((function(t){return t.id||(t.id=D()),t})):[]},requestAnimationFrame((function(){return t.draw()}))},p.prototype.draw=function(){var t=this;if(this.layout&&"string"!=typeof this.layout){this.applyNodeDimensions();var e=this.layout.run(this.graph),n=e instanceof s.Observable?e:s.of(e);this.graphSubscription.add(n.subscribe((function(e){t.graph=e,t.tick()}))),0!==this.graph.nodes.length&&n.pipe(h.first()).subscribe((function(){return t.applyNodeDimensions()}))}},p.prototype.tick=function(){var t=this,e=new Set;this.graph.nodes.map((function(n){n.transform="translate("+(n.position.x-n.dimension.width/2||0)+", "+(n.position.y-n.dimension.height/2||0)+")",n.data||(n.data={}),n.data.color=t.colors.getColor(t.groupResultsBy(n)),e.add(n.id)}));var n=new Set;(this.graph.clusters||[]).map((function(e){e.transform="translate("+(e.position.x-e.dimension.width/2||0)+", "+(e.position.y-e.dimension.height/2||0)+")",e.data||(e.data={}),e.data.color=t.colors.getColor(t.groupResultsBy(e)),n.add(e.id)})),setTimeout((function(){t.oldNodes=e,t.oldClusters=n}),500);var i=[],o=function(t){var e=r.graph.edgeLabels[t],n=t.replace(/[^\w-]*/g,""),o=r.layout&&"string"!=typeof r.layout&&r.layout.settings&&r.layout.settings.multigraph,a=o?r._oldLinks.find((function(t){return""+t.source+t.target+t.id===n})):r._oldLinks.find((function(t){return""+t.source+t.target===n})),s=o?r.graph.edges.find((function(t){return""+t.source+t.target+t.id===n})):r.graph.edges.find((function(t){return""+t.source+t.target===n}));a?a.data&&s&&s.data&&JSON.stringify(a.data)!==JSON.stringify(s.data)&&(a.data=s.data):a=s||e,a.oldLine=a.line;var h=e.points,d=r.generateLine(h),p=Object.assign({},a);p.line=d,p.points=h,r.updateMidpointOnEdge(p,h);var u=h[Math.floor(h.length/2)];u&&(p.textTransform="translate("+(u.x||0)+","+(u.y||0)+")"),p.textAngle=0,p.oldLine||(p.oldLine=p.line),r.calcDominantBaseline(p),i.push(p)},r=this;for(var a in this.graph.edgeLabels)o(a);this.graph.edges=i,this.graph.edges&&(this._oldLinks=this.graph.edges.map((function(t){var e=Object.assign({},t);return e.oldLine=t.line,e}))),this.updateMinimap(),this.autoZoom&&this.zoomToFit(),this.autoCenter&&this.center(),requestAnimationFrame((function(){return t.redrawLines()})),this.cd.markForCheck()},p.prototype.getMinimapTransform=function(){switch(this.miniMapPosition){case t.MiniMapPosition.UpperLeft:return"";case t.MiniMapPosition.UpperRight:return"translate("+(this.dims.width-this.graphDims.width/this.minimapScaleCoefficient)+",0)";default:return""}},p.prototype.updateGraphDims=function(){for(var t=1/0,e=-1/0,n=1/0,i=-1/0,o=0;o<this.graph.nodes.length;o++){var r=this.graph.nodes[o];t=r.position.x<t?r.position.x:t,n=r.position.y<n?r.position.y:n,e=r.position.x+r.dimension.width>e?r.position.x+r.dimension.width:e,i=r.position.y+r.dimension.height>i?r.position.y+r.dimension.height:i}this.showMiniMap&&(t-=100,n-=100,e+=100,i+=100),this.graphDims.width=e-t,this.graphDims.height=i-n,this.minimapOffsetX=t,this.minimapOffsetY=n},p.prototype.updateMinimap=function(){this.graph.nodes&&this.graph.nodes.length&&(this.updateGraphDims(),this.miniMapMaxWidth&&(this.minimapScaleCoefficient=this.graphDims.width/this.miniMapMaxWidth),this.miniMapMaxHeight&&(this.minimapScaleCoefficient=Math.max(this.minimapScaleCoefficient,this.graphDims.height/this.miniMapMaxHeight)),this.minimapTransform=this.getMinimapTransform())},p.prototype.applyNodeDimensions=function(){var t=this;this.nodeElements&&this.nodeElements.length&&this.nodeElements.map((function(e){var n,i,o=e.nativeElement,r=t.graph.nodes.find((function(t){return t.id===o.id}));if(r){var a;try{if(!(a=o.getBBox()).width||!a.height)return}catch(t){return}if(t.nodeHeight?r.dimension.height=r.dimension.height&&r.meta.forceDimensions?r.dimension.height:t.nodeHeight:r.dimension.height=r.dimension.height&&r.meta.forceDimensions?r.dimension.height:a.height,t.nodeMaxHeight&&(r.dimension.height=Math.max(r.dimension.height,t.nodeMaxHeight)),t.nodeMinHeight&&(r.dimension.height=Math.min(r.dimension.height,t.nodeMinHeight)),t.nodeWidth)r.dimension.width=r.dimension.width&&r.meta.forceDimensions?r.dimension.width:t.nodeWidth;else if(o.getElementsByTagName("text").length){var s=void 0;try{try{for(var h=w(o.getElementsByTagName("text")),d=h.next();!d.done;d=h.next()){var p=d.value.getBBox();s?(p.width>s.width&&(s.width=p.width),p.height>s.height&&(s.height=p.height)):s=p}}catch(t){n={error:t}}finally{try{d&&!d.done&&(i=h.return)&&i.call(h)}finally{if(n)throw n.error}}}catch(t){return}r.dimension.width=r.dimension.width&&r.meta.forceDimensions?r.dimension.width:s.width+20}else r.dimension.width=r.dimension.width&&r.meta.forceDimensions?r.dimension.width:a.width;t.nodeMaxWidth&&(r.dimension.width=Math.max(r.dimension.width,t.nodeMaxWidth)),t.nodeMinWidth&&(r.dimension.width=Math.min(r.dimension.width,t.nodeMinWidth))}}))},p.prototype.redrawLines=function(t){var e=this;void 0===t&&(t=this.animate),this.linkElements.map((function(n){var o=e.graph.edges.find((function(t){return t.id===n.nativeElement.id}));o&&(i.select(n.nativeElement).select(".line").attr("d",o.oldLine).transition().ease(r.easeSinInOut).duration(t?500:0).attr("d",o.line),i.select(e.chartElement.nativeElement).select("#"+o.id).attr("d",o.oldTextPath).transition().ease(r.easeSinInOut).duration(t?500:0).attr("d",o.textPath),e.updateMidpointOnEdge(o,o.points))}))},p.prototype.calcDominantBaseline=function(t){var e=t.points[0],n=t.points[t.points.length-1];t.oldTextPath=t.textPath,n.x<e.x?(t.dominantBaseline="text-before-edge",t.textPath=this.generateLine(M(t.points).reverse())):(t.dominantBaseline="text-after-edge",t.textPath=t.line)},p.prototype.generateLine=function(t){return o.line().x((function(t){return t.x})).y((function(t){return t.y})).curve(this.curve)(t)},p.prototype.onZoom=function(t,e){if(!this.enableTrackpadSupport||t.ctrlKey){var n=1+("in"===e?this.zoomSpeed:-this.zoomSpeed),i=this.zoomLevel*n;if(!(i<=this.minZoomLevel||i>=this.maxZoomLevel)&&this.enableZoom)if(!0===this.panOnZoom&&t){var o=t.clientX,r=t.clientY,a=this.chart.nativeElement.querySelector("svg"),s=a.querySelector("g.chart"),h=a.createSVGPoint();h.x=o,h.y=r;var d=h.matrixTransform(s.getScreenCTM().inverse());this.pan(d.x,d.y,!0),this.zoom(n),this.pan(-d.x,-d.y,!0)}else this.zoom(n)}else this.pan(-1*t.deltaX,-1*t.deltaY)},p.prototype.pan=function(t,e,n){void 0===n&&(n=!1);var i=n?1:this.zoomLevel;this.transformationMatrix=d.transform(this.transformationMatrix,d.translate(t/i,e/i)),this.updateTransform()},p.prototype.panTo=function(t,e){if(null!=t&&!isNaN(t)&&null!=e&&!isNaN(e)){var n=-this.panOffsetX-t*this.zoomLevel+this.dims.width/2,i=-this.panOffsetY-e*this.zoomLevel+this.dims.height/2;this.transformationMatrix=d.transform(this.transformationMatrix,d.translate(n/this.zoomLevel,i/this.zoomLevel)),this.updateTransform()}},p.prototype.zoom=function(t){this.transformationMatrix=d.transform(this.transformationMatrix,d.scale(t,t)),this.zoomChange.emit(this.zoomLevel),this.updateTransform()},p.prototype.zoomTo=function(t){this.transformationMatrix.a=isNaN(t)?this.transformationMatrix.a:Number(t),this.transformationMatrix.d=isNaN(t)?this.transformationMatrix.d:Number(t),this.zoomChange.emit(this.zoomLevel),this.updateTransform(),this.update()},p.prototype.onDrag=function(t){var e,n,i=this;if(this.draggingEnabled){var o=this.draggingNode;this.layout&&"string"!=typeof this.layout&&this.layout.onDrag&&this.layout.onDrag(o,t),o.position.x+=t.movementX/this.zoomLevel,o.position.y+=t.movementY/this.zoomLevel;var r=o.position.x-o.dimension.width/2,a=o.position.y-o.dimension.height/2;o.transform="translate("+r+", "+a+")";var h=function(t){if((t.target===o.id||t.source===o.id||t.target.id===o.id||t.source.id===o.id)&&d.layout&&"string"!=typeof d.layout){var e=d.layout.updateEdge(d.graph,t),n=e instanceof s.Observable?e:s.of(e);d.graphSubscription.add(n.subscribe((function(e){i.graph=e,i.redrawEdge(t)})))}},d=this;try{for(var p=w(this.graph.edges),u=p.next();!u.done;u=p.next()){h(u.value)}}catch(t){e={error:t}}finally{try{u&&!u.done&&(n=p.return)&&n.call(p)}finally{if(e)throw e.error}}this.redrawLines(!1),this.updateMinimap()}},p.prototype.redrawEdge=function(t){var e=this.generateLine(t.points);this.calcDominantBaseline(t),t.oldLine=t.line,t.line=e},p.prototype.updateTransform=function(){this.transform=d.toSVG(d.smoothMatrix(this.transformationMatrix,100))},p.prototype.onClick=function(t){this.select.emit(t)},p.prototype.onActivate=function(t){this.activeEntries.indexOf(t)>-1||(this.activeEntries=M([t],this.activeEntries),this.activate.emit({value:t,entries:this.activeEntries}))},p.prototype.onDeactivate=function(t){var e=this.activeEntries.indexOf(t);this.activeEntries.splice(e,1),this.activeEntries=M(this.activeEntries),this.deactivate.emit({value:t,entries:this.activeEntries})},p.prototype.getSeriesDomain=function(){var t=this;return this.nodes.map((function(e){return t.groupResultsBy(e)})).reduce((function(t,e){return-1!==t.indexOf(e)?t:t.concat([e])}),[]).sort()},p.prototype.trackLinkBy=function(t,e){return e.id},p.prototype.trackNodeBy=function(t,e){return e.id},p.prototype.setColors=function(){this.colors=new n.ColorHelper(this.scheme,"ordinal",this.seriesDomain,this.customColors)},p.prototype.getLegendOptions=function(){return{scaleType:"ordinal",domain:this.seriesDomain,colors:this.colors}},p.prototype.onMouseMove=function(t){this.isMouseMoveCalled=!0,(this.isPanning||this.isMinimapPanning)&&this.panningEnabled?this.panWithConstraints(this.panningAxis,t):this.isDragging&&this.draggingEnabled&&this.onDrag(t)},p.prototype.onMouseDown=function(t){this.isMouseMoveCalled=!1},p.prototype.graphClick=function(t){this.isMouseMoveCalled||this.clickHandler.emit(t)},p.prototype.onTouchStart=function(t){this._touchLastX=t.changedTouches[0].clientX,this._touchLastY=t.changedTouches[0].clientY,this.isPanning=!0},p.prototype.onTouchMove=function(t){if(this.isPanning&&this.panningEnabled){var e=t.changedTouches[0].clientX,n=t.changedTouches[0].clientY,i=e-this._touchLastX,o=n-this._touchLastY;this._touchLastX=e,this._touchLastY=n,this.pan(i,o)}},p.prototype.onTouchEnd=function(t){this.isPanning=!1},p.prototype.onMouseUp=function(t){this.isDragging=!1,this.isPanning=!1,this.isMinimapPanning=!1,this.layout&&"string"!=typeof this.layout&&this.layout.onDragEnd&&this.layout.onDragEnd(this.draggingNode,t)},p.prototype.onNodeMouseDown=function(t,e){this.draggingEnabled&&(this.isDragging=!0,this.draggingNode=e,this.layout&&"string"!=typeof this.layout&&this.layout.onDragStart&&this.layout.onDragStart(e,t))},p.prototype.onMinimapDragMouseDown=function(){this.isMinimapPanning=!0},p.prototype.onMinimapPanTo=function(t){var e=t.offsetX-(this.dims.width-(this.graphDims.width+this.minimapOffsetX)/this.minimapScaleCoefficient),n=t.offsetY+this.minimapOffsetY/this.minimapScaleCoefficient;this.panTo(e*this.minimapScaleCoefficient,n*this.minimapScaleCoefficient),this.isMinimapPanning=!0},p.prototype.center=function(){this.panTo(this.graphDims.width/2,this.graphDims.height/2)},p.prototype.zoomToFit=function(){var t,e,n=(null===(t=this.zoomToFitMargin)||void 0===t?void 0:t.x)||0,i=(null===(e=this.zoomToFitMargin)||void 0===e?void 0:e.y)||0,o=this.dims.height/(this.graphDims.height+2*i),r=this.dims.width/(this.graphDims.width+2*n),a=Math.min(o,r,1);a<this.minZoomLevel&&(a=this.minZoomLevel),a>this.maxZoomLevel&&(a=this.maxZoomLevel),a!==this.zoomLevel&&(this.zoomLevel=a,this.updateTransform(),this.zoomChange.emit(this.zoomLevel))},p.prototype.panToNodeId=function(t){var e=this.graph.nodes.find((function(e){return e.id===t}));e&&this.panTo(e.position.x,e.position.y)},p.prototype.panWithConstraints=function(e,n){var i=n.movementX,o=n.movementY;switch(this.isMinimapPanning&&(i=-this.minimapScaleCoefficient*i*this.zoomLevel,o=-this.minimapScaleCoefficient*o*this.zoomLevel),e){case t.PanningAxis.Horizontal:this.pan(i,0);break;case t.PanningAxis.Vertical:this.pan(0,o);break;default:this.pan(i,o)}},p.prototype.updateMidpointOnEdge=function(t,e){if(t&&e)if(e.length%2==1)t.midPoint=e[Math.floor(e.length/2)];else{var n=e[e.length/2],i=e[e.length/2-1];t.midPoint={x:(n.x+i.x)/2,y:(n.y+i.y)/2}}},p}(n.BaseChartComponent);B.decorators=[{type:e.Component,args:[{selector:"ngx-graph",template:'<ngx-charts-chart\n [view]="[width, height]"\n [showLegend]="legend"\n [legendOptions]="legendOptions"\n (legendLabelClick)="onClick($event)"\n (legendLabelActivate)="onActivate($event)"\n (legendLabelDeactivate)="onDeactivate($event)"\n mouseWheel\n (mouseWheelUp)="onZoom($event, \'in\')"\n (mouseWheelDown)="onZoom($event, \'out\')"\n>\n <svg:g\n *ngIf="initialized && graph"\n [attr.transform]="transform"\n (touchstart)="onTouchStart($event)"\n (touchend)="onTouchEnd($event)"\n class="graph chart"\n >\n <defs>\n <ng-container *ngIf="defsTemplate" [ngTemplateOutlet]="defsTemplate"></ng-container>\n <svg:path\n class="text-path"\n *ngFor="let link of graph.edges"\n [attr.d]="link.textPath"\n [attr.id]="link.id"\n ></svg:path>\n </defs>\n\n <svg:rect\n class="panning-rect"\n [attr.width]="dims.width * 100"\n [attr.height]="dims.height * 100"\n [attr.transform]="\'translate(\' + (-dims.width || 0) * 50 + \',\' + (-dims.height || 0) * 50 + \')\'"\n (mousedown)="isPanning = true"\n />\n\n <ng-content></ng-content>\n\n <svg:g class="clusters">\n <svg:g\n #clusterElement\n *ngFor="let node of graph.clusters; trackBy: trackNodeBy"\n class="node-group"\n [class.old-node]="animate && oldClusters.has(node.id)"\n [id]="node.id"\n [attr.transform]="node.transform"\n (click)="onClick(node)"\n >\n <ng-container\n *ngIf="clusterTemplate"\n [ngTemplateOutlet]="clusterTemplate"\n [ngTemplateOutletContext]="{ $implicit: node }"\n ></ng-container>\n <svg:g *ngIf="!clusterTemplate" class="node cluster">\n <svg:rect\n [attr.width]="node.dimension.width"\n [attr.height]="node.dimension.height"\n [attr.fill]="node.data?.color"\n />\n <svg:text alignment-baseline="central" [attr.x]="10" [attr.y]="node.dimension.height / 2">\n {{ node.label }}\n </svg:text>\n </svg:g>\n </svg:g>\n </svg:g>\n\n <svg:g class="links">\n <svg:g #linkElement *ngFor="let link of graph.edges; trackBy: trackLinkBy" class="link-group" [id]="link.id">\n <ng-container\n *ngIf="linkTemplate"\n [ngTemplateOutlet]="linkTemplate"\n [ngTemplateOutletContext]="{ $implicit: link }"\n ></ng-container>\n <svg:path *ngIf="!linkTemplate" class="edge" [attr.d]="link.line" />\n </svg:g>\n </svg:g>\n\n <svg:g class="nodes">\n <svg:g\n #nodeElement\n *ngFor="let node of graph.nodes; trackBy: trackNodeBy"\n class="node-group"\n [class.old-node]="animate && oldNodes.has(node.id)"\n [id]="node.id"\n [attr.transform]="node.transform"\n (click)="onClick(node)"\n (mousedown)="onNodeMouseDown($event, node)"\n >\n <ng-container\n *ngIf="nodeTemplate"\n [ngTemplateOutlet]="nodeTemplate"\n [ngTemplateOutletContext]="{ $implicit: node }"\n ></ng-container>\n <svg:circle\n *ngIf="!nodeTemplate"\n r="10"\n [attr.cx]="node.dimension.width / 2"\n [attr.cy]="node.dimension.height / 2"\n [attr.fill]="node.data?.color"\n />\n </svg:g>\n </svg:g>\n </svg:g>\n\n <svg:clipPath [attr.id]="minimapClipPathId">\n <svg:rect\n [attr.width]="graphDims.width / minimapScaleCoefficient"\n [attr.height]="graphDims.height / minimapScaleCoefficient"\n ></svg:rect>\n </svg:clipPath>\n\n <svg:g\n class="minimap"\n *ngIf="showMiniMap"\n [attr.transform]="minimapTransform"\n [attr.clip-path]="\'url(#\' + minimapClipPathId + \')\'"\n >\n <svg:rect\n class="minimap-background"\n [attr.width]="graphDims.width / minimapScaleCoefficient"\n [attr.height]="graphDims.height / minimapScaleCoefficient"\n (mousedown)="onMinimapPanTo($event)"\n ></svg:rect>\n\n <svg:g\n [style.transform]="\n \'translate(\' +\n -minimapOffsetX / minimapScaleCoefficient +\n \'px,\' +\n -minimapOffsetY / minimapScaleCoefficient +\n \'px)\'\n "\n >\n <svg:g class="minimap-nodes" [style.transform]="\'scale(\' + 1 / minimapScaleCoefficient + \')\'">\n <svg:g\n #nodeElement\n *ngFor="let node of graph.nodes; trackBy: trackNodeBy"\n class="node-group"\n [class.old-node]="animate && oldNodes.has(node.id)"\n [id]="node.id"\n [attr.transform]="node.transform"\n >\n <ng-container\n *ngIf="miniMapNodeTemplate"\n [ngTemplateOutlet]="miniMapNodeTemplate"\n [ngTemplateOutletContext]="{ $implicit: node }"\n ></ng-container>\n <ng-container\n *ngIf="!miniMapNodeTemplate && nodeTemplate"\n [ngTemplateOutlet]="nodeTemplate"\n [ngTemplateOutletContext]="{ $implicit: node }"\n ></ng-container>\n <svg:circle\n *ngIf="!nodeTemplate && !miniMapNodeTemplate"\n r="10"\n [attr.cx]="node.dimension.width / 2 / minimapScaleCoefficient"\n [attr.cy]="node.dimension.height / 2 / minimapScaleCoefficient"\n [attr.fill]="node.data?.color"\n />\n </svg:g>\n </svg:g>\n\n <svg:rect\n [attr.transform]="\n \'translate(\' +\n panOffsetX / zoomLevel / -minimapScaleCoefficient +\n \',\' +\n panOffsetY / zoomLevel / -minimapScaleCoefficient +\n \')\'\n "\n class="minimap-drag"\n [class.panning]="isMinimapPanning"\n [attr.width]="width / minimapScaleCoefficient / zoomLevel"\n [attr.height]="height / minimapScaleCoefficient / zoomLevel"\n (mousedown)="onMinimapDragMouseDown()"\n ></svg:rect>\n </svg:g>\n </svg:g>\n</ngx-charts-chart>\n',encapsulation:e.ViewEncapsulation.None,changeDetection:e.ChangeDetectionStrategy.OnPush,styles:[".minimap .minimap-background{fill:rgba(0,0,0,.1)}.minimap .minimap-drag{cursor:pointer;fill:rgba(0,0,0,.2);stroke:#fff;stroke-dasharray:2px;stroke-dashoffset:2px;stroke-width:1px}.minimap .minimap-drag.panning{fill:rgba(0,0,0,.3)}.minimap .minimap-nodes{opacity:.5;pointer-events:none}.graph{-moz-user-select:none;-ms-user-select:none;-webkit-user-select:none;user-select:none}.graph .edge{fill:none;stroke:#666}.graph .edge .edge-label{fill:#251e1e;font-size:12px;stroke:none}.graph .panning-rect{cursor:move;fill:transparent}.graph .node-group.old-node{transition:transform .5s ease-in-out}.graph .node-group .node:focus{outline:none}.graph .cluster rect{opacity:.2}"]}]}],B.ctorParameters=function(){return[{type:e.ElementRef},{type:e.NgZone},{type:e.ChangeDetectorRef},{type:$}]},B.propDecorators={legend:[{type:e.Input}],nodes:[{type:e.Input}],clusters:[{type:e.Input}],links:[{type:e.Input}],activeEntries:[{type:e.Input}],curve:[{type:e.Input}],draggingEnabled:[{type:e.Input}],nodeHeight:[{type:e.Input}],nodeMaxHeight:[{type:e.Input}],nodeMinHeight:[{type:e.Input}],nodeWidth:[{type:e.Input}],nodeMinWidth:[{type:e.Input}],nodeMaxWidth:[{type:e.Input}],panningEnabled:[{type:e.Input}],panningAxis:[{type:e.Input}],enableZoom:[{type:e.Input}],zoomSpeed:[{type:e.Input}],minZoomLevel:[{type:e.Input}],maxZoomLevel:[{type:e.Input}],autoZoom:[{type:e.Input}],panOnZoom:[{type:e.Input}],animate:[{type:e.Input}],autoCenter:[{type:e.Input}],zoomToFitMargin:[{type:e.Input}],update$:[{type:e.Input}],center$:[{type:e.Input}],zoomToFit$:[{type:e.Input}],panToNode$:[{type:e.Input}],layout:[{type:e.Input}],layoutSettings:[{type:e.Input}],enableTrackpadSupport:[{type:e.Input}],showMiniMap:[{type:e.Input}],miniMapMaxWidth:[{type:e.Input}],miniMapMaxHeight:[{type:e.Input}],miniMapPosition:[{type:e.Input}],activate:[{type:e.Output}],deactivate:[{type:e.Output}],zoomChange:[{type:e.Output}],clickHandler:[{type:e.Output}],linkTemplate:[{type:e.ContentChild,args:["linkTemplate"]}],nodeTemplate:[{type:e.ContentChild,args:["nodeTemplate"]}],clusterTemplate:[{type:e.ContentChild,args:["clusterTemplate"]}],defsTemplate:[{type:e.ContentChild,args:["defsTemplate"]}],miniMapNodeTemplate:[{type:e.ContentChild,args:["miniMapNodeTemplate"]}],chart:[{type:e.ViewChild,args:[n.ChartComponent,{read:e.ElementRef,static:!0}]}],nodeElements:[{type:e.ViewChildren,args:["nodeElement"]}],linkElements:[{type:e.ViewChildren,args:["linkElement"]}],groupResultsBy:[{type:e.Input}],zoomLevel:[{type:e.Input,args:["zoomLevel"]}],panOffsetX:[{type:e.Input,args:["panOffsetX"]}],panOffsetY:[{type:e.Input,args:["panOffsetY"]}],onMouseMove:[{type:e.HostListener,args:["document:mousemove",["$event"]]}],onMouseDown:[{type:e.HostListener,args:["document:mousedown",["$event"]]}],graphClick:[{type:e.HostListener,args:["document:click",["$event"]]}],onTouchMove:[{type:e.HostListener,args:["document:touchmove",["$event"]]}],onMouseUp:[{type:e.HostListener,args:["document:mouseup",["$event"]]}]},function(t,e,n,i){var o,r=arguments.length,a=r<3?e:null===i?i=Object.getOwnPropertyDescriptor(e,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(t,e,n,i);else for(var s=t.length-1;s>=0;s--)(o=t[s])&&(a=(r<3?o(a):r>3?o(e,n,a):o(e,n))||a);r>3&&a&&Object.defineProperty(e,n,a)}([F(500),b("design:type",Function),b("design:paramtypes",[]),b("design:returntype",void 0)],B.prototype,"updateMinimap",null);var H=function(){function t(){this.mouseWheelUp=new e.EventEmitter,this.mouseWheelDown=new e.EventEmitter}return t.prototype.onMouseWheelChrome=function(t){this.mouseWheelFunc(t)},t.prototype.onMouseWheelFirefox=function(t){this.mouseWheelFunc(t)},t.prototype.onWheel=function(t){this.mouseWheelFunc(t)},t.prototype.onMouseWheelIE=function(t){this.mouseWheelFunc(t)},t.prototype.mouseWheelFunc=function(t){window.event&&(t=window.event);var e=Math.max(-1,Math.min(1,t.wheelDelta||-t.detail||t.deltaY||t.deltaX)),n=t.wheelDelta?e>0:e<0,i=t.wheelDelta?e<0:e>0;n?this.mouseWheelUp.emit(t):i&&this.mouseWheelDown.emit(t),t.returnValue=!1,t.preventDefault&&t.preventDefault()},t}();H.decorators=[{type:e.Directive,args:[{selector:"[mouseWheel]"}]}],H.propDecorators={mouseWheelUp:[{type:e.Output}],mouseWheelDown:[{type:e.Output}],onMouseWheelChrome:[{type:e.HostListener,args:["mousewheel",["$event"]]}],onMouseWheelFirefox:[{type:e.HostListener,args:["DOMMouseScroll",["$event"]]}],onWheel:[{type:e.HostListener,args:["wheel",["$event"]]}],onMouseWheelIE:[{type:e.HostListener,args:["onmousewheel",["$event"]]}]};var R=function(){};R.decorators=[{type:e.NgModule,args:[{imports:[n.ChartCommonModule],declarations:[B,H],exports:[B,H],providers:[$]}]}];var X=function(){};X.decorators=[{type:e.NgModule,args:[{imports:[n.NgxChartsModule],exports:[R]}]}],t.ColaForceDirectedLayout=z,t.D3ForceDirectedLayout=I,t.DagreClusterLayout=E,t.DagreLayout=k,t.DagreNodesOnlyLayout=C,t.GraphComponent=B,t.GraphModule=R,t.MouseWheelDirective=H,t.NgxGraphModule=X,t.toD3Node=S,t.toNode=P,t.ɵa=$,t.ɵb=F,Object.defineProperty(t,"__esModule",{value:!0})})); //# sourceMappingURL=swimlane-ngx-graph.umd.min.js.map
23,036
46,017
0.723476
c368b63332abe1f233e739a9ca041f0f185985d4
5,872
go
Go
models/cash_drawer_shift_summary.go
jefflinse/square-connect
dc3cc4a76a901623176ec36f7a6d550029394abe
[ "MIT" ]
null
null
null
models/cash_drawer_shift_summary.go
jefflinse/square-connect
dc3cc4a76a901623176ec36f7a6d550029394abe
[ "MIT" ]
null
null
null
models/cash_drawer_shift_summary.go
jefflinse/square-connect
dc3cc4a76a901623176ec36f7a6d550029394abe
[ "MIT" ]
null
null
null
// Code generated by go-swagger; DO NOT EDIT. package models // This file was generated by the swagger tool. // Editing this file might prove futile when you re-run the swagger generate command import ( "context" "github.com/go-openapi/errors" "github.com/go-openapi/strfmt" "github.com/go-openapi/swag" ) // CashDrawerShiftSummary The summary of a closed cash drawer shift. // This model contains only the money counted to start a cash drawer shift, counted // at the end of the shift, and the amount that should be in the drawer at shift // end based on summing all cash drawer shift events. // // swagger:model CashDrawerShiftSummary type CashDrawerShiftSummary struct { // The shift close time in ISO 8601 format. ClosedAt string `json:"closed_at,omitempty"` // The amount of money found in the cash drawer at the end of the shift by // an auditing employee. The amount must be greater than or equal to zero. ClosedCashMoney *Money `json:"closed_cash_money,omitempty"` // An employee free-text description of a cash drawer shift. Description string `json:"description,omitempty"` // The shift end time in ISO 8601 format. EndedAt string `json:"ended_at,omitempty"` // The amount of money that should be in the cash drawer at the end of the // shift, based on the cash drawer events on the shift. // The amount is correct if all shift employees accurately recorded their // cash drawer shift events. Unrecorded events and events with the wrong amount // result in an incorrect expected_cash_money amount that can be negative. ExpectedCashMoney *Money `json:"expected_cash_money,omitempty"` // The shift unique ID. ID string `json:"id,omitempty"` // The shift start time in ISO 8601 format. OpenedAt string `json:"opened_at,omitempty"` // The amount of money in the cash drawer at the start of the shift. This // must be a positive amount. OpenedCashMoney *Money `json:"opened_cash_money,omitempty"` // The shift current state. // See [CashDrawerShiftState](#type-cashdrawershiftstate) for possible values State string `json:"state,omitempty"` } // Validate validates this cash drawer shift summary func (m *CashDrawerShiftSummary) Validate(formats strfmt.Registry) error { var res []error if err := m.validateClosedCashMoney(formats); err != nil { res = append(res, err) } if err := m.validateExpectedCashMoney(formats); err != nil { res = append(res, err) } if err := m.validateOpenedCashMoney(formats); err != nil { res = append(res, err) } if len(res) > 0 { return errors.CompositeValidationError(res...) } return nil } func (m *CashDrawerShiftSummary) validateClosedCashMoney(formats strfmt.Registry) error { if swag.IsZero(m.ClosedCashMoney) { // not required return nil } if m.ClosedCashMoney != nil { if err := m.ClosedCashMoney.Validate(formats); err != nil { if ve, ok := err.(*errors.Validation); ok { return ve.ValidateName("closed_cash_money") } return err } } return nil } func (m *CashDrawerShiftSummary) validateExpectedCashMoney(formats strfmt.Registry) error { if swag.IsZero(m.ExpectedCashMoney) { // not required return nil } if m.ExpectedCashMoney != nil { if err := m.ExpectedCashMoney.Validate(formats); err != nil { if ve, ok := err.(*errors.Validation); ok { return ve.ValidateName("expected_cash_money") } return err } } return nil } func (m *CashDrawerShiftSummary) validateOpenedCashMoney(formats strfmt.Registry) error { if swag.IsZero(m.OpenedCashMoney) { // not required return nil } if m.OpenedCashMoney != nil { if err := m.OpenedCashMoney.Validate(formats); err != nil { if ve, ok := err.(*errors.Validation); ok { return ve.ValidateName("opened_cash_money") } return err } } return nil } // ContextValidate validate this cash drawer shift summary based on the context it is used func (m *CashDrawerShiftSummary) ContextValidate(ctx context.Context, formats strfmt.Registry) error { var res []error if err := m.contextValidateClosedCashMoney(ctx, formats); err != nil { res = append(res, err) } if err := m.contextValidateExpectedCashMoney(ctx, formats); err != nil { res = append(res, err) } if err := m.contextValidateOpenedCashMoney(ctx, formats); err != nil { res = append(res, err) } if len(res) > 0 { return errors.CompositeValidationError(res...) } return nil } func (m *CashDrawerShiftSummary) contextValidateClosedCashMoney(ctx context.Context, formats strfmt.Registry) error { if m.ClosedCashMoney != nil { if err := m.ClosedCashMoney.ContextValidate(ctx, formats); err != nil { if ve, ok := err.(*errors.Validation); ok { return ve.ValidateName("closed_cash_money") } return err } } return nil } func (m *CashDrawerShiftSummary) contextValidateExpectedCashMoney(ctx context.Context, formats strfmt.Registry) error { if m.ExpectedCashMoney != nil { if err := m.ExpectedCashMoney.ContextValidate(ctx, formats); err != nil { if ve, ok := err.(*errors.Validation); ok { return ve.ValidateName("expected_cash_money") } return err } } return nil } func (m *CashDrawerShiftSummary) contextValidateOpenedCashMoney(ctx context.Context, formats strfmt.Registry) error { if m.OpenedCashMoney != nil { if err := m.OpenedCashMoney.ContextValidate(ctx, formats); err != nil { if ve, ok := err.(*errors.Validation); ok { return ve.ValidateName("opened_cash_money") } return err } } return nil } // MarshalBinary interface implementation func (m *CashDrawerShiftSummary) MarshalBinary() ([]byte, error) { if m == nil { return nil, nil } return swag.WriteJSON(m) } // UnmarshalBinary interface implementation func (m *CashDrawerShiftSummary) UnmarshalBinary(b []byte) error { var res CashDrawerShiftSummary if err := swag.ReadJSON(b, &res); err != nil { return err } *m = res return nil }
27.568075
119
0.722411
74d046024ccef2a8077c21d99f32704efcf988c9
6,818
js
JavaScript
myqq-webapp/src/views/Login/index.js
WHUT-XGP/chat-webapp
53eba4e223411ca5b988857c56a38cc962d3c27e
[ "MIT" ]
23
2020-12-25T08:39:11.000Z
2022-03-23T07:12:23.000Z
myqq-webapp/src/views/Login/index.js
WHUT-XGP/chat-webapp
53eba4e223411ca5b988857c56a38cc962d3c27e
[ "MIT" ]
1
2022-01-02T14:31:28.000Z
2022-01-02T14:31:28.000Z
myqq-webapp/src/views/Login/index.js
WHUT-XGP/chat-webapp
53eba4e223411ca5b988857c56a38cc962d3c27e
[ "MIT" ]
null
null
null
import React, { useState, useEffect, useCallback } from 'react' import { connect } from 'react-redux' // 导入store相关 import { actionCreator } from './store' // 导入CSS import { LoginStyle } from './style' // 导入组件 import Icon from '../../components/context/Icon' import LoginInput from '../../components/common/LoginInput' import Dialog from '../../components/common/Dialog' import Loading from '../../components/common/loading' import Toast from '../../components/common/Toast' import { getInfo } from '../../api/LoginRequest' function Login(props) { // 登录用户名和密码 const { loading, error, history, register, token } = props const { getLogin, changeToken, changeLoading, changeIsError, registerUser, changeRegister } = props; const [password, setPassword] = useState(''); const [username, setUsername] = useState(''); const [isLoginStatus, setIsLoginStatus] = useState(true); const [confirmPassword, setConfirmPassword] = useState(''); const [toast, setToast] = useState(false); const [content, setContent] = useState(''); // 设置错误提示事件 // 通过useCallback改写 const changeToast = useCallback((content) => { setContent(content) setToast(true) // 两秒后消失 setTimeout(() => { setToast(false) }, 2000); }, [setToast, setContent]) // 从本地获取token useEffect(() => { const localToken = localStorage.getItem('token'); if (localToken) { changeToken(localToken); } }, [changeToken]) // 登录成功的逻辑处理 useEffect(() => { if (token) { // 存进本地 getInfo('', token).then(() => { localStorage.setItem('token', token) history.push('/home/message') }).catch((err) => { console.log(err) }) } }, [token, history]) // 中途出错的逻辑处理 useEffect(() => { if (error) { changeToast(isLoginStatus ? '密码或用户名错误' : '用户名已存在') // 重置 changeIsError(false) } }, [error, changeIsError, isLoginStatus,changeToast]) // 注册成功 useEffect(() => { if (register) { changeToast('恭喜你! 注册成功!') changeRegister(false); setTimeout(() => { setIsLoginStatus(true); }, 500); } }, [register, changeRegister,changeToast]) return ( <LoginStyle> {/**标志 */} <div className="icon-box"> <a href="/"><Icon xlinkHref='#icon-crew_react-copy'></Icon></a> <span>MyQQ</span> </div> {/**登录输入框 */} { isLoginStatus && (<div className="input-box"> <LoginInput xlinkHref='#icon-morentouxiang' type="text" value={username} handleInput={(e) => { setUsername(e) }} placeHolder="请输入用户名" /> <LoginInput xlinkHref='#icon-mima' type="password" value={password} placeHolder="请输入密码" handleInput={(e) => { setPassword(e) }} /> </div>) } {/**注册输入框 */} { !isLoginStatus && (<div className="input-box"> <LoginInput xlinkHref='#icon-morentouxiang' type="text" value={username} handleInput={(e) => { setUsername(e) }} placeHolder="请输入用户名" /> <LoginInput xlinkHref='#icon-mima' type="password" value={password} placeHolder="请输入密码" handleInput={(e) => { setPassword(e) }} /> <LoginInput xlinkHref={confirmPassword === "" ? "#icon-crew_react" : confirmPassword === password ? '#icon-querenmima' : '#icon-cuowu'} type="password" value={confirmPassword} placeHolder="确认密码" handleInput={(e) => { setConfirmPassword(e) }} /> </div>) } {/**控制按钮 */} <div className='button-go' style={{ animation: loading ? "circle 1s linear infinite" : "" }} onClick={() => { if (isLoginStatus) { // 登录 通过redux获取数据 if (username && password) { getLogin(username, password) changeLoading(true) } else { changeToast('信息不足,请完成填写') } } else { // 注册 if (username && password && password === confirmPassword) { registerUser(username, password) changeLoading(true); } else { changeToast('请完成填写') } } }} > <Icon xlinkHref='#icon-denglu' size="1.3rem" /> </div> {/**切换按钮 */} <span style={{ marginTop: '1rem', fontSize: "0.8rem", textDecoration: 'underline', color: '#3F91CF' }} onClick={() => { setIsLoginStatus(!isLoginStatus) }} >{isLoginStatus ? '点我注册' : '切换登录'}</span> {/**加载提示组件 */} <Dialog open={props.loading} title='加载中...' > <Loading /> </Dialog> {/** 轻提示组件*/} <Toast open={toast} content={content}></Toast> </LoginStyle> ) } // 配置redux映射关系 const mapStateToProps = (state) => { return { token: state.LoginReducer.token, userInfo: state.LoginReducer.userInfo, loading: state.LoginReducer.loading, isLogin: state.LoginReducer.isLogin, error: state.LoginReducer.isError, register: state.LoginReducer.isRegister } } const mapDispatchToProps = (dispatch) => { return { getLogin: (username, password) => { dispatch(actionCreator.getLogin(username, password)) }, getInfo: (username) => { dispatch(actionCreator.getUserInfo(username)) }, changeToken: (token) => { dispatch(actionCreator.tokenChange(token)) }, changeLoading: (status) => { dispatch(actionCreator.changeLoadingStatus(status)) }, changeIsLogin: (status) => { dispatch(actionCreator.changeIsLoginStatus(status)) }, changeIsError: (status) => { dispatch(actionCreator.changeErrorStatus(status)) }, registerUser: (username, password) => { dispatch(actionCreator.getRegister(username, password)) }, changeRegister: (status) => { dispatch(actionCreator.changeRegisterStatus(status)) } } } export default connect(mapStateToProps, mapDispatchToProps)(React.memo(Login))
35.510417
236
0.512174
75975bb3ef1e4c0b5a1725817c731329b2fde232
353
h
C
nfa2.h
priseup/nfa
c8c92cff7a613803a2469da47953499e6de32eed
[ "Apache-2.0" ]
1
2021-08-20T14:00:39.000Z
2021-08-20T14:00:39.000Z
nfa2.h
priseup/nfa
c8c92cff7a613803a2469da47953499e6de32eed
[ "Apache-2.0" ]
null
null
null
nfa2.h
priseup/nfa
c8c92cff7a613803a2469da47953499e6de32eed
[ "Apache-2.0" ]
null
null
null
#ifndef NFA2_H #define NFA2_H #include <string> struct State; struct Edge { int match_content; State* to_state; }; struct State { int sequence; Edge e1; Edge e2; }; struct Fragment { State* start; State* end; }; State* post2nfa(const std::string &s); bool match(const std::string &str, State* start); #endif // NFA2_H
11.387097
49
0.645892
dd24654cf7600a45cd983893f29bfdfda867005d
6,788
go
Go
models/outlook_task_group.go
microsoftgraph/msgraph-beta-sdk-go
aa0e88784f9ae169fe97d86df95e5a34e7ce401e
[ "MIT" ]
4
2021-11-23T07:58:53.000Z
2022-02-20T06:58:06.000Z
models/outlook_task_group.go
microsoftgraph/msgraph-beta-sdk-go
aa0e88784f9ae169fe97d86df95e5a34e7ce401e
[ "MIT" ]
28
2021-11-03T20:05:54.000Z
2022-03-25T04:34:36.000Z
models/outlook_task_group.go
microsoftgraph/msgraph-beta-sdk-go
aa0e88784f9ae169fe97d86df95e5a34e7ce401e
[ "MIT" ]
2
2021-11-21T14:30:10.000Z
2022-03-17T01:13:04.000Z
package models import ( i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91 "github.com/microsoft/kiota-abstractions-go/serialization" ) // OutlookTaskGroup type OutlookTaskGroup struct { Entity // The version of the task group. changeKey *string // The unique GUID identifier for the task group. groupKey *string // True if the task group is the default task group. isDefaultGroup *bool // The name of the task group. name *string // The collection of task folders in the task group. Read-only. Nullable. taskFolders []OutlookTaskFolderable } // NewOutlookTaskGroup instantiates a new outlookTaskGroup and sets the default values. func NewOutlookTaskGroup()(*OutlookTaskGroup) { m := &OutlookTaskGroup{ Entity: *NewEntity(), } return m } // CreateOutlookTaskGroupFromDiscriminatorValue creates a new instance of the appropriate class based on discriminator value func CreateOutlookTaskGroupFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) { return NewOutlookTaskGroup(), nil } // GetChangeKey gets the changeKey property value. The version of the task group. func (m *OutlookTaskGroup) GetChangeKey()(*string) { if m == nil { return nil } else { return m.changeKey } } // GetFieldDeserializers the deserialization information for the current model func (m *OutlookTaskGroup) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) { res := m.Entity.GetFieldDeserializers() res["changeKey"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error { val, err := n.GetStringValue() if err != nil { return err } if val != nil { m.SetChangeKey(val) } return nil } res["groupKey"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error { val, err := n.GetStringValue() if err != nil { return err } if val != nil { m.SetGroupKey(val) } return nil } res["isDefaultGroup"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error { val, err := n.GetBoolValue() if err != nil { return err } if val != nil { m.SetIsDefaultGroup(val) } return nil } res["name"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error { val, err := n.GetStringValue() if err != nil { return err } if val != nil { m.SetName(val) } return nil } res["taskFolders"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error { val, err := n.GetCollectionOfObjectValues(CreateOutlookTaskFolderFromDiscriminatorValue) if err != nil { return err } if val != nil { res := make([]OutlookTaskFolderable, len(val)) for i, v := range val { res[i] = v.(OutlookTaskFolderable) } m.SetTaskFolders(res) } return nil } return res } // GetGroupKey gets the groupKey property value. The unique GUID identifier for the task group. func (m *OutlookTaskGroup) GetGroupKey()(*string) { if m == nil { return nil } else { return m.groupKey } } // GetIsDefaultGroup gets the isDefaultGroup property value. True if the task group is the default task group. func (m *OutlookTaskGroup) GetIsDefaultGroup()(*bool) { if m == nil { return nil } else { return m.isDefaultGroup } } // GetName gets the name property value. The name of the task group. func (m *OutlookTaskGroup) GetName()(*string) { if m == nil { return nil } else { return m.name } } // GetTaskFolders gets the taskFolders property value. The collection of task folders in the task group. Read-only. Nullable. func (m *OutlookTaskGroup) GetTaskFolders()([]OutlookTaskFolderable) { if m == nil { return nil } else { return m.taskFolders } } // Serialize serializes information the current object func (m *OutlookTaskGroup) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) { err := m.Entity.Serialize(writer) if err != nil { return err } { err = writer.WriteStringValue("changeKey", m.GetChangeKey()) if err != nil { return err } } { err = writer.WriteStringValue("groupKey", m.GetGroupKey()) if err != nil { return err } } { err = writer.WriteBoolValue("isDefaultGroup", m.GetIsDefaultGroup()) if err != nil { return err } } { err = writer.WriteStringValue("name", m.GetName()) if err != nil { return err } } if m.GetTaskFolders() != nil { cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetTaskFolders())) for i, v := range m.GetTaskFolders() { cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable) } err = writer.WriteCollectionOfObjectValues("taskFolders", cast) if err != nil { return err } } return nil } // SetChangeKey sets the changeKey property value. The version of the task group. func (m *OutlookTaskGroup) SetChangeKey(value *string)() { if m != nil { m.changeKey = value } } // SetGroupKey sets the groupKey property value. The unique GUID identifier for the task group. func (m *OutlookTaskGroup) SetGroupKey(value *string)() { if m != nil { m.groupKey = value } } // SetIsDefaultGroup sets the isDefaultGroup property value. True if the task group is the default task group. func (m *OutlookTaskGroup) SetIsDefaultGroup(value *bool)() { if m != nil { m.isDefaultGroup = value } } // SetName sets the name property value. The name of the task group. func (m *OutlookTaskGroup) SetName(value *string)() { if m != nil { m.name = value } } // SetTaskFolders sets the taskFolders property value. The collection of task folders in the task group. Read-only. Nullable. func (m *OutlookTaskGroup) SetTaskFolders(value []OutlookTaskFolderable)() { if m != nil { m.taskFolders = value } }
33.438424
221
0.650707
d2b6047de2b61e79f461aad1a4224dcdf66bcbe6
544
kt
Kotlin
jetbrains-core/tst-203-211/software/aws/toolkits/jetbrains/core/docker/ToolkitDockerAdapterTestUtils.kt
drakejin/aws-toolkit-jetbrains
fec0dbb39f5dfabf2f3abc617805c2a592bd3714
[ "Apache-2.0" ]
610
2018-09-18T17:15:44.000Z
2022-03-02T11:29:45.000Z
jetbrains-core/tst-203-211/software/aws/toolkits/jetbrains/core/docker/ToolkitDockerAdapterTestUtils.kt
drakejin/aws-toolkit-jetbrains
fec0dbb39f5dfabf2f3abc617805c2a592bd3714
[ "Apache-2.0" ]
2,639
2018-09-18T17:16:42.000Z
2022-03-29T14:06:05.000Z
jetbrains-core/tst-203-211/software/aws/toolkits/jetbrains/core/docker/ToolkitDockerAdapterTestUtils.kt
drakejin/aws-toolkit-jetbrains
fec0dbb39f5dfabf2f3abc617805c2a592bd3714
[ "Apache-2.0" ]
142
2018-09-18T17:27:00.000Z
2022-03-05T21:00:52.000Z
// Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package software.aws.toolkits.jetbrains.core.docker import com.intellij.docker.agent.DockerAgentApplication import org.mockito.kotlin.mock import org.mockito.kotlin.whenever fun mockDockerApplication(imageId: String, tags: Array<String>?): DockerAgentApplication { val mock = mock<DockerAgentApplication>() whenever(mock.imageId).thenReturn(imageId) whenever(mock.imageRepoTags).thenReturn(tags) return mock }
32
90
0.788603
0be4094ec9c88b491ea00f03e9587e97033d9ed4
5,404
js
JavaScript
src/app/main/registros/Registros.js
lucianoarmoa98/indufar_prospeccion_medica-campos-recetas-main
bb075c325597be524f58a74f5a8ae6a9ba59291c
[ "MIT" ]
null
null
null
src/app/main/registros/Registros.js
lucianoarmoa98/indufar_prospeccion_medica-campos-recetas-main
bb075c325597be524f58a74f5a8ae6a9ba59291c
[ "MIT" ]
null
null
null
src/app/main/registros/Registros.js
lucianoarmoa98/indufar_prospeccion_medica-campos-recetas-main
bb075c325597be524f58a74f5a8ae6a9ba59291c
[ "MIT" ]
null
null
null
// React y Redux. import React from 'react'; import {connect} from 'react-redux'; import {bindActionCreators} from 'redux'; import * as registrosActions from './store/actions'; // Material UI. import MaterialTable, {MTableToolbar} from 'material-table-hotfix-initial-page-remote-data'; // Otros. import {FusePageSimple} from '@fuse'; import {configuracionDeTabla} from './RegistrosConfig'; import { construirParametrosDePaginacion, END_POINT_REGISTROS, languageConfig } from '../UIUtils'; import {withRouter} from 'react-router-dom'; import {Paper} from '@material-ui/core'; import Button from '@material-ui/core/Button'; import BackupIcon from '@material-ui/icons/Backup'; import Footer from '../../../components/Form/Footer'; class Registros extends React.Component { _isMounted = false; constructor(props) { super(props); this.state = { selectedFile: null }; this.tableRef = React.createRef(); this.onChangeHandler = this.onChangeHandler.bind(this); } componentDidMount() { this._isMounted = true; } componentWillUnmount() { this._isMounted = false; } onChangeHandler(event) { this.props.formEditSubmit(event.target.files[0]); } render() { const { registros: {list, formEdit}, listChangePage, listChangeQuantityPerPage, setSearchValue } = this.props; const {isSubmiting, success, error} = formEdit; return ( <FusePageSimple content={ <div className="p-24"> <MaterialTable title={configuracionDeTabla.titulo} columns={configuracionDeTabla.columnas} tableRef={this.tableRef} data={query => ( new Promise(resolve => { let url = construirParametrosDePaginacion(query, END_POINT_REGISTROS); fetch(url) .then(response => response.json()) .then(result => { if (!this._isMounted) { return; } if (setSearchValue) { setSearchValue(query.search); } resolve({ data: result.data, page: result.paginaActual, totalCount: result.totalRegistros }); }); }) )} components={{ Container: props => <Paper {...props} elevation={0}/>, Toolbar: props => ( <div> <MTableToolbar {...props} /> {/*<div style={{*/} {/* display: 'flex',*/} {/* flexDirection: 'row-reverse',*/} {/* height: 56*/} {/*}}>*/} {/* <input*/} {/* id="contained-button-file"*/} {/* type="file"*/} {/* multiple*/} {/* name="file"*/} {/* onChange={this.onChangeHandler}*/} {/* style={{display: 'none'}}/>*/} {/* <label htmlFor="contained-button-file">*/} {/* <Button*/} {/* component="span"*/} {/* size='small'*/} {/* variant="contained"*/} {/* disableElevation*/} {/* style={{*/} {/* alignSelf: 'center',*/} {/* marginRight: 16*/} {/* }}*/} {/* color='secondary'*/} {/* startIcon={<BackupIcon />}>*/} {/* Importar Excel*/} {/* </Button>*/} {/* </label>*/} {/* <div style={{width: 400, marginLeft: 16, marginRight: 16}}>*/} {/* <Footer*/} {/* submitting={isSubmiting}*/} {/* error={error}*/} {/* success={success}/>*/} {/* </div>*/} {/*</div>*/} </div> ) }} onChangePage={listChangePage} onChangeRowsPerPage={listChangeQuantityPerPage} localization={languageConfig} options={{ pageSize: list.pageSize, pageSizeOptions: list.pageSizeOptions, initialPage: list.page, searchText: list.searchText, padding: 'dense', actionsColumnIndex: -1, debounceInterval: 900 }}/> </div> }/> ); } } function mapStateToProps({registros}) { return {registros}; } function mapDispatchToProps(dispatch) { return bindActionCreators( { listChangePage: registrosActions.listChangePage, listChangeQuantityPerPage: registrosActions.listChangeQuantityPerPage, setSearchValue: registrosActions.setSearchValue, changeFilterValue: registrosActions.changeFilterValue, formEditSubmit: registrosActions.formEditSubmit }, dispatch ); } export default withRouter(connect(mapStateToProps, mapDispatchToProps)(Registros));
33.358025
92
0.477979
3c0d93647e25a34855dfcad32cb778dbe7187b9c
1,089
rs
Rust
colang/src/analyzer/bodies/expressions/string_literal.rs
kodek16/colang
0328961d7e158ecdcc05f66c9633d0e89851baf2
[ "MIT" ]
3
2020-05-19T10:40:56.000Z
2021-11-19T02:05:19.000Z
colang/src/analyzer/bodies/expressions/string_literal.rs
kodek16/colang
0328961d7e158ecdcc05f66c9633d0e89851baf2
[ "MIT" ]
4
2020-05-18T16:16:36.000Z
2020-11-25T23:38:32.000Z
colang/src/analyzer/bodies/expressions/string_literal.rs
kodek16/colang
0328961d7e158ecdcc05f66c9633d0e89851baf2
[ "MIT" ]
null
null
null
use crate::context::CompilerContext; use crate::source::SourceOrigin; use crate::{ast, errors, escapes, program}; pub fn compile_string_literal_expr( expression: ast::StringLiteralExpr, context: &mut CompilerContext, ) -> program::Expression { let literal = escapes::unescape(&expression.value, expression.span); let literal = match literal { Ok(literal) => literal, Err(error) => { context.errors.push(error); return program::Expression::error(expression.span); } }; let literal = match String::from_utf8(literal) { Ok(literal) => literal, Err(_) => { let error = errors::literal_not_utf8(SourceOrigin::Plain(expression.span)); context.errors.push(error); return program::Expression::error(expression.span); } }; program::Expression::new( program::LiteralExpr { value: program::LiteralValue::String(literal), location: SourceOrigin::Plain(expression.span), }, context.program.types_mut(), ) }
31.114286
87
0.618916
1676c5f08b9cbdccaea637a74442d117553c9be7
813
c
C
minix/lib/libsys/pci_next_dev.c
calmsacibis995/minix
dfba95598f553b6560131d35a76658f1f8c9cf38
[ "Unlicense" ]
3
2021-10-07T18:19:37.000Z
2021-10-07T19:02:14.000Z
minix/lib/libsys/pci_next_dev.c
calmsacibis995/minix
dfba95598f553b6560131d35a76658f1f8c9cf38
[ "Unlicense" ]
null
null
null
minix/lib/libsys/pci_next_dev.c
calmsacibis995/minix
dfba95598f553b6560131d35a76658f1f8c9cf38
[ "Unlicense" ]
3
2021-12-02T11:09:09.000Z
2022-01-25T21:31:23.000Z
/* pci_next_dev.c */ #include "pci.h" #include "syslib.h" #include <minix/sysutil.h> /*===========================================================================* * pci_next_dev * *===========================================================================*/ int pci_next_dev(devindp, vidp, didp) int *devindp; u16_t *vidp; u16_t *didp; { int r; message m; m.m_type= BUSC_PCI_NEXT_DEV; m.m1_i1= *devindp; r= ipc_sendrec(pci_procnr, &m); if (r != 0) panic("pci_next_dev: can't talk to PCI: %d", r); if (m.m_type == 1) { *devindp= m.m1_i1; *vidp= m.m1_i2; *didp= m.m1_i3; #if 0 printf("pci_next_dev: got device %d, %04x/%04x\n", *devindp, *vidp, *didp); #endif return 1; } if (m.m_type != 0) panic("pci_next_dev: got bad reply from PCI: %d", m.m_type); return 0; }
18.477273
79
0.496925
fa18eb14d3c366b687b2b1098546c48fb8fd39d5
247
sql
SQL
src/db/migrations/00029.sql
agu3rra/InfraBox
a814e83bfc4d31292b578b2a54b27d70eafc787f
[ "Apache-2.0" ]
265
2018-04-20T21:09:06.000Z
2022-02-20T19:58:02.000Z
src/db/migrations/00029.sql
agu3rra/InfraBox
a814e83bfc4d31292b578b2a54b27d70eafc787f
[ "Apache-2.0" ]
295
2018-04-23T08:53:18.000Z
2022-03-25T07:05:11.000Z
src/db/migrations/00029.sql
agu3rra/InfraBox
a814e83bfc4d31292b578b2a54b27d70eafc787f
[ "Apache-2.0" ]
75
2018-05-14T07:56:35.000Z
2022-03-26T09:37:29.000Z
CREATE TABLE sshkey ( project_id uuid NOT NULL, id uuid DEFAULT gen_random_uuid() NOT NULL, name character varying(255) NOT NULL, secret_id uuid NOT NULL ); ALTER TABLE ONLY sshkey ADD CONSTRAINT sshkey_pkey PRIMARY KEY (id);
24.7
48
0.724696
732ca77e35362a907f50a618543b9c91b13c8315
9,647
asm
Assembly
src/main.asm
gb-archive/waveform-gb
016c923745620d2166bd24e6e9afc6bd35a89a4b
[ "MIT" ]
null
null
null
src/main.asm
gb-archive/waveform-gb
016c923745620d2166bd24e6e9afc6bd35a89a4b
[ "MIT" ]
null
null
null
src/main.asm
gb-archive/waveform-gb
016c923745620d2166bd24e6e9afc6bd35a89a4b
[ "MIT" ]
null
null
null
INCLUDE "constants.asm" KNOB_BASE_TILE EQU 0 KNOB_TRACK_TILE EQU 1 KNOB_LEFT_TILE EQU 2 KNOB_RIGHT_TILE EQU 3 KNOB_BOTH_TILE EQU 4 KNOB_START_X EQU 2 KNOB_START_Y EQU 1 NUM_COLUMNS EQU WAVE_SIZE NUM_ROWS EQU 1 << BITS_PER_WAVE_SAMPLE KNOB_HEIGHT EQU 1 KNOB_WIDTH EQU 5 NUMBER_X EQU (KNOB_START_X) - 1 NUMBER_Y EQU KNOB_START_Y FONT_BASE_TILE EQU $20 FONT_HEIGHT EQU 6 FONT_WIDTH EQU 16 HEX_BASE_TILE EQU $10 HEX_X EQU KNOB_START_X HEX_Y EQU KNOB_START_Y + NUM_ROWS HEX_HEIGHT EQU 1 HEX_WIDTH EQU 16 ARROW_TILE EQU 0 ARROW_X EQU 8 * KNOB_START_X + 6 ARROW_Y EQU 8 * (KNOB_START_Y + 1) ARROW_HEIGHT EQU 1 ARROW_WIDTH EQU 4 MIN_ARROW_POS EQU 0 MAX_ARROW_POS EQU (NUM_WAVE_SAMPLES) - 1 SECTION "Main WRAM", WRAM0 wWave:: ds WAVE_SIZE wWaveSlot:: ds 1 wCursorPos: ds 1 wKnobColumn: ds NUM_ROWS wHexTiles: ds BYTES_PER_TILE * HEX_WIDTH wNewHexTile: ds BYTES_PER_TILE SECTION "Main", ROM0 Main:: call Setup .loop call WaitVBlank call Update jr .loop Update: call Joypad ld c, 0 ld a, [wCursorPos] jbz 0, .even ld c, 1 .even srl a ldr de, a ld hl, wWave add hl, de ld a, [wJoyPressed] je D_UP, .pressedUp je D_DOWN, .pressedDown je D_LEFT, .pressedLeft je D_RIGHT, .pressedRight je START, .pressedStart ret .pressedUp ld a, [hl] jb 0, c, .skipOdd1 swap a ; skip for odd knobs .skipOdd1 and $0F je $F, .isMax inc a jb 0, c, .skipOdd2 swap a ; skip for odd knobs .skipOdd2 ld b, a ld a, [hl] jb 0, c, .skipOdd3 and $0F ; for even knobs jr .skipEven1 .skipOdd3 and $F0 ; for odd knobs .skipEven1 or b ld [hl], a jr .afterWaveChange .isMax ret .pressedDown ld a, [hl] jb 0, c, .skipOdd4 swap a ; skip for odd knobs .skipOdd4 and $0F jz .isMin dec a jb 0, c, .skipOdd5 swap a ; skip for odd knobs .skipOdd5 ld b, a ld a, [hl] jb 0, c, .skipOdd6 and $0F ; for even knobs jr .skipEven2 .skipOdd6 and $F0 ; for odd knobs .skipEven2 or b ld [hl], a jr .afterWaveChange .isMin ret .afterWaveChange call UpdateKnobTilemap_Defer call UpdateHexTile_Defer call UpdateWave call PlayNote ret .pressedLeft ld a, [wCursorPos] dec a jne (MIN_ARROW_POS) - 1, .noUnderflow ld a, MAX_ARROW_POS .noUnderflow ld [wCursorPos], a ld d, a ld e, 4 call Multiply ld bc, ARROW_X add hl, bc put [wOAM + 1], l ret .pressedRight ld a, [wCursorPos] inc a jne MAX_ARROW_POS + 1, .noOverflow ld a, MIN_ARROW_POS .noOverflow ld [wCursorPos], a ld d, a ld e, 4 call Multiply ld bc, ARROW_X add hl, bc put [wOAM + 1], l ret .pressedStart ld a, [wCursorPos] jle 8, .noHide ; push arrow oam data ld a, [wOAM + 0] push af ld a, [wOAM + 1] push af put [wOAM + 0], 0 put [wOAM + 1], 0 .noHide put [wOAM + 2], 2 ld hl, StartMenuOptions xor a call OpenMenu ld a, [wCursorPos] jle 8, .noShow ; pop arrow oam data pop af ld [wOAM + 1], a pop af ld [wOAM + 0], a .noShow put [wOAM + 2], 0 ret StartMenuOptions: dw SaveLabel, SaveAction dw LoadLabel, LoadAction dw DefaultsLabel, DefaultsAction dw CancelLabel, CancelAction dw 0 SaveLabel: db "Save...", 0 SaveAction: ld hl, SaveMenuOptions ld a, [wWaveSlot] scf call OpenMenu je -1, .cancelled ld [wWaveSlot], a .cancelled ret LoadLabel: db "Load...", 0 LoadAction: ld hl, LoadMenuOptions ld a, [wWaveSlot] scf call OpenMenu je -1, .cancelled ld [wWaveSlot], a .cancelled ret DefaultsLabel: db "Defaults...", 0 DefaultsAction: ld hl, DefaultsMenuOptions xor a call OpenMenu je -1, .cancelled call LoadDefaultAction .cancelled ret RefreshWave: call WaitForCallbacks ld a, [wCursorPos] push af put [wCursorPos], 0 ld c, NUM_COLUMNS .refreshLoop push bc call UpdateKnobTilemap_Defer call UpdateHexTile_Defer call WaitForCallbacks ld a, [wCursorPos] add 2 ld [wCursorPos], a pop bc dec c jr nz, .refreshLoop pop af ld [wCursorPos], a ret CancelLabel: db "Cancel", 0 CancelAction: ret SaveMenuOptions: dw Wave1Label, SaveWaveAction dw Wave2Label, SaveWaveAction dw Wave3Label, SaveWaveAction dw Wave4Label, SaveWaveAction dw Wave5Label, SaveWaveAction dw Wave6Label, SaveWaveAction dw Wave7Label, SaveWaveAction dw Wave8Label, SaveWaveAction ; dw CancelLabel, CancelAction dw 0 Wave1Label: db "Wave 1", 0 Wave2Label: db "Wave 2", 0 Wave3Label: db "Wave 3", 0 Wave4Label: db "Wave 4", 0 Wave5Label: db "Wave 5", 0 Wave6Label: db "Wave 6", 0 Wave7Label: db "Wave 7", 0 Wave8Label: db "Wave 8", 0 SaveWaveAction: call SaveSAV ret LoadMenuOptions: dw Wave1Label, LoadWaveAction dw Wave2Label, LoadWaveAction dw Wave3Label, LoadWaveAction dw Wave4Label, LoadWaveAction dw Wave5Label, LoadWaveAction dw Wave6Label, LoadWaveAction dw Wave7Label, LoadWaveAction dw Wave8Label, LoadWaveAction ; dw CancelLabel, CancelAction dw 0 LoadWaveAction: call LoadSAV call UpdateWave call RefreshWave call PlayNote ret DefaultsMenuOptions: dw Default1Label, LoadDefaultAction dw Default2Label, LoadDefaultAction dw Default3Label, LoadDefaultAction dw Default4Label, LoadDefaultAction dw Default5Label, LoadDefaultAction dw Default6Label, LoadDefaultAction dw Default7Label, LoadDefaultAction dw Default8Label, LoadDefaultAction ; dw CancelLabel, CancelAction dw 0 Default1Label: db "Triangle", 0 Default2Label: db "Sawtooth", 0 Default3Label: db "50% Square", 0 Default4Label: db "Sine", 0 Default5Label: db "Sine Saw", 0 Default6Label: db "Double Saw", 0 Default7Label: db "Arrow 1", 0 Default8Label: db "Arrow 2", 0 LoadDefaultAction: call LoadDefaultWave call RefreshWave call PlayNote ret UpdateWave: ld hl, wWave call LoadWave ret Setup: call InitSound put [wWaveSlot], 0 call LoadSAV call UpdateWave call DisableLCD ld bc, KnobGraphics ld de, vChars2 + KNOB_BASE_TILE * BYTES_PER_TILE ld a, KNOB_WIDTH * KNOB_HEIGHT call LoadGfx ld bc, HexGraphics ld de, wHexTiles ld a, HEX_WIDTH * HEX_HEIGHT call LoadGfx ld bc, FontGraphics ld de, vChars2 + FONT_BASE_TILE * BYTES_PER_TILE ld a, FONT_WIDTH * FONT_HEIGHT call LoadGfx ld bc, ArrowsGraphics ld de, vChars0 + ARROW_TILE * BYTES_PER_TILE ld a, ARROW_WIDTH * ARROW_HEIGHT call LoadGfx put [wCursorPos], 0 REPT NUM_COLUMNS call UpdateKnobTilemap call UpdateHexTile ld a, [wCursorPos] add 2 ld [wCursorPos], a ENDR put [wCursorPos], MIN_ARROW_POS call DrawNumberTilemap ld hl, vBGMap0 + BG_WIDTH * HEX_Y + HEX_X ld a, HEX_BASE_TILE REPT NUM_COLUMNS ld [hli], a inc a ENDR ld hl, wOAM put [hli], ARROW_Y put [hli], ARROW_X + MIN_ARROW_POS * 4 put [hli], ARROW_TILE put [hli], $00 call SetPalette call EnableLCD call PlayNote ret ; update knob tilemap and copy to vram immediately UpdateKnobTilemap: call UpdateKnobTilemap_ call CopyKnobTilemap ret ; update knob tilemap and copy to vram on vblank UpdateKnobTilemap_Defer: call UpdateKnobTilemap_ callback CopyKnobTilemap ret ; update knob tilemap by updating the current column ; clear the column, then place the left and right knob ; use KNOB_BOTH_TILE if both knobs have same value UpdateKnobTilemap_: ld hl, wKnobColumn ld a, KNOB_TRACK_TILE REPT NUM_ROWS ld [hli], a ENDR ld a, [wCursorPos] srl a ldr bc, a ld hl, wWave add hl, bc ld a, [hl] ld b, a and $0F push af ld a, b swap a and $0F ld b, a ld a, $0F sub b ld d, a ; backup ldr bc, a ld hl, wKnobColumn add hl, bc ld [hl], KNOB_LEFT_TILE pop af ld b, a ld a, $0F sub b ldr bc, a ld hl, wKnobColumn add hl, bc ld [hl], KNOB_RIGHT_TILE jne d, .different ld [hl], KNOB_BOTH_TILE .different ret ; copy the updated knob column to vram CopyKnobTilemap: ld a, [wCursorPos] srl a ldr bc, a ld hl, vBGMap0 + BG_WIDTH * KNOB_START_Y + KNOB_START_X add hl, bc ld de, wKnobColumn ld bc, BG_WIDTH REPT NUM_ROWS put [hl], [de] add hl, bc inc de ENDR ret ; update hex digit tile and copy to vram immediately UpdateHexTile: call UpdateHexTile_ call CopyHexTile ret ; update hex digit tile and copy to vram on vblank UpdateHexTile_Defer: call UpdateHexTile_ callback CopyHexTile ret ; update hex digit tile by using the values of the left ; and right knob of the current column UpdateHexTile_: ld a, [wCursorPos] srl a ldr bc, a ld hl, wWave add hl, bc ld a, [hl] push af and $F0 ld b, a pop af and $0F swap a ld hl, wHexTiles ldr de, a add hl, de push hl pop de ld a, b ld hl, wHexTiles ldr bc, a add hl, bc push hl pop bc ; combine tiles at bc and de ; left half of tile at bc gets placed in left half of tile at hl ; left half of tile at de gets placed in right half of tile at hl ld hl, wNewHexTile ld a, BYTES_PER_TILE .hexLoop push af ld a, [bc] inc bc push bc and $F0 ld b, a ld a, [de] inc de and $F0 swap a or b ld [hli], a pop bc pop af dec a jr nz, .hexLoop ret ; copy the updated hex digit tile to vram CopyHexTile: ld a, [wCursorPos] srl a swap a ldr bc, a ld hl, vChars2 + HEX_BASE_TILE * BYTES_PER_TILE add hl, bc ld de, wNewHexTile REPT BYTES_PER_TILE put [hli], [de] inc de ENDR ret ; draw the knob values to the left of the knob columns DrawNumberTilemap: ld de, .numberTilemap ld hl, vBGMap0 + BG_WIDTH * NUMBER_Y + NUMBER_X ld bc, BG_WIDTH .numberLoop ld a, [de] inc de jz .numbersDone ld [hl], a add hl, bc jr .numberLoop .numbersDone ret .numberTilemap: db "FEDCBA9876543210", 0 SetPalette: ld a, %11100100 ; quaternary: 3210 ld [rOBP0], a ld [rOBP1], a ld [rBGP], a ret KnobGraphics: INCBIN "gfx/knob.2bpp" HexGraphics: INCBIN "gfx/hex.2bpp" FontGraphics: INCBIN "gfx/font.2bpp" ArrowsGraphics: INCBIN "gfx/arrows.2bpp"
15.814754
66
0.715559
f07ba993b761298b9607592b98ecaaae352368b1
5,872
js
JavaScript
lib/MethodStubVerificator.js
egmacke/ts-mockito
96594832b7b13ae3e9136eba870751b9f9664808
[ "MIT" ]
null
null
null
lib/MethodStubVerificator.js
egmacke/ts-mockito
96594832b7b13ae3e9136eba870751b9f9664808
[ "MIT" ]
null
null
null
lib/MethodStubVerificator.js
egmacke/ts-mockito
96594832b7b13ae3e9136eba870751b9f9664808
[ "MIT" ]
null
null
null
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.MethodStubVerificator = void 0; var MethodCallToStringConverter_1 = require("./utils/MethodCallToStringConverter"); var MethodStubVerificator = (function () { function MethodStubVerificator(methodToVerify) { this.methodToVerify = methodToVerify; this.methodCallToStringConverter = new MethodCallToStringConverter_1.MethodCallToStringConverter(); } MethodStubVerificator.prototype.called = function () { this.atLeast(1); }; MethodStubVerificator.prototype.never = function () { this.times(0); }; MethodStubVerificator.prototype.once = function () { this.times(1); }; MethodStubVerificator.prototype.twice = function () { this.times(2); }; MethodStubVerificator.prototype.thrice = function () { this.times(3); }; MethodStubVerificator.prototype.times = function (value) { var allMatchingActions = this.methodToVerify.mocker.getAllMatchingActions(this.methodToVerify.name, this.methodToVerify.matchers); if (value !== allMatchingActions.length) { var methodToVerifyAsString = this.methodCallToStringConverter.convert(this.methodToVerify); var msg = "Expected \"".concat(methodToVerifyAsString, "to be called ").concat(value, " time(s). But has been called ").concat(allMatchingActions.length, " time(s)."); throw new Error("".concat(msg, "\n").concat(this.actualCalls())); } }; MethodStubVerificator.prototype.atLeast = function (value) { var allMatchingActions = this.methodToVerify.mocker.getAllMatchingActions(this.methodToVerify.name, this.methodToVerify.matchers); if (value > allMatchingActions.length) { var methodToVerifyAsString = this.methodCallToStringConverter.convert(this.methodToVerify); throw new Error("Expected \"".concat(methodToVerifyAsString, "to be called at least ").concat(value, " time(s). But has been called ").concat(allMatchingActions.length, " time(s).")); } }; MethodStubVerificator.prototype.atMost = function (value) { var allMatchingActions = this.methodToVerify.mocker.getAllMatchingActions(this.methodToVerify.name, this.methodToVerify.matchers); if (value < allMatchingActions.length) { var methodToVerifyAsString = this.methodCallToStringConverter.convert(this.methodToVerify); throw new Error("Expected \"".concat(methodToVerifyAsString, "to be called at least ").concat(value, " time(s). But has been called ").concat(allMatchingActions.length, " time(s).")); } }; MethodStubVerificator.prototype.calledBefore = function (method) { var firstMethodAction = this.methodToVerify.mocker.getFirstMatchingAction(this.methodToVerify.name, this.methodToVerify.matchers); var secondMethodAction = method.mocker.getFirstMatchingAction(method.name, method.matchers); var mainMethodToVerifyAsString = this.methodCallToStringConverter.convert(this.methodToVerify); var secondMethodAsString = this.methodCallToStringConverter.convert(method); var errorBeginning = "Expected \"".concat(mainMethodToVerifyAsString, " to be called before ").concat(secondMethodAsString); if (firstMethodAction && secondMethodAction) { if (!firstMethodAction.hasBeenCalledBefore(secondMethodAction)) { throw new Error("".concat(errorBeginning, "but has been called after.")); } } else if (firstMethodAction && !secondMethodAction) { throw new Error("".concat(errorBeginning, "but ").concat(secondMethodAsString, "has never been called.")); } else if (!firstMethodAction && secondMethodAction) { throw new Error("".concat(errorBeginning, "but ").concat(mainMethodToVerifyAsString, "has never been called.")); } else { throw new Error("".concat(errorBeginning, "but none of them has been called.")); } }; MethodStubVerificator.prototype.calledAfter = function (method) { var firstMethodAction = this.methodToVerify.mocker.getFirstMatchingAction(this.methodToVerify.name, this.methodToVerify.matchers); var secondMethodAction = method.mocker.getFirstMatchingAction(method.name, method.matchers); var mainMethodToVerifyAsString = this.methodCallToStringConverter.convert(this.methodToVerify); var secondMethodAsString = this.methodCallToStringConverter.convert(method); var errorBeginning = "Expected \"".concat(mainMethodToVerifyAsString, "to be called after ").concat(secondMethodAsString); if (firstMethodAction && secondMethodAction) { if (firstMethodAction.hasBeenCalledBefore(secondMethodAction)) { throw new Error("".concat(errorBeginning, "but has been called before.")); } } else if (firstMethodAction && !secondMethodAction) { throw new Error("".concat(errorBeginning, "but ").concat(secondMethodAsString, "has never been called.")); } else if (!firstMethodAction && secondMethodAction) { throw new Error("".concat(errorBeginning, "but ").concat(mainMethodToVerifyAsString, "has never been called.")); } else { throw new Error("".concat(errorBeginning, "but none of them has been called.")); } }; MethodStubVerificator.prototype.actualCalls = function () { var calls = this.methodToVerify.mocker.getActionsByName(this.methodToVerify.name); return "Actual calls:\n ".concat(this.methodCallToStringConverter.convertActualCalls(calls).join("\n ")); }; return MethodStubVerificator; }()); exports.MethodStubVerificator = MethodStubVerificator; //# sourceMappingURL=MethodStubVerificator.js.map
61.166667
195
0.700443
7b9de706b2f4422c27c52ee8fe83a66dac965f04
97
rb
Ruby
app/models/student_questions.rb
jehough/quizsite
01ac1f639d60be0a2b871e6682b6b7ea5fd324e9
[ "MIT" ]
1
2019-08-13T14:45:28.000Z
2019-08-13T14:45:28.000Z
app/models/student_questions.rb
jehough/quizsite
01ac1f639d60be0a2b871e6682b6b7ea5fd324e9
[ "MIT" ]
4
2020-02-26T00:09:47.000Z
2022-02-26T05:18:58.000Z
app/models/student_questions.rb
jehough/quizsite
01ac1f639d60be0a2b871e6682b6b7ea5fd324e9
[ "MIT" ]
null
null
null
class StudentQuestion < ActiveRecord::Base belongs_to :question belongs_to :student_quiz end
19.4
42
0.814433
6b83467dd76f63021ccb9b2771a02235029e1cff
206
h
C
URJapan/ViewController.h
superweiyan/URJapan
93a1754354990b51ed7800e68cf24d5acedecd3d
[ "MIT" ]
null
null
null
URJapan/ViewController.h
superweiyan/URJapan
93a1754354990b51ed7800e68cf24d5acedecd3d
[ "MIT" ]
null
null
null
URJapan/ViewController.h
superweiyan/URJapan
93a1754354990b51ed7800e68cf24d5acedecd3d
[ "MIT" ]
null
null
null
// // ViewController.h // URJapan // // Created by weiyan on 13/09/2017. // Copyright © 2017 URWY. All rights reserved. // #import <UIKit/UIKit.h> @interface ViewController : UIViewController @end
12.875
47
0.679612
f51ea74045d5aa8e7f16bc66c89fef08f2dc1661
677
lua
Lua
plugin/src/FormatScript/Vendor/Llama/List/zip.lua
howmanysmall/StyluaPlugin
a5f10432a82f68f2d746723007638e6240f759e9
[ "MIT" ]
null
null
null
plugin/src/FormatScript/Vendor/Llama/List/zip.lua
howmanysmall/StyluaPlugin
a5f10432a82f68f2d746723007638e6240f759e9
[ "MIT" ]
null
null
null
plugin/src/FormatScript/Vendor/Llama/List/zip.lua
howmanysmall/StyluaPlugin
a5f10432a82f68f2d746723007638e6240f759e9
[ "MIT" ]
null
null
null
local Debug = require(script.Parent.Parent.Parent.Debug) local Typer = require(script.Parent.Parent.Parent.Typer) local Debug_Assert = Debug.Assert local Typer_Array = Typer.Array local function zip(...) local new = {} local argCount = select("#", ...) if argCount <= 0 then return new end local firstList = Debug_Assert(Typer_Array(select(1, ...))) local minLen = #firstList for i = 2, argCount do local list = Debug_Assert(Typer_Array(select(i, ...))) local len = #list if len < minLen then minLen = len end end for i = 1, minLen do new[i] = {} for j = 1, argCount do new[i][j] = select(j, ...)[i] end end return new end return zip
17.358974
60
0.661743
3e3ec1a50679a25089373338095fad715f9a5bea
9,884
h
C
contrib/removedInCortex9/attributeCache/include/IECore/InterpolatedCache.h
goddardl/cortex
323a160fd831569591cde1504f415a638f8b85bc
[ "BSD-3-Clause" ]
null
null
null
contrib/removedInCortex9/attributeCache/include/IECore/InterpolatedCache.h
goddardl/cortex
323a160fd831569591cde1504f415a638f8b85bc
[ "BSD-3-Clause" ]
null
null
null
contrib/removedInCortex9/attributeCache/include/IECore/InterpolatedCache.h
goddardl/cortex
323a160fd831569591cde1504f415a638f8b85bc
[ "BSD-3-Clause" ]
1
2020-09-26T01:15:37.000Z
2020-09-26T01:15:37.000Z
////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2007-2011, Image Engine Design Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // * Neither the name of Image Engine Design nor the names of any // other contributors to this software may be used to endorse or // promote products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////// #ifndef IECORE_INTERPOLATEDCACHE_H #define IECORE_INTERPOLATEDCACHE_H #include "IECore/Export.h" #include "IECore/AttributeCache.h" #include "IECore/OversamplesCalculator.h" namespace IECore { IE_CORE_FORWARDDECLARE( FileSequence ); /// Provides higher level access to cache files by automatically interpolating data from multiple files. /// Or returns the data from the nearest frame if the data cannot be interpolated. /// The interface looks like AttributeCache reader functions. /// \threading This class provides limited thread safety. The methods which specify the caches /// to be read are not safe to call while other threads are operating on the object. However, once /// the caches have been specified it is safe to call the read methods from multiple concurrent threads and /// with multiple different frame arguments. See the documentation of the individual methods for more details. /// \todo It might be great to pass interpolation and oversamples calculator to each read method rather /// than have them store as state. This would allow different interpolation and oversampling per call and per thread. /// If we did this I think we should look at replacing the OversamplesCalculator class with some more sensible /// Time or TimeSampler class, and passing everything in one argument. /// \ingroup ioGroup class IECORE_API InterpolatedCache : public RefCounted { public : typedef IECore::AttributeCache::ObjectHandle ObjectHandle; typedef IECore::AttributeCache::HeaderHandle HeaderHandle; typedef IECore::AttributeCache::AttributeHandle AttributeHandle; IE_CORE_DECLAREMEMBERPTR( InterpolatedCache ); enum Interpolation { None = 0, Linear, Cubic }; /// Constructor /// pathTemplate must be a valid FileSequence filename specifier, e.g. "myCacheFile.####.cob" InterpolatedCache( const std::string &pathTemplate = "", Interpolation interpolation = None, const OversamplesCalculator &o = OversamplesCalculator(), size_t maxOpenFiles = 10 ); ~InterpolatedCache(); /// Changes the path template for cache files. /// \threading It is not safe to call this method while other threads are accessing /// this object. void setPathTemplate( const std::string &pathTemplate ); /// Returns the current path template used to open cache files. /// \threading It is safe to call this method while other threads are calling const /// methods of this class. const std::string &getPathTemplate() const; /// Sets the maximum number of caches this class will keep open at one time. /// \threading It is not safe to call this method while other threads are accessing /// this object. void setMaxOpenFiles( size_t maxOpenFiles ); /// Returns the maximum number of caches this class will keep open at one time. /// \threading It is safe to call this method while other threads are calling const /// methods of this class. size_t getMaxOpenFiles() const; /// Sets the interpolation method. /// \threading It is not safe to call this method while other threads are accessing /// this object. void setInterpolation( Interpolation interpolation ); /// Returns the current interpolation method. /// \threading It is safe to call this method while other threads are calling const /// methods of this class. Interpolation getInterpolation() const; /// Sets the OversamplesCalculator. /// \threading It is not safe to call this method while other threads are accessing /// this object. void setOversamplesCalculator( const OversamplesCalculator & ); /// Returns the current OversamplesCalculator. /// \threading It is safe to call this method while other threads are calling const /// methods of this class. const OversamplesCalculator &getOversamplesCalculator() const; /// Read a piece of data associated with the specified object and attribute from the cache. /// Throws an exception if the requested data is not present in the cache or if the cache file is not found. /// \threading It is safe to call this method while other threads are calling const /// methods of this class. ObjectPtr read( float frame, const ObjectHandle &obj, const AttributeHandle &attr ) const; /// Read a piece of data associated with the specified object from the cache. /// Returns a CompoundObject with attribute as keys. /// Throws an exception if the requested data is not present in the cache or if the cache file is not found. /// \threading It is safe to call this method while other threads are calling const /// methods of this class. CompoundObjectPtr read( float frame, const ObjectHandle &obj ) const; /// Read data associated with the specified header from the open cache files. /// The result will be interpolated whenever possible. Objects not existent in /// every opened file will not be interpolated and will be returned if they come from the nearest frame. /// Throws an exception if the requested header is not present in the cache or if the cache file is not found. /// \threading It is safe to call this method while other threads are calling const /// methods of this class. ObjectPtr readHeader( float frame, const HeaderHandle &hdr ) const; /// Creates a CompoundObject with the header names as keys. /// Read all header data present in the open cache files. The result will be /// interpolated whenever possible. Objects not existent in every opened file will not be interpolated and /// will be returned if they come from the nearest frame. /// Throws an exception if the cache file is not found. /// \threading It is safe to call this method while other threads are calling const /// methods of this class. CompoundObjectPtr readHeader( float frame ) const; /// Retrieve the list of object handles from the cache /// Throws an exception if the cache file is not found. /// \threading It is safe to call this method while other threads are calling const /// methods of this class. void objects( float frame, std::vector<ObjectHandle> &objs ) const; /// Retrieve the list of header handles from the cache (from the nearest frame). /// Throws an exception if the cache file is not found. /// \threading It is safe to call this method while other threads are calling const /// methods of this class. void headers( float frame, std::vector<HeaderHandle> &hds ) const; /// Retrieve the list of attribute handles from the specified objects. /// Throws an exception if the object is not within the cache or the cache file is not found. /// \threading It is safe to call this method while other threads are calling const /// methods of this class. void attributes( float frame, const ObjectHandle &obj, std::vector<AttributeHandle> &attrs ) const; /// Retrieve the list of attribute handles that match the given regex from the specified objects. /// Throws an exception if the object is not within the cache or the cache file is not found. /// \threading It is safe to call this method while other threads are calling const /// methods of this class. void attributes( float frame, const ObjectHandle &obj, const std::string regex, std::vector<AttributeHandle> &attrs ) const; /// Determines whether or not the cache contains the specified object /// Throws an exception if the cache file is not found. /// \threading It is safe to call this method while other threads are calling const /// methods of this class. bool contains( float frame, const ObjectHandle &obj ) const; /// Determines whether or not the cache contains the specified object and attribute /// Throws an exception if the cache file is not found. /// \threading It is safe to call this method while other threads are calling const /// methods of this class. bool contains( float frame, const ObjectHandle &obj, const AttributeHandle &attr ) const; private : IE_CORE_FORWARDDECLARE( Implementation ); ImplementationPtr m_implementation; }; IE_CORE_DECLAREPTR( InterpolatedCache ); } // namespace IECore #endif // IECORE_INTERPOLATEDCACHE_H
48.930693
126
0.737859
f595b6b57244149a1962be9135a6d44ec41ef483
854
css
CSS
style/css/onlyMypage.css
tech-is/Kinstagram
046fa7156e14740260123ee364f2bba28d5584fa
[ "MIT" ]
null
null
null
style/css/onlyMypage.css
tech-is/Kinstagram
046fa7156e14740260123ee364f2bba28d5584fa
[ "MIT" ]
73
2020-12-19T05:36:55.000Z
2021-04-11T02:38:32.000Z
style/css/onlyMypage.css
tech-is/Kinstagram
046fa7156e14740260123ee364f2bba28d5584fa
[ "MIT" ]
null
null
null
/* application/public/style.css*/ /* cssやjsを外部リンクで読みだす時にはcodeigniterの直下にフォルダを作成しそこにファイルを格納する */ body{ margin: 0 auto; /*中央寄せ*/ } .profile-inline{ width:100%; height:auto; margin: 0 auto; /*中央寄せ*/ text-align: center; } .profile-img img{ width: 170px; height: 170px; object-fit: cover; border-radius: 5%; background-color: #CFCFCF; } .user_name > p { font-size: 18px; color: #CFCFCF; text-align: center; } .new-primary{ background-color: #02A5EB; color:#CFCFCF; } .bg-black{ background-color: black; color:#CFCFCF; } .bg-gray { background-color: #A0A09F; } .img-list { width: 100%; height:auto; margin:auto; } .img-list img {padding: 2px;box-sizing: border-box;width:33%;height: 320px;object-fit: cover;} .mainPhotflame{ margin: 5%; }
16.745098
95
0.611241
0b6861770f6d11f0e6e5144b7f72620064b17922
2,217
py
Python
Tools/Scripts/Python/module_Basemap_RegCM_domain.py
taobrienlbl/RegCM
bda1c78790f0a1501916d0979b843216a08b2cef
[ "AFL-1.1" ]
27
2019-04-23T08:36:25.000Z
2021-11-15T08:55:01.000Z
Tools/Scripts/Python/module_Basemap_RegCM_domain.py
taobrienlbl/RegCM
bda1c78790f0a1501916d0979b843216a08b2cef
[ "AFL-1.1" ]
9
2020-02-20T06:43:03.000Z
2021-09-24T11:26:46.000Z
Tools/Scripts/Python/module_Basemap_RegCM_domain.py
taobrienlbl/RegCM
bda1c78790f0a1501916d0979b843216a08b2cef
[ "AFL-1.1" ]
17
2019-06-10T12:49:05.000Z
2021-11-14T06:55:20.000Z
#!/usr/bin/python2.6 """ Here a comment starts, with 3 quotation marks. In the same way, the comment ends ... Purpose: Draw a base map of the CORDEX domain Selected projection: Lambert Conformal Projection Date: Sept. 26, 2018 Author: S. STRADA REFERENCES: Basemap Tool http://basemaptutorial.readthedocs.org/en/latest/index.html https://matplotlib.org/basemap/ """ ###################################################### # Import modules you need #----------------------------------------------------- from mpl_toolkits.basemap import Basemap, cm import matplotlib.pyplot as plt import numpy as np ###################################################### ### Python fuction to build a map using a specific projection #----------------------------------------------------- def map_RegCMdomain(ax, lat_start, lat_end, lon_start, lon_end, lon0, lat0, fontsize, dparall, dmerid): """ How to call the function in a script to create a basemap object : 1. Import function to create the domain from module_RegCM_domain import basemap_RegCMdomain 2. Call the function and pass to it all needed variables map = map_RegCMdomain(ax, lat_start, lat_end, lon_start, lon_end, lon_end, lon_0, lat0, fontsize)) Setup Miller Cyclindrical Projection --> llcrnrlat,llcrnrlon,urcrnrlat,urcrnrlon are the lat/lon values of the lower left and upper right corners of the map --> resolution = 'i' means intermediate coastline resolution --> area_thresh=1000 means don't plot coastline features less than 1000 km^2 in area (pay attention to this if you need to plot small islands!) """ m = Basemap(ax=ax, llcrnrlon=lon_start, llcrnrlat=lat_start, urcrnrlon=lon_end, urcrnrlat=lat_end, resolution='i', area_thresh=1000., projection='mill', lon_0=lon0, lat_0=lat0, lat_ts=0) m.drawcoastlines(color='k',linewidth=1, zorder=10) m.drawcountries(color='k',linewidth=0.5, zorder=11) m.drawparallels(range(-90, 90, dparall), labels=[1,0,0,0], fontsize=fontsize, dashes=[1, 2],linewidth=1, color='k', zorder=12) m.drawmeridians(range(-180, 180, dmerid),labels=[0,0,0,1], fontsize=fontsize, dashes=[1, 2],linewidth=1, color='k', zorder=12) return m
41.830189
145
0.656292
7b9189120f735679e039b1aaa6d6b34f75fd6b1f
797
rb
Ruby
lib/opal/nodes/args/extract_block_arg.rb
ahmadine/opal
21ae8e92136fb7acd112cd1bac775daab40b8edd
[ "MIT" ]
2,849
2015-01-01T04:53:23.000Z
2022-03-30T12:00:20.000Z
lib/opal/nodes/args/extract_block_arg.rb
kachick/opal
96b55a33cf6472d33803c10116e983c67595e74f
[ "MIT" ]
1,456
2015-01-01T22:40:04.000Z
2022-03-31T08:04:20.000Z
lib/opal/nodes/args/extract_block_arg.rb
kachick/opal
96b55a33cf6472d33803c10116e983c67595e74f
[ "MIT" ]
312
2015-01-06T17:50:48.000Z
2022-03-25T01:26:49.000Z
# frozen_string_literal: true require 'opal/nodes/base' module Opal module Nodes module Args # Compiles extraction of the block argument # def m(&block); end # ^^^^^^ # # This node doesn't exist in the original AST, # InlineArgs rewriter creates it to simplify compilation class ExtractBlockarg < Base handle :extract_blockarg children :name def compile scope.uses_block! scope.add_arg name scope.block_name = name scope_name = scope.identity yielder = scope.block_name add_temp "$iter = #{scope_name}.$$p" add_temp "#{yielder} = $iter || nil" line "if ($iter) #{scope_name}.$$p = null;" end end end end end
22.771429
62
0.570891
183f992cdb7463c2558108e17b4736ff98f0f958
16,410
asm
Assembly
libsrc/_DEVELOPMENT/math/float/math32/z80/d32_fsadd.asm
rjcorrig/z88dk
c49c26bb232c17ea5a45d21bb81b6343572b7f4c
[ "ClArtistic" ]
null
null
null
libsrc/_DEVELOPMENT/math/float/math32/z80/d32_fsadd.asm
rjcorrig/z88dk
c49c26bb232c17ea5a45d21bb81b6343572b7f4c
[ "ClArtistic" ]
null
null
null
libsrc/_DEVELOPMENT/math/float/math32/z80/d32_fsadd.asm
rjcorrig/z88dk
c49c26bb232c17ea5a45d21bb81b6343572b7f4c
[ "ClArtistic" ]
null
null
null
; ; Copyright (c) 2015 Digi International Inc. ; ; This Source Code Form is subject to the terms of the Mozilla Public ; License, v. 2.0. If a copy of the MPL was not distributed with this ; file, You can obtain one at http://mozilla.org/MPL/2.0/. ; ; feilipu, 2019 April ; adapted for z80, z180, and z80-zxn ; ;------------------------------------------------------------------------- ; m32_fsadd - z80, z180, z80-zxn floating point add ; m32_fssub - z80, z180, z80-zxn floating point subtract ;------------------------------------------------------------------------- ; 1) first section: unpack from F_add: to sort: ; one unpacked number in hldebc the other in hl'de'bc' ; unpacked format: h==0; mantissa= lde, sign in b, exponent in c ; in addition af' holds b xor b' used to test if add or sub needed ; ; 2) second section: sort from sort to align, sets up smaller number in hldebc and larger in hl'de'bc' ; This section sorts out the special cases: ; to alignzero - if no alignment (right) shift needed ; alignzero has properties: up to 23 normalize shifts needed if signs differ ; not know which mantissa is larger for different signs until sub performed ; no alignment shifts needed ; to alignone - if one alignment shift needed ; alignone has properties: up to 23 normalize shifts needed if signs differ ; mantissa aligned is always smaller than other mantissa ; one alignment shift needed ; to align - 2 to 23 alignment shifts needed ; numbers aligned 2-23 have properties: max of 1 normalize shift needed ; mantissa aligned always smaller ; 2-23 alignment shifts needed ; number too small to add, return larger number (to doadd1) ; ; 3) third section alignment - aligns smaller number mantissa with larger mantissa ; This section does the right shift. Lost bits shifted off, are tested. Up to 8 lost bits ; are used for the test. If any are non-zero a one is or'ed into remaining mantissa bit 0. ; align 2-23 - worst case right shift by 7 with lost bits ; 4) 4th section add or subtract ; ; 5) 5th section post normalize ; ; 6) 6th section pack up ; ;------------------------------------------------------------------------- ; FIXME clocks ;------------------------------------------------------------------------- SECTION code_clib SECTION code_math PUBLIC m32_fssub, m32_fssub_callee PUBLIC m32_fsadd, m32_fsadd_callee PUBLIC m32_fsnormalize ; enter here for floating subtract, x-y x on stack, y in dehl .m32_fssub ld a,d ; toggle the sign bit for subtraction xor 080h ld d,a ; enter here for floating add, x+y, x on stack, y in bcde, result in bcde .m32_fsadd ex de,hl ; DEHL -> HLDE ld b,h ; place op1.s in b[7] add hl,hl ; unpack op1 ld c,h ; save op1.e in c ld a,h or a jr Z,faunp1 ; add implicit bit if op1.e!=0 scf .faunp1 rr l ; rotate in op1.m's implicit bit ld a,b ; place op1.s in a[7] exx ld hl,002h ; get second operand off of the stack add hl,sp ld e,(hl) inc hl ld d,(hl) inc hl ld c,(hl) inc hl ld h,(hl) ld l,c ; hlde = seeeeeee emmmmmmm mmmmmmmm mmmmmmmm jp farejoin ; enter here for floating subtract callee, x-y x on stack, y in dehl .m32_fssub_callee ld a,d ; toggle the sign bit for subtraction xor 080h ld d,a ; enter here for floating add callee, x+y, x on stack, y in bcde, result in bcde .m32_fsadd_callee ex de,hl ; DEHL -> HLDE ld b,h ; place op1.s in b[7] add hl,hl ; unpack op1 ld c,h ; save op1.e in c ld a,h or a jr Z,faunp1_callee ; add implicit bit if op1.e!=0 scf .faunp1_callee rr l ; rotate in op1.m's implicit bit ld a,b ; place op1.s in a[7] exx pop bc ; pop return address pop de ; get second operand off of the stack pop hl ; hlde = seeeeeee emmmmmmm mmmmmmmm mmmmmmmm push bc ; return address on stack .farejoin ld b,h ; save op2.s in b[7] add hl,hl ; unpack op2 ld c,h ; save op2.e in c xor b ; check if op1.s==op2.s ex af,af ; save results sign in f' (C clear in af') ld a,h or a jr Z,faunp2 ; add implicit bit if op2.e!=0 scf .faunp2 rr l ; rotate in op2.m's implicit bit xor a ld h,a ; op2 mantissa: h = 00000000, lde = 1mmmmmmm mmmmmmmm mmmmmmmm exx ld h,a ; op1 mantissa: h = 00000000, lde = 1mmmmmmm mmmmmmmm mmmmmmmm ; sort larger from smaller and compute exponent difference .sort ld a,c exx cp a,c ; nc if a>=c jp Z,alignzero ; no alignment mantissas equal jr NC,sort2 ; if a larger than c ld a,c exx .sort2 sub a,c ; positive difference in a cp a,1 ; if one difference, special case jp Z,alignone ; smaller mantissa on top cp a,24 ; check for too many shifts jr C,align ; if 23 or fewer shifts ; use other side, adding small quantity that can be ignored exx jp doadd1 ; pack result ; align begin align count zero .align or a rra jr NC,al_2 srl h rr l rr d rr e .al_2 rra ; 1st lost bit to a jr NC,al_3 srl h rr l rr d rr e rr h rr l rr d rr e .al_3 rra ; 2nd lost bit to a jr NC,al_4 srl h rr l rr d rr e rr h rr l rr d rr e rr h rr l rr d rr e rr h rr l rr d rr e ; check for 8 bit right shift .al_4 rra ; 3rd lost bit to a check shift by 8, jr NC,al_5 ; shift by 8 right, no 16 possible ld a,e ; lost bits, keep only 8 ld e,d ld d,l ld hl,0 ; upper zero or a ; test lost bits jr Z,aldone set 0,e ; lost bits jr aldone ; here possible 16 .al_5 rra ; shift in a zero, lost bits in 6,5,4 jr NC,al_6 ; no shift by 16 ; here shift by 16 ; toss lost bits in a which are remote for 16 shift ; consider only lost bits in d and h ld e,l ld a,d ; lost bits ld d,0 or a,h ld h,d ; hl zero ld l,d jr Z,aldone set 0,e ; lost bits jr aldone ; here no 8 or 16 shift, lost bits in a-reg bits 6,5,4, other bits zero's .al_6 or a,h ; more lost bits ld h,0 jr Z,aldone set 0,e ; aldone here .aldone ex af,af ; carry clear jp P,doadd ; here for subtract, smaller shifted right at least 2, so no more than ; one step of normalize push hl exx ex de,hl ex (sp),hl ex de,hl exx pop hl ; subtract the mantissas sbc hl,de exx sbc hl,de push de exx ex (sp),hl exx pop de ; difference larger-smaller in hlde ; exponent of result in c sign of result in b bit 7,l ; check for norm jr NZ,doadd1 ; no normalize step, pack it up or a sla e rl d adc hl,hl dec c jr doadd1 ; pack ; here for do add c has exponent of result (larger) b or b' has sign .doadd push hl exx ex de,hl ex (sp),hl ex de,hl exx pop hl ; add the mantissas add hl,de exx adc hl,de push de exx ex (sp),hl exx pop de ; get least of sum xor a or a,h ; see if overflow to h jr Z,doadd1 rr h rr l rr d rr e jr NC,doadd0 set 0,e .doadd0 inc c jr Z,foverflow .doadd1 ; now pack result add hl,hl ld h,c ; exp rl b rr h rr l ex de,hl ; return DEHL ret .foverflow ld a,b and 080h or 07fh ld d,a ld e,0ffh ld hl,0ffffh ; max number scf ; error ret ; here one alignment needed .alignone ; from fadd rr h rr l rr d rr e jr NC,alignone_a set 0,e .alignone_a ex af,af jp M,fasub jr doadd .alignzero ex af,af jp P,doadd ; here do subtract ; enter with aligned, smaller in hlde, exp of result in c' ; sign of result in b' ; larger number in hl'de' ; c is clear .fasub push hl exx ex de,hl ex (sp),hl ex de,hl exx pop hl ; subtract the mantissas sbc hl,de exx sbc hl,de jr NC,noneg ; *** what if zero ; fix up and subtract in reverse direction exx ld a,b ; get reversed sign add hl,de ; reverse sub exx adc hl,de ; reverse sub exx ex de,hl or a sbc hl,de exx ex de,hl sbc hl,de ld b,a ; get proper sign to result .noneg push de exx ex (sp),hl exx pop de ; get least part of result ; sub zero alignment from fadd ; difference larger-smaller in hlde ; exponent of result in c sign of result in b ; now do normalize scf ex af,af ; if no C an alternate exit is taken ; enter here with af' carry clear for float functions m32_float32, m32_float32u .m32_fsnormalize ; now begin normalize xor a or a,l jr Z,fa8a and 0f0h jp Z,S24L ; shift 24 bits, most significant in low nibble jr S24H ; shift 24 bits in high .fa8a xor a or a,d jr Z,fa8b and 0f0h jp Z,S16L ; shift 16 bits, most significant in low nibble jp S16H ; shift 16 bits in high .fa8b xor a or a,e jp Z,normzero ; all zeros and 0f0h jp Z,S8L ; shift 8 bits, most significant in low nibble jp S8H ; shift 8 bits in high .S24H ; shift 24 bits 0 to 3 left, count in c sla e rl d rl l jr C,S24H1 sla e rl d rl l jr C,S24H2 sla e rl d rl l jr C,S24H3 ld a,-3 ; count jr normdone1 ; from normalize .S24H1 rr l rr d rr e ; reverse overshift ld a,c ; zero adjust jr normdone1_a .S24H2 rr l rr d rr e ld a,-1 jr normdone1 .S24H3 rr l rr d rr e ld a,-2 jr normdone1 .S24L ; shift 24 bits 4-7 left, count in C sla e rl d rl l sla e rl d rl l sla e rl d rl l ld a,0f0h and a,l jp Z,S24L4more ; if still no bits in high nibble, total of 7 shifts sla e rl d rl l ; 0, 1 or 2 shifts possible here sla e rl d rl l jr C,S24Lover1 sla e rl d rl l jr C,S24Lover2 ; 6 shift case ld a,-6 jr normdone1 .S24L4more sla e rl d rl l sla e rl d rl l sla e rl d rl l sla e rl d rl l ld a,-7 jr normdone1 .S24Lover1 ; total of 4 shifts rr l rr d rr e ; correct overshift ld a,-4 jr normdone1 .S24Lover2 ; total of 5 shifts rr l rr d rr e ld a,-5 ; this is the very worst case, drop through to .normdone1 ; enter here to continue after normalize ; this path only on subtraction ; a has left shift count, lde has mantissa, c has exponent before shift ; b has original sign of larger number ; .normdone1 ; worst case from align to here add a,c ; exponent of result jr NC,normzero ; if underflow return zero .normdone1_a ; case of zero shift rl l rl b ; sign rra rr l ld h,a ; exponent ex de,hl ; return DEHL ex af,af ret .normzero ; return zero ld hl,0 ld d,h ld e,l ex af,af ret ; all bits in lower 4 bits of e (bits 0-3 of mantissa) ; shift 8 bits 4-7 bits left ; e, l, d=zero .S8L sla e sla e sla e ld a,0f0h and a,e jp Z,S8L4more ; if total is 7 sla e ; guaranteed sla e ; 5th shift jr C,S8Lover1 ; if overshift sla e ; the shift jr C,S8Lover2 ; total of 6, case 7 already handled ld l,e ld e,d ; zero ld a,-22 jr normdone1 .S8Lover1 ; total of 4 rr e ld l,e ld e,d ; zero ld a,-20 jr normdone1 .S8Lover2 ; total of 5 rr e ld l,e ld e,d ; zero ld a,-21 jr normdone1 .S8L4more sla e sla e sla e sla e ld l,e ld e,d ; zero ld a,-23 jr normdone1 ; shift 16 bit fraction by 4-7 ; l is zero, 16 bits number in de .S16L sla e rl d sla e rl d sla e rl d ; 3 shifts ld a,0f0h and a,d jp Z,S16L4more ; if still not bits n upper after 3 sla e rl d ; guaranteed shift 4 jp M,S16L4 ; complete at 4 sla e rl d jp M,S16L5 ; complete at 5 sla e rl d ; 6 shifts, case of 7 already taken care of must be good ld a,-14 ld l,d ld d,e ld e,0 jp normdone1 .S16L4 ld a,-12 ld l,d ld d,e ld e,0 jp normdone1 .S16L5 ; for total of 5 shifts left ld a,-13 ld l,d ld d,e ld e,0 jp normdone1 .S16L4more sla e rl d sla e rl d sla e rl d sla e rl d ld l,d ld d,e ld e,0 ld a,-15 jp normdone1 ; ; worst case 68 to get past this section ; shift 0-3, l is zero , 16 bits in de ; .S16H sla e rl d jr C,S16H1 ; if zero jp M,S16H2 ; if 1 shift sla e rl d jp M,S16H3 ; if 2 ok ; must be 3 sla e rl d ld l,d ld d,e ld e,0 ld a,-11 jp normdone1 .S16H1 ; overshift rr d rr e ld l,d ld d,e ld a,-8 ld e,0 jp normdone1 .S16H2 ; one shift ld l,d ld d,e ld a,-9 ld e,0 jp normdone1 .S16H3 ld l,d ld d,e ld a,-10 ld e,0 jp normdone1 ; shift 8 left 0-3 ; number in e, l, d==zero .S8H sla e jr C,S8H1 ; jump if bit found in data sla e jr C,S8H2 sla e jr C,S8H3 ; 3 good shifts, number in a shifted left 3 ok ld l,e ld e,d ; zero ld a,-19 jp normdone1 .S8H1 rr e ; correct overshift ld l,e ld e,d ld a,-16 ; zero shifts jp normdone1 .S8H2 rr e ; correct overshift ld l,e ld e,d ld a,-17 ; one shift jp normdone1 .S8H3 rr e ; correct overshift ld l,e ld e,d ld a,-18 jp normdone1 ; worst case S8H
23.080169
111
0.4844
e8e12c70a26b28e73712420fd03691434cb4267c
13,354
py
Python
adversarial-transfer-nlp/CW_attack.py
AI-secure/Uncovering-the-Connections-BetweenAdversarial-Transferability-and-Knowledge-Transferability
a2fb10f56618c6d6dd1638967d59c4a83ffa1c05
[ "CC0-1.0" ]
8
2021-06-18T10:32:27.000Z
2022-01-16T06:46:25.000Z
adversarial-transfer-nlp/CW_attack.py
AI-secure/Does-Adversairal-Transferability-Indicate-Knowledge-Transferability
a2fb10f56618c6d6dd1638967d59c4a83ffa1c05
[ "CC0-1.0" ]
2
2021-08-25T15:14:12.000Z
2022-02-09T23:55:46.000Z
adversarial-transfer-nlp/CW_attack.py
AI-secure/Does-Adversairal-Transferability-Indicate-Knowledge-Transferability
a2fb10f56618c6d6dd1638967d59c4a83ffa1c05
[ "CC0-1.0" ]
null
null
null
import sys import torch import numpy as np from torch import optim from util import args class CarliniL2: def __init__(self, targeted=True, search_steps=None, max_steps=None, cuda=True, debug=False, num_classes=14): self.debug = debug self.targeted = targeted self.num_classes = num_classes self.confidence = args.confidence # FIXME need to find a good value for this, 0 value used in paper not doing much... self.initial_const = args.const # bumped up from default of .01 in reference code self.binary_search_steps = search_steps or 1 self.repeat = self.binary_search_steps >= 10 self.max_steps = max_steps or args.max_steps self.abort_early = True self.cuda = cuda self.mask = None self.batch_info = None self.wv = None self.seq = None self.seq_len = None self.init_rand = False # an experiment, does a random starting point help? def _compare(self, output, target): if not isinstance(output, (float, int, np.int64)): output = np.copy(output) # if self.targeted: # output[target] -= self.confidence # else: # output[target] += self.confidence output = np.argmax(output) if self.targeted: return output == target else: return output != target def _compare_untargeted(self, output, target): if not isinstance(output, (float, int, np.int64)): output = np.copy(output) # if self.targeted: # output[target] -= self.confidence # else: # output[target] += self.confidence output = np.argmax(output) if self.targeted: return output == target + 1 or output == target - 1 else: return output != target def _loss(self, output, target, dist, scale_const): # compute the probability of the label class versus the maximum other real = (target * output).sum(1) other = ((1. - target) * output - target * 10000.).max(1)[0] if self.targeted: # if targeted, optimize for making the other class most likely loss1 = torch.clamp(other - real + self.confidence, min=0.) # equiv to max(..., 0.) else: # if non-targeted, optimize for making this class least likely. loss1 = torch.clamp(real - other + self.confidence, min=0.) # equiv to max(..., 0.) loss1 = torch.sum(scale_const * loss1) loss2 = dist.sum() if args.debug_cw: print("loss 1:", loss1.item(), " loss 2:", loss2.item()) loss = loss1 + loss2 return loss def _optimize(self, optimizer, model, input_var, modifier_var, target_var, scale_const_var, input_token=None): # apply modifier and clamp resulting image to keep bounded from clip_min to clip_max batch_adv_sent = [] if self.mask is None: # not word-level attack input_adv = modifier_var + input_var output = model(input_adv) input_adv = model.get_embedding() input_var = input_token seqback = model.get_seqback() batch_adv_sent = seqback.adv_sent.copy() seqback.adv_sent = [] # input_adv = self.itereated_var = modifier_var + self.itereated_var else: # word level attack input_adv = modifier_var * self.mask + self.itereated_var # input_adv = modifier_var * self.mask + input_var for i in range(input_adv.size(0)): # for batch size new_word_list = [] add_start = self.batch_info['add_start'][i] add_end = self.batch_info['add_end'][i] if add_end < 0: add_end = len(input_adv[i]) - 1 for j in range(add_start, add_end): new_placeholder = input_adv[i, j].data temp_place = new_placeholder.expand_as(self.wv) new_dist = torch.norm(temp_place - self.wv.data, 2, -1) _, new_word = torch.min(new_dist, 0) new_word_list.append(new_word.item()) # input_adv.data[j, i] = self.wv[new_word.item()].data input_adv.data[i, j] = self.itereated_var.data[i, j] = self.wv[new_word.item()].data del temp_place batch_adv_sent.append(new_word_list) output = model(self.seq, self.batch_info['segment_ids'], self.batch_info['input_mask'], inputs_embeds=input_adv) if args.debug_cw: print("output:", batch_adv_sent) print("input_adv:", input_adv) print("output:", output) adv_seq = torch.tensor(self.seq) for bi, (add_start, add_end) in enumerate(zip(self.batch_info['add_start'], self.batch_info['add_end'])): adv_seq.data[bi, add_start:add_end] = torch.LongTensor(batch_adv_sent) print("out:", adv_seq) print("out embedding:", model.bert.embeddings.word_embeddings(adv_seq)) out = model(adv_seq, self.seq_len)['pred'] print("out:", out) def reduce_sum(x, keepdim=True): # silly PyTorch, when will you get proper reducing sums/means? for a in reversed(range(1, x.dim())): x = x.sum(a, keepdim=keepdim) return x def l1_dist(x, y, keepdim=True): d = torch.abs(x - y) return reduce_sum(d, keepdim=keepdim) def l2_dist(x, y, keepdim=True): d = (x - y) ** 2 return reduce_sum(d, keepdim=keepdim) # distance to the original input data if args.l1: dist = l1_dist(input_adv, input_var, keepdim=False) else: dist = l2_dist(input_adv, input_var, keepdim=False) loss = self._loss(output, target_var, dist, scale_const_var) if args.debug_cw: print(loss) optimizer.zero_grad() if input_token is None: loss.backward() else: loss.backward(retain_graph=True) torch.nn.utils.clip_grad_norm_([modifier_var], args.clip) # print(modifier_var) optimizer.step() # print(modifier_var) # modifier_var.data -= 2 * modifier_var.grad.data # modifier_var.grad.data.zero_() loss_np = loss.item() dist_np = dist.data.cpu().numpy() output_np = output.data.cpu().numpy() input_adv_np = input_adv.data.cpu().numpy() return loss_np, dist_np, output_np, input_adv_np, batch_adv_sent def run(self, model, input, target, batch_idx=0, batch_size=None, input_token=None): if batch_size is None: batch_size = input.size(0) # ([length, batch_size, nhim]) # set the lower and upper bounds accordingly lower_bound = np.zeros(batch_size) scale_const = np.ones(batch_size) * self.initial_const upper_bound = np.ones(batch_size) * 1e10 # python/numpy placeholders for the overall best l2, label score, and adversarial image o_best_l2 = [1e10] * batch_size o_best_score = [-1] * batch_size o_best_logits = {} if input_token is None: best_attack = input.cpu().detach().numpy() o_best_attack = input.cpu().detach().numpy() else: best_attack = input_token.cpu().detach().numpy() o_best_attack = input_token.cpu().detach().numpy() self.o_best_sent = {} self.best_sent = {} # setup input (image) variable, clamp/scale as necessary input_var = torch.tensor(input, requires_grad=False) self.itereated_var = torch.tensor(input_var) # setup the target variable, we need it to be in one-hot form for the loss function target_onehot = torch.zeros(target.size() + (self.num_classes,)) # print(target_onehot.size()) if self.cuda: target_onehot = target_onehot.cuda() target_onehot.scatter_(1, target.unsqueeze(1), 1.) target_var = torch.tensor(target_onehot, requires_grad=False) # setup the modifier variable, this is the variable we are optimizing over modifier = torch.zeros(input_var.size()).float().cuda() if self.cuda: modifier = modifier.cuda() modifier_var = torch.tensor(modifier, requires_grad=True) optimizer = optim.Adam([modifier_var], lr=args.lr) for search_step in range(self.binary_search_steps): if args.debug_cw: print('Batch: {0:>3}, search step: {1}'.format(batch_idx, search_step)) print('Const:') for i, x in enumerate(scale_const): print(i, x) best_l2 = [1e10] * batch_size best_score = [-1] * batch_size best_logits = {} # The last iteration (if we run many steps) repeat the search once. if self.repeat and search_step == self.binary_search_steps - 1: scale_const = upper_bound scale_const_tensor = torch.from_numpy(scale_const).float() if self.cuda: scale_const_tensor = scale_const_tensor.cuda() scale_const_var = torch.tensor(scale_const_tensor, requires_grad=False) for step in range(self.max_steps): # perform the attack if self.mask is None: if args.decreasing_temp: cur_temp = args.temp - (args.temp - 0.1) / (self.max_steps - 1) * step model.set_temp(cur_temp) if args.debug_cw: print("temp:", cur_temp) else: model.set_temp(args.temp) loss, dist, output, adv_img, adv_sents = self._optimize( optimizer, model, input_var, modifier_var, target_var, scale_const_var, input_token) for i in range(batch_size): target_label = target[i] output_logits = output[i] output_label = np.argmax(output_logits) di = dist[i] if self.debug: if step % 100 == 0: print('{0:>2} dist: {1:.5f}, output: {2:>3}, {3:5.3}, target {4:>3}'.format( i, di, output_label, output_logits[output_label], target_label)) if di < best_l2[i] and self._compare_untargeted(output_logits, target_label): # if self._compare(output_logits, target_label): if self.debug: print('{0:>2} best step, prev dist: {1:.5f}, new dist: {2:.5f}'.format( i, best_l2[i], di)) best_l2[i] = di best_score[i] = output_label best_logits[i] = output_logits best_attack[i] = adv_img[i] self.best_sent[i] = adv_sents[i] if di < o_best_l2[i] and self._compare(output_logits, target_label): # if self._compare(output_logits, target_label): if self.debug: print('{0:>2} best total, prev dist: {1:.5f}, new dist: {2:.5f}'.format( i, o_best_l2[i], di)) o_best_l2[i] = di o_best_score[i] = output_label o_best_logits[i] = output_logits o_best_attack[i] = adv_img[i] self.o_best_sent[i] = adv_sents[i] sys.stdout.flush() # end inner step loop # adjust the constants batch_failure = 0 batch_success = 0 for i in range(batch_size): if self._compare(o_best_score[i], target[i]) and o_best_score[i] != -1: batch_success += 1 if args.debug_cw: print(self.o_best_sent[i]) print(o_best_score[i]) print(o_best_logits[i]) elif self._compare_untargeted(best_score[i], target[i]) and best_score[i] != -1: o_best_l2[i] = best_l2[i] o_best_score[i] = best_score[i] o_best_attack[i] = best_attack[i] self.o_best_sent[i] = self.best_sent[i] if args.debug_cw: print(self.o_best_sent[i]) print(o_best_score[i]) print(o_best_logits[i]) batch_success += 1 else: batch_failure += 1 print('Num failures: {0:2d}, num successes: {1:2d}\n'.format(batch_failure, batch_success)) sys.stdout.flush() # end outer search loop return o_best_attack
44.962963
126
0.543582
c69da1894d8c42e1a805bd3bc5478b15f15822a3
100
rb
Ruby
mruby/ruby_test/99_main.rb
breml/mygoplayground
abf4ef4e11aa9114dd3942bc1fed4412afc61cf0
[ "MIT" ]
null
null
null
mruby/ruby_test/99_main.rb
breml/mygoplayground
abf4ef4e11aa9114dd3942bc1fed4412afc61cf0
[ "MIT" ]
null
null
null
mruby/ruby_test/99_main.rb
breml/mygoplayground
abf4ef4e11aa9114dd3942bc1fed4412afc61cf0
[ "MIT" ]
null
null
null
require './testfilter' tf = TestFilter.new puts tf.filter({"message" => "input", "key" => "value"})
25
56
0.64
8ce5e7a78d070fdb15b66f608843b4ca66e9b7b4
35,405
asm
Assembly
Appl/Calendar/DayPlan/dayplanPrint.asm
steakknife/pcgeos
95edd7fad36df400aba9bab1d56e154fc126044a
[ "Apache-2.0" ]
504
2018-11-18T03:35:53.000Z
2022-03-29T01:02:51.000Z
Appl/Calendar/DayPlan/dayplanPrint.asm
steakknife/pcgeos
95edd7fad36df400aba9bab1d56e154fc126044a
[ "Apache-2.0" ]
96
2018-11-19T21:06:50.000Z
2022-03-06T10:26:48.000Z
Appl/Calendar/DayPlan/dayplanPrint.asm
steakknife/pcgeos
95edd7fad36df400aba9bab1d56e154fc126044a
[ "Apache-2.0" ]
73
2018-11-19T20:46:53.000Z
2022-03-29T00:59:26.000Z
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Copyright (c) GeoWorks 1989 -- All Rights Reserved PROJECT: PC GEOS MODULE: Calendar/DayPlan FILE: dayplanPrint.asm AUTHOR: Don Reeves, May 27, 1990 ROUTINES: Name Description ---- ----------- DayPlanPrint High level print routine for EventWindow DayPlanPrintsetup Internal setup for printing EventWindow DayPlanPrintDatesEvents High level printing of events in a month DayPlanPrintSingleDate High level printing of single date in month DayPlanPrintEngine Medium level print routine for events DayPlanCreatePrintEvent Creates a PrintEvent object used for printing DayPlanNukePrintEvent Destroys the forementioned object DayPlanPrintAllEvents Medium level routine to print built EventTable DayPlanPrintOneEvent Low level print rouinte for a single event DayPlanPrepareDateEvent Specialized routine to max space used in date DayPlanPrintEventCrossesPage Handles events that cross 1 or more pages DayPlanPrintCalcNextOffset Sub-routine for events that cross page boundary InitPagePosition Simple routine to create new page REVISION HISTORY: Name Date Description ---- ---- ----------- Don 5/27/90 Initial revision DESCRIPTION: $Id: dayplanPrint.asm,v 1.1 97/04/04 14:47:30 newdeal Exp $ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ PrintCode segment resource COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% DayPlanStartPrinting %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Responds to all printing requests from the PrintControl for event information. CALLED BY: GLOBAL (MSG_PRINT_START_PRINTING) PASS: DS:*SI = DayPlanClass instance data DS:DI = DayPlanClass specific instance data BP = GState CX:DX = PrintControl OD RETURN: Nothing DESTROYED: AX, BX, CX, DX, DI, SI, BP PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: none REVISION HISTORY: Name Date Description ---- ---- ----------- Don 5/27/90 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ DayPlanStartPrinting method DayPlanClass, MSG_PRINT_START_PRINTING .enter ; Some set-up work ; push cx, dx ; save the SPC OutputDesc. call DayPlanPrintSetup ; => CX:DX width, height sub sp, size PrintRangeStruct ; allocate this structure mov bx, sp ; PrintRangeStruct => SS:BX mov ss:[bx].PRS_width, cx mov ss:[bx].PRS_height, dx mov ss:[bx].PRS_gstate, bp ; store the GState mov ss:[bx].PRS_pointSize, 12 ; twelve point text mov ss:[bx].PRS_specialValue, 2 ; normal event printing mov dx, ds:[di].DPI_startYear mov ss:[bx].PRS_range.RS_startYear, dx mov dx, ds:[di].DPI_endYear mov ss:[bx].PRS_range.RS_endYear, dx mov dx, {word} ds:[di].DPI_startDay mov {word} ss:[bx].PRS_range.RS_startDay, dx mov dx, {word} ds:[di].DPI_endDay mov {word} ss:[bx].PRS_range.RS_endDay, dx mov ss:[bx].PRS_currentSizeObj, 0 ; no handle allocated ; Perform the actual printing ; mov cx, {word} ds:[di].DPI_flags ; DayPlanInfoFlags => CL ; DayPlanPrintFlags => CH cmp ds:[di].DPI_rangeLength, 1 jne doPrinting or ch, mask DPPF_FORCE_HEADERS ; if 1 day, force a header doPrinting: mov bp, bx ; PrintRangeStruct => SS:BP mov ax, MSG_DP_PRINT_ENGINE ; now do the real work call ObjCallInstanceNoLock ; End the page properly ; mov_tr dx, ax ; number of pages => DX mov di, ss:[bp].PRS_gstate mov al, PEC_FORM_FEED call GrNewPage add sp, size PrintRangeStruct ; clean up the stack ; Now clean up ; pop bx, si ; PrintControl OD => BX:SI mov cx, 1 mov ax, MSG_PRINT_CONTROL_SET_TOTAL_PAGE_RANGE call ObjMessage_print_send ; number of pages = (DX-CX+1) mov ax, MSG_PRINT_CONTROL_PRINTING_COMPLETED call ObjMessage_print_send .leave ret DayPlanStartPrinting endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% DayPlanPrintSetup %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Sets up the DayPlan for printing, and returns the print information. CALLED BY: INTERNAL - DayPlanStartPrinting PASS: DS:*SI = DayPlanClass instance data ES = DGroup CX:DX = PrintControl OD BP = GState to print with RETURN: CX = Usable width of document DX = Usable height of document DS:DI = DayPlanClass specific instance data DESTROYED: AX, BX PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: none REVISION HISTORY: Name Date Description ---- ---- ----------- Don 5/27/90 Initial version Don 6/28/90 Took out unnecessary calls %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ DayPlanPrintSetup proc near .enter ; Set the inital translation ; mov di, bp ; GState => DI call InitPagePosition ; account for the page borders mov di, ds:[si] ; dereference the handle add di, ds:[di].DayPlan_offset ; access the instance data mov cx, es:[printWidth] mov dx, es:[printHeight] .leave ret DayPlanPrintSetup endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% DayPlanPrintDatesEvents %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Print a date's worth of events - designed to work with printing events inside of a Calendar. CALLED BY: GLOBAL (MSG_DP_PRINT_DATES_EVENTS) PASS: DS:*SI = DayPlanClass instance data ES = DGroup SS:BP = MonthPrintRangeStruct CL = DOW of 1st day CH = Last day in month RETURN: Nothing DESTROYED: TBD PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: none REVISION HISTORY: Name Date Description ---- ---- ----------- Don 6/2/90 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ DayPlanPrintDatesEvents method DayPlanClass, MSG_DP_PRINT_DATES_EVENTS .enter ; Some set-up work ; push ds:[di].DPI_rangeLength ; save the range length mov ds:[di].DPI_rangeLength, 1 ; to avoid header events or es:[systemStatus], SF_PRINT_MONTH_EVENTS mov dl, 7 ; seven columns sub dl, cl ; start at DOW mov cl, 1 ; start with 1st day in month mov ax, mask PEI_IN_DATE ; PrintEventInfo => AX call DayPlanCreatePrintEvent ; print event => DS:*BX mov ss:[bp].PRS_currentSizeObj, bx ; store the handle jnc printDates ; if carry clear, A-OK ; Else ask the user what to do ; push cx, dx, bp ; save MonthPrintRangeStruct mov bp, CAL_ERROR_EVENTS_WONT_FIT ; message to display mov bx, ds:[LMBH_handle] ; block handle => BX call MemOwner ; process handle => BX mov ax, MSG_CALENDAR_DISPLAY_ERROR mov di, mask MF_FIXUP_DS or mask MF_CALL call ObjMessage pop cx, dx, bp ; restore MonthPrintRangeStruct cmp ax, IC_YES ; print empty month ? je cleanUpOK ; yes mov ax, MSG_PRINT_CONTROL_PRINTING_CANCELLED jmp cleanUp ; Draw the events, day by day ; printDates: mov ax, ss:[bp].MPRS_newXOffset ; X position => AX mov bx, ss:[bp].MPRS_newYOffset ; Y position => BX anotherDay: mov ss:[bp].MPRS_newXOffset, ax ; store the current X offset mov ss:[bp].MPRS_newYOffset, bx ; store the current Y offset push ax, bx, cx, dx ; save important data mov ss:[bp].PRS_range.RS_startDay, cl mov ss:[bp].PRS_range.RS_endDay, cl call DayPlanPrintSingleDate ; print this date pop ax, bx, cx, dx ; restore the important data add ax, ss:[bp].MPRS_dateWidth ; move over one date dec dl ; one less column in this row jnz nextDate ; if not done, next add bx, ss:[bp].MPRS_dateHeight ; else go down one row... mov ax, MONTH_BORDER_HORIZ ; and to the left column mov dl, 7 ; reset the day counter nextDate: inc cl ; increment the day cmp cl, ch ; are we done yet ?? jle anotherDay ; Clean up ; cleanUpOK: mov ax, MSG_PRINT_CONTROL_PRINTING_COMPLETED cleanUp: mov di, ds:[si] add di, ds:[di].DayPlan_offset pop ds:[di].DPI_rangeLength ; restore range length push ax ; save the method to send and es:[systemStatus], not SF_PRINT_MONTH_EVENTS mov dx, ss:[bp].PRS_currentSizeObj ; size object => DS:*DX call DayPlanNukePrintEvent ; free up the event ; End the page properly ; mov di, ss:[bp].PRS_gstate mov al, PEC_FORM_FEED call GrNewPage ; Now tell the PrintControl that we're done ; pop ax ; method to send GetResourceHandleNS CalendarPrintControl, bx mov si, offset CalendarPrintControl call ObjMessage_print_call ; send that method .leave ret DayPlanPrintDatesEvents endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% DayPlanPrintSingleDate %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Print a single date's events, that appear inside of a month. CALLED BY: INTERNAL - DayPlanPrintDatesEvents PASS: DS:*SI = DayPlanClass instance data SS:BP = MonthPrintRangeStruct ES = DGroup RETURN: Nothing DESTROYED: AX, BX, CX, DX, DI PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: none REVISION HISTORY: Name Date Description ---- ---- ----------- Don 10/1/90 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ DayPlanPrintSingleDate proc near .enter ; First translate ; push si ; save the DayPlan handle mov di, ss:[bp].PRS_gstate ; GState => DI call GrSetNullTransform ; go back to 0,0 mov dx, ss:[bp].MPRS_newXOffset ; raw X offset => DX add dx, es:[printMarginLeft] inc dx mov bx, ss:[bp].MPRS_newYOffset ; raw Y offset => BX add bx, es:[printMarginTop] ; y offset => BX clr ax ; no fractions clr cx ; no fractions call GrApplyTranslation ; perform the translation ; Now set the clip region ; mov bx, ax ; top (and left) zero mov cx, ss:[bp].PRS_width ; right mov dx, ss:[bp].PRS_height ; bottom mov si, PCT_REPLACE call GrSetClipRect ; set the clip rectangle ; Now do the real printing ; pop si ; restore the DayPlan handle clr cx ; no template or headers mov ax, MSG_DP_PRINT_ENGINE ; do the real work call ObjCallInstanceNoLock .leave ret DayPlanPrintSingleDate endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% DayPlanPrintEngine %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Performs the actual printing of events that fall within the desired range. CALLED BY: GLOBAL PASS: ES = DGroup DS:*SI = DayPlanClass instance data SS:BP = PrintRangeStruct CL = DayPlanInfoFlags DP_TEMPLATE (attempt template mode) DP_HEADERS (attempt headers mode) CH = DayPlanPrintFlags RETURN: AX = Number of pages that were printed DESTROYED: BX, DI, SI NOTES: PRS_currentSizeObj must be accurately filled in when passed If no current print object, then zero Else, valid handle in DPResource block PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: none REVISION HISTORY: Name Date Description ---- ---- ----------- Don 5/27/90 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ DayPlanPrintEngine method DayPlanClass, MSG_DP_PRINT_ENGINE uses cx, dx, bp .enter ; First call for everything to be updated ; mov ax, 1 ; assume 1 page printed test es:[systemStatus], SF_VALID_FILE LONG jz done ; if no file, do nothing! push cx ; save the flags mov ax, MSG_DP_UPDATE_ALL_EVENTS call ObjCallInstanceNoLock cmp ds:[LMBH_blockSize], LARGE_BLOCK_SIZE jb eventTable ; if smaller, don't worry mov ax, MSG_DP_FREE_MEM ; free as much mem as possible call ObjCallInstanceNoLock ; do the work now! ; Allocate an EventTable, and initialize it eventTable: mov cx, size EventTableHeader ; allocate an EventTable mov al, mask OCF_IGNORE_DIRTY ; not dirty call LMemAlloc ; chunk handle => AX mov bx, ax ; table handle => BX mov di, ds:[bx] ; derference the handle mov ds:[di].ETH_last, cx ; initialize the header... mov ds:[di].ETH_screenFirst, OFF_SCREEN_TOP mov ds:[di].ETH_screenLast, OFF_SCREEN_BOTTOM ; Save some important values, and reload them ; mov di, ds:[si] ; dereference the handle add di, ds:[di].DayPlan_offset ; access my instance data pop cx ; restore the flags push ds:[di].DPI_eventTable ; save these values... push {word} ds:[di].DPI_flags ; save InfoFlags & PrintFlags push ds:[di].DPI_textHeight ; save one-line text height push ds:[di].DPI_viewWidth ; save the view width push ds:[di].DPI_docHeight ; save the document height mov ds:[di].DPI_eventTable, ax ; store the new EventTable mov {word} ds:[di].DPI_flags, cx ; store some new flags or ds:[di].DPI_flags, DP_LOADING ; to avoid re-draw requests mov cx, ss:[bp].PRS_width ; screen width => CX mov ds:[di].DPI_viewWidth, cx ; store the width here mov bx, ss:[bp].PRS_currentSizeObj ; current handle => BX tst bx ; check for valid handle jnz havePrintEvent ; if exists, then print if SUPPORT_ONE_LINE_PRINT clr ax ; assume not one-line print test ds:[di].DPI_printFlags, mask DPPF_ONE_LINE_EVENT jz notOneLine mov ax, mask PEI_ONE_LINE_PRINT notOneLine: else clr ax ; PrintEventInfo => AX endif call DayPlanCreatePrintEvent ; print event => DS:*BX havePrintEvent: EC < push si ; save DayPlan handle > EC < mov si, bx ; move event handle > EC < call ECCheckLMemObject ; object in DS:*SI > EC < pop si ; restore DayPlan handle> mov es:[timeOffset], 0 ; no time offset ! push bp, bx ; save structure & DayEvent ; Load the events, and then print them out ; call DayPlanLoadEvents ; load all of the events pop bp, dx ; restore structure & DayEvent call DayPlanPrintAllEvents ; print all of the events ; number of pages => CX ; Clean up ; tst ss:[bp].PRS_currentSizeObj ; start with a size object ?? jnz finishUp ; yes, so don't kill it call DayPlanNukePrintEvent ; else destroy the print event finishUp: mov di, ds:[si] ; dereference the chunk add di, ds:[di].DayPlan_offset ; access my instace data mov ax, ds:[di].DPI_eventTable ; print EventTable => AX pop ds:[di].DPI_docHeight ; restore the document height pop ds:[di].DPI_viewWidth ; restore the view width pop ds:[di].DPI_textHeight ; resotre one-line text height pop {word} ds:[di].DPI_flags ; restore InfoFlags & PrintFlags pop ds:[di].DPI_eventTable ; save these values... call LMemFree ; free up the print table mov ax, cx ; number of pages => AX done: .leave ret DayPlanPrintEngine endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% DayPlanCreatePrintEvent %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Create a DayEvent to use only for printing. Also use one of the MyText Objects created as the SizeObject, so that all the text heights will be correctly calculated. CALLED BY: DayPlanPrintEngine PASS: DS:*SI = DayPlanClass instance data ES = DGroup SS:BP = PrintRangeStruct AX = PrintEventInfo RETURN: DS:*BX = DayEventClass object to print with Carry = Clear if sufficient room to print = Set if not DESTROYED: Nothing PSEUDO CODE/STRATEGY: Query the SPC for the print mode Create the event buffer Set the proper font Calculate the height of a one-line TEO KNOWN BUGS/SIDE EFFECTS/IDEAS: none REVISION HISTORY: Name Date Description ---- ---- ----------- Don 6/29/90 Initial version kho 12/18/96 One-line printing added %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ DayPlanCreatePrintEvent proc near class DayEventClass uses ax, cx, dx, di .enter ; Store some important information ; push bp, si ; save DayPlan, structure push ax ; save PrintEventInfo if SUPPORT_ONE_LINE_PRINT push ax ; one more time endif mov ax, es:[SizeTextObject] mov ss:[bp].PRS_sizeTextObj, ax mov ax, es:[oneLineTextHeight] mov ss:[bp].PRS_oneLineText, ax mov ax, es:[timeWidth] mov ss:[bp].PRS_timeWidth, ax mov ax, es:[timeOffset] mov ss:[bp].PRS_timeOffset, ax ; Query the MyPrint for the output mode ; push ss:[bp].PRS_pointSize ; save the pointsize GetResourceHandleNS CalendarPrintOptions, bx mov si, offset CalendarPrintOptions ; OD => BX:SI mov ax, MSG_MY_PRINT_GET_INFO call ObjMessage_print_call push cx ; save the FontID mov di, offset PrintEventClass ; parent Event class => ES:DI call BufferCreate ; PrintEvent => CX:*DX EC < cmp cx, ds:[LMBH_handle] ; must be in this block > EC < ERROR_NE DP_CREATE_PRINT_EVENT_WRONG_RESOURCE > ; Now tell the DayEvent to set a new font & size ; mov si, dx ; DayEvent OD => DS:*SI pop cx ; FontID => CX pop dx ; pointsize => DX pop bp ; PrintEventInfo => BP mov ax, MSG_PE_SET_FONT_AND_SIZE ; set the font and pointsize call ObjCallInstanceNoLock ; send the method ; Set up the event text for multiple rulers ; mov bx, si ; DayEvent handle => BX mov di, ds:[si] ; dereference the DayEvent add di, ds:[di].DayEvent_offset ; instance data => DS:DI mov si, ds:[di].DEI_textHandle ; text MyText => DS:*DI mov es:[SizeTextObject], si ; store the handle here if SUPPORT_ONE_LINE_PRINT ; If one-line-print, set the VisTextStates of event text accordingly ; pop ax test ax, mask PEI_ONE_LINE_PRINT jz notOneLine mov ax, MSG_VIS_TEXT_MODIFY_EDITABLE_SELECTABLE mov cx, (0 shl 8) or mask VTS_ONE_LINE ; Set VTS_ONE_LINE call ObjCallInstanceNoLock notOneLine: endif mov ax, MSG_VIS_TEXT_CREATE_STORAGE mov cx, mask VTSF_MULTIPLE_PARA_ATTRS call ObjCallInstanceNoLock ; send the method mov ax, MSG_VIS_TEXT_SET_MAX_LENGTH mov cx, MAX_TEXT_FIELD_LENGTH+1 ; possibly 1 character too big call ObjCallInstanceNoLock ; send the method ; Finally, calculate the one line height ; pop si ; DayPlan handle => SI mov ax, MSG_DP_CALC_ONE_LINE_HEIGHT call ObjCallInstanceNoLock ; perform the calculation pop bp ; PrintRangeStruct => SS:BP mov ss:[bp].PRS_oneLineHeight, dx ; store the height ; Check to see if there is sufficient room to print events ; mov ax, es:[timeWidth] ; move the time width => AX cmp ss:[bp].PRS_width,ax ; compare with widths ; this sets/clears the carry .leave ret DayPlanCreatePrintEvent endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% DayPlanNukePrintEvent %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Destory the DayEvent object used to print with CALLED BY: DayPlanPrintEngine PASS: DS:*DX = DayEventClass object to nuke SS:BP = PrintRangeStruct ES = DGroup RETURN: Nothing DESTROYED: Nothing PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: none REVISION HISTORY: Name Date Description ---- ---- ----------- Don 6/29/90 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ DayPlanNukePrintEvent proc near uses ax, cx, dx, bp, si .enter ; Restore some important information ; mov ax, ss:[bp].PRS_sizeTextObj mov es:[SizeTextObject], ax mov ax, ss:[bp].PRS_oneLineText mov es:[oneLineTextHeight], ax mov ax, ss:[bp].PRS_timeWidth mov es:[timeWidth], ax mov ax, ss:[bp].PRS_timeOffset mov es:[timeOffset], ax ; Now destroy the print event ; mov si, dx ; OD => DS:*SI mov ax, MSG_VIS_DESTROY ; destroy the entire branch mov dl, VUM_NOW ; destroy stuff now call ObjCallInstanceNoLock ; send the method .leave ret DayPlanNukePrintEvent endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% DayPlanPrintAllEvents %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Prints all of the events in the EventTable CALLED BY: DayPlanPrintEngine PASS: ES = DGroup DS:SI = DayPlanClass instance data SS:BP = PrintRangeStruct DS:DX = DayEventClass object to use for printing RETURN: CX = Number of pages printed DESTROYED: AX, BX, DI PSEUDO CODE/STRATEGY: A PrintPositionStruct is allocated on the stack, which is used to pass values to PositionDayEvent(), and to maintain some internal state. Note that a PositionStruct is the first element of a PrintPositionStruct. KNOWN BUGS/SIDE EFFECTS/IDEAS: none REVISION HISTORY: Name Date Description ---- ---- ----------- Don 5/27/90 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ DayPlanPrintAllEvents proc near class DayPlanClass uses dx, si, bp .enter ; Some set-up work ; sub sp, size PrintPositionStruct ; allocate the PositionStruct mov bx, sp ; structure => SS:BX mov ax, ss:[bp].PRS_width mov ss:[bx].PS_totalWidth, ax ; store the document width mov ss:[bx].PS_timeLeft, 0 ; never draw the icons mov ax, ss:[bp].PRS_oneLineHeight mov ss:[bx].PS_timeHeight, ax ; store the one line height mov ax, ss:[bp].PRS_height mov ss:[bx].PPS_pageHeight, ax ; store the page height mov ax, ss:[bp].PRS_specialValue ; either 1 or 2 mov ss:[bx].PPS_singlePage, al ; store the page boolean mov ss:[bx].PPS_numPages, 1 ; initally, one page mov ss:[bx].PPS_nextOffset, 0 ; no next offset mov ax, dx ; PrintEvent => DS:*AX mov dx, bx ; PositionStruct => SS:DX mov bp, ss:[bp].PRS_gstate ; GState => BP mov si, ds:[si] ; dereference the handle add si, ds:[si].DayPlan_offset ; access my instance data mov si, ds:[si].DPI_eventTable ; event table handle => SI mov di, ds:[si] ; dereference the handle mov bx, size EventTableHeader ; go to the first event clr cx ; start at the top! jmp midLoop ; start looping ; Loop here eventLoop: call DayPlanPrintOneEvent ; print the event jc done ; if carry set, abort add bx, size EventTableEntry midLoop: cmp bx, ds:[di].ETH_last ; are we done ?? jl eventLoop ; Let's do some clean up work ; done: mov bp, dx ; PrintPositionStruct => SS:BP mov cx, ss:[bp].PPS_numPages ; number of pages => AX add sp, size PrintPositionStruct ; clean up the stack .leave ret DayPlanPrintAllEvents endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% DayPlanPrintOneEvent %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Prints one event corresponding to the EventTableEntry CALLED BY: DayPlanPrintEngine() PASS: ES = DGroup DS:*SI = EventTable DS:DI = EventTable DS:*AX = PrintEvent to use SS:DX = PrintPositionStruct BP = GState CX = Y-position BX = Offset to the EventTableEntry to be printed RETURN: DS:DI = EventTable (updated) CX = Y-position in document (updated) Carry = Set to stop printing of this range DESTROYED: Nothing PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: none REVISION HISTORY: Name Date Description ---- ---- ----------- Don 5/27/90 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ DayPlanPrintOneEvent proc near .enter ; First stuff the event ; push si, bp, dx ; table handle, GState, struct add di, bx ; go to the proper ETE mov bp, ds:[di].ETE_size ; event height => BP mov dx, DO_NOT_INSERT_VALUE ; don't insert into vistree call StuffDayEvent ; load time & text strings mov si, ax ; DayEvent => SI mov dx, bp ; event height => DX pop bp ; PositionStruct => SS:BP pop di ; GState => DI cmp ss:[bp].PPS_singlePage, 1 ; printing events in a month? jnz position ; no, so use regular values call DayPlanPrintPrepareDateEvent ; set some styles, etc... ; Now position the sucker (possibly on a new page) ; position: mov ax, cx ; y-position => AX add ax, dx ; calculate to end of event cmp ss:[bp].PPS_pageHeight, ax ; does it fit on the page ?? jge positionNow ; yes, so jump printAgain: call DayPlanPrintEventCrossesPage ; determine what to do positionNow: pushf ; save the carry flag call PositionDayEvent ; position the event (at CX) add cx, dx ; update the document position ; Enable the event for printing ; mov ax, MSG_PE_PRINT_ENABLE call ObjCallInstanceNoLock ; CX, DX, BP are preserved ; Finally draw the event ; push bp, dx, cx ; save doc offset & struct mov bp, di ; GState => BP mov ax, MSG_VIS_DRAW mov cl, mask DF_PRINT ; we're printing call ObjCallInstanceNoLock ; draw the event pop bp, dx, cx ; restore doc offset, struct cmp ss:[bp].PPS_singlePage, 1 ; print to single page only ? je noLoop ; yes, so don't loop again popf ; restore the carry flag jc printAgain ; multiple-page event pushf ; else store CF=0 noLoop: popf ; restore the CF ; Clean up work ; mov dx, bp ; PrintPositionStruct => SS:DX mov bp, di ; GState => BP mov ax, si ; PrintEvent => DS:*AX pop si ; restore the EventTable chunk mov di, ds:[si] ; dereference the handle .leave ret DayPlanPrintOneEvent endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% DayPlanPrintPrepareDateEvent %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Set the margin and border information for this event to fully utilize the space inside of a date. CALLED BY: GLOBAL PASS: DS:*SI = DayEventClass object used for printing SS:BP = PrintPositionStruct ES = DGroup RETURN: DX = Height of the event DESTROYED: Nothing PSEUDO CODE/STRATEGY: We are being very tricky here, because the SizeTextObject, at this point, holds the text of the event. All we need to do is determine if there is a valid time, and if so, set up the first paragraph and the rest of the object rulers. KNOWN BUGS/SIDE EFFECTS/IDEAS: none REVISION HISTORY: Name Date Description ---- ---- ----------- Don 10/4/90 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ TEXT_INDENT_LEVEL = 2 ; basic text indentation level CRString byte '\r', 0 ; a carriage return VTRP_textPtr equ <VTRP_textReference.TR_ref.TRU_pointer.TRP_pointer> DayPlanPrintPrepareDateEvent proc near uses ax, bx, cx, di, si, bp class VisTextClass .enter ; Set the default margin ; mov di, bp ; PrintPositionStruct => SS:DI push si ; save the DayEvent handle mov si, es:[SizeTextObject] ; OD => DS:*SI sub sp, size VisTextSetMarginParams mov bp, sp clrdw ss:[bp].VTSMP_range.VTR_start movdw ss:[bp].VTSMP_range.VTR_end, TEXT_ADDRESS_PAST_END mov ss:[bp].VTSMP_position, TEXT_INDENT_LEVEL * 8 mov ax, MSG_VIS_TEXT_SET_LEFT_AND_PARA_MARGIN call ObjCallInstanceNoLock ; send the method add sp, size VisTextSetMarginParams ; Do we have any time ? ; mov bx, si ; MyText handle => BX pop si ; DayEvent handle => SI mov ax, MSG_DE_GET_TIME call ObjCallInstanceNoLock ; time => CX mov si, bx ; MyText handle => SI cmp cx, -1 ; no time ?? je calcSize ; just re-calculate the size ; Check if the space between the time and the border is wide enough ; to hold some text. If it is not, insert a CR at the front of the ; text. ; mov cx, ss:[di].PPS_posStruct.PS_totalWidth sub cx, es:[timeWidth] ; 1st line's wdith => CX cmp cx, VIS_TEXT_MIN_TEXT_FIELD_WIDTH jge setMargin ; if big enough, continue sub sp, size VisTextReplaceParameters mov bp, sp ; structure => SS:BP clr ax mov ss:[bp].VTRP_flags, ax clrdw ss:[bp].VTRP_range.VTR_start, ax clrdw ss:[bp].VTRP_range.VTR_end, ax mov ss:[bp].VTRP_insCount.high, ax inc ax mov ss:[bp].VTRP_insCount.low, ax ; insert one character mov ss:[bp].VTRP_textReference.TR_type, TRT_POINTER mov ss:[bp].VTRP_textPtr.segment, cs mov ss:[bp].VTRP_textPtr.offset, offset CRString mov ax, MSG_VIS_TEXT_REPLACE_TEXT call ObjCallInstanceNoLock ; insert the CR. add sp, size VisTextReplaceParameters jmp calcSize ; finish up ; Else set the paragraph margin for the first paragraph ; setMargin: sub sp, size VisTextSetMarginParams mov bp, sp clr ax clrdw ss:[bp].VTSMP_range.VTR_start, ax clrdw ss:[bp].VTSMP_range.VTR_end, ax mov ax, es:[timeWidth] ; time width => AX shl ax, 1 shl ax, 1 shl ax, 1 mov ss:[bp].VTSMP_position, ax mov ax, MSG_VIS_TEXT_SET_PARA_MARGIN call ObjCallInstanceNoLock ; set paragraph margin in BP add sp, size VisTextSetMarginParams ; Calculate the final size. I had to add a horrible hack to ; clear a field in the text object, so that the actual height ; of the text will be properly returned, rather than the height ; of the first text to be drawn. -Don 9/29/93 ; calcSize: mov cx, ss:[di].PPS_posStruct.PS_totalWidth clr dx ; don't cache the height mov di, ds:[si] add di, ds:[di].Vis_offset clr ds:[di].VTI_lastWidth mov ax, MSG_VIS_TEXT_CALC_HEIGHT ; using width in CX call ObjCallInstanceNoLock ; height => DX .leave ret DayPlanPrintPrepareDateEvent endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% DayPlanPrintEventCrossesPage %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: An event does not fit on one page, by the amount in AX. Determine where to print the event. CALLED BY: DayPlanPrintOneEvent PASS: ES = DGroup SS:BP = PrintPositionStruct CX = Offset in page to the top of the event DX = Length of the event DI = GState RETURN: CX = Offset at which we should print the event. Carry = Set to print this event again DESTROYED: AX PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: none REVISION HISTORY: Name Date Description ---- ---- ----------- Don 6/30/90 Initial version Don 7/19/90 Deal with multi-page events better %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ MAX_SPACE_AT_BOTTOM_OF_PAGE = 36 ; (up to 3 lines of 12pt text) DayPlanPrintEventCrossesPage proc near uses bx, dx .enter ; Will we need to draw again ?? ; mov bx, ss:[bp].PPS_pageHeight ; height of a page => BX cmp ss:[bp].PPS_singlePage, 1 ; keep on one page ?? je forceClip ; force event to be clipped ; Are we in the middle of a multi-page event ; tst ss:[bp].PPS_nextOffset ; is there a next offset ?? jz firstTime ; no, so continue mov cx, ss:[bp].PPS_nextOffset ; grab the next offset jmp newPage ; See where we should place this event ; firstTime: mov ax, bx ; bottom of page => AX sub ax, cx ; how far from the bottom => AX cmp ax, MAX_SPACE_AT_BOTTOM_OF_PAGE ; split on two pages ?? jg nextPageCalc ; yes, so calc next offset clr cx ; else offset = 0 on a new page ; Create a new page ; newPage: inc ss:[bp].PPS_numPages ; count the number of pages mov al, PEC_FORM_FEED call GrNewPage ; new page to the GString call InitPagePosition ; initialize the drawing ; See if it will now fit on the rest of this page ; nextPageCalc: mov ss:[bp].PPS_nextOffset, 0 ; assume no next offset mov ax, cx ; offset => AX add ax, dx ; length of the page cmp bx, ax ; does it fit on the page ?? jge done ; yes forceClip: call DayPlanPrintCalcNextOffset ; else do the dirty work! stc ; ensure the carry is set! done: .leave ret DayPlanPrintEventCrossesPage endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% DayPlanPrintCalcNextOffset %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Calculate the offset of the event text for the next page, to ensure the text starts with a complete line. Also sets the clip rectangle (if any) for the bottom of the current page. CALLED BY: DayPlanPrintEventCrossesPage PASS: ES = DGroup SS:BP = PrintPositionStruct BX = Page length CX = Offset of the event text DX = Length of the event text DI = GState RETURN: Nothing DESTROYED: AX, BX, DX PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: none REVISION HISTORY: Name Date Description ---- ---- ----------- Don 7/19/90 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ DayPlanPrintCalcNextOffset proc near uses cx .enter ; Calculate the raw offset to the next page ; mov ss:[bp].PPS_nextOffset, cx ; store the current offset sub ss:[bp].PPS_nextOffset, bx ; subtract offset to next page ; See if we break between lines ; mov ax, bx ; page width => AX sub ax, cx ; space left on page => AX sub ax, EVENT_TB_MARGIN ; allow for top margin mov cx, es:[oneLineTextHeight] sub cx, 2 * EVENT_TB_MARGIN ; space per line => CX clr dx ; difference => DX:AX div cx ; perform the division tst dx ; any remainder ?? jz done ; no, so we're done ; Else we must set a clip rectangle, and adjust the next offset ; push si ; save this register add ss:[bp].PPS_nextOffset, dx ; adjust next offset! sub bx, dx ; offset to end of text ;;; dec bx ; text goes from 0->N-1 mov dx, bx ; bottom edge mov cx, ss:[bp].PS_totalWidth ; right edge clr ax ; left edge mov bx, ax ; top edge mov si, PCT_REPLACE ; set a new clip rectangle call GrSetClipRect ; set the clip rectangle pop si ; restore this register done: .leave ret DayPlanPrintCalcNextOffset endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% InitPagePosition %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Account for the page borders by translating the page down and right by the border amount CALLED BY: INTERNAL PASS: DI = GString RETURN: Nothing DESTROYED: Nothing PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: none REVISION HISTORY: Name Date Description ---- ---- ----------- Don 6/29/90 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ InitPagePosition proc near uses ax, bx, cx, dx, si .enter ; Initialize the page position ; mov dx, es:[printMarginLeft] clr cx ; x translation => DX:CX mov bx, es:[printMarginTop] mov ax, cx ; y translation => BX:AX call GrApplyTranslation ; allow fro print margins ; Alse set the color mapping mode ; mov al, ColorMapMode <1, 0, CMT_CLOSEST> call GrSetAreaColorMap ; map to solid colors ; Set a clip rectangle for the entire page ; clr ax, bx mov cx, es:[printWidth] mov dx, es:[printHeight] mov si, PCT_REPLACE ; set a new clip rectangle call GrSetClipRect ; set the clip rectangle .leave ret InitPagePosition endp PrintCode ends
29.260331
79
0.632679
4da8444d1aae31cc625a9c1453b35ed644947237
1,229
html
HTML
conf/compare-sequences.html
acorg/seqdb-3
55513a55381f9911ebfe58d0d60fac366f89c07b
[ "MIT" ]
null
null
null
conf/compare-sequences.html
acorg/seqdb-3
55513a55381f9911ebfe58d0d60fac366f89c07b
[ "MIT" ]
null
null
null
conf/compare-sequences.html
acorg/seqdb-3
55513a55381f9911ebfe58d0d60fac366f89c07b
[ "MIT" ]
null
null
null
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <link href="amino-acid-colors.css" rel="stylesheet"> <link href="compare-sequences.css" rel="stylesheet"> <script src="data.js"></script> <script src="compare-sequences.js"></script> <script> /* const isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent); * function main() { * document.querySelectorAll(".pdf[src]").forEach(element => { * let src = element.getAttribute("src"); * if (isSafari) * element.innerHTML = `<img src="${src}">` * else * element.innerHTML = `<object data="${src}#toolbar="></object>` * }); * } */ </script> <title>Compare sequences</title> </head> <body> <h2>Compare sequences</h2> <div id="compare-sequences" class="compare-sequences"> <div class="most-frequent-per-group"></div> <div class="frequency-per-group"></div> <div class="positions-with-diversity"></div> <div class="full-sequences"></div> </div> </body> </html>
36.147059
88
0.506103
279958270514f59bc3dc2c55a8268a4d9def3138
134
css
CSS
src/app/rodape/rodape.component.css
Jefferson1202/Funcionarios-spring
67c7a3b6be63698123e09b4d6411abc006778bbc
[ "Apache-2.0" ]
null
null
null
src/app/rodape/rodape.component.css
Jefferson1202/Funcionarios-spring
67c7a3b6be63698123e09b4d6411abc006778bbc
[ "Apache-2.0" ]
null
null
null
src/app/rodape/rodape.component.css
Jefferson1202/Funcionarios-spring
67c7a3b6be63698123e09b4d6411abc006778bbc
[ "Apache-2.0" ]
null
null
null
p{ color:black; margin-top: 4px; margin-right: 890px; font-family: 'Times New Roman', Times, serif; }
13.4
50
0.537313
0bcd6e0452c9e0950764e5c3195e52f23ff13a1e
3,432
js
JavaScript
template.webmodule/build/browser.js
Qorpent/qorpent.kernel
09943aa3851e462f759c5ee2db31728e586c0fed
[ "Apache-2.0" ]
null
null
null
template.webmodule/build/browser.js
Qorpent/qorpent.kernel
09943aa3851e462f759c5ee2db31728e586c0fed
[ "Apache-2.0" ]
null
null
null
template.webmodule/build/browser.js
Qorpent/qorpent.kernel
09943aa3851e462f759c5ee2db31728e586c0fed
[ "Apache-2.0" ]
null
null
null
/** * Created by comdiv on 12.11.2014. */ require.config({ baseUrl: "../tests/", paths: { "jquery": "../lib/jquery", "mocha": "../lib/mocha", "chai": "../lib/chai", "angular": "../lib/angular", "teamcity": "../lib/teamcity", "angular-mocks": "../lib/angular-mocks", "testmap": "../build/testmap", "moment": "../lib/moment" }, shim: { jquery: { exports: "$" }, mocha: { exports: 'mocha', deps: ["teamcity"], init: function (tc) { mocha.setup({ ui: "bdd", ignoreLeaks: true, reporter: function (runner) { new Mocha.reporters.HTML(runner); new tc(Mocha.reporters.Base, runner); } }); return this.mocha; } }, chai: { deps: ["mocha"] }, angular: { deps: ['jquery'], exports: 'angular' }, "angular-mocks": { deps: ['angular'] } }, deps: ["mocha", "chai", "teamcity", "jquery", "angular"], callback: function () { $.get("../package.json", function (data) { define("package",[],function(){ return data; }); require(["testmap"], function () { var $tests = require("testmap"); var profile = {browser: true}; if (window.callPhantom) { profile.phantom = true; } profile.context = document.location.href; require($tests(profile), function () { var chai = require("chai"); var should = chai.Should(); if (!Function.prototype.bind) { Function.prototype.bind = function (oThis) { if (typeof this !== "function") { // closest thing possible to the ECMAScript 5 // internal IsCallable function throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable"); } var aArgs = Array.prototype.slice.call(arguments, 1), fToBind = this, fNOP = function () { }, fBound = function () { return fToBind.apply(this instanceof fNOP && oThis ? this : oThis, aArgs.concat(Array.prototype.slice.call(arguments))); }; fNOP.prototype = this.prototype; fBound.prototype = new fNOP(); return fBound; }; } document.finished = false; mocha.run(function () { if (typeof window.callPhantom === 'function') { window.callPhantom(); } }); }); }); }); } });
34.666667
124
0.372086
754724f47d8102d9212cf2e85a3e74e4623fc9a0
2,692
h
C
source/libgltf/file_loader.h
fossabot/libgltf
50adc368b61a0dc011b79da0abe94f389e531eca
[ "MIT" ]
52
2017-09-14T23:10:50.000Z
2022-02-10T10:38:24.000Z
source/libgltf/file_loader.h
fossabot/libgltf
50adc368b61a0dc011b79da0abe94f389e531eca
[ "MIT" ]
10
2017-09-13T18:30:32.000Z
2021-11-12T03:30:10.000Z
source/libgltf/file_loader.h
fossabot/libgltf
50adc368b61a0dc011b79da0abe94f389e531eca
[ "MIT" ]
6
2017-11-20T03:58:46.000Z
2021-09-06T00:21:36.000Z
/* * This software is released under the MIT license. * * Copyright (c) 2017-2021 Alex Chi, The Code 4 Game Organization * * 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. */ #pragma once #include "common.h" namespace libgltf { /// a simple path class class CPath { public: CPath(); CPath(const CPath& _Another); explicit CPath(const string_t& _sPath); public: void SetPath(const string_t& _sPath); bool IsRelative() const; CPath Parent() const; public: operator string_t() const; CPath& operator=(const CPath& _Another); CPath& operator=(const string_t& _sPath); CPath operator/(const CPath& _Another) const; bool operator<(const CPath& _Another) const; private: string_t m_sPath; }; /// a file loader, a file pool class CFileLoader { typedef std::map<CPath, std::vector<uint8_t>> TFileDatas; public: explicit CFileLoader(const string_t& _sRootPath = GLTFTEXT("")); public: bool Load(const string_t& _sFilePath); void Release(); public: const std::vector<uint8_t>& operator[](const string_t& file) const; bool ReadByte(const string_t& _sFilePath, size_t _Offset, void* _pData, size_t _Size) const; string_t AsString(const string_t& file, size_t _Offset = 0, size_t _Size = 0) const; protected: const std::vector<uint8_t>& Find(const CPath& _sFilePath) const; std::vector<uint8_t>& FindOrAdd(const CPath& _sFilePath); private: CPath m_RootPath; CPath m_FilePath; TFileDatas m_FileDatas; }; }
32.829268
100
0.68425
5fc3ed8fa849ad0293e81991ce0afc49da8786b9
4,837
h
C
audio/common/Semantic/jhcTxtAssoc.h
jconnell11/ALIA
f7a6c9dfd775fbd41239051aeed7775adb878b0a
[ "Apache-2.0" ]
1
2020-03-01T13:22:34.000Z
2020-03-01T13:22:34.000Z
audio/common/Semantic/jhcTxtAssoc.h
jconnell11/ALIA
f7a6c9dfd775fbd41239051aeed7775adb878b0a
[ "Apache-2.0" ]
null
null
null
audio/common/Semantic/jhcTxtAssoc.h
jconnell11/ALIA
f7a6c9dfd775fbd41239051aeed7775adb878b0a
[ "Apache-2.0" ]
1
2020-07-30T10:24:58.000Z
2020-07-30T10:24:58.000Z
// jhcTxtAssoc.h : key and values in a singly linked association list // // Written by Jonathan H. Connell, [email protected] // /////////////////////////////////////////////////////////////////////////// // // Copyright 2013-2020 IBM Corporation // // 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. // /////////////////////////////////////////////////////////////////////////// #ifndef _JHCTXTASSOC_ /* CPPDOC_BEGIN_EXCLUDE */ #define _JHCTXTASSOC_ /* CPPDOC_END_EXCLUDE */ #include "jhcGlobal.h" #include "Semantic/jhcTxtList.h" //= Key and values in a singly linked association list. // keys are always unique but ALWAYS include a default "" category // values are also unique but CANNOT include "" blank entries // each key can have an optional prior probability (saved) // Note: automatically deallocates values and rest of list when deleted class jhcTxtAssoc { // PRIVATE MEMBER VARIABLES private: char tmp[200]; /** Temporary output string. */ char key[200]; /** Indexing term string. */ jhcTxtAssoc *next; /** Rest of indexing terms. */ jhcTxtList *vals; /** Expansion for index. */ int klen; /** Length of key string. */ int last; /** Set if last request. */ // PUBLIC MEMBER VARIABLES public: double prob; /** Likelihood of term. */ // PUBLIC MEMBER FUNCTIONS public: // creation and configuration jhcTxtAssoc (); ~jhcTxtAssoc (); void Seed (); // properties and retrieval int NumKeys () const; int MaxDepth (int blank =0) const; int TotalVals () const; int MaxLength () const; const char *KeyTxtN (int n =0) const; const char *KeyTxtFor (const char *vtxt) const; bool Member (const char *ktag, const char *vtxt, int def =0, int caps =0) const; int Invert (const jhcTxtAssoc &src, int clean =0); // random selection void Reset (); const char *PickRnd (const char *ktag =NULL, int def =0); // keys and values const char *KeyTxt () const {return key;} int KeyLen () const {return klen;} const jhcTxtAssoc *NextKey () const {return next;} const jhcTxtAssoc *ReadKey (const char *ktag) const; jhcTxtAssoc *GetKey (const char *ktag); int NumVals () const; const jhcTxtList *Values () const {return vals;} // building and editing jhcTxtAssoc *AddKey (const char *ktag, double p =1.0, int force =0); int RemKey (const char *ktag); void ClrKeys (); const jhcTxtList *AddVal (const char *vtxt, double w =1.0); int IncVal (const char *vtxt, double amt =1.0); int RemVal (const char *vtxt); int ClrVals (); // file operations int LoadList (const char *fname, int clean =0, int merge =0); int SaveList (const char *fname) const; // variable substitution char *MsgRnd (const char *ktag =NULL, const char *arg0 =NULL, const char *arg1 =NULL, const char *arg2 =NULL, const char *arg3 =NULL, const char *arg4 =NULL, const char *arg5 =NULL, const char *arg6 =NULL, const char *arg7 =NULL, const char *arg8 =NULL, const char *arg9 =NULL); char *FillRnd (char *full, const char *ktag =NULL, const char *arg0 =NULL, const char *arg1 =NULL, const char *arg2 =NULL, const char *arg3 =NULL, const char *arg4 =NULL, const char *arg5 =NULL, const char *arg6 =NULL, const char *arg7 =NULL, const char *arg8 =NULL, const char *arg9 =NULL); char *Compose (char *full, const char *pattern, const char *arg0 =NULL, const char *arg1 =NULL, const char *arg2 =NULL, const char *arg3 =NULL, const char *arg4 =NULL, const char *arg5 =NULL, const char *arg6 =NULL, const char *arg7 =NULL, const char *arg8 =NULL, const char *arg9 =NULL) const; // PRIVATE MEMBER FUNCTIONS private: // low-level value functions jhcTxtList *nth_val (int n) const; const jhcTxtList *read_val (const char *vtxt, int caps) const; jhcTxtList *get_val (jhcTxtList **p, const char *vtxt); jhcTxtList *insert_val (const char *vtxt, double w); void drop_val (jhcTxtList *p, jhcTxtList *v); // random selection int enabled (int force); jhcTxtList *first_choice (); jhcTxtList *rand_choice (); // file operations char *trim_wh (char *src) const; }; #endif // once
34.55
95
0.637999
85963afcca8eca6c1bb7832716a10d2260d05acc
1,474
js
JavaScript
client/src/components/utils/InfiniteScroll.js
palaumarc/flickr_gallery
e6a194955016fa696610176c897aca1f88ab7acd
[ "MIT" ]
null
null
null
client/src/components/utils/InfiniteScroll.js
palaumarc/flickr_gallery
e6a194955016fa696610176c897aca1f88ab7acd
[ "MIT" ]
null
null
null
client/src/components/utils/InfiniteScroll.js
palaumarc/flickr_gallery
e6a194955016fa696610176c897aca1f88ab7acd
[ "MIT" ]
null
null
null
import React, { Component, Fragment } from 'react'; import PropTypes from 'prop-types'; import Spin from './Spin'; class InfiniteScroll extends Component { static propTypes = { loadMore: PropTypes.func.isRequired, hasMore: PropTypes.bool } static defaultProps = { hasMore: true } state = { isLoading: false } onScroll = () => { const { isLoading } = this.state; if (isLoading) return; // Checks that the page has scrolled to the bottom if (window.innerHeight + document.documentElement.scrollTop === document.documentElement.offsetHeight) { this.execLoadMore(); } }; execLoadMore = async () => { this.setState(prevState => ({...prevState, isLoading: true})); await this.props.loadMore() this.setState(prevState => ({...prevState, isLoading: false})); if (!this.props.hasMore) { document.removeEventListener('scroll', this.onScroll); } } async componentDidMount() { document.addEventListener('scroll', this.onScroll); // Keep loading until available height is filled or there are no more elements while (document.documentElement.offsetHeight < window.innerHeight && this.props.hasMore) { await this.execLoadMore(); } } render() { return ( <Fragment> {this.props.children} {this.state.isLoading ? <Spin /> : null} </Fragment> ) } } export default InfiniteScroll;
24.163934
110
0.630258