text
stringlengths 4
5.48M
| meta
stringlengths 14
6.54k
|
---|---|
extern "C"
{
#endif
#include <stdio.h>
typedef enum tjson_valuetype {
TJSON_TYPE_ERROR = 0,
TJSON_TYPE_STRING,
TJSON_TYPE_NUMBER,
TJSON_TYPE_BOOLEAN,
TJSON_TYPE_NULL,
TJSON_TYPE_OBJECT,
TJSON_TYPE_ARRAY
} tjson_valuetype;
typedef struct tjson_object tjson_object;
typedef struct tjson_array tjson_array;
typedef union tjson_metadata tjson_metadata;
typedef struct tjson_value tjson_value;
struct tjson_object {
const char **keys;
tjson_value **values;
size_t count;
};
struct tjson_array {
tjson_value **items;
size_t count;
};
union tjson_metadata {
const char *string;
double number;
int boolean;
int null;
tjson_object *object;
tjson_array *array;
};
struct tjson_value {
tjson_valuetype type;
tjson_metadata data;
};
tjson_value *tjson_parse_data(const char *json_data);
tjson_value *tjson_parse_file(const char *path);
void tjson_value_free(tjson_value **root);
tjson_valuetype tjson_gettype(const tjson_value *value);
int tjson_isstring(const tjson_value *value);
int tjson_isnumber(const tjson_value *value);
int tjson_isboolean(const tjson_value *value);
int tjson_isnull(const tjson_value *value);
int tjson_isobject(const tjson_value *value);
int tjson_isarray(const tjson_value *value);
int tjson_iserror(const tjson_value *value);
const char *tjson_value_string(const tjson_value *value);
double tjson_value_number(const tjson_value *value);
int tjson_value_boolean(const tjson_value *value);
int tjson_value_null(const tjson_value *value);
tjson_value *tjson_value_object(const tjson_value *value, const char *key);
tjson_value *tjson_value_array(const tjson_value *value, int index);
#ifdef __cplusplus
}
#endif
#endif
| {'content_hash': '437f07dea04ed5692a8e755881c6eec6', 'timestamp': '', 'source': 'github', 'line_count': 73, 'max_line_length': 75, 'avg_line_length': 23.65753424657534, 'alnum_prop': 0.72495657209033, 'repo_name': 'isayme/tJson', 'id': 'de66c37cccbbdd1c61f23c6e93e7f9de0a8aa6cd', 'size': '1779', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'inc/tjson.h', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '14381'}]} |
#ifndef INCLUDE_IRC_EVENTS_H
#define INCLUDE_IRC_EVENTS_H
#ifndef IN_INCLUDE_LIBIRC_H
#error This file should not be included directly, include just libircclient.h
#endif
/*!
* \fn typedef void (*irc_event_callback_t) (irc_session_t * session, const char * event, const char * origin, const char ** params, unsigned int count)
* \brief A most common event callback
*
* \param session the session, which generates an event
* \param event the text name of the event. Useful in case you use a single
* event handler for several events simultaneously.
* \param origin the originator of the event. See the note below.
* \param params a list of event params. Depending on the event nature, it
* could have zero or more params. The actual number of params
* is specified in count. None of the params can be NULL, but
* 'params' pointer itself could be NULL for some events.
* \param count the total number of params supplied.
*
* Every event generates a callback. This callback is generated by most events.
* Depending on the event nature, it can provide zero or more params. For each
* event, the number of provided params is fixed, and their meaning is
* described.
*
* Every event has origin, though the \a origin variable may be NULL, which
* means that event origin is unknown. The origin usually looks like
* nick!host\@ircserver, i.e. like tim!home\@irc.krasnogorsk.ru. Such origins
* can not be used in IRC commands, and need to be stripped (i.e. host and
* server part should be cut off) before using. This can be done either
* explicitly, by calling irc_target_get_nick(), or implicitly for all the
* events - by setting the #LIBIRC_OPTION_STRIPNICKS option with irc_option_set().
*
* \ingroup events
*/
typedef void (*irc_event_callback_t) (irc_session_t * session, const char * event, const char * origin, const char ** params, unsigned int count);
/*!
* \fn typedef void (*irc_eventcode_callback_t) (irc_session_t * session, unsigned int event, const char * origin, const char ** params, unsigned int count)
* \brief A numeric event callback
*
* \param session the session, which generates an event
* \param event the numeric code of the event. Useful in case you use a
* single event handler for several events simultaneously.
* \param origin the originator of the event. See the note below.
* \param params a list of event params. Depending on the event nature, it
* could have zero or more params. The actual number of params
* is specified in count. None of the params can be NULL, but
* 'params' pointer itself could be NULL for some events.
* \param count the total number of params supplied.
*
* Most times in reply to your actions the IRC server generates numeric
* callbacks. Most of them are error codes, and some of them mark list start
* and list stop markers. Every code has its own set of params; for details
* you can either experiment, or read RFC 1459.
*
* Every event has origin, though the \a origin variable may be NULL, which
* means that event origin is unknown. The origin usually looks like
* nick!host\@ircserver, i.e. like tim!home\@irc.krasnogorsk.ru. Such origins
* can not be used in IRC commands, and need to be stripped (i.e. host and
* server part should be cut off) before using. This can be done either
* explicitly, by calling irc_target_get_nick(), or implicitly for all the
* events - by setting the #LIBIRC_OPTION_STRIPNICKS option with irc_option_set().
*
* \ingroup events
*/
typedef void (*irc_eventcode_callback_t) (irc_session_t * session, unsigned int event, const char * origin, const char ** params, unsigned int count);
/*!
* \fn typedef void (*irc_event_dcc_chat_t) (irc_session_t * session, const char * nick, const char * addr, irc_dcc_t dccid)
* \brief A remote DCC CHAT request callback
*
* \param session the session, which generates an event
* \param nick the person who requested DCC CHAT with you.
* \param addr the person's IP address in decimal-dot notation.
* \param dccid an id associated with this request. Use it in calls to
* irc_dcc_accept() or irc_dcc_decline().
*
* This callback is called when someone requests DCC CHAT with you. In respond
* you should call either irc_dcc_accept() to accept chat request, or
* irc_dcc_decline() to decline chat request.
*
* \sa irc_dcc_accept or irc_dcc_decline
* \ingroup events
*/
typedef void (*irc_event_dcc_chat_t) (irc_session_t * session, const char * nick, const char * addr, irc_dcc_t dccid);
/*!
* \fn typedef void (*irc_event_dcc_send_t) (irc_session_t * session, const char * nick, const char * addr, const char * filename, unsigned long size, irc_dcc_t dccid)
* \brief A remote DCC CHAT request callback
*
* \param session the session, which generates an event
* \param nick the person who requested DCC CHAT with you.
* \param addr the person's IP address in decimal-dot notation.
* \param filename the sent filename.
* \param size the filename size.
* \param dccid an id associated with this request. Use it in calls to
* irc_dcc_accept() or irc_dcc_decline().
*
* This callback is called when someone wants to send a file to you using
* DCC SEND. As with chat, in respond you should call either irc_dcc_accept()
* to accept this request and receive the file, or irc_dcc_decline() to
* decline this request.
*
* \sa irc_dcc_accept or irc_dcc_decline
* \ingroup events
*/
typedef void (*irc_event_dcc_send_t) (irc_session_t * session, const char * nick, const char * addr, const char * filename, unsigned long size, irc_dcc_t dccid);
/*! \brief Event callbacks structure.
*
* All the communication with the IRC network is based on events. Generally
* speaking, event is anything generated by someone else in the network,
* or by the IRC server itself. "Someone sends you a message", "Someone
* has joined the channel", "Someone has quits IRC" - all these messages
* are events.
*
* Every event has its own event handler, which is called when the
* appropriate event is received. You don't have to define all the event
* handlers; define only the handlers for the events you need to intercept.
*
* Most event callbacks are the types of ::irc_event_callback_t. There are
* also events, which generate ::irc_eventcode_callback_t,
* ::irc_event_dcc_chat_t and ::irc_event_dcc_send_t callbacks.
*
* \ingroup events
*/
typedef struct
{
/*!
* The "on_connect" event is triggered when the client successfully
* connects to the server, and could send commands to the server.
* No extra params supplied; \a params is 0.
*/
irc_event_callback_t event_connect;
/*!
* The "nick" event is triggered when the client receives a NICK message,
* meaning that someone (including you) on a channel with the client has
* changed their nickname.
*
* \param origin the person, who changes the nick. Note that it can be you!
* \param params[0] mandatory, contains the new nick.
*/
irc_event_callback_t event_nick;
/*!
* The "quit" event is triggered upon receipt of a QUIT message, which
* means that someone on a channel with the client has disconnected.
*
* \param origin the person, who is disconnected
* \param params[0] optional, contains the reason message (user-specified).
*/
irc_event_callback_t event_quit;
/*!
* The "join" event is triggered upon receipt of a JOIN message, which
* means that someone has entered a channel that the client is on.
*
* \param origin the person, who joins the channel. By comparing it with
* your own nickname, you can check whether your JOIN
* command succeed.
* \param params[0] mandatory, contains the channel name.
*/
irc_event_callback_t event_join;
/*!
* The "part" event is triggered upon receipt of a PART message, which
* means that someone has left a channel that the client is on.
*
* \param origin the person, who leaves the channel. By comparing it with
* your own nickname, you can check whether your PART
* command succeed.
* \param params[0] mandatory, contains the channel name.
* \param params[1] optional, contains the reason message (user-defined).
*/
irc_event_callback_t event_part;
/*!
* The "mode" event is triggered upon receipt of a channel MODE message,
* which means that someone on a channel with the client has changed the
* channel's parameters.
*
* \param origin the person, who changed the channel mode.
* \param params[0] mandatory, contains the channel name.
* \param params[1] mandatory, contains the changed channel mode, like
* '+t', '-i' and so on.
* \param params[2] optional, contains the mode argument (for example, a
* key for +k mode, or user who got the channel operator status for
* +o mode)
*/
irc_event_callback_t event_mode;
/*!
* The "umode" event is triggered upon receipt of a user MODE message,
* which means that your user mode has been changed.
*
* \param origin the person, who changed the channel mode.
* \param params[0] mandatory, contains the user changed mode, like
* '+t', '-i' and so on.
*/
irc_event_callback_t event_umode;
/*!
* The "topic" event is triggered upon receipt of a TOPIC message, which
* means that someone on a channel with the client has changed the
* channel's topic.
*
* \param origin the person, who changes the channel topic.
* \param params[0] mandatory, contains the channel name.
* \param params[1] optional, contains the new topic.
*/
irc_event_callback_t event_topic;
/*!
* The "kick" event is triggered upon receipt of a KICK message, which
* means that someone on a channel with the client (or possibly the
* client itself!) has been forcibly ejected.
*
* \param origin the person, who kicked the poor.
* \param params[0] mandatory, contains the channel name.
* \param params[0] optional, contains the nick of kicked person.
* \param params[1] optional, contains the kick text
*/
irc_event_callback_t event_kick;
/*!
* The "channel" event is triggered upon receipt of a PRIVMSG message
* to an entire channel, which means that someone on a channel with
* the client has said something aloud. Your own messages don't trigger
* PRIVMSG event.
*
* \param origin the person, who generates the message.
* \param params[0] mandatory, contains the channel name.
* \param params[1] optional, contains the message text
*/
irc_event_callback_t event_channel;
/*!
* The "privmsg" event is triggered upon receipt of a PRIVMSG message
* which is addressed to one or more clients, which means that someone
* is sending the client a private message.
*
* \param origin the person, who generates the message.
* \param params[0] mandatory, contains your nick.
* \param params[1] optional, contains the message text
*/
irc_event_callback_t event_privmsg;
/*!
* The "notice" event is triggered upon receipt of a NOTICE message
* which means that someone has sent the client a public or private
* notice. According to RFC 1459, the only difference between NOTICE
* and PRIVMSG is that you should NEVER automatically reply to NOTICE
* messages. Unfortunately, this rule is frequently violated by IRC
* servers itself - for example, NICKSERV messages require reply, and
* are NOTICEs.
*
* \param origin the person, who generates the message.
* \param params[0] mandatory, contains the target nick name.
* \param params[1] optional, contains the message text
*/
irc_event_callback_t event_notice;
/*!
* The "channel_notice" event is triggered upon receipt of a NOTICE
* message which means that someone has sent the client a public
* notice. According to RFC 1459, the only difference between NOTICE
* and PRIVMSG is that you should NEVER automatically reply to NOTICE
* messages. Unfortunately, this rule is frequently violated by IRC
* servers itself - for example, NICKSERV messages require reply, and
* are NOTICEs.
*
* \param origin the person, who generates the message.
* \param params[0] mandatory, contains the channel name.
* \param params[1] optional, contains the message text
*/
irc_event_callback_t event_channel_notice;
/*!
* The "invite" event is triggered upon receipt of an INVITE message,
* which means that someone is permitting the client's entry into a +i
* channel.
*
* \param origin the person, who INVITEs you.
* \param params[0] mandatory, contains your nick.
* \param params[1] mandatory, contains the channel name you're invited into.
*
* \sa irc_cmd_invite irc_cmd_chanmode_invite
*/
irc_event_callback_t event_invite;
/*!
* The "ctcp" event is triggered when the client receives the CTCP
* request. By default, the built-in CTCP request handler is used. The
* build-in handler automatically replies on most CTCP messages, so you
* will rarely need to override it.
*
* \param origin the person, who generates the message.
* \param params[0] mandatory, the complete CTCP message, including its
* arguments.
*
* Mirc generates PING, FINGER, VERSION, TIME and ACTION messages,
* check the source code of \c libirc_event_ctcp_internal function to
* see how to write your own CTCP request handler. Also you may find
* useful this question in FAQ: \ref faq4
*/
irc_event_callback_t event_ctcp_req;
/*!
* The "ctcp" event is triggered when the client receives the CTCP reply.
*
* \param origin the person, who generates the message.
* \param params[0] mandatory, the CTCP message itself with its arguments.
*/
irc_event_callback_t event_ctcp_rep;
/*!
* The "action" event is triggered when the client receives the CTCP
* ACTION message. These messages usually looks like:\n
* \code
* [23:32:55] * Tim gonna sleep.
* \endcode
*
* \param origin the person, who generates the message.
* \param params[0] mandatory, the ACTION message.
*/
irc_event_callback_t event_ctcp_action;
/*!
* The "unknown" event is triggered upon receipt of any number of
* unclassifiable miscellaneous messages, which aren't handled by the
* library.
*/
irc_event_callback_t event_unknown;
/*!
* The "numeric" event is triggered upon receipt of any numeric response
* from the server. There is a lot of such responses, see the full list
* here: \ref rfcnumbers.
*
* See the params in ::irc_eventcode_callback_t specification.
*/
irc_eventcode_callback_t event_numeric;
/*!
* The "dcc chat" event is triggered when someone requests a DCC CHAT from
* you.
*
* See the params in ::irc_event_dcc_chat_t specification.
*/
irc_event_dcc_chat_t event_dcc_chat_req;
/*!
* The "dcc chat" event is triggered when someone wants to send a file
* to you via DCC SEND request.
*
* See the params in ::irc_event_dcc_send_t specification.
*/
irc_event_dcc_send_t event_dcc_send_req;
} irc_callbacks_t;
#endif /* INCLUDE_IRC_EVENTS_H */
| {'content_hash': 'c0c29e9d20ab6f8b9e169c7dbd413562', 'timestamp': '', 'source': 'github', 'line_count': 377, 'max_line_length': 167, 'avg_line_length': 40.76657824933687, 'alnum_prop': 0.6937992061942873, 'repo_name': 'Chronister/insobot', 'id': '15711f73e69620e67c0b86cd96ba115a5f8a77fd', 'size': '15963', 'binary': False, 'copies': '6', 'ref': 'refs/heads/hmh_bot', 'path': 'include/libirc_events.h', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '101734'}, {'name': 'C++', 'bytes': '21917'}, {'name': 'Makefile', 'bytes': '789'}, {'name': 'Shell', 'bytes': '1084'}]} |
require "spec_helper"
RSpec.describe Omniauth::Outreach do
it "has a version number" do
expect(Omniauth::Outreach::VERSION).not_to be nil
end
it "does something useful" do
expect(false).to eq(true)
end
end
| {'content_hash': '5169afaec6480d8ba8d2a5d6782e642a', 'timestamp': '', 'source': 'github', 'line_count': 11, 'max_line_length': 53, 'avg_line_length': 20.363636363636363, 'alnum_prop': 0.7098214285714286, 'repo_name': 'proleadsio/omniauth-outreach', 'id': '1bf9756f90adc547b01390fcca4f0204f21b80e3', 'size': '224', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'spec/omniauth/outreach_spec.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Ruby', 'bytes': '3540'}, {'name': 'Shell', 'bytes': '131'}]} |
#pragma once
#include <aws/route53/Route53_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
namespace Aws
{
namespace Utils
{
namespace Xml
{
class XmlNode;
} // namespace Xml
} // namespace Utils
namespace Route53
{
namespace Model
{
/**
* <p> <i>Alias resource record sets only:</i> Information about the CloudFront
* distribution, Elastic Beanstalk environment, ELB load balancer, Amazon S3
* bucket, or Amazon Route 53 resource record set to which you are redirecting
* queries. The Elastic Beanstalk environment must have a regionalized
* subdomain.</p> <p>When creating resource record sets for a private hosted zone,
* note the following:</p> <ul> <li> <p>Resource record sets cannot be created for
* CloudFront distributions in a private hosted zone.</p> </li> <li> <p>Creating
* geolocation alias resource record sets or latency alias resource record sets in
* a private hosted zone is unsupported.</p> </li> <li> <p>For information about
* creating failover resource record sets in a private hosted zone, see <a
* href="http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover-private-hosted-zones.html">Configuring
* Failover in a Private Hosted Zone</a>.</p> </li> </ul>
*/
class AWS_ROUTE53_API AliasTarget
{
public:
AliasTarget();
AliasTarget(const Aws::Utils::Xml::XmlNode& xmlNode);
AliasTarget& operator=(const Aws::Utils::Xml::XmlNode& xmlNode);
void AddToNode(Aws::Utils::Xml::XmlNode& parentNode) const;
/**
* <p> <i>Alias resource records sets only</i>: The value used depends on where the
* queries are routed:</p> <dl> <dt>A CloudFront distribution</dt> <dd> <p>Specify
* <code>Z2FDTNDATAQYW2</code>.</p> <note> <p>Alias resource record sets for
* CloudFront cannot be created in a private zone.</p> </note> </dd> <dt>Elastic
* Beanstalk environment</dt> <dd> <p>Specify the hosted zone ID for the region in
* which you created the environment. The environment must have a regionalized
* subdomain. For a list of regions and the corresponding hosted zone IDs, see <a
* href="http://docs.aws.amazon.com/general/latest/gr/rande.html#elasticbeanstalk_region">AWS
* Elastic Beanstalk</a> in the Regions and Endpoints chapter of the <i>AWS General
* Reference</i>.</p> </dd> <dt>ELB load balancer</dt> <dd> <p>Specify the value of
* the hosted zone ID for the load balancer. Use the following methods to get the
* hosted zone ID:</p> <ul> <li> <p>AWS Management Console: Go to the Amazon EC2;
* page, click Load Balancers in the navigation pane, select the load balancer, and
* get the value of the Hosted Zone ID field on the Description tab. Use the same
* process to get the DNS Name. See <a>HostedZone$Name</a>.</p> </li> <li>
* <p>Elastic Load Balancing API: Use <code>DescribeLoadBalancers</code> to get the
* value of <code>CanonicalHostedZoneNameID</code>. Use the same process to get the
* <code>CanonicalHostedZoneName</code>. See <a>HostedZone$Name</a>.</p> </li> <li>
* <p>AWS CLI: Use <code> <a
* href="http://docs.aws.amazon.com/cli/latest/reference/elb/describe-load-balancers.html">describe-load-balancers</a>
* </code> to get the value of <code>CanonicalHostedZoneNameID</code>. Use the same
* process to get the <code>CanonicalHostedZoneName</code>. See
* <a>HostedZone$Name</a>.</p> </li> </ul> </dd> <dt>An Amazon S3 bucket configured
* as a static website</dt> <dd> <p>Specify the hosted zone ID for the Amazon S3
* website endpoint in which you created the bucket. For more information about
* valid values, see the table <a
* href="http://docs.aws.amazon.com/general/latest/gr/rande.html#s3_region"> Amazon
* S3 (S3) Website Endpoints</a> in the <i>Amazon Web Services General
* Reference</i>.</p> </dd> <dt>Another Amazon Route 53 resource record set in your
* hosted zone</dt> <dd> <p>Specify the hosted zone ID of your hosted zone. (An
* alias resource record set cannot reference a resource record set in a different
* hosted zone.)</p> </dd> </dl>
*/
inline const Aws::String& GetHostedZoneId() const{ return m_hostedZoneId; }
/**
* <p> <i>Alias resource records sets only</i>: The value used depends on where the
* queries are routed:</p> <dl> <dt>A CloudFront distribution</dt> <dd> <p>Specify
* <code>Z2FDTNDATAQYW2</code>.</p> <note> <p>Alias resource record sets for
* CloudFront cannot be created in a private zone.</p> </note> </dd> <dt>Elastic
* Beanstalk environment</dt> <dd> <p>Specify the hosted zone ID for the region in
* which you created the environment. The environment must have a regionalized
* subdomain. For a list of regions and the corresponding hosted zone IDs, see <a
* href="http://docs.aws.amazon.com/general/latest/gr/rande.html#elasticbeanstalk_region">AWS
* Elastic Beanstalk</a> in the Regions and Endpoints chapter of the <i>AWS General
* Reference</i>.</p> </dd> <dt>ELB load balancer</dt> <dd> <p>Specify the value of
* the hosted zone ID for the load balancer. Use the following methods to get the
* hosted zone ID:</p> <ul> <li> <p>AWS Management Console: Go to the Amazon EC2;
* page, click Load Balancers in the navigation pane, select the load balancer, and
* get the value of the Hosted Zone ID field on the Description tab. Use the same
* process to get the DNS Name. See <a>HostedZone$Name</a>.</p> </li> <li>
* <p>Elastic Load Balancing API: Use <code>DescribeLoadBalancers</code> to get the
* value of <code>CanonicalHostedZoneNameID</code>. Use the same process to get the
* <code>CanonicalHostedZoneName</code>. See <a>HostedZone$Name</a>.</p> </li> <li>
* <p>AWS CLI: Use <code> <a
* href="http://docs.aws.amazon.com/cli/latest/reference/elb/describe-load-balancers.html">describe-load-balancers</a>
* </code> to get the value of <code>CanonicalHostedZoneNameID</code>. Use the same
* process to get the <code>CanonicalHostedZoneName</code>. See
* <a>HostedZone$Name</a>.</p> </li> </ul> </dd> <dt>An Amazon S3 bucket configured
* as a static website</dt> <dd> <p>Specify the hosted zone ID for the Amazon S3
* website endpoint in which you created the bucket. For more information about
* valid values, see the table <a
* href="http://docs.aws.amazon.com/general/latest/gr/rande.html#s3_region"> Amazon
* S3 (S3) Website Endpoints</a> in the <i>Amazon Web Services General
* Reference</i>.</p> </dd> <dt>Another Amazon Route 53 resource record set in your
* hosted zone</dt> <dd> <p>Specify the hosted zone ID of your hosted zone. (An
* alias resource record set cannot reference a resource record set in a different
* hosted zone.)</p> </dd> </dl>
*/
inline void SetHostedZoneId(const Aws::String& value) { m_hostedZoneIdHasBeenSet = true; m_hostedZoneId = value; }
/**
* <p> <i>Alias resource records sets only</i>: The value used depends on where the
* queries are routed:</p> <dl> <dt>A CloudFront distribution</dt> <dd> <p>Specify
* <code>Z2FDTNDATAQYW2</code>.</p> <note> <p>Alias resource record sets for
* CloudFront cannot be created in a private zone.</p> </note> </dd> <dt>Elastic
* Beanstalk environment</dt> <dd> <p>Specify the hosted zone ID for the region in
* which you created the environment. The environment must have a regionalized
* subdomain. For a list of regions and the corresponding hosted zone IDs, see <a
* href="http://docs.aws.amazon.com/general/latest/gr/rande.html#elasticbeanstalk_region">AWS
* Elastic Beanstalk</a> in the Regions and Endpoints chapter of the <i>AWS General
* Reference</i>.</p> </dd> <dt>ELB load balancer</dt> <dd> <p>Specify the value of
* the hosted zone ID for the load balancer. Use the following methods to get the
* hosted zone ID:</p> <ul> <li> <p>AWS Management Console: Go to the Amazon EC2;
* page, click Load Balancers in the navigation pane, select the load balancer, and
* get the value of the Hosted Zone ID field on the Description tab. Use the same
* process to get the DNS Name. See <a>HostedZone$Name</a>.</p> </li> <li>
* <p>Elastic Load Balancing API: Use <code>DescribeLoadBalancers</code> to get the
* value of <code>CanonicalHostedZoneNameID</code>. Use the same process to get the
* <code>CanonicalHostedZoneName</code>. See <a>HostedZone$Name</a>.</p> </li> <li>
* <p>AWS CLI: Use <code> <a
* href="http://docs.aws.amazon.com/cli/latest/reference/elb/describe-load-balancers.html">describe-load-balancers</a>
* </code> to get the value of <code>CanonicalHostedZoneNameID</code>. Use the same
* process to get the <code>CanonicalHostedZoneName</code>. See
* <a>HostedZone$Name</a>.</p> </li> </ul> </dd> <dt>An Amazon S3 bucket configured
* as a static website</dt> <dd> <p>Specify the hosted zone ID for the Amazon S3
* website endpoint in which you created the bucket. For more information about
* valid values, see the table <a
* href="http://docs.aws.amazon.com/general/latest/gr/rande.html#s3_region"> Amazon
* S3 (S3) Website Endpoints</a> in the <i>Amazon Web Services General
* Reference</i>.</p> </dd> <dt>Another Amazon Route 53 resource record set in your
* hosted zone</dt> <dd> <p>Specify the hosted zone ID of your hosted zone. (An
* alias resource record set cannot reference a resource record set in a different
* hosted zone.)</p> </dd> </dl>
*/
inline void SetHostedZoneId(Aws::String&& value) { m_hostedZoneIdHasBeenSet = true; m_hostedZoneId = value; }
/**
* <p> <i>Alias resource records sets only</i>: The value used depends on where the
* queries are routed:</p> <dl> <dt>A CloudFront distribution</dt> <dd> <p>Specify
* <code>Z2FDTNDATAQYW2</code>.</p> <note> <p>Alias resource record sets for
* CloudFront cannot be created in a private zone.</p> </note> </dd> <dt>Elastic
* Beanstalk environment</dt> <dd> <p>Specify the hosted zone ID for the region in
* which you created the environment. The environment must have a regionalized
* subdomain. For a list of regions and the corresponding hosted zone IDs, see <a
* href="http://docs.aws.amazon.com/general/latest/gr/rande.html#elasticbeanstalk_region">AWS
* Elastic Beanstalk</a> in the Regions and Endpoints chapter of the <i>AWS General
* Reference</i>.</p> </dd> <dt>ELB load balancer</dt> <dd> <p>Specify the value of
* the hosted zone ID for the load balancer. Use the following methods to get the
* hosted zone ID:</p> <ul> <li> <p>AWS Management Console: Go to the Amazon EC2;
* page, click Load Balancers in the navigation pane, select the load balancer, and
* get the value of the Hosted Zone ID field on the Description tab. Use the same
* process to get the DNS Name. See <a>HostedZone$Name</a>.</p> </li> <li>
* <p>Elastic Load Balancing API: Use <code>DescribeLoadBalancers</code> to get the
* value of <code>CanonicalHostedZoneNameID</code>. Use the same process to get the
* <code>CanonicalHostedZoneName</code>. See <a>HostedZone$Name</a>.</p> </li> <li>
* <p>AWS CLI: Use <code> <a
* href="http://docs.aws.amazon.com/cli/latest/reference/elb/describe-load-balancers.html">describe-load-balancers</a>
* </code> to get the value of <code>CanonicalHostedZoneNameID</code>. Use the same
* process to get the <code>CanonicalHostedZoneName</code>. See
* <a>HostedZone$Name</a>.</p> </li> </ul> </dd> <dt>An Amazon S3 bucket configured
* as a static website</dt> <dd> <p>Specify the hosted zone ID for the Amazon S3
* website endpoint in which you created the bucket. For more information about
* valid values, see the table <a
* href="http://docs.aws.amazon.com/general/latest/gr/rande.html#s3_region"> Amazon
* S3 (S3) Website Endpoints</a> in the <i>Amazon Web Services General
* Reference</i>.</p> </dd> <dt>Another Amazon Route 53 resource record set in your
* hosted zone</dt> <dd> <p>Specify the hosted zone ID of your hosted zone. (An
* alias resource record set cannot reference a resource record set in a different
* hosted zone.)</p> </dd> </dl>
*/
inline void SetHostedZoneId(const char* value) { m_hostedZoneIdHasBeenSet = true; m_hostedZoneId.assign(value); }
/**
* <p> <i>Alias resource records sets only</i>: The value used depends on where the
* queries are routed:</p> <dl> <dt>A CloudFront distribution</dt> <dd> <p>Specify
* <code>Z2FDTNDATAQYW2</code>.</p> <note> <p>Alias resource record sets for
* CloudFront cannot be created in a private zone.</p> </note> </dd> <dt>Elastic
* Beanstalk environment</dt> <dd> <p>Specify the hosted zone ID for the region in
* which you created the environment. The environment must have a regionalized
* subdomain. For a list of regions and the corresponding hosted zone IDs, see <a
* href="http://docs.aws.amazon.com/general/latest/gr/rande.html#elasticbeanstalk_region">AWS
* Elastic Beanstalk</a> in the Regions and Endpoints chapter of the <i>AWS General
* Reference</i>.</p> </dd> <dt>ELB load balancer</dt> <dd> <p>Specify the value of
* the hosted zone ID for the load balancer. Use the following methods to get the
* hosted zone ID:</p> <ul> <li> <p>AWS Management Console: Go to the Amazon EC2;
* page, click Load Balancers in the navigation pane, select the load balancer, and
* get the value of the Hosted Zone ID field on the Description tab. Use the same
* process to get the DNS Name. See <a>HostedZone$Name</a>.</p> </li> <li>
* <p>Elastic Load Balancing API: Use <code>DescribeLoadBalancers</code> to get the
* value of <code>CanonicalHostedZoneNameID</code>. Use the same process to get the
* <code>CanonicalHostedZoneName</code>. See <a>HostedZone$Name</a>.</p> </li> <li>
* <p>AWS CLI: Use <code> <a
* href="http://docs.aws.amazon.com/cli/latest/reference/elb/describe-load-balancers.html">describe-load-balancers</a>
* </code> to get the value of <code>CanonicalHostedZoneNameID</code>. Use the same
* process to get the <code>CanonicalHostedZoneName</code>. See
* <a>HostedZone$Name</a>.</p> </li> </ul> </dd> <dt>An Amazon S3 bucket configured
* as a static website</dt> <dd> <p>Specify the hosted zone ID for the Amazon S3
* website endpoint in which you created the bucket. For more information about
* valid values, see the table <a
* href="http://docs.aws.amazon.com/general/latest/gr/rande.html#s3_region"> Amazon
* S3 (S3) Website Endpoints</a> in the <i>Amazon Web Services General
* Reference</i>.</p> </dd> <dt>Another Amazon Route 53 resource record set in your
* hosted zone</dt> <dd> <p>Specify the hosted zone ID of your hosted zone. (An
* alias resource record set cannot reference a resource record set in a different
* hosted zone.)</p> </dd> </dl>
*/
inline AliasTarget& WithHostedZoneId(const Aws::String& value) { SetHostedZoneId(value); return *this;}
/**
* <p> <i>Alias resource records sets only</i>: The value used depends on where the
* queries are routed:</p> <dl> <dt>A CloudFront distribution</dt> <dd> <p>Specify
* <code>Z2FDTNDATAQYW2</code>.</p> <note> <p>Alias resource record sets for
* CloudFront cannot be created in a private zone.</p> </note> </dd> <dt>Elastic
* Beanstalk environment</dt> <dd> <p>Specify the hosted zone ID for the region in
* which you created the environment. The environment must have a regionalized
* subdomain. For a list of regions and the corresponding hosted zone IDs, see <a
* href="http://docs.aws.amazon.com/general/latest/gr/rande.html#elasticbeanstalk_region">AWS
* Elastic Beanstalk</a> in the Regions and Endpoints chapter of the <i>AWS General
* Reference</i>.</p> </dd> <dt>ELB load balancer</dt> <dd> <p>Specify the value of
* the hosted zone ID for the load balancer. Use the following methods to get the
* hosted zone ID:</p> <ul> <li> <p>AWS Management Console: Go to the Amazon EC2;
* page, click Load Balancers in the navigation pane, select the load balancer, and
* get the value of the Hosted Zone ID field on the Description tab. Use the same
* process to get the DNS Name. See <a>HostedZone$Name</a>.</p> </li> <li>
* <p>Elastic Load Balancing API: Use <code>DescribeLoadBalancers</code> to get the
* value of <code>CanonicalHostedZoneNameID</code>. Use the same process to get the
* <code>CanonicalHostedZoneName</code>. See <a>HostedZone$Name</a>.</p> </li> <li>
* <p>AWS CLI: Use <code> <a
* href="http://docs.aws.amazon.com/cli/latest/reference/elb/describe-load-balancers.html">describe-load-balancers</a>
* </code> to get the value of <code>CanonicalHostedZoneNameID</code>. Use the same
* process to get the <code>CanonicalHostedZoneName</code>. See
* <a>HostedZone$Name</a>.</p> </li> </ul> </dd> <dt>An Amazon S3 bucket configured
* as a static website</dt> <dd> <p>Specify the hosted zone ID for the Amazon S3
* website endpoint in which you created the bucket. For more information about
* valid values, see the table <a
* href="http://docs.aws.amazon.com/general/latest/gr/rande.html#s3_region"> Amazon
* S3 (S3) Website Endpoints</a> in the <i>Amazon Web Services General
* Reference</i>.</p> </dd> <dt>Another Amazon Route 53 resource record set in your
* hosted zone</dt> <dd> <p>Specify the hosted zone ID of your hosted zone. (An
* alias resource record set cannot reference a resource record set in a different
* hosted zone.)</p> </dd> </dl>
*/
inline AliasTarget& WithHostedZoneId(Aws::String&& value) { SetHostedZoneId(value); return *this;}
/**
* <p> <i>Alias resource records sets only</i>: The value used depends on where the
* queries are routed:</p> <dl> <dt>A CloudFront distribution</dt> <dd> <p>Specify
* <code>Z2FDTNDATAQYW2</code>.</p> <note> <p>Alias resource record sets for
* CloudFront cannot be created in a private zone.</p> </note> </dd> <dt>Elastic
* Beanstalk environment</dt> <dd> <p>Specify the hosted zone ID for the region in
* which you created the environment. The environment must have a regionalized
* subdomain. For a list of regions and the corresponding hosted zone IDs, see <a
* href="http://docs.aws.amazon.com/general/latest/gr/rande.html#elasticbeanstalk_region">AWS
* Elastic Beanstalk</a> in the Regions and Endpoints chapter of the <i>AWS General
* Reference</i>.</p> </dd> <dt>ELB load balancer</dt> <dd> <p>Specify the value of
* the hosted zone ID for the load balancer. Use the following methods to get the
* hosted zone ID:</p> <ul> <li> <p>AWS Management Console: Go to the Amazon EC2;
* page, click Load Balancers in the navigation pane, select the load balancer, and
* get the value of the Hosted Zone ID field on the Description tab. Use the same
* process to get the DNS Name. See <a>HostedZone$Name</a>.</p> </li> <li>
* <p>Elastic Load Balancing API: Use <code>DescribeLoadBalancers</code> to get the
* value of <code>CanonicalHostedZoneNameID</code>. Use the same process to get the
* <code>CanonicalHostedZoneName</code>. See <a>HostedZone$Name</a>.</p> </li> <li>
* <p>AWS CLI: Use <code> <a
* href="http://docs.aws.amazon.com/cli/latest/reference/elb/describe-load-balancers.html">describe-load-balancers</a>
* </code> to get the value of <code>CanonicalHostedZoneNameID</code>. Use the same
* process to get the <code>CanonicalHostedZoneName</code>. See
* <a>HostedZone$Name</a>.</p> </li> </ul> </dd> <dt>An Amazon S3 bucket configured
* as a static website</dt> <dd> <p>Specify the hosted zone ID for the Amazon S3
* website endpoint in which you created the bucket. For more information about
* valid values, see the table <a
* href="http://docs.aws.amazon.com/general/latest/gr/rande.html#s3_region"> Amazon
* S3 (S3) Website Endpoints</a> in the <i>Amazon Web Services General
* Reference</i>.</p> </dd> <dt>Another Amazon Route 53 resource record set in your
* hosted zone</dt> <dd> <p>Specify the hosted zone ID of your hosted zone. (An
* alias resource record set cannot reference a resource record set in a different
* hosted zone.)</p> </dd> </dl>
*/
inline AliasTarget& WithHostedZoneId(const char* value) { SetHostedZoneId(value); return *this;}
/**
* <p> <i>Alias resource record sets only:</i> The value that you specify depends
* on where you want to route queries:</p> <ul> <li> <p> <b>A CloudFront
* distribution:</b> Specify the domain name that CloudFront assigned when you
* created your distribution.</p> <p>Your CloudFront distribution must include an
* alternate domain name that matches the name of the resource record set. For
* example, if the name of the resource record set is <i>acme.example.com</i>, your
* CloudFront distribution must include <i>acme.example.com</i> as one of the
* alternate domain names. For more information, see <a
* href="http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/CNAMEs.html">Using
* Alternate Domain Names (CNAMEs)</a> in the <i>Amazon CloudFront Developer
* Guide</i>.</p> </li> <li> <p> <b>Elastic Beanstalk environment</b>: Specify the
* <code>CNAME</code> attribute for the environment. (The environment must have a
* regionalized domain name.) You can use the following methods to get the value of
* the CNAME attribute:</p> <ul> <li> <p> <i>AWS Managment Console</i>: For
* information about how to get the value by using the console, see <a
* href="http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/customdomains.html">Using
* Custom Domains with Elastic Beanstalk</a> in the <i>AWS Elastic Beanstalk
* Developer Guide</i>.</p> </li> <li> <p> <i>Elastic Load Balancing API</i>: Use
* the <code>DescribeEnvironments</code> action to get the value of the
* <code>CNAME</code> attribute. For more information, see <a
* href="http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/API_DescribeEnvironments.html">DescribeEnvironments</a>
* in the <i>AWS Elastic Beanstalk API Reference</i>.</p> </li> <li> <p> <i>AWS
* CLI</i>: Use the describe-environments command to get the value of the
* <code>CNAME</code> attribute. For more information, see <a
* href="http://docs.aws.amazon.com/cli/latest/reference/elasticbeanstalk/describe-environments.html">describe-environments</a>
* in the <i>AWS Command Line Interface Reference</i>.</p> </li> </ul> </li> <li>
* <p> <b>An ELB load balancer:</b> Specify the DNS name associated with the load
* balancer. Get the DNS name by using the AWS Management Console, the ELB API, or
* the AWS CLI. Use the same method to get values for <code>HostedZoneId</code> and
* <code>DNSName</code>. If you get one value from the console and the other value
* from the API or the CLI, creating the resource record set will fail.</p> <ul>
* <li> <p> <i>AWS Management Console</i>: Go to the Amazon EC2 page, click Load
* Balancers in the navigation pane, choose the load balancer, choose the
* Description tab, and get the value of the DNS Name field that begins with
* dualstack. Use the same process to get the Hosted Zone ID. See
* <a>HostedZone$Id</a>.</p> </li> <li> <p> <i>Elastic Load Balancing API</i>: Use
* <code> <a
* href="http://docs.aws.amazon.com/ElasticLoadBalancing/latest/APIReference/API_DescribeLoadBalancers.html">DescribeLoadBalancers</a>
* </code> to get the value of <code>CanonicalHostedZoneName</code>. Use the same
* process to get the <code>CanonicalHostedZoneNameId</code>. See
* <a>HostedZone$Id</a>.</p> </li> <li> <p> <i>AWS CLI</i>: Use <code> <a
* href="http://docs.aws.amazon.com/ElasticLoadBalancing/latest/APIReference/API_DescribeLoadBalancers.html">describe-load-balancers</a>
* </code> to get the value of <code>CanonicalHostedZoneName</code>. Use the same
* process to get the <code>CanonicalHostedZoneNameId</code>. See HostedZoneId.</p>
* </li> </ul> </li> <li> <p> <b>An Amazon S3 bucket that is configured as a static
* website:</b> Specify the domain name of the Amazon S3 website endpoint in which
* you created the bucket; for example,
* <code>s3-website-us-east-1.amazonaws.com</code>. For more information about
* valid values, see the table <a
* href="http://docs.aws.amazon.com/general/latest/gr/rande.html#s3_region">Amazon
* Simple Storage Service (S3) Website Endpoints</a> in the <i>Amazon Web Services
* General Reference</i>. For more information about using Amazon S3 buckets for
* websites, see <a
* href="http://docs.aws.amazon.com/AmazonS3/latest/dev/WebsiteHosting.html">Hosting
* a Static Website on Amazon S3</a> in the <i>Amazon Simple Storage Service
* Developer Guide.</i> </p> </li> <li> <p> <b>Another Amazon Route 53 resource
* record set</b>: Specify the value of the <code>Name</code> element for a
* resource record set in the current hosted zone.</p> </li> </ul>
*/
inline const Aws::String& GetDNSName() const{ return m_dNSName; }
/**
* <p> <i>Alias resource record sets only:</i> The value that you specify depends
* on where you want to route queries:</p> <ul> <li> <p> <b>A CloudFront
* distribution:</b> Specify the domain name that CloudFront assigned when you
* created your distribution.</p> <p>Your CloudFront distribution must include an
* alternate domain name that matches the name of the resource record set. For
* example, if the name of the resource record set is <i>acme.example.com</i>, your
* CloudFront distribution must include <i>acme.example.com</i> as one of the
* alternate domain names. For more information, see <a
* href="http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/CNAMEs.html">Using
* Alternate Domain Names (CNAMEs)</a> in the <i>Amazon CloudFront Developer
* Guide</i>.</p> </li> <li> <p> <b>Elastic Beanstalk environment</b>: Specify the
* <code>CNAME</code> attribute for the environment. (The environment must have a
* regionalized domain name.) You can use the following methods to get the value of
* the CNAME attribute:</p> <ul> <li> <p> <i>AWS Managment Console</i>: For
* information about how to get the value by using the console, see <a
* href="http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/customdomains.html">Using
* Custom Domains with Elastic Beanstalk</a> in the <i>AWS Elastic Beanstalk
* Developer Guide</i>.</p> </li> <li> <p> <i>Elastic Load Balancing API</i>: Use
* the <code>DescribeEnvironments</code> action to get the value of the
* <code>CNAME</code> attribute. For more information, see <a
* href="http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/API_DescribeEnvironments.html">DescribeEnvironments</a>
* in the <i>AWS Elastic Beanstalk API Reference</i>.</p> </li> <li> <p> <i>AWS
* CLI</i>: Use the describe-environments command to get the value of the
* <code>CNAME</code> attribute. For more information, see <a
* href="http://docs.aws.amazon.com/cli/latest/reference/elasticbeanstalk/describe-environments.html">describe-environments</a>
* in the <i>AWS Command Line Interface Reference</i>.</p> </li> </ul> </li> <li>
* <p> <b>An ELB load balancer:</b> Specify the DNS name associated with the load
* balancer. Get the DNS name by using the AWS Management Console, the ELB API, or
* the AWS CLI. Use the same method to get values for <code>HostedZoneId</code> and
* <code>DNSName</code>. If you get one value from the console and the other value
* from the API or the CLI, creating the resource record set will fail.</p> <ul>
* <li> <p> <i>AWS Management Console</i>: Go to the Amazon EC2 page, click Load
* Balancers in the navigation pane, choose the load balancer, choose the
* Description tab, and get the value of the DNS Name field that begins with
* dualstack. Use the same process to get the Hosted Zone ID. See
* <a>HostedZone$Id</a>.</p> </li> <li> <p> <i>Elastic Load Balancing API</i>: Use
* <code> <a
* href="http://docs.aws.amazon.com/ElasticLoadBalancing/latest/APIReference/API_DescribeLoadBalancers.html">DescribeLoadBalancers</a>
* </code> to get the value of <code>CanonicalHostedZoneName</code>. Use the same
* process to get the <code>CanonicalHostedZoneNameId</code>. See
* <a>HostedZone$Id</a>.</p> </li> <li> <p> <i>AWS CLI</i>: Use <code> <a
* href="http://docs.aws.amazon.com/ElasticLoadBalancing/latest/APIReference/API_DescribeLoadBalancers.html">describe-load-balancers</a>
* </code> to get the value of <code>CanonicalHostedZoneName</code>. Use the same
* process to get the <code>CanonicalHostedZoneNameId</code>. See HostedZoneId.</p>
* </li> </ul> </li> <li> <p> <b>An Amazon S3 bucket that is configured as a static
* website:</b> Specify the domain name of the Amazon S3 website endpoint in which
* you created the bucket; for example,
* <code>s3-website-us-east-1.amazonaws.com</code>. For more information about
* valid values, see the table <a
* href="http://docs.aws.amazon.com/general/latest/gr/rande.html#s3_region">Amazon
* Simple Storage Service (S3) Website Endpoints</a> in the <i>Amazon Web Services
* General Reference</i>. For more information about using Amazon S3 buckets for
* websites, see <a
* href="http://docs.aws.amazon.com/AmazonS3/latest/dev/WebsiteHosting.html">Hosting
* a Static Website on Amazon S3</a> in the <i>Amazon Simple Storage Service
* Developer Guide.</i> </p> </li> <li> <p> <b>Another Amazon Route 53 resource
* record set</b>: Specify the value of the <code>Name</code> element for a
* resource record set in the current hosted zone.</p> </li> </ul>
*/
inline void SetDNSName(const Aws::String& value) { m_dNSNameHasBeenSet = true; m_dNSName = value; }
/**
* <p> <i>Alias resource record sets only:</i> The value that you specify depends
* on where you want to route queries:</p> <ul> <li> <p> <b>A CloudFront
* distribution:</b> Specify the domain name that CloudFront assigned when you
* created your distribution.</p> <p>Your CloudFront distribution must include an
* alternate domain name that matches the name of the resource record set. For
* example, if the name of the resource record set is <i>acme.example.com</i>, your
* CloudFront distribution must include <i>acme.example.com</i> as one of the
* alternate domain names. For more information, see <a
* href="http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/CNAMEs.html">Using
* Alternate Domain Names (CNAMEs)</a> in the <i>Amazon CloudFront Developer
* Guide</i>.</p> </li> <li> <p> <b>Elastic Beanstalk environment</b>: Specify the
* <code>CNAME</code> attribute for the environment. (The environment must have a
* regionalized domain name.) You can use the following methods to get the value of
* the CNAME attribute:</p> <ul> <li> <p> <i>AWS Managment Console</i>: For
* information about how to get the value by using the console, see <a
* href="http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/customdomains.html">Using
* Custom Domains with Elastic Beanstalk</a> in the <i>AWS Elastic Beanstalk
* Developer Guide</i>.</p> </li> <li> <p> <i>Elastic Load Balancing API</i>: Use
* the <code>DescribeEnvironments</code> action to get the value of the
* <code>CNAME</code> attribute. For more information, see <a
* href="http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/API_DescribeEnvironments.html">DescribeEnvironments</a>
* in the <i>AWS Elastic Beanstalk API Reference</i>.</p> </li> <li> <p> <i>AWS
* CLI</i>: Use the describe-environments command to get the value of the
* <code>CNAME</code> attribute. For more information, see <a
* href="http://docs.aws.amazon.com/cli/latest/reference/elasticbeanstalk/describe-environments.html">describe-environments</a>
* in the <i>AWS Command Line Interface Reference</i>.</p> </li> </ul> </li> <li>
* <p> <b>An ELB load balancer:</b> Specify the DNS name associated with the load
* balancer. Get the DNS name by using the AWS Management Console, the ELB API, or
* the AWS CLI. Use the same method to get values for <code>HostedZoneId</code> and
* <code>DNSName</code>. If you get one value from the console and the other value
* from the API or the CLI, creating the resource record set will fail.</p> <ul>
* <li> <p> <i>AWS Management Console</i>: Go to the Amazon EC2 page, click Load
* Balancers in the navigation pane, choose the load balancer, choose the
* Description tab, and get the value of the DNS Name field that begins with
* dualstack. Use the same process to get the Hosted Zone ID. See
* <a>HostedZone$Id</a>.</p> </li> <li> <p> <i>Elastic Load Balancing API</i>: Use
* <code> <a
* href="http://docs.aws.amazon.com/ElasticLoadBalancing/latest/APIReference/API_DescribeLoadBalancers.html">DescribeLoadBalancers</a>
* </code> to get the value of <code>CanonicalHostedZoneName</code>. Use the same
* process to get the <code>CanonicalHostedZoneNameId</code>. See
* <a>HostedZone$Id</a>.</p> </li> <li> <p> <i>AWS CLI</i>: Use <code> <a
* href="http://docs.aws.amazon.com/ElasticLoadBalancing/latest/APIReference/API_DescribeLoadBalancers.html">describe-load-balancers</a>
* </code> to get the value of <code>CanonicalHostedZoneName</code>. Use the same
* process to get the <code>CanonicalHostedZoneNameId</code>. See HostedZoneId.</p>
* </li> </ul> </li> <li> <p> <b>An Amazon S3 bucket that is configured as a static
* website:</b> Specify the domain name of the Amazon S3 website endpoint in which
* you created the bucket; for example,
* <code>s3-website-us-east-1.amazonaws.com</code>. For more information about
* valid values, see the table <a
* href="http://docs.aws.amazon.com/general/latest/gr/rande.html#s3_region">Amazon
* Simple Storage Service (S3) Website Endpoints</a> in the <i>Amazon Web Services
* General Reference</i>. For more information about using Amazon S3 buckets for
* websites, see <a
* href="http://docs.aws.amazon.com/AmazonS3/latest/dev/WebsiteHosting.html">Hosting
* a Static Website on Amazon S3</a> in the <i>Amazon Simple Storage Service
* Developer Guide.</i> </p> </li> <li> <p> <b>Another Amazon Route 53 resource
* record set</b>: Specify the value of the <code>Name</code> element for a
* resource record set in the current hosted zone.</p> </li> </ul>
*/
inline void SetDNSName(Aws::String&& value) { m_dNSNameHasBeenSet = true; m_dNSName = value; }
/**
* <p> <i>Alias resource record sets only:</i> The value that you specify depends
* on where you want to route queries:</p> <ul> <li> <p> <b>A CloudFront
* distribution:</b> Specify the domain name that CloudFront assigned when you
* created your distribution.</p> <p>Your CloudFront distribution must include an
* alternate domain name that matches the name of the resource record set. For
* example, if the name of the resource record set is <i>acme.example.com</i>, your
* CloudFront distribution must include <i>acme.example.com</i> as one of the
* alternate domain names. For more information, see <a
* href="http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/CNAMEs.html">Using
* Alternate Domain Names (CNAMEs)</a> in the <i>Amazon CloudFront Developer
* Guide</i>.</p> </li> <li> <p> <b>Elastic Beanstalk environment</b>: Specify the
* <code>CNAME</code> attribute for the environment. (The environment must have a
* regionalized domain name.) You can use the following methods to get the value of
* the CNAME attribute:</p> <ul> <li> <p> <i>AWS Managment Console</i>: For
* information about how to get the value by using the console, see <a
* href="http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/customdomains.html">Using
* Custom Domains with Elastic Beanstalk</a> in the <i>AWS Elastic Beanstalk
* Developer Guide</i>.</p> </li> <li> <p> <i>Elastic Load Balancing API</i>: Use
* the <code>DescribeEnvironments</code> action to get the value of the
* <code>CNAME</code> attribute. For more information, see <a
* href="http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/API_DescribeEnvironments.html">DescribeEnvironments</a>
* in the <i>AWS Elastic Beanstalk API Reference</i>.</p> </li> <li> <p> <i>AWS
* CLI</i>: Use the describe-environments command to get the value of the
* <code>CNAME</code> attribute. For more information, see <a
* href="http://docs.aws.amazon.com/cli/latest/reference/elasticbeanstalk/describe-environments.html">describe-environments</a>
* in the <i>AWS Command Line Interface Reference</i>.</p> </li> </ul> </li> <li>
* <p> <b>An ELB load balancer:</b> Specify the DNS name associated with the load
* balancer. Get the DNS name by using the AWS Management Console, the ELB API, or
* the AWS CLI. Use the same method to get values for <code>HostedZoneId</code> and
* <code>DNSName</code>. If you get one value from the console and the other value
* from the API or the CLI, creating the resource record set will fail.</p> <ul>
* <li> <p> <i>AWS Management Console</i>: Go to the Amazon EC2 page, click Load
* Balancers in the navigation pane, choose the load balancer, choose the
* Description tab, and get the value of the DNS Name field that begins with
* dualstack. Use the same process to get the Hosted Zone ID. See
* <a>HostedZone$Id</a>.</p> </li> <li> <p> <i>Elastic Load Balancing API</i>: Use
* <code> <a
* href="http://docs.aws.amazon.com/ElasticLoadBalancing/latest/APIReference/API_DescribeLoadBalancers.html">DescribeLoadBalancers</a>
* </code> to get the value of <code>CanonicalHostedZoneName</code>. Use the same
* process to get the <code>CanonicalHostedZoneNameId</code>. See
* <a>HostedZone$Id</a>.</p> </li> <li> <p> <i>AWS CLI</i>: Use <code> <a
* href="http://docs.aws.amazon.com/ElasticLoadBalancing/latest/APIReference/API_DescribeLoadBalancers.html">describe-load-balancers</a>
* </code> to get the value of <code>CanonicalHostedZoneName</code>. Use the same
* process to get the <code>CanonicalHostedZoneNameId</code>. See HostedZoneId.</p>
* </li> </ul> </li> <li> <p> <b>An Amazon S3 bucket that is configured as a static
* website:</b> Specify the domain name of the Amazon S3 website endpoint in which
* you created the bucket; for example,
* <code>s3-website-us-east-1.amazonaws.com</code>. For more information about
* valid values, see the table <a
* href="http://docs.aws.amazon.com/general/latest/gr/rande.html#s3_region">Amazon
* Simple Storage Service (S3) Website Endpoints</a> in the <i>Amazon Web Services
* General Reference</i>. For more information about using Amazon S3 buckets for
* websites, see <a
* href="http://docs.aws.amazon.com/AmazonS3/latest/dev/WebsiteHosting.html">Hosting
* a Static Website on Amazon S3</a> in the <i>Amazon Simple Storage Service
* Developer Guide.</i> </p> </li> <li> <p> <b>Another Amazon Route 53 resource
* record set</b>: Specify the value of the <code>Name</code> element for a
* resource record set in the current hosted zone.</p> </li> </ul>
*/
inline void SetDNSName(const char* value) { m_dNSNameHasBeenSet = true; m_dNSName.assign(value); }
/**
* <p> <i>Alias resource record sets only:</i> The value that you specify depends
* on where you want to route queries:</p> <ul> <li> <p> <b>A CloudFront
* distribution:</b> Specify the domain name that CloudFront assigned when you
* created your distribution.</p> <p>Your CloudFront distribution must include an
* alternate domain name that matches the name of the resource record set. For
* example, if the name of the resource record set is <i>acme.example.com</i>, your
* CloudFront distribution must include <i>acme.example.com</i> as one of the
* alternate domain names. For more information, see <a
* href="http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/CNAMEs.html">Using
* Alternate Domain Names (CNAMEs)</a> in the <i>Amazon CloudFront Developer
* Guide</i>.</p> </li> <li> <p> <b>Elastic Beanstalk environment</b>: Specify the
* <code>CNAME</code> attribute for the environment. (The environment must have a
* regionalized domain name.) You can use the following methods to get the value of
* the CNAME attribute:</p> <ul> <li> <p> <i>AWS Managment Console</i>: For
* information about how to get the value by using the console, see <a
* href="http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/customdomains.html">Using
* Custom Domains with Elastic Beanstalk</a> in the <i>AWS Elastic Beanstalk
* Developer Guide</i>.</p> </li> <li> <p> <i>Elastic Load Balancing API</i>: Use
* the <code>DescribeEnvironments</code> action to get the value of the
* <code>CNAME</code> attribute. For more information, see <a
* href="http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/API_DescribeEnvironments.html">DescribeEnvironments</a>
* in the <i>AWS Elastic Beanstalk API Reference</i>.</p> </li> <li> <p> <i>AWS
* CLI</i>: Use the describe-environments command to get the value of the
* <code>CNAME</code> attribute. For more information, see <a
* href="http://docs.aws.amazon.com/cli/latest/reference/elasticbeanstalk/describe-environments.html">describe-environments</a>
* in the <i>AWS Command Line Interface Reference</i>.</p> </li> </ul> </li> <li>
* <p> <b>An ELB load balancer:</b> Specify the DNS name associated with the load
* balancer. Get the DNS name by using the AWS Management Console, the ELB API, or
* the AWS CLI. Use the same method to get values for <code>HostedZoneId</code> and
* <code>DNSName</code>. If you get one value from the console and the other value
* from the API or the CLI, creating the resource record set will fail.</p> <ul>
* <li> <p> <i>AWS Management Console</i>: Go to the Amazon EC2 page, click Load
* Balancers in the navigation pane, choose the load balancer, choose the
* Description tab, and get the value of the DNS Name field that begins with
* dualstack. Use the same process to get the Hosted Zone ID. See
* <a>HostedZone$Id</a>.</p> </li> <li> <p> <i>Elastic Load Balancing API</i>: Use
* <code> <a
* href="http://docs.aws.amazon.com/ElasticLoadBalancing/latest/APIReference/API_DescribeLoadBalancers.html">DescribeLoadBalancers</a>
* </code> to get the value of <code>CanonicalHostedZoneName</code>. Use the same
* process to get the <code>CanonicalHostedZoneNameId</code>. See
* <a>HostedZone$Id</a>.</p> </li> <li> <p> <i>AWS CLI</i>: Use <code> <a
* href="http://docs.aws.amazon.com/ElasticLoadBalancing/latest/APIReference/API_DescribeLoadBalancers.html">describe-load-balancers</a>
* </code> to get the value of <code>CanonicalHostedZoneName</code>. Use the same
* process to get the <code>CanonicalHostedZoneNameId</code>. See HostedZoneId.</p>
* </li> </ul> </li> <li> <p> <b>An Amazon S3 bucket that is configured as a static
* website:</b> Specify the domain name of the Amazon S3 website endpoint in which
* you created the bucket; for example,
* <code>s3-website-us-east-1.amazonaws.com</code>. For more information about
* valid values, see the table <a
* href="http://docs.aws.amazon.com/general/latest/gr/rande.html#s3_region">Amazon
* Simple Storage Service (S3) Website Endpoints</a> in the <i>Amazon Web Services
* General Reference</i>. For more information about using Amazon S3 buckets for
* websites, see <a
* href="http://docs.aws.amazon.com/AmazonS3/latest/dev/WebsiteHosting.html">Hosting
* a Static Website on Amazon S3</a> in the <i>Amazon Simple Storage Service
* Developer Guide.</i> </p> </li> <li> <p> <b>Another Amazon Route 53 resource
* record set</b>: Specify the value of the <code>Name</code> element for a
* resource record set in the current hosted zone.</p> </li> </ul>
*/
inline AliasTarget& WithDNSName(const Aws::String& value) { SetDNSName(value); return *this;}
/**
* <p> <i>Alias resource record sets only:</i> The value that you specify depends
* on where you want to route queries:</p> <ul> <li> <p> <b>A CloudFront
* distribution:</b> Specify the domain name that CloudFront assigned when you
* created your distribution.</p> <p>Your CloudFront distribution must include an
* alternate domain name that matches the name of the resource record set. For
* example, if the name of the resource record set is <i>acme.example.com</i>, your
* CloudFront distribution must include <i>acme.example.com</i> as one of the
* alternate domain names. For more information, see <a
* href="http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/CNAMEs.html">Using
* Alternate Domain Names (CNAMEs)</a> in the <i>Amazon CloudFront Developer
* Guide</i>.</p> </li> <li> <p> <b>Elastic Beanstalk environment</b>: Specify the
* <code>CNAME</code> attribute for the environment. (The environment must have a
* regionalized domain name.) You can use the following methods to get the value of
* the CNAME attribute:</p> <ul> <li> <p> <i>AWS Managment Console</i>: For
* information about how to get the value by using the console, see <a
* href="http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/customdomains.html">Using
* Custom Domains with Elastic Beanstalk</a> in the <i>AWS Elastic Beanstalk
* Developer Guide</i>.</p> </li> <li> <p> <i>Elastic Load Balancing API</i>: Use
* the <code>DescribeEnvironments</code> action to get the value of the
* <code>CNAME</code> attribute. For more information, see <a
* href="http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/API_DescribeEnvironments.html">DescribeEnvironments</a>
* in the <i>AWS Elastic Beanstalk API Reference</i>.</p> </li> <li> <p> <i>AWS
* CLI</i>: Use the describe-environments command to get the value of the
* <code>CNAME</code> attribute. For more information, see <a
* href="http://docs.aws.amazon.com/cli/latest/reference/elasticbeanstalk/describe-environments.html">describe-environments</a>
* in the <i>AWS Command Line Interface Reference</i>.</p> </li> </ul> </li> <li>
* <p> <b>An ELB load balancer:</b> Specify the DNS name associated with the load
* balancer. Get the DNS name by using the AWS Management Console, the ELB API, or
* the AWS CLI. Use the same method to get values for <code>HostedZoneId</code> and
* <code>DNSName</code>. If you get one value from the console and the other value
* from the API or the CLI, creating the resource record set will fail.</p> <ul>
* <li> <p> <i>AWS Management Console</i>: Go to the Amazon EC2 page, click Load
* Balancers in the navigation pane, choose the load balancer, choose the
* Description tab, and get the value of the DNS Name field that begins with
* dualstack. Use the same process to get the Hosted Zone ID. See
* <a>HostedZone$Id</a>.</p> </li> <li> <p> <i>Elastic Load Balancing API</i>: Use
* <code> <a
* href="http://docs.aws.amazon.com/ElasticLoadBalancing/latest/APIReference/API_DescribeLoadBalancers.html">DescribeLoadBalancers</a>
* </code> to get the value of <code>CanonicalHostedZoneName</code>. Use the same
* process to get the <code>CanonicalHostedZoneNameId</code>. See
* <a>HostedZone$Id</a>.</p> </li> <li> <p> <i>AWS CLI</i>: Use <code> <a
* href="http://docs.aws.amazon.com/ElasticLoadBalancing/latest/APIReference/API_DescribeLoadBalancers.html">describe-load-balancers</a>
* </code> to get the value of <code>CanonicalHostedZoneName</code>. Use the same
* process to get the <code>CanonicalHostedZoneNameId</code>. See HostedZoneId.</p>
* </li> </ul> </li> <li> <p> <b>An Amazon S3 bucket that is configured as a static
* website:</b> Specify the domain name of the Amazon S3 website endpoint in which
* you created the bucket; for example,
* <code>s3-website-us-east-1.amazonaws.com</code>. For more information about
* valid values, see the table <a
* href="http://docs.aws.amazon.com/general/latest/gr/rande.html#s3_region">Amazon
* Simple Storage Service (S3) Website Endpoints</a> in the <i>Amazon Web Services
* General Reference</i>. For more information about using Amazon S3 buckets for
* websites, see <a
* href="http://docs.aws.amazon.com/AmazonS3/latest/dev/WebsiteHosting.html">Hosting
* a Static Website on Amazon S3</a> in the <i>Amazon Simple Storage Service
* Developer Guide.</i> </p> </li> <li> <p> <b>Another Amazon Route 53 resource
* record set</b>: Specify the value of the <code>Name</code> element for a
* resource record set in the current hosted zone.</p> </li> </ul>
*/
inline AliasTarget& WithDNSName(Aws::String&& value) { SetDNSName(value); return *this;}
/**
* <p> <i>Alias resource record sets only:</i> The value that you specify depends
* on where you want to route queries:</p> <ul> <li> <p> <b>A CloudFront
* distribution:</b> Specify the domain name that CloudFront assigned when you
* created your distribution.</p> <p>Your CloudFront distribution must include an
* alternate domain name that matches the name of the resource record set. For
* example, if the name of the resource record set is <i>acme.example.com</i>, your
* CloudFront distribution must include <i>acme.example.com</i> as one of the
* alternate domain names. For more information, see <a
* href="http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/CNAMEs.html">Using
* Alternate Domain Names (CNAMEs)</a> in the <i>Amazon CloudFront Developer
* Guide</i>.</p> </li> <li> <p> <b>Elastic Beanstalk environment</b>: Specify the
* <code>CNAME</code> attribute for the environment. (The environment must have a
* regionalized domain name.) You can use the following methods to get the value of
* the CNAME attribute:</p> <ul> <li> <p> <i>AWS Managment Console</i>: For
* information about how to get the value by using the console, see <a
* href="http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/customdomains.html">Using
* Custom Domains with Elastic Beanstalk</a> in the <i>AWS Elastic Beanstalk
* Developer Guide</i>.</p> </li> <li> <p> <i>Elastic Load Balancing API</i>: Use
* the <code>DescribeEnvironments</code> action to get the value of the
* <code>CNAME</code> attribute. For more information, see <a
* href="http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/API_DescribeEnvironments.html">DescribeEnvironments</a>
* in the <i>AWS Elastic Beanstalk API Reference</i>.</p> </li> <li> <p> <i>AWS
* CLI</i>: Use the describe-environments command to get the value of the
* <code>CNAME</code> attribute. For more information, see <a
* href="http://docs.aws.amazon.com/cli/latest/reference/elasticbeanstalk/describe-environments.html">describe-environments</a>
* in the <i>AWS Command Line Interface Reference</i>.</p> </li> </ul> </li> <li>
* <p> <b>An ELB load balancer:</b> Specify the DNS name associated with the load
* balancer. Get the DNS name by using the AWS Management Console, the ELB API, or
* the AWS CLI. Use the same method to get values for <code>HostedZoneId</code> and
* <code>DNSName</code>. If you get one value from the console and the other value
* from the API or the CLI, creating the resource record set will fail.</p> <ul>
* <li> <p> <i>AWS Management Console</i>: Go to the Amazon EC2 page, click Load
* Balancers in the navigation pane, choose the load balancer, choose the
* Description tab, and get the value of the DNS Name field that begins with
* dualstack. Use the same process to get the Hosted Zone ID. See
* <a>HostedZone$Id</a>.</p> </li> <li> <p> <i>Elastic Load Balancing API</i>: Use
* <code> <a
* href="http://docs.aws.amazon.com/ElasticLoadBalancing/latest/APIReference/API_DescribeLoadBalancers.html">DescribeLoadBalancers</a>
* </code> to get the value of <code>CanonicalHostedZoneName</code>. Use the same
* process to get the <code>CanonicalHostedZoneNameId</code>. See
* <a>HostedZone$Id</a>.</p> </li> <li> <p> <i>AWS CLI</i>: Use <code> <a
* href="http://docs.aws.amazon.com/ElasticLoadBalancing/latest/APIReference/API_DescribeLoadBalancers.html">describe-load-balancers</a>
* </code> to get the value of <code>CanonicalHostedZoneName</code>. Use the same
* process to get the <code>CanonicalHostedZoneNameId</code>. See HostedZoneId.</p>
* </li> </ul> </li> <li> <p> <b>An Amazon S3 bucket that is configured as a static
* website:</b> Specify the domain name of the Amazon S3 website endpoint in which
* you created the bucket; for example,
* <code>s3-website-us-east-1.amazonaws.com</code>. For more information about
* valid values, see the table <a
* href="http://docs.aws.amazon.com/general/latest/gr/rande.html#s3_region">Amazon
* Simple Storage Service (S3) Website Endpoints</a> in the <i>Amazon Web Services
* General Reference</i>. For more information about using Amazon S3 buckets for
* websites, see <a
* href="http://docs.aws.amazon.com/AmazonS3/latest/dev/WebsiteHosting.html">Hosting
* a Static Website on Amazon S3</a> in the <i>Amazon Simple Storage Service
* Developer Guide.</i> </p> </li> <li> <p> <b>Another Amazon Route 53 resource
* record set</b>: Specify the value of the <code>Name</code> element for a
* resource record set in the current hosted zone.</p> </li> </ul>
*/
inline AliasTarget& WithDNSName(const char* value) { SetDNSName(value); return *this;}
/**
* <p> <i>Applies only to alias, weighted alias, latency alias, and failover alias
* record sets:</i> If you set the value of <code>EvaluateTargetHealth</code> to
* <code>true</code> for the resource record set or sets in an alias, weighted
* alias, latency alias, or failover alias resource record set, and if you specify
* a value for <code> <a>HealthCheck$Id</a> </code> for every resource record set
* that is referenced by these alias resource record sets, the alias resource
* record sets inherit the health of the referenced resource record sets.</p> <p>In
* this configuration, when Amazon Route 53 receives a DNS query for an alias
* resource record set:</p> <ul> <li> <p>Amazon Route 53 looks at the resource
* record sets that are referenced by the alias resource record sets to determine
* which health checks they're using.</p> </li> <li> <p>Amazon Route 53 checks the
* current status of each health check. (Amazon Route 53 periodically checks the
* health of the endpoint that is specified in a health check; it doesn't perform
* the health check when the DNS query arrives.)</p> </li> <li> <p>Based on the
* status of the health checks, Amazon Route 53 determines which resource record
* sets are healthy. Unhealthy resource record sets are immediately removed from
* consideration. In addition, if all of the resource record sets that are
* referenced by an alias resource record set are unhealthy, that alias resource
* record set also is immediately removed from consideration.</p> </li> <li>
* <p>Based on the configuration of the alias resource record sets (weighted alias
* or latency alias, for example) and the configuration of the resource record sets
* that they reference, Amazon Route 53 chooses a resource record set from the
* healthy resource record sets, and responds to the query.</p> </li> </ul> <p>Note
* the following:</p> <ul> <li> <p>You cannot set <code>EvaluateTargetHealth</code>
* to <code>true</code> when the alias target is a CloudFront distribution.</p>
* </li> <li> <p>If the AWS resource that you specify in <code>AliasTarget</code>
* is a resource record set or a group of resource record sets (for example, a
* group of weighted resource record sets), but it is not another alias resource
* record set, we recommend that you associate a health check with all of the
* resource record sets in the alias target.For more information, see <a
* href="http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover-complex-configs.html#dns-failover-complex-configs-hc-omitting">What
* Happens When You Omit Health Checks?</a> in the <i>Amazon Route 53 Developer
* Guide</i>.</p> </li> <li> <p>If you specify an Elastic Beanstalk environment in
* <code>HostedZoneId</code> and <code>DNSName</code>, and if the environment
* contains an ELB load balancer, Elastic Load Balancing routes queries only to the
* healthy Amazon EC2 instances that are registered with the load balancer. (An
* environment automatically contains an ELB load balancer if it includes more than
* one Amazon EC2 instance.) If you set <code>EvaluateTargetHealth</code> to
* <code>true</code> and either no Amazon EC2 instances are healthy or the load
* balancer itself is unhealthy, Amazon Route 53 routes queries to other available
* resources that are healthy, if any.</p> <p>If the environment contains a single
* Amazon EC2 instance, there are no special requirements.</p> </li> <li> <p>If you
* specify an ELB load balancer in <code> <a>AliasTarget</a> </code>, Elastic Load
* Balancing routes queries only to the healthy Amazon EC2 instances that are
* registered with the load balancer. If no Amazon EC2 instances are healthy or if
* the load balancer itself is unhealthy, and if <code>EvaluateTargetHealth</code>
* is true for the corresponding alias resource record set, Amazon Route 53 routes
* queries to other resources. When you create a load balancer, you configure
* settings for Elastic Load Balancing health checks; they're not Amazon Route 53
* health checks, but they perform a similar function. Do not create Amazon Route
* 53 health checks for the Amazon EC2 instances that you register with an ELB load
* balancer.</p> <p>For more information, see <a
* href="http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover-complex-configs.html">How
* Health Checks Work in More Complex Amazon Route 53 Configurations</a> in the
* <i>Amazon Route 53 Developers Guide</i>.</p> </li> <li> <p>We recommend that you
* set <code>EvaluateTargetHealth</code> to true only when you have enough idle
* capacity to handle the failure of one or more endpoints.</p> </li> </ul> <p>For
* more information and examples, see <a
* href="http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover.html">Amazon
* Route 53 Health Checks and DNS Failover</a> in the <i>Amazon Route 53 Developer
* Guide</i>.</p>
*/
inline bool GetEvaluateTargetHealth() const{ return m_evaluateTargetHealth; }
/**
* <p> <i>Applies only to alias, weighted alias, latency alias, and failover alias
* record sets:</i> If you set the value of <code>EvaluateTargetHealth</code> to
* <code>true</code> for the resource record set or sets in an alias, weighted
* alias, latency alias, or failover alias resource record set, and if you specify
* a value for <code> <a>HealthCheck$Id</a> </code> for every resource record set
* that is referenced by these alias resource record sets, the alias resource
* record sets inherit the health of the referenced resource record sets.</p> <p>In
* this configuration, when Amazon Route 53 receives a DNS query for an alias
* resource record set:</p> <ul> <li> <p>Amazon Route 53 looks at the resource
* record sets that are referenced by the alias resource record sets to determine
* which health checks they're using.</p> </li> <li> <p>Amazon Route 53 checks the
* current status of each health check. (Amazon Route 53 periodically checks the
* health of the endpoint that is specified in a health check; it doesn't perform
* the health check when the DNS query arrives.)</p> </li> <li> <p>Based on the
* status of the health checks, Amazon Route 53 determines which resource record
* sets are healthy. Unhealthy resource record sets are immediately removed from
* consideration. In addition, if all of the resource record sets that are
* referenced by an alias resource record set are unhealthy, that alias resource
* record set also is immediately removed from consideration.</p> </li> <li>
* <p>Based on the configuration of the alias resource record sets (weighted alias
* or latency alias, for example) and the configuration of the resource record sets
* that they reference, Amazon Route 53 chooses a resource record set from the
* healthy resource record sets, and responds to the query.</p> </li> </ul> <p>Note
* the following:</p> <ul> <li> <p>You cannot set <code>EvaluateTargetHealth</code>
* to <code>true</code> when the alias target is a CloudFront distribution.</p>
* </li> <li> <p>If the AWS resource that you specify in <code>AliasTarget</code>
* is a resource record set or a group of resource record sets (for example, a
* group of weighted resource record sets), but it is not another alias resource
* record set, we recommend that you associate a health check with all of the
* resource record sets in the alias target.For more information, see <a
* href="http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover-complex-configs.html#dns-failover-complex-configs-hc-omitting">What
* Happens When You Omit Health Checks?</a> in the <i>Amazon Route 53 Developer
* Guide</i>.</p> </li> <li> <p>If you specify an Elastic Beanstalk environment in
* <code>HostedZoneId</code> and <code>DNSName</code>, and if the environment
* contains an ELB load balancer, Elastic Load Balancing routes queries only to the
* healthy Amazon EC2 instances that are registered with the load balancer. (An
* environment automatically contains an ELB load balancer if it includes more than
* one Amazon EC2 instance.) If you set <code>EvaluateTargetHealth</code> to
* <code>true</code> and either no Amazon EC2 instances are healthy or the load
* balancer itself is unhealthy, Amazon Route 53 routes queries to other available
* resources that are healthy, if any.</p> <p>If the environment contains a single
* Amazon EC2 instance, there are no special requirements.</p> </li> <li> <p>If you
* specify an ELB load balancer in <code> <a>AliasTarget</a> </code>, Elastic Load
* Balancing routes queries only to the healthy Amazon EC2 instances that are
* registered with the load balancer. If no Amazon EC2 instances are healthy or if
* the load balancer itself is unhealthy, and if <code>EvaluateTargetHealth</code>
* is true for the corresponding alias resource record set, Amazon Route 53 routes
* queries to other resources. When you create a load balancer, you configure
* settings for Elastic Load Balancing health checks; they're not Amazon Route 53
* health checks, but they perform a similar function. Do not create Amazon Route
* 53 health checks for the Amazon EC2 instances that you register with an ELB load
* balancer.</p> <p>For more information, see <a
* href="http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover-complex-configs.html">How
* Health Checks Work in More Complex Amazon Route 53 Configurations</a> in the
* <i>Amazon Route 53 Developers Guide</i>.</p> </li> <li> <p>We recommend that you
* set <code>EvaluateTargetHealth</code> to true only when you have enough idle
* capacity to handle the failure of one or more endpoints.</p> </li> </ul> <p>For
* more information and examples, see <a
* href="http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover.html">Amazon
* Route 53 Health Checks and DNS Failover</a> in the <i>Amazon Route 53 Developer
* Guide</i>.</p>
*/
inline void SetEvaluateTargetHealth(bool value) { m_evaluateTargetHealthHasBeenSet = true; m_evaluateTargetHealth = value; }
/**
* <p> <i>Applies only to alias, weighted alias, latency alias, and failover alias
* record sets:</i> If you set the value of <code>EvaluateTargetHealth</code> to
* <code>true</code> for the resource record set or sets in an alias, weighted
* alias, latency alias, or failover alias resource record set, and if you specify
* a value for <code> <a>HealthCheck$Id</a> </code> for every resource record set
* that is referenced by these alias resource record sets, the alias resource
* record sets inherit the health of the referenced resource record sets.</p> <p>In
* this configuration, when Amazon Route 53 receives a DNS query for an alias
* resource record set:</p> <ul> <li> <p>Amazon Route 53 looks at the resource
* record sets that are referenced by the alias resource record sets to determine
* which health checks they're using.</p> </li> <li> <p>Amazon Route 53 checks the
* current status of each health check. (Amazon Route 53 periodically checks the
* health of the endpoint that is specified in a health check; it doesn't perform
* the health check when the DNS query arrives.)</p> </li> <li> <p>Based on the
* status of the health checks, Amazon Route 53 determines which resource record
* sets are healthy. Unhealthy resource record sets are immediately removed from
* consideration. In addition, if all of the resource record sets that are
* referenced by an alias resource record set are unhealthy, that alias resource
* record set also is immediately removed from consideration.</p> </li> <li>
* <p>Based on the configuration of the alias resource record sets (weighted alias
* or latency alias, for example) and the configuration of the resource record sets
* that they reference, Amazon Route 53 chooses a resource record set from the
* healthy resource record sets, and responds to the query.</p> </li> </ul> <p>Note
* the following:</p> <ul> <li> <p>You cannot set <code>EvaluateTargetHealth</code>
* to <code>true</code> when the alias target is a CloudFront distribution.</p>
* </li> <li> <p>If the AWS resource that you specify in <code>AliasTarget</code>
* is a resource record set or a group of resource record sets (for example, a
* group of weighted resource record sets), but it is not another alias resource
* record set, we recommend that you associate a health check with all of the
* resource record sets in the alias target.For more information, see <a
* href="http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover-complex-configs.html#dns-failover-complex-configs-hc-omitting">What
* Happens When You Omit Health Checks?</a> in the <i>Amazon Route 53 Developer
* Guide</i>.</p> </li> <li> <p>If you specify an Elastic Beanstalk environment in
* <code>HostedZoneId</code> and <code>DNSName</code>, and if the environment
* contains an ELB load balancer, Elastic Load Balancing routes queries only to the
* healthy Amazon EC2 instances that are registered with the load balancer. (An
* environment automatically contains an ELB load balancer if it includes more than
* one Amazon EC2 instance.) If you set <code>EvaluateTargetHealth</code> to
* <code>true</code> and either no Amazon EC2 instances are healthy or the load
* balancer itself is unhealthy, Amazon Route 53 routes queries to other available
* resources that are healthy, if any.</p> <p>If the environment contains a single
* Amazon EC2 instance, there are no special requirements.</p> </li> <li> <p>If you
* specify an ELB load balancer in <code> <a>AliasTarget</a> </code>, Elastic Load
* Balancing routes queries only to the healthy Amazon EC2 instances that are
* registered with the load balancer. If no Amazon EC2 instances are healthy or if
* the load balancer itself is unhealthy, and if <code>EvaluateTargetHealth</code>
* is true for the corresponding alias resource record set, Amazon Route 53 routes
* queries to other resources. When you create a load balancer, you configure
* settings for Elastic Load Balancing health checks; they're not Amazon Route 53
* health checks, but they perform a similar function. Do not create Amazon Route
* 53 health checks for the Amazon EC2 instances that you register with an ELB load
* balancer.</p> <p>For more information, see <a
* href="http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover-complex-configs.html">How
* Health Checks Work in More Complex Amazon Route 53 Configurations</a> in the
* <i>Amazon Route 53 Developers Guide</i>.</p> </li> <li> <p>We recommend that you
* set <code>EvaluateTargetHealth</code> to true only when you have enough idle
* capacity to handle the failure of one or more endpoints.</p> </li> </ul> <p>For
* more information and examples, see <a
* href="http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover.html">Amazon
* Route 53 Health Checks and DNS Failover</a> in the <i>Amazon Route 53 Developer
* Guide</i>.</p>
*/
inline AliasTarget& WithEvaluateTargetHealth(bool value) { SetEvaluateTargetHealth(value); return *this;}
private:
Aws::String m_hostedZoneId;
bool m_hostedZoneIdHasBeenSet;
Aws::String m_dNSName;
bool m_dNSNameHasBeenSet;
bool m_evaluateTargetHealth;
bool m_evaluateTargetHealthHasBeenSet;
};
} // namespace Model
} // namespace Route53
} // namespace Aws
| {'content_hash': 'a51cb1fbf6809c634d4c93d237358988', 'timestamp': '', 'source': 'github', 'line_count': 935, 'max_line_length': 150, 'avg_line_length': 76.04598930481284, 'alnum_prop': 0.6935712979761754, 'repo_name': 'ambasta/aws-sdk-cpp', 'id': 'da59e76370a92e169f4eed778638e57e005f7f95', 'size': '71676', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'aws-cpp-sdk-route53/include/aws/route53/model/AliasTarget.h', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '2305'}, {'name': 'C++', 'bytes': '74273816'}, {'name': 'CMake', 'bytes': '412257'}, {'name': 'Java', 'bytes': '229873'}, {'name': 'Python', 'bytes': '62933'}]} |
from .workflow import Workflow
from .workflow_manager import WorkflowManager
| {'content_hash': 'bf8e20d6717f67fa933baa6d697a5ffe', 'timestamp': '', 'source': 'github', 'line_count': 2, 'max_line_length': 45, 'avg_line_length': 38.5, 'alnum_prop': 0.8571428571428571, 'repo_name': 'IRC-SPHERE/HyperStream', 'id': 'c3b62adc826af71cf8635e6a9a6f6ea73b6fa7a5', 'size': '1210', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'hyperstream/workflow/__init__.py', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '24331'}, {'name': 'HTML', 'bytes': '16016'}, {'name': 'JavaScript', 'bytes': '94024'}, {'name': 'Jupyter Notebook', 'bytes': '60569'}, {'name': 'Makefile', 'bytes': '7617'}, {'name': 'Python', 'bytes': '742564'}, {'name': 'Shell', 'bytes': '1300'}]} |
/*
* Created on Nov 19, 2005
*/
package org.cobraparser.html.renderer;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Insets;
import java.awt.Rectangle;
import java.awt.event.MouseEvent;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.SortedSet;
import java.util.TreeSet;
import org.eclipse.jdt.annotation.NonNull;
import org.cobraparser.html.HtmlRendererContext;
import org.cobraparser.html.domimpl.HTMLElementImpl;
import org.cobraparser.html.domimpl.ModelNode;
import org.cobraparser.html.renderer.TableMatrix.RTableRowGroup;
import org.cobraparser.html.style.RenderState;
import org.cobraparser.html.style.RenderThreadState;
import org.cobraparser.ua.UserAgentContext;
import org.cobraparser.util.CollectionUtilities;
class RTable extends BaseBlockyRenderable {
private static final int MAX_CACHE_SIZE = 10;
private final Map<LayoutKey, LayoutValue> cachedLayout = new HashMap<>(5);
private final TableMatrix tableMatrix;
private SortedSet<@NonNull PositionedRenderable> positionedRenderables;
private int otherOrdinal;
private LayoutKey lastLayoutKey = null;
private LayoutValue lastLayoutValue = null;
public RTable(final HTMLElementImpl modelNode, final UserAgentContext pcontext, final HtmlRendererContext rcontext,
final FrameContext frameContext,
final RenderableContainer container) {
super(container, modelNode, pcontext);
this.tableMatrix = new TableMatrix(modelNode, pcontext, rcontext, frameContext, this, this);
}
@Override
public void paintShifted(final Graphics g) {
final RenderState rs = this.modelNode.getRenderState();
if ((rs != null) && (rs.getVisibility() != RenderState.VISIBILITY_VISIBLE)) {
// Just don't paint it.
return;
}
this.prePaint(g);
final Dimension size = this.getSize();
// TODO: No scrollbars
final TableMatrix tm = this.tableMatrix;
tm.paint(g, size);
final Collection<PositionedRenderable> prs = this.positionedRenderables;
if (prs != null) {
final Iterator<PositionedRenderable> i = prs.iterator();
while (i.hasNext()) {
final PositionedRenderable pr = i.next();
pr.paint(g);
/*
final BoundableRenderable r = pr.renderable;
r.paintTranslated(g);
*/
}
}
}
@Override
public void doLayout(final int availWidth, final int availHeight, final boolean sizeOnly) {
final Map<LayoutKey, LayoutValue> cachedLayout = this.cachedLayout;
final RenderState rs = this.modelNode.getRenderState();
final int whitespace = rs == null ? RenderState.WS_NORMAL : rs.getWhiteSpace();
final Font font = rs == null ? null : rs.getFont();
// Having whiteSpace == NOWRAP and having a NOWRAP override
// are not exactly the same thing.
final boolean overrideNoWrap = RenderThreadState.getState().overrideNoWrap;
final LayoutKey layoutKey = new LayoutKey(availWidth, availHeight, whitespace, font, overrideNoWrap);
LayoutValue layoutValue;
if (sizeOnly) {
layoutValue = cachedLayout.get(layoutKey);
} else {
if (java.util.Objects.equals(layoutKey, this.lastLayoutKey)) {
layoutValue = this.lastLayoutValue;
} else {
layoutValue = null;
}
}
if (layoutValue == null) {
final Collection<PositionedRenderable> prs = this.positionedRenderables;
if (prs != null) {
prs.clear();
}
this.otherOrdinal = 0;
this.clearGUIComponents();
this.clearDelayedPairs();
this.applyStyle(availWidth, availHeight);
final TableMatrix tm = this.tableMatrix;
final Insets insets = this.getInsets(false, false);
tm.reset(insets, availWidth, availHeight);
// TODO: No scrollbars
tm.build(availWidth, availHeight, sizeOnly);
tm.doLayout(insets);
// Import applicable delayed pairs.
// Only needs to be done if layout was forced. Otherwise, they should've been imported already.
final Collection<DelayedPair> pairs = this.delayedPairs;
if (pairs != null) {
final Iterator<DelayedPair> i = pairs.iterator();
while (i.hasNext()) {
final DelayedPair pair = i.next();
if (pair.containingBlock == this) {
this.importDelayedPair(pair);
}
}
}
layoutValue = new LayoutValue(tm.getTableWidth(), tm.getTableHeight());
if (sizeOnly) {
if (cachedLayout.size() > MAX_CACHE_SIZE) {
// Unlikely, but we should ensure it's bounded.
cachedLayout.clear();
}
cachedLayout.put(layoutKey, layoutValue);
this.lastLayoutKey = null;
this.lastLayoutValue = null;
} else {
this.lastLayoutKey = layoutKey;
this.lastLayoutValue = layoutValue;
}
}
this.width = layoutValue.width;
this.height = layoutValue.height;
this.sendGUIComponentsToParent();
this.sendDelayedPairsToParent();
}
@Override
public void invalidateLayoutLocal() {
super.invalidateLayoutLocal();
this.cachedLayout.clear();
this.lastLayoutKey = null;
this.lastLayoutValue = null;
}
/*
* (non-Javadoc)
*
* @see org.xamjwg.html.renderer.BoundableRenderable#getRenderablePoint(int,
* int)
*/
public RenderableSpot getLowestRenderableSpot(final int x, final int y) {
final Collection<PositionedRenderable> prs = this.positionedRenderables;
if (prs != null) {
final Iterator<PositionedRenderable> i = prs.iterator();
while (i.hasNext()) {
final PositionedRenderable pr = i.next();
final BoundableRenderable r = pr.renderable;
final int childX = x - r.getVisualX();
final int childY = y - r.getVisualY();
final RenderableSpot rs = r.getLowestRenderableSpot(childX, childY);
if (rs != null) {
return rs;
}
}
}
final RenderableSpot rs = this.tableMatrix.getLowestRenderableSpot(x, y);
if (rs != null) {
return rs;
}
return new RenderableSpot(this, x, y);
}
/*
* (non-Javadoc)
*
* @see
* org.xamjwg.html.renderer.BoundableRenderable#onMouseClick(java.awt.event
* .MouseEvent, int, int)
*/
public boolean onMouseClick(final MouseEvent event, final int x, final int y) {
final Collection<PositionedRenderable> prs = this.positionedRenderables;
if (prs != null) {
final Iterator<PositionedRenderable> i = prs.iterator();
while (i.hasNext()) {
final PositionedRenderable pr = i.next();
final BoundableRenderable r = pr.renderable;
final Rectangle bounds = r.getVisualBounds();
if (bounds.contains(x, y)) {
final int childX = x - r.getVisualX();
final int childY = y - r.getVisualY();
if (!r.onMouseClick(event, childX, childY)) {
return false;
}
}
}
}
return this.tableMatrix.onMouseClick(event, x, y);
}
public boolean onDoubleClick(final MouseEvent event, final int x, final int y) {
final Collection<PositionedRenderable> prs = this.positionedRenderables;
if (prs != null) {
final Iterator<PositionedRenderable> i = prs.iterator();
while (i.hasNext()) {
final PositionedRenderable pr = i.next();
final BoundableRenderable r = pr.renderable;
final Rectangle bounds = r.getVisualBounds();
if (bounds.contains(x, y)) {
final int childX = x - r.getVisualX();
final int childY = y - r.getVisualY();
if (!r.onDoubleClick(event, childX, childY)) {
return false;
}
}
}
}
return this.tableMatrix.onDoubleClick(event, x, y);
}
/*
* (non-Javadoc)
*
* @see
* org.xamjwg.html.renderer.BoundableRenderable#onMouseDisarmed(java.awt.event
* .MouseEvent)
*/
public boolean onMouseDisarmed(final MouseEvent event) {
return this.tableMatrix.onMouseDisarmed(event);
}
/*
* (non-Javadoc)
*
* @see
* org.xamjwg.html.renderer.BoundableRenderable#onMousePressed(java.awt.event
* .MouseEvent, int, int)
*/
public boolean onMousePressed(final MouseEvent event, final int x, final int y) {
final Collection<PositionedRenderable> prs = this.positionedRenderables;
if (prs != null) {
final Iterator<PositionedRenderable> i = prs.iterator();
while (i.hasNext()) {
final PositionedRenderable pr = i.next();
final BoundableRenderable r = pr.renderable;
final Rectangle bounds = r.getVisualBounds();
if (bounds.contains(x, y)) {
final int childX = x - r.getVisualX();
final int childY = y - r.getVisualY();
if (!r.onMousePressed(event, childX, childY)) {
return false;
}
}
}
}
return this.tableMatrix.onMousePressed(event, x, y);
}
/*
* (non-Javadoc)
*
* @see
* org.xamjwg.html.renderer.BoundableRenderable#onMouseReleased(java.awt.event
* .MouseEvent, int, int)
*/
public boolean onMouseReleased(final MouseEvent event, final int x, final int y) {
final Collection<PositionedRenderable> prs = this.positionedRenderables;
if (prs != null) {
final Iterator<PositionedRenderable> i = prs.iterator();
while (i.hasNext()) {
final PositionedRenderable pr = i.next();
final BoundableRenderable r = pr.renderable;
final Rectangle bounds = r.getVisualBounds();
if (bounds.contains(x, y)) {
final int childX = x - r.getVisualX();
final int childY = y - r.getVisualY();
if (!r.onMouseReleased(event, childX, childY)) {
return false;
}
}
}
}
return this.tableMatrix.onMouseReleased(event, x, y);
}
/*
* (non-Javadoc)
*
* @see org.xamjwg.html.renderer.RCollection#getRenderables()
*/
public Iterator<@NonNull ? extends Renderable> getRenderables(final boolean topFirst) {
final Collection<@NonNull PositionedRenderable> prs = this.positionedRenderables;
if (prs != null) {
final List<@NonNull Renderable> c = new java.util.LinkedList<>();
final Iterator<@NonNull PositionedRenderable> i = prs.iterator();
while (i.hasNext()) {
final PositionedRenderable pr = i.next();
final BoundableRenderable r = pr.renderable;
c.add(r);
}
final Iterator<@NonNull RAbstractCell> i2 = this.tableMatrix.getCells();
while (i2.hasNext()) {
c.add(i2.next());
}
final Iterator<@NonNull RTableRowGroup> i3 = this.tableMatrix.getRowGroups();
while (i3.hasNext()) {
c.add(i3.next());
}
if (topFirst) {
Collections.reverse(c);
}
return c.iterator();
} else {
final Iterator<@NonNull Renderable>[] rs = new Iterator[] {this.tableMatrix.getCells(), this.tableMatrix.getRowGroups()};
return CollectionUtilities.iteratorUnion(rs);
}
}
public void repaint(final ModelNode modelNode) {
// NOP
}
/*
* (non-Javadoc)
*
* @see org.xamjwg.html.renderer.RenderableContainer#getBackground()
*/
public Color getPaintedBackgroundColor() {
return this.container.getPaintedBackgroundColor();
}
private final void addPositionedRenderable(final @NonNull BoundableRenderable renderable, final boolean verticalAlignable, final boolean isFloat, final boolean isFixed) {
// Expected to be called only in GUI thread.
SortedSet<@NonNull PositionedRenderable> others = this.positionedRenderables;
if (others == null) {
others = new TreeSet<>(new ZIndexComparator());
this.positionedRenderables = others;
}
others.add(new PositionedRenderable(renderable, verticalAlignable, this.otherOrdinal++, isFloat, isFixed, false));
renderable.setParent(this);
if (renderable instanceof RUIControl) {
this.container.addComponent(((RUIControl) renderable).widget.getComponent());
}
}
private void importDelayedPair(final DelayedPair pair) {
BoundableRenderable r = pair.positionPairChild();
// final BoundableRenderable r = pair.child;
this.addPositionedRenderable(r, false, false, pair.isFixed);
}
@Override
public String toString() {
return "RTable[this=" + System.identityHashCode(this) + ",node=" + this.modelNode + "]";
}
private static class LayoutKey {
public final int availWidth;
public final int availHeight;
public final int whitespace;
public final Font font;
public final boolean overrideNoWrap;
public LayoutKey(final int availWidth, final int availHeight, final int whitespace, final Font font, final boolean overrideNoWrap) {
super();
this.availWidth = availWidth;
this.availHeight = availHeight;
this.whitespace = whitespace;
this.font = font;
this.overrideNoWrap = overrideNoWrap;
}
@Override
public boolean equals(final Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof LayoutKey)) {
return false;
}
final LayoutKey other = (LayoutKey) obj;
return (other.availWidth == this.availWidth) && (other.availHeight == this.availHeight) && (other.whitespace == this.whitespace)
&& (other.overrideNoWrap == this.overrideNoWrap) && java.util.Objects.equals(other.font, this.font);
}
@Override
public int hashCode() {
final Font font = this.font;
return ((this.availWidth * 1000) + this.availHeight) ^ (font == null ? 0 : font.hashCode()) ^ this.whitespace;
}
}
private static class LayoutValue {
public final int width;
public final int height;
public LayoutValue(final int width, final int height) {
this.width = width;
this.height = height;
}
}
@Override
public void layout(int availWidth, int availHeight, boolean b, boolean c, FloatingBoundsSource source, boolean sizeOnly) {
this.doLayout(availWidth, availHeight, sizeOnly);
}
}
| {'content_hash': 'c8efc88b22849d91fd796cb9d37a584d', 'timestamp': '', 'source': 'github', 'line_count': 417, 'max_line_length': 172, 'avg_line_length': 33.853717026378895, 'alnum_prop': 0.6625345328327549, 'repo_name': 'lobobrowser/Cobra', 'id': '9f4067ff63395a4f11309b3796d7e80f26a27a99', 'size': '14997', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/main/java/org/cobraparser/html/renderer/RTable.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'HTML', 'bytes': '1133'}, {'name': 'Java', 'bytes': '2002748'}, {'name': 'Kotlin', 'bytes': '1133'}, {'name': 'TSQL', 'bytes': '838'}]} |
require 'spec_helper'
# This spec was generated by rspec-rails when you ran the scaffold generator.
# It demonstrates how one might use RSpec to specify the controller code that
# was generated by Rails when you ran the scaffold generator.
#
# It assumes that the implementation code is generated by the rails scaffold
# generator. If you are using any extension libraries to generate different
# controller code, this generated spec may or may not pass.
#
# It only uses APIs available in rails and/or rspec-rails. There are a number
# of tools you can use to make these specs even more expressive, but we're
# sticking to rails and rspec-rails APIs to keep things simple and stable.
#
# Compared to earlier versions of this generator, there is very limited use of
# stubs and message expectations in this spec. Stubs are only used when there
# is no simpler way to get a handle on the object needed for the example.
# Message expectations are only used when there is no simpler way to specify
# that an instance is receiving a specific message.
describe StatusesController do
# This should return the minimal set of attributes required to create a valid
# Status. As you add validations to Status, be sure to
# adjust the attributes here as well.
let(:valid_attributes) { { "title" => "MyString" } }
# This should return the minimal set of values that should be in the session
# in order to pass any filters (e.g. authentication) defined in
# StatusesController. Be sure to keep this updated too.
let(:valid_session) { {} }
describe "GET index" do
it "assigns all statuses as @statuses" do
status = Status.create! valid_attributes
get :index, {}, valid_session
assigns(:statuses).should eq([status])
end
end
describe "GET show" do
it "assigns the requested status as @status" do
status = Status.create! valid_attributes
get :show, {:id => status.to_param}, valid_session
assigns(:status).should eq(status)
end
end
describe "GET new" do
it "assigns a new status as @status" do
get :new, {}, valid_session
assigns(:status).should be_a_new(Status)
end
end
describe "GET edit" do
it "assigns the requested status as @status" do
status = Status.create! valid_attributes
get :edit, {:id => status.to_param}, valid_session
assigns(:status).should eq(status)
end
end
describe "POST create" do
describe "with valid params" do
it "creates a new Status" do
expect {
post :create, {:status => valid_attributes}, valid_session
}.to change(Status, :count).by(1)
end
it "assigns a newly created status as @status" do
post :create, {:status => valid_attributes}, valid_session
assigns(:status).should be_a(Status)
assigns(:status).should be_persisted
end
it "redirects to the created status" do
post :create, {:status => valid_attributes}, valid_session
response.should redirect_to(Status.last)
end
end
describe "with invalid params" do
it "assigns a newly created but unsaved status as @status" do
# Trigger the behavior that occurs when invalid params are submitted
Status.any_instance.stub(:save).and_return(false)
post :create, {:status => { "title" => "invalid value" }}, valid_session
assigns(:status).should be_a_new(Status)
end
it "re-renders the 'new' template" do
# Trigger the behavior that occurs when invalid params are submitted
Status.any_instance.stub(:save).and_return(false)
post :create, {:status => { "title" => "invalid value" }}, valid_session
response.should render_template("new")
end
end
end
describe "PUT update" do
describe "with valid params" do
it "updates the requested status" do
status = Status.create! valid_attributes
# Assuming there are no other statuses in the database, this
# specifies that the Status created on the previous line
# receives the :update_attributes message with whatever params are
# submitted in the request.
Status.any_instance.should_receive(:update).with({ "title" => "MyString" })
put :update, {:id => status.to_param, :status => { "title" => "MyString" }}, valid_session
end
it "assigns the requested status as @status" do
status = Status.create! valid_attributes
put :update, {:id => status.to_param, :status => valid_attributes}, valid_session
assigns(:status).should eq(status)
end
it "redirects to the status" do
status = Status.create! valid_attributes
put :update, {:id => status.to_param, :status => valid_attributes}, valid_session
response.should redirect_to(status)
end
end
describe "with invalid params" do
it "assigns the status as @status" do
status = Status.create! valid_attributes
# Trigger the behavior that occurs when invalid params are submitted
Status.any_instance.stub(:save).and_return(false)
put :update, {:id => status.to_param, :status => { "title" => "invalid value" }}, valid_session
assigns(:status).should eq(status)
end
it "re-renders the 'edit' template" do
status = Status.create! valid_attributes
# Trigger the behavior that occurs when invalid params are submitted
Status.any_instance.stub(:save).and_return(false)
put :update, {:id => status.to_param, :status => { "title" => "invalid value" }}, valid_session
response.should render_template("edit")
end
end
end
describe "DELETE destroy" do
it "destroys the requested status" do
status = Status.create! valid_attributes
expect {
delete :destroy, {:id => status.to_param}, valid_session
}.to change(Status, :count).by(-1)
end
it "redirects to the statuses list" do
status = Status.create! valid_attributes
delete :destroy, {:id => status.to_param}, valid_session
response.should redirect_to(statuses_url)
end
end
end
| {'content_hash': '861ca287b4767dc924961c4270ea4ac7', 'timestamp': '', 'source': 'github', 'line_count': 160, 'max_line_length': 103, 'avg_line_length': 38.38125, 'alnum_prop': 0.6692721055202736, 'repo_name': 'Alntjan/Sinapse', 'id': '362590f3197efccae9153a7db65aeafe621566c3', 'size': '6141', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'spec/controllers/statuses_controller_spec.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '140800'}, {'name': 'CoffeeScript', 'bytes': '1899'}, {'name': 'HTML', 'bytes': '233101'}, {'name': 'JavaScript', 'bytes': '783'}, {'name': 'Ruby', 'bytes': '83171'}]} |
import "../wpt-env.js";
/* Delete created databases
*
* Go through each finished test, see if it has an associated database. Close
* that and delete the database. */
add_completion_callback(function (tests) {
for (var i in tests) {
if (tests[i].db) {
tests[i].db.close();
self.indexedDB.deleteDatabase(tests[i].db.name);
}
}
});
function fail(test, desc) {
return test.step_func(function (e) {
if (e && e.message && e.target.error)
assert_unreached(
desc + " (" + e.target.error.name + ": " + e.message + ")",
);
else if (e && e.message)
assert_unreached(desc + " (" + e.message + ")");
else if (e && e.target.readyState === "done" && e.target.error)
assert_unreached(desc + " (" + e.target.error.name + ")");
else assert_unreached(desc);
});
}
function createdb(test, dbname, version) {
var rq_open = createdb_for_multiple_tests(dbname, version);
return rq_open.setTest(test);
}
function createdb_for_multiple_tests(dbname, version) {
var rq_open,
fake_open = {},
test = null,
dbname = dbname
? dbname
: "testdb-" + new Date().getTime() + Math.random();
if (version) rq_open = self.indexedDB.open(dbname, version);
else rq_open = self.indexedDB.open(dbname);
function auto_fail(evt, current_test) {
/* Fail handlers, if we haven't set on/whatever/, don't
* expect to get event whatever. */
rq_open.manually_handled = {};
rq_open.addEventListener(evt, function (e) {
if (current_test !== test) {
return;
}
test.step(function () {
if (!rq_open.manually_handled[evt]) {
assert_unreached("unexpected open." + evt + " event");
}
if (
e.target.result + "" == "[object IDBDatabase]" &&
!this.db
) {
this.db = e.target.result;
this.db.onerror = fail(test, "unexpected db.error");
this.db.onabort = fail(test, "unexpected db.abort");
this.db.onversionchange = fail(
test,
"unexpected db.versionchange",
);
}
});
});
rq_open.__defineSetter__("on" + evt, function (h) {
rq_open.manually_handled[evt] = true;
if (!h) rq_open.addEventListener(evt, function () {});
else rq_open.addEventListener(evt, test.step_func(h));
});
}
// add a .setTest method to the IDBOpenDBRequest object
Object.defineProperty(rq_open, "setTest", {
enumerable: false,
value: function (t) {
test = t;
auto_fail("upgradeneeded", test);
auto_fail("success", test);
auto_fail("blocked", test);
auto_fail("error", test);
return this;
},
});
return rq_open;
}
function assert_key_equals(actual, expected, description) {
assert_equals(indexedDB.cmp(actual, expected), 0, description);
}
function indexeddb_test(upgrade_func, open_func, description, options) {
async_test(function (t) {
options = Object.assign({ upgrade_will_abort: false }, options);
var dbname = location + "-" + t.name;
var del = indexedDB.deleteDatabase(dbname);
del.onerror = t.unreached_func("deleteDatabase should succeed");
var open = indexedDB.open(dbname, 1);
open.onupgradeneeded = t.step_func(function () {
var db = open.result;
t.add_cleanup(function () {
// If open didn't succeed already, ignore the error.
open.onerror = function (e) {
e.preventDefault();
};
db.close();
indexedDB.deleteDatabase(db.name);
});
var tx = open.transaction;
upgrade_func(t, db, tx, open);
});
if (options.upgrade_will_abort) {
open.onsuccess = t.unreached_func("open should not succeed");
} else {
open.onerror = t.unreached_func("open should succeed");
open.onsuccess = t.step_func(function () {
var db = open.result;
if (open_func) open_func(t, db, open);
});
}
}, description);
}
// Call with a Test and an array of expected results in order. Returns
// a function; call the function when a result arrives and when the
// expected number appear the order will be asserted and test
// completed.
function expect(t, expected) {
var results = [];
return (result) => {
results.push(result);
if (results.length === expected.length) {
assert_array_equals(results, expected);
t.done();
}
};
}
// Checks to see if the passed transaction is active (by making
// requests against the named store).
function is_transaction_active(tx, store_name) {
try {
const request = tx.objectStore(store_name).get(0);
request.onerror = (e) => {
e.preventDefault();
e.stopPropagation();
};
return true;
} catch (ex) {
assert_equals(
ex.name,
"TransactionInactiveError",
"Active check should either not throw anything, or throw " +
"TransactionInactiveError",
);
return false;
}
}
// Keeps the passed transaction alive indefinitely (by making requests
// against the named store). Returns a function that asserts that the
// transaction has not already completed and then ends the request loop so that
// the transaction may autocommit and complete.
function keep_alive(tx, store_name) {
let completed = false;
tx.addEventListener("complete", () => {
completed = true;
});
let keepSpinning = true;
function spin() {
if (!keepSpinning) return;
tx.objectStore(store_name).get(0).onsuccess = spin;
}
spin();
return () => {
assert_false(completed, "Transaction completed while kept alive");
keepSpinning = false;
};
}
var t = async_test(),
open_rq = createdb(t);
open_rq.onupgradeneeded = function (e) {
var db = e.target.result;
db.createObjectStore("My cool object store name");
assert_true(
db.objectStoreNames.contains("My cool object store name"),
"objectStoreNames.contains",
);
};
open_rq.onsuccess = function (e) {
var db = e.target.result;
assert_true(
db.objectStoreNames.contains("My cool object store name"),
"objectStoreNames.contains (in success)",
);
t.done();
};
| {'content_hash': 'f6fea8971a64e09a80fdd9184ccce1f7', 'timestamp': '', 'source': 'github', 'line_count': 218, 'max_line_length': 79, 'avg_line_length': 31.495412844036696, 'alnum_prop': 0.5506845324788815, 'repo_name': 'dumbmatter/fakeIndexedDB', 'id': 'dd9951681cd94c147d258c584b879a7a8581ad69', 'size': '6866', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/test/web-platform-tests/converted/idbdatabase_createObjectStore5.js', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'HTML', 'bytes': '761271'}, {'name': 'JavaScript', 'bytes': '3534850'}, {'name': 'Shell', 'bytes': '59'}, {'name': 'TypeScript', 'bytes': '177316'}]} |
package uk.theretiredprogrammer.authentication;
import javax.servlet.annotation.WebServlet;
import uk.theretiredprogrammer.jeelibrary.PingServlet;
/**
* Servlet to handle request to ping this end point.
*
* (Class generated by NetBeans Platform Code Generator tools using script.xml.
* Do not edit this file. Apply any changes to the definition file and
* regenerate all files.)
*
* @author Richard Linsdale (richard at theretiredprogrammer.uk)
*/
@WebServlet("/")
public class AuthenticationPingServlet extends PingServlet {
}
| {'content_hash': 'd323f9fdcfd5ea9524e50d60785a33cf', 'timestamp': '', 'source': 'github', 'line_count': 18, 'max_line_length': 79, 'avg_line_length': 29.944444444444443, 'alnum_prop': 0.7829313543599258, 'repo_name': 'Richard-Linsdale/authentication', 'id': '94545aa2a987815c59b44d761feadda49a71efd0', 'size': '1275', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'src/main/java/uk/theretiredprogrammer/authentication/AuthenticationPingServlet.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '195960'}, {'name': 'Shell', 'bytes': '1149'}]} |
//
// UIView+MIPipeline.h
// MinyaDemo
//
// Created by Konka on 2016/9/27.
// Copyright © 2016年 Minya. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "MIPipeline.h"
NS_ASSUME_NONNULL_BEGIN
/**
* UIView+MIPipeline Category
*
* UIView category for pipeline
*/
@interface UIView (MIPipeline)
/**
* Set up the view's pipeline
*
* @param pipeline pipeline for current view
*/
- (void)setupPipeline:(__kindof MIPipeline * _Nonnull)pipeline;
@end
NS_ASSUME_NONNULL_END
| {'content_hash': '4745e7f51741835cdc494d7ca5950fd7', 'timestamp': '', 'source': 'github', 'line_count': 30, 'max_line_length': 63, 'avg_line_length': 16.466666666666665, 'alnum_prop': 0.6842105263157895, 'repo_name': 'southpeak/Minya', 'id': '256f134724b18438baa6c6832688dd3d108a16ee', 'size': '497', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Minya/MVCS/UIView+MIPipeline.h', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '30544'}, {'name': 'Objective-C', 'bytes': '1871443'}, {'name': 'Python', 'bytes': '4954'}, {'name': 'Ruby', 'bytes': '102'}, {'name': 'Shell', 'bytes': '9034'}]} |
checkbox
{
padding-top:1px;
padding-bottom:4px;
color:black;
}
checkbox:disabled
{
color:darkgray;
}
checkbox focus
{
border-image-slice:3 4 4 3 fill;
border-image-width:3px 4px 4px 3px;
border-image-repeat:repeat;
border-image-source:url('res:FocusDottedLine');
}
checkbox checker
{
padding-right: 3px;
background-position:center center;
background-repeat:no-repeat;
background-attachment:scroll;
width:13px;
height:13px;
}
checkbox checker:checked:normal
{
background-image:url('res:CheckBoxCheckedNormal');
}
checkbox checker:checked:hover
{
background-image:url('res:CheckBoxCheckedHot');
}
checkbox checker:checked:pressed
{
background-image:url('res:CheckBoxCheckedPressed');
}
checkbox checker:checked:disabled
{
background-image:url('res:CheckBoxCheckedDisabled');
}
checkbox checker:unchecked:normal
{
background-image:url('res:CheckBoxUncheckedNormal');
}
checkbox checker:unchecked:pressed
{
background-image:url('res:CheckBoxUncheckedPressed');
}
checkbox checker:unchecked:disabled
{
background-image:url('res:CheckBoxUncheckedDisabled');
}
checkbox checker:unchecked:hover
{
background-image:url('res:CheckBoxUncheckedHot');
}
checkbox checker:indeterminated:normal
{
background-image:url('res:CheckBoxIndeterminatedNormal');
}
checkbox checker:indeterminated:pressed
{
background-image:url('res:CheckBoxIndeterminatedPressed');
}
checkbox checker:indeterminated:disabled
{
background-image:url('res:CheckBoxIndeterminatedDisabled');
}
checkbox checker:indeterminated:hover
{
background-image:url('res:CheckBoxIndeterminatedHot');
}
| {'content_hash': '69f9f2368e6be211e73136365c96a3cd', 'timestamp': '', 'source': 'github', 'line_count': 90, 'max_line_length': 61, 'avg_line_length': 18.788888888888888, 'alnum_prop': 0.7386162034299231, 'repo_name': 'LeviOfficalDriftingRealmsDev/DriftingRealmsWorldEditor', 'id': 'f863799e657fad7c1ae17fb7a505a0cfdd9191ea', 'size': '1691', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'GUIResources/GUIThemeAero/checkbox.css', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C++', 'bytes': '647143'}, {'name': 'CSS', 'bytes': '129256'}]} |
package schema
import (
"fmt"
"testing"
. "github.com/smartystreets/goconvey/convey"
)
func TestSchema(t *testing.T) {
Convey("Schema", t, func() {
Convey("Getters/Setters", func() {
s := NewSchema()
So(s, ShouldNotBeNil)
t1 := NewTable()
t1.SetName("single_table")
s.SetTable(t1)
So(s.Table().Name(), ShouldEqual, "single_table")
for i := 1; i <= 3; i++ {
t := NewTable()
t.SetName(fmt.Sprintf("table_%d", i))
s.AddTable(t)
}
So(s.Tables(), ShouldNotBeNil)
So(s.Tables().Len(), ShouldEqual, 3)
So(s.GetTable("table_1"), ShouldNotBeNil)
So(s.GetTable("table_1").Name(), ShouldEqual, "table_1")
So(s.GetTable("table_1").IsApex(), ShouldBeTrue)
t1 = s.GetTable("table_1")
t2 := s.GetTable("table_2")
t3 := s.GetTable("table_3")
So(t1, ShouldNotBeNil)
So(t2, ShouldNotBeNil)
So(t3, ShouldNotBeNil)
t3.SetParentName(t2.Name())
t2.SetParentName(t1.Name())
err := s.Traverse()
So(err, ShouldBeNil)
So(t3.IsApex(), ShouldBeFalse)
So(t2.IsApex(), ShouldBeFalse)
So(t1.IsApex(), ShouldBeTrue)
// Child links should be set as well
So(t1.HasChild(), ShouldBeTrue)
So(t1.Child().Name(), ShouldEqual, t2.Name())
So(t2.HasChild(), ShouldBeTrue)
So(t2.Child().Name(), ShouldEqual, t3.Name())
So(t3.HasChild(), ShouldBeFalse)
So(t3.IsBottom(), ShouldBeTrue)
// Get apex
apex := t3.GetApex()
So(apex, ShouldNotBeNil)
So(apex.Name(), ShouldEqual, t1.Name())
// get apex on apex returns itself
So(t1.GetApex().Name(), ShouldEqual, t1.Name())
// GetAllRelationNames
relativeNames := t3.GetAllRelationNames()
So(relativeNames, ShouldHaveLength, 3)
So(relativeNames, ShouldContain, t1.Name())
So(relativeNames, ShouldContain, t2.Name())
So(relativeNames, ShouldContain, t3.Name())
// Missing parent tables should return error
// I actually don't even know if this is possible but it's handled
t4 := NewTable()
t4.SetName("table_4")
t4.SetParentName("NOT_EXIST")
s.AddTable(t4)
err = s.Traverse()
So(err, ShouldNotBeNil)
// Non-interleaved
t5 := NewTable()
t5.SetName("table_5")
So(t5.IsInterleaved(), ShouldBeFalse)
// getapex on non-interleaved should be nil
So(t5.GetApex(), ShouldBeNil)
})
})
}
| {'content_hash': '48fcb4cd697fe450de1a4eaf2ca14b71', 'timestamp': '', 'source': 'github', 'line_count': 93, 'max_line_length': 69, 'avg_line_length': 24.655913978494624, 'alnum_prop': 0.6428259921500218, 'repo_name': 'cloudspannerecosystem/gcsb', 'id': '9010dc7eaf72dc8f5e2d052ba0ee9ab5000d61bd', 'size': '2882', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'pkg/schema/schema_test.go', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Dockerfile', 'bytes': '411'}, {'name': 'Go', 'bytes': '268541'}, {'name': 'Makefile', 'bytes': '415'}]} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_29) on Sat Mar 17 18:06:03 MSK 2012 -->
<TITLE>
Uses of Class org.apache.poi.hwpf.model.types.SHDAbstractType (POI API Documentation)
</TITLE>
<META NAME="date" CONTENT="2012-03-17">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.apache.poi.hwpf.model.types.SHDAbstractType (POI API Documentation)";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../org/apache/poi/hwpf/model/types/SHDAbstractType.html" title="class in org.apache.poi.hwpf.model.types"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../../index.html?org/apache/poi/hwpf/model/types/\class-useSHDAbstractType.html" target="_top"><B>FRAMES</B></A>
<A HREF="SHDAbstractType.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<CENTER>
<H2>
<B>Uses of Class<br>org.apache.poi.hwpf.model.types.SHDAbstractType</B></H2>
</CENTER>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Packages that use <A HREF="../../../../../../../org/apache/poi/hwpf/model/types/SHDAbstractType.html" title="class in org.apache.poi.hwpf.model.types">SHDAbstractType</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><A HREF="#org.apache.poi.hwpf.usermodel"><B>org.apache.poi.hwpf.usermodel</B></A></TD>
<TD> </TD>
</TR>
</TABLE>
<P>
<A NAME="org.apache.poi.hwpf.usermodel"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Uses of <A HREF="../../../../../../../org/apache/poi/hwpf/model/types/SHDAbstractType.html" title="class in org.apache.poi.hwpf.model.types">SHDAbstractType</A> in <A HREF="../../../../../../../org/apache/poi/hwpf/usermodel/package-summary.html">org.apache.poi.hwpf.usermodel</A></FONT></TH>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2">Subclasses of <A HREF="../../../../../../../org/apache/poi/hwpf/model/types/SHDAbstractType.html" title="class in org.apache.poi.hwpf.model.types">SHDAbstractType</A> in <A HREF="../../../../../../../org/apache/poi/hwpf/usermodel/package-summary.html">org.apache.poi.hwpf.usermodel</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../../org/apache/poi/hwpf/usermodel/ShadingDescriptor.html" title="class in org.apache.poi.hwpf.usermodel">ShadingDescriptor</A></B></CODE>
<BR>
The SHD is a substructure of the CHP, PAP, and TC for Word 2000.</TD>
</TR>
</TABLE>
<P>
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../org/apache/poi/hwpf/model/types/SHDAbstractType.html" title="class in org.apache.poi.hwpf.model.types"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../../index.html?org/apache/poi/hwpf/model/types/\class-useSHDAbstractType.html" target="_top"><B>FRAMES</B></A>
<A HREF="SHDAbstractType.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
<i>Copyright 2012 The Apache Software Foundation or
its licensors, as applicable.</i>
</BODY>
</HTML>
| {'content_hash': '1a63fb4e465361619b0638f8e1822637', 'timestamp': '', 'source': 'github', 'line_count': 183, 'max_line_length': 326, 'avg_line_length': 44.94535519125683, 'alnum_prop': 0.6184802431610942, 'repo_name': 'Stephania16/ProductDesignGame', 'id': '8d9cde8c293fa30b4ec66be1ed422156c013bcc8', 'size': '8225', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'MinimaxAlgorithm/poi-3.8/docs/apidocs/org/apache/poi/hwpf/model/types/class-use/SHDAbstractType.html', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '15337'}, {'name': 'HTML', 'bytes': '74071650'}, {'name': 'Java', 'bytes': '37924'}]} |
An in-progress rewrite of [the 𝜋-Base topology database](https://github.com/jamesdabbs/pi-base.hs).
Major goals are:
* Extract business logic apart from persistence layer (and allow treatment of multiple axiom sets)
* Separate out a useable API and a JS-based frontend client
* Tests!
* Use Servant to generate a JS client and documentation
* Rewrite auth system (since Persona is going away)
# TODOs
* Space index / show frontend
* Search frontend
* Finish porting functionality (implementing the `error` calls)
* Add and test error monitoring | {'content_hash': '629272567aaac5a323df84ea61c85202', 'timestamp': '', 'source': 'github', 'line_count': 15, 'max_line_length': 99, 'avg_line_length': 36.46666666666667, 'alnum_prop': 0.7769652650822669, 'repo_name': 'jamesdabbs/pi-base-2', 'id': '26dd7872d49e73b1c97f9da63660e0e89dd44cb1', 'size': '565', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'README.md', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'HTML', 'bytes': '16'}, {'name': 'Haskell', 'bytes': '62631'}]} |
#include "tensorflow/core/common_runtime/threadpool_device.h"
#include "tensorflow/core/common_runtime/local_device.h"
#include "tensorflow/core/common_runtime/scoped_allocator.h"
#include "tensorflow/core/common_runtime/scoped_allocator_mgr.h"
#include "tensorflow/core/framework/allocator.h"
#include "tensorflow/core/framework/allocator_registry.h"
#include "tensorflow/core/framework/device_base.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/tensor.pb.h"
#include "tensorflow/core/framework/tensor_util.h"
#include "tensorflow/core/framework/types.h"
#include "tensorflow/core/graph/types.h"
#include "tensorflow/core/lib/hash/hash.h"
#include "tensorflow/core/platform/tracing.h"
#include "tensorflow/core/platform/types.h"
#include "tensorflow/core/public/session_options.h"
#include "tensorflow/core/util/util.h"
#ifdef INTEL_MKL
#ifdef _OPENMP
#include <omp.h>
#endif
#include "tensorflow/core/common_runtime/mkl_cpu_allocator.h"
#include "tensorflow/core/platform/cpu_info.h"
#endif
namespace tensorflow {
ThreadPoolDevice::ThreadPoolDevice(const SessionOptions& options,
const string& name, Bytes memory_limit,
const DeviceLocality& locality,
Allocator* allocator)
: LocalDevice(options, Device::BuildDeviceAttributes(
name, DEVICE_CPU, memory_limit, locality)),
allocator_(allocator),
scoped_allocator_mgr_(new ScopedAllocatorMgr(name)) {
#if !defined(ENABLE_MKLDNN_THREADPOOL) && defined(INTEL_MKL)
// Early return when MKL is disabled
if (DisableMKL()) return;
#ifdef _OPENMP
const char* user_omp_threads = getenv("OMP_NUM_THREADS");
if (user_omp_threads == nullptr) {
// OMP_NUM_THREADS controls MKL's intra-op parallelization
// Default to available physical cores
const int mkl_intra_op = port::NumSchedulableCPUs();
const int ht = port::NumHyperthreadsPerCore();
omp_set_num_threads((mkl_intra_op + ht - 1) / ht);
} else {
uint64 user_val = 0;
if (strings::safe_strtou64(user_omp_threads, &user_val)) {
// Superflous but triggers OpenMP loading
omp_set_num_threads(user_val);
}
}
#endif // _OPENMP
#endif // !defined(ENABLE_MKLDNN_THREADPOOL) && defined(INTEL_MKL)
}
ThreadPoolDevice::~ThreadPoolDevice() {}
Allocator* ThreadPoolDevice::GetAllocator(AllocatorAttributes attr) {
return allocator_;
}
Allocator* ThreadPoolDevice::GetScopedAllocator(AllocatorAttributes attr,
int64 step_id) {
if (attr.scope_id > 0) {
return scoped_allocator_mgr_->GetContainer(step_id)->GetInstance(
attr.scope_id);
}
LOG(FATAL) << "Unexpected call to ThreadPoolDevice::GetScopedAllocator "
<< "attr.scope_id = " << attr.scope_id;
return allocator_;
}
Status ThreadPoolDevice::MakeTensorFromProto(
const TensorProto& tensor_proto, const AllocatorAttributes alloc_attrs,
Tensor* tensor) {
if (tensor_proto.dtype() > 0 && tensor_proto.dtype() <= DataType_MAX) {
Tensor parsed(tensor_proto.dtype());
if (parsed.FromProto(allocator_, tensor_proto)) {
*tensor = std::move(parsed);
return Status::OK();
}
}
return errors::InvalidArgument("Cannot parse tensor from proto: ",
tensor_proto.DebugString());
}
void ThreadPoolDevice::CopyTensorInSameDevice(
const Tensor* input_tensor, Tensor* output_tensor,
const DeviceContext* device_context, StatusCallback done) {
if (input_tensor->NumElements() != output_tensor->NumElements()) {
done(errors::Internal(
"CPU->CPU copy shape mismatch: input=", input_tensor->shape(),
", output=", output_tensor->shape()));
return;
}
tensor::DeepCopy(*input_tensor, output_tensor);
done(Status::OK());
}
#ifdef INTEL_MKL
namespace {
class MklCPUAllocatorFactory : public AllocatorFactory {
public:
bool NumaEnabled() override { return false; }
Allocator* CreateAllocator() override { return new MklCPUAllocator; }
// Note: Ignores numa_node, for now.
virtual SubAllocator* CreateSubAllocator(int numa_node) {
return new MklSubAllocator;
}
};
#ifdef ENABLE_MKL
REGISTER_MEM_ALLOCATOR("MklCPUAllocator", (DisableMKL() ? 50 : 200),
MklCPUAllocatorFactory);
#endif // ENABLE_MKL
} // namespace
#endif // INTEL_MKL
} // namespace tensorflow
| {'content_hash': '0dac501b8929128f2107089d620c585e', 'timestamp': '', 'source': 'github', 'line_count': 128, 'max_line_length': 75, 'avg_line_length': 34.875, 'alnum_prop': 0.6852598566308243, 'repo_name': 'aldian/tensorflow', 'id': '44fa5bf2d3a8c20814e11b581d5bbddbabfc9bf6', 'size': '5132', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'tensorflow/core/common_runtime/threadpool_device.cc', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '8458'}, {'name': 'C', 'bytes': '201402'}, {'name': 'C++', 'bytes': '29667924'}, {'name': 'CMake', 'bytes': '647100'}, {'name': 'Go', 'bytes': '976514'}, {'name': 'Java', 'bytes': '412117'}, {'name': 'Jupyter Notebook', 'bytes': '1833675'}, {'name': 'LLVM', 'bytes': '6536'}, {'name': 'Makefile', 'bytes': '38128'}, {'name': 'Objective-C', 'bytes': '7056'}, {'name': 'Objective-C++', 'bytes': '63210'}, {'name': 'Perl', 'bytes': '6715'}, {'name': 'Protocol Buffer', 'bytes': '275733'}, {'name': 'PureBasic', 'bytes': '24932'}, {'name': 'Python', 'bytes': '26424665'}, {'name': 'Ruby', 'bytes': '327'}, {'name': 'Shell', 'bytes': '373109'}]} |
date: 2016-09-13T09:00:00+00:00
title: Virtual Hosts
menu:
main:
identifier: "virtual-hosts-v095"
parent: "Using Vamp"
weight: 180
---
Vamp can leverage the virtual hosting offered by HAproxy to support serving multiple endpoints on for example port 80
and port 443. This mostly comes in handy when you are offering public (internet) facing services where adding a port number
to a URL is not an option.
## Enabling Virtual Hosts
To enable the use of virtual hosts you need to configure the following options in the Vamp configuration.
The option `virtual-hosts-domain` functions as the TLD and can be anything you like. In our example this means we could
create virtual hosts like `myservices.mydomain.vamp`
```
vamp.operation.gateway {
virtual-hosts = true
virtual-hosts-domain = "vamp"
}
```
## Automatic Virtual Hosts
When Vamp is configured to allow virtual hosting, Vamp automatically creates a virtual host and binds it to port 80
for each gateway you define using the following pattern:
```
{ PORT }.{ DEPLOYMENT NAME }.{ DOMAIN }
```
{{< note title="Note!" >}}
Virtual hosts are automatically bound to port 80! You do not need supply that port anywhere in the configuration.
{{< /note >}}
Let's say we deploy the following blueprint: a deployment called `simpleservice` with a gateway defined on port `9050`.
```yaml
name: simpleservice
gateways:
9050: simpleservice/web
clusters:
simpleservice:
services:
breed:
name: simpleservice:1.0.0
deployable: magneticio/simpleservice:1.0.0
ports:
web: 3000/http
scale:
cpu: 0.2
memory: 128MB
instances: 1
```
After deployment, we have an external gateway called `simpleservice/9050` with a virtual host called `9050.simpleservice.vamp`.
This service is now available on port `9050` but also on port `80` when explicitly using the virtual host name in het HOST
header of the HTTP request,
i.e using HTTPie
```bash
http ${VAMP_GATEWAY_AGENT_IP} Host:9050.simpleservice.vamp
```
or using Curl
```bash
curl --resolve 9050.simpleservice.vamp:80:${VAMP_GATEWAY_AGENT_IP} http://9050.simpleservice.vamp
```
This means you could put a `CNAME` record in your DNS pointing `9050.simpleservice.vamp` to the IP of your public facing
Vamp Gateway.
{{< note title="Note!" >}}
If you are running Vamp in one of the quick setups, `${VAMP_GATEWAY_AGENT_IP}` should have value of `${DOCKER_HOST_IP}` - See the [hello world quick setup instructions](/documentation/installation/hello-world#step-2-run-vamp).
{{< /note >}}
## Custom Virtual Hosts
In addition to automatically generated virtual hosts, you can also provide your own virtual host name(s). We just need to
expand the gateway definition a bit, adding separate `routes` and `virtual_hosts` keys. Afte deployment, you can leverage
the same
```yaml
name: simpleservice
gateways:
9050:
routes: simpleservice/web
virtual_hosts: ["my.simple-vhost.service", "alternative.simple-vhost.name"]
clusters:
simpleservice:
services:
breed:
name: simpleservice:1.0.0
deployable: magneticio/simpleservice:1.0.0
ports:
web: 3000/http
scale:
cpu: 0.2
memory: 128MB
instances: 1
```
{{< note title="What next?" >}}
* Check the [API documentation](/documentation/api/v0.9.5/api-reference)
* [Try Vamp](/documentation/installation/hello-world)
{{< /note >}}
| {'content_hash': '3396e36d74a698f4e3328f3829a17169', 'timestamp': '', 'source': 'github', 'line_count': 115, 'max_line_length': 226, 'avg_line_length': 29.704347826086956, 'alnum_prop': 0.7201405152224825, 'repo_name': 'magneticio/vamp.io', 'id': '4c6b999a052ae05f7f2d412c5e2dd0c6b57bcd8a', 'size': '3420', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'content/documentation/using vamp/v0.9.5/virtual-hosts.md', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '297439'}, {'name': 'HTML', 'bytes': '142384'}, {'name': 'JavaScript', 'bytes': '546033'}, {'name': 'Shell', 'bytes': '31347'}]} |
* Contributor may contribute code, tests, ideas and feedback via e-mail: [email protected] or via GitHub
* Maintainers may, but not have to use the contribution
* Maintainers may use the contribution in its entirety, or just part(s) of it, modified or unmodified
* Contributor by contributing a contribution is giving consent for using and publishing the contribution under [MIT license](http://opensource.org/licenses/MIT) with current or future [license headers](LICENSE)
* Please contribute only those contributions for which you have right to contribute and to give before mentioned consent
##### Contributing code or tests via GitHub:
* Fork the project.
* Make your feature addition or bug fix.
* Add tests for it. This is important so I don't break it in a future version unintentionally.
* Commit just the modifications, do not mess with the composer.json or CHANGELOG.md files.
* Ensure your code is nicely formatted in the [PSR-2](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md)
style and that all tests pass.
* Send the pull request.
* Check that the Travis CI build passed. If not, rinse and repeat.
| {'content_hash': 'af53c31354dbedc0d86570ed9445e254', 'timestamp': '', 'source': 'github', 'line_count': 16, 'max_line_length': 210, 'avg_line_length': 72.6875, 'alnum_prop': 0.7824591573516767, 'repo_name': 'derdiggn/omnipay-klarna', 'id': 'ecb58dd5c551361760c10d4ad939f7bd0d0efe43', 'size': '1205', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'CONTRIBUTING.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'PHP', 'bytes': '138406'}]} |
@interface PedidoRequest : NSObject
@property (retain, readonly) NSString *CodigoAutorizacao;
@property (retain) DadosPedidoRequest *DadosPedido;
@property (retain) DadosAntiFraudeRequest *DadosAntiFraude;
- (id)init;
- (void)criarPedido:(PedidoRequest *) objPedidoRequest completo:(void (^)(PedidoResponse *objPedidoResponse))block;
@end
| {'content_hash': '8525dacab68d834bd32d103784586843', 'timestamp': '', 'source': 'github', 'line_count': 8, 'max_line_length': 115, 'avg_line_length': 42.5, 'alnum_prop': 0.8, 'repo_name': 'onebuy/onebuy_crossapp_ios', 'id': 'be7c55dedf683e90a67c0417da10319dc77a55e5', 'size': '651', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'OneBuy/Request/PedidoRequest.h', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Objective-C', 'bytes': '128603'}, {'name': 'Ruby', 'bytes': '544'}]} |
package dtos.validation.validators;
import dtos.validation.ValidationErrorMessage;
import dtos.validation.ValidationException;
import dtos.validation.Validator;
import java.util.Collection;
import java.util.LinkedList;
/**
* Checks if the given ipAddress is a valid ip address
* with respect to ipV4.
* <p>
* Licensed under Apache 2.0 License, copyright for the regex by Google
*
* @see <a href="https://developers.google.com/web/fundamentals/input/form/provide-real-time-validation">Google WebFundamentals</a>
*/
public class IpV4AddressValidator implements Validator<String> {
private static final String IPV4Regex =
"^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$";
@Override public Collection<ValidationErrorMessage> validate(String s)
throws ValidationException {
if (s == null) {
throw new ValidationException("Given ip address must not be null.");
}
Collection<ValidationErrorMessage> validationErrorMessages = new LinkedList<>();
if (!s.matches(IPV4Regex)) {
validationErrorMessages
.add(ValidationErrorMessage.of(String.format("%s is not a valid ipv4 address", s)));
}
return validationErrorMessages;
}
}
| {'content_hash': 'cd4216f4501ea0010554e4e0836c7627', 'timestamp': '', 'source': 'github', 'line_count': 38, 'max_line_length': 131, 'avg_line_length': 33.973684210526315, 'alnum_prop': 0.6793183578621224, 'repo_name': 'ech1965/colosseum', 'id': 'b3d75317786b013e20ef9179d24cb13cf5526cd4', 'size': '2010', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'app/dtos/validation/validators/IpV4AddressValidator.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '4089'}, {'name': 'HTML', 'bytes': '482'}, {'name': 'Java', 'bytes': '968793'}, {'name': 'JavaScript', 'bytes': '1522'}, {'name': 'Scala', 'bytes': '3668'}]} |
from __future__ import absolute_import
# Copyright (c) 2010-2015 openpyxl
from openpyxl.descriptors import Float, Set, Sequence, Alias, NoneSet
from openpyxl.compat import safe_string
from .colors import ColorDescriptor, Color
from .hashable import HashableObject
from openpyxl.xml.functions import Element, localname, safe_iterator
from openpyxl.xml.constants import SHEET_MAIN_NS
FILL_NONE = 'none'
FILL_SOLID = 'solid'
FILL_PATTERN_DARKDOWN = 'darkDown'
FILL_PATTERN_DARKGRAY = 'darkGray'
FILL_PATTERN_DARKGRID = 'darkGrid'
FILL_PATTERN_DARKHORIZONTAL = 'darkHorizontal'
FILL_PATTERN_DARKTRELLIS = 'darkTrellis'
FILL_PATTERN_DARKUP = 'darkUp'
FILL_PATTERN_DARKVERTICAL = 'darkVertical'
FILL_PATTERN_GRAY0625 = 'gray0625'
FILL_PATTERN_GRAY125 = 'gray125'
FILL_PATTERN_LIGHTDOWN = 'lightDown'
FILL_PATTERN_LIGHTGRAY = 'lightGray'
FILL_PATTERN_LIGHTGRID = 'lightGrid'
FILL_PATTERN_LIGHTHORIZONTAL = 'lightHorizontal'
FILL_PATTERN_LIGHTTRELLIS = 'lightTrellis'
FILL_PATTERN_LIGHTUP = 'lightUp'
FILL_PATTERN_LIGHTVERTICAL = 'lightVertical'
FILL_PATTERN_MEDIUMGRAY = 'mediumGray'
fills = (FILL_SOLID, FILL_PATTERN_DARKDOWN, FILL_PATTERN_DARKGRAY,
FILL_PATTERN_DARKGRID, FILL_PATTERN_DARKHORIZONTAL, FILL_PATTERN_DARKTRELLIS,
FILL_PATTERN_DARKUP, FILL_PATTERN_DARKVERTICAL, FILL_PATTERN_GRAY0625,
FILL_PATTERN_GRAY125, FILL_PATTERN_LIGHTDOWN, FILL_PATTERN_LIGHTGRAY,
FILL_PATTERN_LIGHTGRID, FILL_PATTERN_LIGHTHORIZONTAL,
FILL_PATTERN_LIGHTTRELLIS, FILL_PATTERN_LIGHTUP, FILL_PATTERN_LIGHTVERTICAL,
FILL_PATTERN_MEDIUMGRAY)
class Fill(HashableObject):
"""Base class"""
tagname = "fill"
@classmethod
def from_tree(cls, el):
children = [c for c in el]
if not children:
return
child = children[0]
if "patternFill" in child.tag:
return PatternFill._from_tree(child)
else:
return GradientFill._from_tree(child)
class PatternFill(Fill):
"""Area fill patterns for use in styles.
Caution: if you do not specify a fill_type, other attributes will have
no effect !"""
tagname = "patternFill"
__fields__ = ('patternType',
'fgColor',
'bgColor')
__elements__ = ('fgColor', 'bgColor')
patternType = NoneSet(values=fills)
fill_type = Alias("patternType")
fgColor = ColorDescriptor()
start_color = Alias("fgColor")
bgColor = ColorDescriptor()
end_color = Alias("bgColor")
def __init__(self, patternType=None, fgColor=Color(), bgColor=Color(),
fill_type=None, start_color=None, end_color=None):
if fill_type is not None:
patternType = fill_type
self.patternType = patternType
if start_color is not None:
fgColor = start_color
self.fgColor = fgColor
if end_color is not None:
bgColor = end_color
self.bgColor = bgColor
@classmethod
def _from_tree(cls, el):
attrib = dict(el.attrib)
for child in el:
desc = localname(child)
attrib[desc] = Color.from_tree(child)
return cls(**attrib)
def to_tree(self, tagname=None):
parent = Element("fill")
el = Element(self.tagname)
if self.patternType is not None:
el.set('patternType', self.patternType)
for c in self.__elements__:
value = getattr(self, c)
if value != Color():
el.append(value.to_tree(c))
parent.append(el)
return parent
DEFAULT_EMPTY_FILL = PatternFill()
DEFAULT_GRAY_FILL = PatternFill(patternType='gray125')
class GradientFill(Fill):
tagname = "gradientFill"
__fields__ = ('type', 'degree', 'left', 'right', 'top', 'bottom', 'stop')
type = Set(values=('linear', 'path'))
fill_type = Alias("type")
degree = Float()
left = Float()
right = Float()
top = Float()
bottom = Float()
stop = Sequence(expected_type=Color, nested=True)
def __init__(self, type="linear", degree=0, left=0, right=0, top=0,
bottom=0, stop=(), fill_type=None):
self.degree = degree
self.left = left
self.right = right
self.top = top
self.bottom = bottom
self.stop = stop
if fill_type is not None:
type = fill_type
self.type = type
def __iter__(self):
for attr in self.__attrs__:
value = getattr(self, attr)
if value:
yield attr, safe_string(value)
@classmethod
def _from_tree(cls, node):
colors = []
for color in safe_iterator(node, "{%s}color" % SHEET_MAIN_NS):
colors.append(Color.from_tree(color))
return cls(stop=colors, **node.attrib)
def _serialise_nested(self, sequence):
"""
Colors need special handling
"""
for idx, color in enumerate(sequence):
stop = Element("stop", position=str(idx))
stop.append(color.to_tree())
yield stop
def to_tree(self, tagname=None):
parent = Element("fill")
el = super(GradientFill, self).to_tree()
parent.append(el)
return parent
| {'content_hash': '33d513da35689969b7d54cd1a1067149', 'timestamp': '', 'source': 'github', 'line_count': 176, 'max_line_length': 86, 'avg_line_length': 29.789772727272727, 'alnum_prop': 0.6236887278275797, 'repo_name': 'Darthkpo/xtt', 'id': '92f60304568bb5003eccfae32221da4956db85af', 'size': '5243', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'openpyxl/styles/fills.py', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Python', 'bytes': '794012'}]} |
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.napoleon',
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
#
# source_suffix = ['.rst', '.md']
source_suffix = '.rst'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'testcontainers'
copyright = u'2017, Sergey Pirogov'
author = u'Sergey Pirogov'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = u'2.0.0'
# The full version, including alpha/beta/rc tags.
release = u'2.0.0'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = None
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This patterns also effect to html_static_path and html_extra_path
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = False
# -- Options for HTML output ----------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
html_theme = 'alabaster'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#
# html_theme_options = {}
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
# html_static_path = ['_static']
# -- Options for HTMLHelp output ------------------------------------------
# Output file base name for HTML help builder.
htmlhelp_basename = 'testcontainersdoc'
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#
# 'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#
# 'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#
# 'preamble': '',
# Latex figure (float) alignment
#
# 'figure_align': 'htbp',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(master_doc, 'testcontainers.tex', u'testcontainers Documentation',
u'Sergey Pirogov', 'manual'),
]
# -- Options for manual page output ---------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(master_doc, 'testcontainers', u'testcontainers Documentation',
[author], 1)
]
# -- Options for Texinfo output -------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(master_doc, 'testcontainers', u'testcontainers Documentation',
author, 'testcontainers', 'One line description of project.',
'Miscellaneous'),
]
| {'content_hash': 'ddf95f9d00a05d31a08c6fb44a4f9598', 'timestamp': '', 'source': 'github', 'line_count': 124, 'max_line_length': 78, 'avg_line_length': 30.451612903225808, 'alnum_prop': 0.668697033898305, 'repo_name': 'SergeyPirogov/testcontainers-python', 'id': '7270d20d5abda2c16e92f685b8c733eff0eb1e76', 'size': '4835', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'docs/conf.py', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Dockerfile', 'bytes': '262'}, {'name': 'Python', 'bytes': '27727'}]} |
#include "util/logging.h"
#include <ctime>
#include <boost/thread.hpp>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <ostream>
#include <string>
using namespace std;
namespace xtreemfs {
namespace util {
Logging::Logging(LogLevel level, std::ostream* stream)
: log_stream_(*stream), log_file_stream_(stream), level_(level) {
}
Logging::Logging(LogLevel level)
: log_stream_(std::cout), log_file_stream_(NULL), level_(level) {
}
Logging::~Logging() {
if (log_file_stream_) {
delete log_file_stream_;
}
}
std::ostream& Logging::getLog(LogLevel level, const char* file, int line) {
timeval current_time;
gettimeofday(¤t_time, 0);
struct tm* tm = localtime(¤t_time.tv_sec);
log_stream_
<< "[ " << levelToChar(level)
<< " | " << file << ":" << line << " | "
<< setiosflags(ios::dec)
<< setw(2) << (tm->tm_mon + 1) << "/" << setw(2) << tm->tm_mday << " "
<< setfill('0') << setw(2) << tm->tm_hour << ":"
<< setfill('0') << setw(2) << tm->tm_min << ":"
<< setfill('0') << setw(2) << tm->tm_sec << "."
<< setfill('0') << setw(3) << (current_time.tv_usec / 1000) << " | "
<< boost::this_thread::get_id() << " ] "
// Reset modifiers.
<< setfill(' ') << setiosflags(ios::dec);
return log_stream_;
}
char Logging::levelToChar(LogLevel level) {
switch (level) {
case LEVEL_EMERG: return 'e';
case LEVEL_ALERT: return 'A';
case LEVEL_CRIT: return 'C';
case LEVEL_ERROR: return 'E';
case LEVEL_WARN: return 'W';
case LEVEL_NOTICE: return 'N';
case LEVEL_INFO: return 'I';
case LEVEL_DEBUG: return 'D';
}
std::cerr << "Could not determine log level." << std::endl;
return 'U'; // unkown
}
bool Logging::loggingActive(LogLevel level) {
return (level <= level_);
}
LogLevel stringToLevel(std::string stringLevel, LogLevel defaultLevel) {
if (stringLevel == "EMERG") {
return LEVEL_EMERG;
} else if (stringLevel == "ALERT") {
return LEVEL_ALERT;
} else if (stringLevel == "CRIT") {
return LEVEL_CRIT;
} else if (stringLevel == "ERR") {
return LEVEL_ERROR;
} else if (stringLevel == "WARNING") {
return LEVEL_WARN;
} else if (stringLevel == "NOTICE") {
return LEVEL_NOTICE;
} else if (stringLevel == "INFO") {
return LEVEL_INFO;
} else if (stringLevel == "DEBUG") {
return LEVEL_DEBUG;
} else {
// Return the default.
return defaultLevel;
}
}
void initialize_logger(std::string stringLevel,
std::string logfilePath,
LogLevel defaultLevel) {
initialize_logger(stringToLevel(stringLevel, defaultLevel), logfilePath);
}
/**
* Log to a file given by logfilePath. If logfilePath is empty,
* stdout is used.
*/
void initialize_logger(LogLevel level, std::string logfilePath) {
// Do not initialize the logging multiple times.
if (Logging::log) {
return;
}
if (!logfilePath.empty()) {
ofstream* logfile = new std::ofstream(logfilePath.c_str());
if (logfile != NULL && logfile->is_open()) {
cerr << "Logging to file " << logfilePath.c_str() << "." << endl;
Logging::log = new Logging(level, logfile);
return;
}
cerr << "Could not log to file " << logfilePath.c_str()
<< ". Fallback to stdout." << endl;
}
// in case of an error, log to stdout
Logging::log = new Logging(level);
}
/**
* Log to stdout
*/
void initialize_logger(LogLevel level) {
// Do not initialize the logging multiple times.
if (Logging::log) {
return;
}
Logging::log = new Logging(level);
}
void shutdown_logger() {
delete Logging::log;
Logging::log = NULL;
}
Logging* Logging::log = NULL;
} // namespace util
} // namespace xtreemfs
| {'content_hash': '1665f875e9690760db7c98fad42963cc', 'timestamp': '', 'source': 'github', 'line_count': 146, 'max_line_length': 76, 'avg_line_length': 25.732876712328768, 'alnum_prop': 0.6039393132818739, 'repo_name': 'gurkerl83/millipede-xtreemfs', 'id': '92b68d6ef85401fa8d5db93722f1f356c4d240cd', 'size': '3902', 'binary': False, 'copies': '1', 'ref': 'refs/heads/pseiferth-libxtreemfsjava', 'path': 'cpp/src/util/logging.cpp', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'C', 'bytes': '540126'}, {'name': 'C++', 'bytes': '10803345'}, {'name': 'Emacs Lisp', 'bytes': '7798'}, {'name': 'Java', 'bytes': '7496961'}, {'name': 'Perl', 'bytes': '11732'}, {'name': 'Python', 'bytes': '993906'}, {'name': 'Rust', 'bytes': '1330'}, {'name': 'Shell', 'bytes': '2697381'}, {'name': 'VimL', 'bytes': '3774'}, {'name': 'Visual Basic', 'bytes': '1285'}]} |
<ion-view id="view-init" view-title="Enter screen" class="bg-positive">
<ion-content scroll="false">
<div class="card">
<h1 class="">Angular1 Star Rating</h1>
<p class="lead">
Angular1 Star Rating is a >1.5 Angular component written in typescript.<br/>
It is based on <a href="https://github.com/BioPhoton/css-star-rating">Css Star Rating</a>,
a fully featured and customizable css only star rating component written in scss.
</p>
<p>
{{single.showHalfStars}}?
<star-rating-comp
id="single.id"
rating="single.rating"
show-half-stars="single.showHalfStars"
show-hover-stars="single.showHoverStars"
disabled="single.disabled"
read-only="single.readOnly"
space="single.space"
size="single.size"
num-of-stars="single.numOfStars"
static-color="single.color"
speed="single.speed"
label-text="single.rating"
label-position="single.position"
label-hidden="single.labelHidden"
star-type="single.starType"
get-color="single.getColor"
get-half-star-visible="single.getHalfStarVisible"
on-hover="single.onHover($event)"
on-click="single.onClick($event)"
on-rating-change="single.onRatingChange($event)">
</star-rating-comp>
<!--
get-color="single.getColor(rating, numOfStars)"
on-click="single.onClick($event)"
on-rating-change="single.onRatingChange(rating)"
-->
</p>
</div>
<!--
<div style="width: 300px; margin: 30px auto; background: #fafafa; height: 100px; display:flex; align-items: center; justify-content: center;">
<div style="width: 100%;">
<star-rating-comp
id="single.id"
rating="single.rating"
show-half-stars="single.showHalfStars"
disabled="single.disabled"
read-only="single.readOnly"
space="single.space"
size="single.size"
num-of-stars="single.numOfStars"
color="single.color"
speed="single.speed"
label-text="single.rating"
label-position="single.position"
star-type="single.starType"
get-half-star-class="single.getHalfStarClass(rating)"
on-rating-change="single.onRatingChange(rating)"
on-click="single.onClick($event)">
</star-rating-comp>
</div>
</div>
-->
<ion-list class="">
<div class="row">
<div class="col-4">
<fieldset class="form-group">
<legend>Layout</legend>
<div class="form-check">
<label class="form-check-label">
<input type="checkbox" class="form-check-input" ng-model="single.labelHidden">
Label Hidden
</label>
</div>
<div class="form-check">
<label class="col-4 col-form-label">Label Position</label>
<div class="col-8">
<select class="form-control" ng-model="single.position">
<option value="">position</option>
<option value="{{value}}" ng-repeat="(key, value) in single.labelPositionOptions">{{value}}
</option>
</select>
</div>
</div>
<div class="form-group">
<label class="col-6 col-form-label">starOptions: {{single.starType}}</label>
<div class="col-6">
<select class="form-control" ng-model="single.starType">
<option value="">starType</option>
<option value="{{value}}" ng-repeat="(key, value) in single.starOptions">{{value}}
</option>
</select>
</div>
</div>
<div class="form-group">
<label class="col-4 col-form-label">Space</label>
<div class="col-8">
<select class="form-control" ng-model="single.space">
<option value="">space</option>
<option value="{{value}}" ng-repeat="(key, value) in single.spaceOptions">{{value}}
</option>
</select>
</div>
</div>
</fieldset>
</div>
<div class="col-4">
<fieldset class="form-group row">
<legend>Dimensions
</legend>
<div class="form-group">
<label class="col-6 col-form-label">NumOfStars</label>
<div class="col-6">
<input type="number" class="form-control" placeholder="NumOfStars"
ng-model="single.numOfStars">
</div>
</div>
<div class="form-group">
<label class="col-6 col-form-label">Size: {{single.size}}</label>
<div class="col-6">
<select class="form-control" ng-model="single.size">
<option value="">size</option>
<option value="{{value}}" ng-repeat="(key, value) in single.sizeOptions">{{value}}
</option>
</select>
</div>
</div>
</fieldset>
</div>
<div class="col-4">
<fieldset class="form-group">
<legend>Styling
</legend>
<div class="form-group">
<label class="col-4 col-form-label">Color</label>
<div class="col-8">
<select class="form-control" ng-model="single.color">
<option value="">color</option>
<option value="{{value}}" ng-repeat="(key, value) in single.colorOptions">{{value}}
</option>
</select>
</div>
</div>
<div class="form-check">
<label class="form-check-label">
<input type="checkbox" class="form-check-input" ng-change="single.updateGetColorBinding()" ng-model="single.useCustomCetColor">
use custom getColor function
</label>
</div>
<div class="form-check">
<label class="form-check-label">
<input type="checkbox" class="form-check-input" ng-model="single.disabled">
Disabled
</label>
</div>
<div class="form-group">
<label class="col-4 col-form-label">Speed: {{single.speed}}</label>
<div class="col-8">
<select class="form-control" ng-model="single.speed">
<option value="">speed</option>
<option value="{{value}}" ng-repeat="(key, value) in single.speedOptions">{{value}}
</option>
</select>
</div>
</div>
</fieldset>
</div>
</div>
<div class="row">
<div class="col-4">
<fieldset class="form-group">
<legend>Other
</legend>
<div class="form-group">
<label class="col-6 col-form-label">Id</label>
<div class="col-6">
<input type="text" class="form-control" placeholder="Id" ng-model="single.id">
</div>
</div>
<div class="form-group">
<label class="col-6 col-form-label">Rating</label>
<div class="col-6">
<input type="number" class="form-control" placeholder="rating" step="0.5" ng-model="single.rating">
</div>
</div>
<div class="form-check">
<label class="form-check-label">
<input type="checkbox" class="form-check-input" ng-model="single.showHalfStars">
showHalfStars
</label>
</div>
<div class="form-check">
<label class="form-check-label">
<input type="checkbox" class="form-check-input" ng-model="single.showHoverStars">
showHoverStars
</label>
</div>
<div class="form-check">
<label class="form-check-label">
<input type="checkbox" class="form-check-input" ng-change="single.updateGetHalfStarVisibleBinding()" ng-model="single.useCustomGetHalfStarVisible">
use custom getHalfStarVisible function
</label>
</div>
<div class="form-check">
<label class="form-check-label">
<input type="checkbox" class="form-check-input" ng-model="single.readOnly">
ReadOnly
</label>
</div>
<div class="form-group">
<label class="col-6 col-form-label">Text</label>
<div class="col-6">
<input type="text" class="form-control" placeholder=":Label text" ng-model="single.labelText">
</div>
</div>
</fieldset>
</div>
</div>
</ion-list>
</ion-content>
</ion-view>
| {'content_hash': '33cec796f4f922afc7b6b58d23374f71', 'timestamp': '', 'source': 'github', 'line_count': 260, 'max_line_length': 163, 'avg_line_length': 35.91153846153846, 'alnum_prop': 0.4949127128628039, 'repo_name': 'BioPhoton/ionic1-star-rating', 'id': '67aaf163b58748b94e3d22771302b2fe83848550', 'size': '9337', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'examples/ionic1/src/app/components/init/init.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'HTML', 'bytes': '1273'}, {'name': 'JavaScript', 'bytes': '45733'}, {'name': 'Shell', 'bytes': '977'}, {'name': 'TypeScript', 'bytes': '4625'}]} |
import imp
import sys
import os
import json
import BaseHTTPServer
import ssl
import urlparse
import urllib2
import webbrowser
import federated_exceptions as fe
import federated_utils as futils
## The super-function calls different API methods to obtain the scoped token
# @param keystoneEndpoint The keystone url
# @param realm The IdP the user will be using
# @param tenantFn The tenant friendly name the user wants to use
def federatedAuthentication(keystoneEndpoint, realm = None, tenantFn = None, v3 = False):
realms = getRealmList(keystoneEndpoint)
if realm is None or realm['name'] not in [x['name'] for x in realms['realms']]:
realm = futils.selectRealm(realms['realms'])
request = getIdPRequest(keystoneEndpoint, realm)
# Load the correct protocol module according to the IdP type
protocol = realm['type'].split('.')[1]
try:
processing_module = load_protocol_module(protocol)
except IOError as e:
print "The selected Identity Service is not supported by your client, please restart the process and choose an alternative provider"
sys.exit(1)
response = processing_module.getIdPResponse(request['idpEndpoint'], request['idpRequest'], realm)
tenantData = getUnscopedToken(keystoneEndpoint, response, realm)
print "=======tenantData==========", tenantData
tenant = futils.getTenantId(tenantData['tenants'], tenantFn)
type = "tenantId"
if tenant is None:
tenant = futils.selectTenantOrDomain(tenantData['tenants'])
if tenant.get("project", None) is None and tenant.get("domain", None) is None:
tenant = tenant["id"]
type = "tenantId"
else:
if tenant.get("domain", None) is None:
tenant = tenant["project"]["id"]
type = "tenantId"
else:
tenant = tenant["domain"]["id"]
type = "domainId"
scopedToken = swapTokens(keystoneEndpoint, tenantData['unscopedToken'], type, tenant)
return scopedToken
def load_protocol_module(protocol):
''' Dynamically load correct module for processing authentication
according to identity provider's protocol'''
return imp.load_source(protocol, os.path.dirname(__file__)+'/protocols/'+protocol+".py")
## Get the list of all the IdP available
# @param keystoneEndpoint The keystone url
def getRealmList(keystoneEndpoint):
data = {}
resp = futils.middlewareRequest(keystoneEndpoint, data, 'POST')
info = json.loads(resp.read())
return info
## Get the authentication request to send to the IdP
# @param keystoneEndpoint The keystone url
# @param realm The name of the IdP
def getIdPRequest(keystoneEndpoint, realm):
data = {'realm': realm}
resp = futils.middlewareRequest(keystoneEndpoint, data, 'POST')
info = json.loads(resp.read())
return info
# This variable is necessary to get the IdP response
response = None
## Sends the authentication request to the IdP along
# @param idpEndpoint The IdP address
# @param idpRequest The authentication request returned by Keystone
def getIdPResponse(idpEndpoint, idpRequest):
global response
response = None
config = open(os.path.join(os.path.dirname(__file__),"config/federated.cfg"), "Ur")
line = config.readline().rstrip()
key = ""
cert = ""
timeout = 300
while line:
if line.split('=')[0] == "KEY":
key = line.split("=")[1].rstrip()
if line.split("=")[0] == "CERT":
cert = line.split("=")[1].rstrip()
if line.split('=')[0] == "TIMEOUT":
timeout = int(line.split("=")[1])
line = config.readline().rstrip()
config.close()
if key == "default":
key = os.path.join(os.path.dirname(__file__),"certs/server.key")
if cert == "default":
cert = os.path.join(os.path.dirname(__file__),"certs/server.crt")
webbrowser.open(idpEndpoint + idpRequest)
class RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
def log_request(code=0, size=0):
return
def log_error(format="", msg=""):
return
def log_request(format="", msg=""):
return
def do_POST(self):
global response
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
varLen = int(self.headers["Content-Length"])
#response = urlparse.parse_qs(self.rfile.read(varLen))
response = self.rfile.read(varLen)
if response is None:
self.wfile.write("An error occured.")
raise federated_exceptions.CommunicationsError()
self.wfile.write("You have successfully logged in. "
"You can close this window now.")
httpd = BaseHTTPServer.HTTPServer(('localhost', 8080), RequestHandler)
try:
httpd.socket = ssl.wrap_socket(httpd.socket, keyfile=key, certfile=cert, server_side=True)
httpd.socket.settimeout(1)
except BaseException as e:
print e.value
count = 0
while response is None and count < timeout:
try:
httpd.handle_request()
count = count + 1
except Exception as e:
print e.value
if response is None:
print ("There was no response from the Identity Provider or the request timed out")
exit("An error occurred, please try again")
return response
## Get an unscoped token for the user along with the tenants list
# @param keystoneEndpoint The keystone url
# @param idpResponse The assertion retreived from the IdP
def getUnscopedToken(keystoneEndpoint, idpResponse, realm = None):
if realm is None:
data = {'idpResponse' : idpResponse}
else:
data = {'idpResponse' : idpResponse, 'realm' : realm}
resp = futils.middlewareRequest(keystoneEndpoint, data, 'POST')
info = json.loads(resp.read())
return info
## Get a tenant-scoped token for the user
# @param keystoneEndpoint The keystone url
# @param idpResponse The assertion retreived from the IdP
# @param tenantFn The tenant friendly name
def getScopedToken(keystoneEndpoint, idpResponse, tenantFn):
response = getUnscopedToken(keystoneEndpoint, idpResponse)
type, tenantId = futils.getTenantId(response["tenants"])
if tenantId is None:
print "Error the tenant could not be found, should raise InvalidTenant"
scoped = swapTokens(keystoneEndpoint, response["unscopedToken"], type, tenantId)
return scoped
## Get a scoped token from an unscoped one
# @param keystoneEndpoint The keystone url
# @param unscopedToken The unscoped authentication token obtained from getUnscopedToken()
# @param tenanId The tenant Id the user wants to use
def swapTokens(keystoneEndpoint, unscopedToken, type, tenantId):
data = {'auth' : {'token' : {'id' : unscopedToken}, type : tenantId}}
if "v3" in keystoneEndpoint:
keystoneEndpoint+="auth/"
data = {"auth": {"identity": {"methods": ["token"],"token": {"id": unscopedToken}, "scope":{}}}}
if type == 'domainId':
data["auth"]["identity"]["scope"]["domain"] = {"id": tenantId}
else:
data["auth"]["identity"]["scope"]["project"] = {"id": tenantId}
resp = futils.middlewareRequest(keystoneEndpoint + "tokens", data,'POST', withheader = False)
return json.loads(resp.read())
| {'content_hash': '8c11cda1d393d0dfed0ca7830775666f', 'timestamp': '', 'source': 'github', 'line_count': 179, 'max_line_length': 140, 'avg_line_length': 41.00558659217877, 'alnum_prop': 0.6645776566757493, 'repo_name': 'deepakselvaraj/federated_api', 'id': '7855a81910cd527ab3c902a19ef1b505a91d65de', 'size': '7340', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'swiftclient/contrib/federated/federated.py', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Python', 'bytes': '158997'}, {'name': 'Shell', 'bytes': '1096'}]} |
namespace LibRbxl.Internal
{
public class DoubleProperty : Property<double>
{
public DoubleProperty(string name, double value) : base(name, PropertyType.Double, value)
{
}
}
}
| {'content_hash': '9e0accb0d8bda326cd7580108bebd0a1', 'timestamp': '', 'source': 'github', 'line_count': 9, 'max_line_length': 97, 'avg_line_length': 23.666666666666668, 'alnum_prop': 0.6338028169014085, 'repo_name': 'GregoryComer/LibRbxl', 'id': 'adbb71b69729dbb4b132f418cc1fd30f0242251c', 'size': '215', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'LibRbxl/Internal/DoubleProperty.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C#', 'bytes': '303881'}]} |
#include "stdafx.h"
#include <atlstr.h>
#include "JunctionPoint.h"
using namespace std;
using namespace neosmart;
int PrintSyntax()
{
_tprintf(_T("ln [/s] source destination"));
return -1;
}
int _tmain(int argc, _TCHAR* argv[])
{
if(argc < 3 || argc > 4 || (argc == 4 && _tcsicmp(argv[1], _T("-s")) != 0 && _tcsicmp(argv[1], _T("/s"))))
{
return PrintSyntax();
}
bool softlink = argc == 4;
CString source, destination;
int index = 1;
if(softlink)
++index;
source = argv[index++];
destination = argv[index];
if(GetFileAttributes(destination) != INVALID_FILE_ATTRIBUTES)
{
_tprintf(_T("Destination already exists!\r\n"));
return -1;
}
bool isDirectory = (GetFileAttributes(source) & FILE_ATTRIBUTE_DIRECTORY) != 0;
if(softlink)
CreateSymbolicLink(destination, source, isDirectory ? SYMBOLIC_LINK_FLAG_DIRECTORY : 0);
else if(isDirectory)
CreateJunctionPoint(source, destination);
else
CreateHardLink(destination, source, NULL);
return 0;
}
| {'content_hash': '409b299945f0af60a721775ce565bf77', 'timestamp': '', 'source': 'github', 'line_count': 51, 'max_line_length': 110, 'avg_line_length': 22.41176470588235, 'alnum_prop': 0.5756780402449694, 'repo_name': 'neosmart/ln-win', 'id': '43cff2b0d63e3f2910cd50a65f151bb866b8dc12', 'size': '1344', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'ln-win/ln-win.cpp', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '3007'}, {'name': 'C++', 'bytes': '9924'}]} |
package cn.hjf.downloader.sample;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import java.util.List;
import cn.hjf.downloader.Progress;
import cn.hjf.downloader.Task;
/**
* Created by huangjinfu on 2017/8/7.
*/
public class TaskAdapter extends BaseAdapter {
private Context context;
private List<Task> taskList;
private OnEventListener onEventListener;
public interface OnEventListener {
void onStart(Task task);
void onStop(Task task);
void onDelete(Task task);
}
public TaskAdapter(Context context, List<Task> taskList) {
this.context = context;
this.taskList = taskList;
}
@Override
public int getCount() {
return taskList == null ? 0 : taskList.size();
}
@Override
public Object getItem(int position) {
return taskList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = LayoutInflater.from(context).inflate(R.layout.lv_task, parent, false);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
initValue(holder, position);
initEvent(holder, position);
return convertView;
}
private void initValue(ViewHolder holder, int position) {
Task task = taskList.get(position);
holder.infoTv.setText("url:" + task.getUrlStr() + "\npath:" + task.getFilePath());
Progress progress = task.getProgress();
if (progress != null) {
holder.pb.setMax(100);
holder.pb.setProgress((int) (progress.getDownloaded() * 100.0 / progress.getTotal()));
holder.speedTv.setText(progress.getNetworkSpeed() + "kb/s");
} else {
holder.pb.setMax(0);
holder.pb.setProgress(0);
holder.speedTv.setText("0kb/s");
}
holder.statusTv.setText(task.getStatus().toString());
holder.priorityTv.setText(task.getPriority().toString());
if (task.getStatus() == Task.Status.NEW) {
holder.startBtn.setEnabled(true);
holder.stopBtn.setEnabled(false);
} else if (task.getStatus() == Task.Status.WAITING || task.getStatus() == Task.Status.RUNNING) {
holder.startBtn.setEnabled(false);
holder.stopBtn.setEnabled(true);
} else if (task.getStatus() == Task.Status.STOPPED) {
holder.startBtn.setEnabled(true);
holder.stopBtn.setEnabled(false);
} else if (task.getStatus() == Task.Status.FINISHED) {
holder.startBtn.setEnabled(false);
holder.stopBtn.setEnabled(false);
} else if (task.getStatus() == Task.Status.ERROR) {
holder.startBtn.setEnabled(true);
holder.stopBtn.setEnabled(false);
}
}
private void initEvent(ViewHolder holder, final int position) {
holder.startBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (onEventListener != null) {
onEventListener.onStart(taskList.get(position));
}
}
});
holder.stopBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (onEventListener != null) {
onEventListener.onStop(taskList.get(position));
}
}
});
holder.deleteBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (onEventListener != null) {
onEventListener.onDelete(taskList.get(position));
}
}
});
}
public void setOnEventListener(OnEventListener onEventListener) {
this.onEventListener = onEventListener;
}
private static class ViewHolder {
TextView infoTv, statusTv, priorityTv, speedTv;
ProgressBar pb;
Button startBtn, stopBtn, deleteBtn;
public ViewHolder(View rootView) {
infoTv = (TextView) rootView.findViewById(R.id.infoTv);
statusTv = (TextView) rootView.findViewById(R.id.statusTv);
priorityTv = (TextView) rootView.findViewById(R.id.priorityTv);
speedTv = (TextView) rootView.findViewById(R.id.speedTv);
pb = (ProgressBar) rootView.findViewById(R.id.pb);
startBtn = (Button) rootView.findViewById(R.id.start);
stopBtn = (Button) rootView.findViewById(R.id.stop);
deleteBtn = (Button) rootView.findViewById(R.id.delete);
}
}
}
| {'content_hash': 'fce455cebdde259325b00ec1247719f3', 'timestamp': '', 'source': 'github', 'line_count': 157, 'max_line_length': 104, 'avg_line_length': 32.732484076433124, 'alnum_prop': 0.609067912045145, 'repo_name': 'xyhuangjinfu/MiniDownloader', 'id': '8a1c76fbb9cda50bbfd03b37f6b69c25633afbbe', 'size': '5139', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'sample/src/main/java/cn/hjf/downloader/sample/TaskAdapter.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '89019'}]} |
using System;
namespace TodoList_Service.Areas.HelpPage.ModelDescriptions
{
public class ParameterAnnotation
{
public Attribute AnnotationAttribute { get; set; }
public string Documentation { get; set; }
}
} | {'content_hash': '184da631270155e67e7056c7a233569d', 'timestamp': '', 'source': 'github', 'line_count': 11, 'max_line_length': 59, 'avg_line_length': 21.545454545454547, 'alnum_prop': 0.70042194092827, 'repo_name': 'AzureADQuickStarts/v2-WebApp-WebAPI-OpenIDConnect-DotNet', 'id': '8ca79f344618c489db2f7f08f67b5b4da8ca50b0', 'size': '237', 'binary': False, 'copies': '1', 'ref': 'refs/heads/complete', 'path': 'TodoList-Service/Areas/HelpPage/ModelDescriptions/ParameterAnnotation.cs', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'ASP', 'bytes': '216'}, {'name': 'C#', 'bytes': '178104'}, {'name': 'CSS', 'bytes': '3311'}, {'name': 'HTML', 'bytes': '10192'}, {'name': 'JavaScript', 'bytes': '30543'}]} |
/* -*- Mode: C; c-basic-offset:4 ; -*- */
/*
* (C) 2001 by Argonne National Laboratory.
* See COPYRIGHT in top-level directory.
*
* This file is automatically generated by buildiface
* DO NOT EDIT
*/
#include "mpi_fortimpl.h"
/* mpierrs.h and mpierror.h for the error code creation */
#include "mpierrs.h"
#include <stdio.h>
#include "mpierror.h"
/* -- Begin Profiling Symbol Block for routine MPI_Status_f2c */
#if defined(USE_WEAK_SYMBOLS) && !defined(USE_ONLY_MPI_NAMES)
#if defined(HAVE_PRAGMA_WEAK)
#pragma weak MPI_Status_f2c = PMPI_Status_f2c
#elif defined(HAVE_PRAGMA_HP_SEC_DEF)
#pragma _HP_SECONDARY_DEF PMPI_Status_f2c MPI_Status_f2c
#elif defined(HAVE_PRAGMA_CRI_DUP)
#pragma _CRI duplicate MPI_Status_f2c as PMPI_Status_f2c
#endif
#endif
/* -- End Profiling Symbol Block */
/* Define MPICH_MPI_FROM_PMPI if weak symbols are not supported to build
the MPI routines */
#ifndef MPICH_MPI_FROM_PMPI
#undef MPI_Status_f2c
#define MPI_Status_f2c PMPI_Status_f2c
#endif
#undef FUNCNAME
#define FUNCNAME MPI_Status_f2c
int MPI_Status_f2c( const MPI_Fint *f_status, MPI_Status *c_status )
{
int mpi_errno = MPI_SUCCESS;
if (f_status == MPI_F_STATUS_IGNORE) {
/* The call is erroneous (see 4.12.5 in MPI-2) */
mpi_errno = MPIR_Err_create_code( MPI_SUCCESS, MPIR_ERR_RECOVERABLE,
"MPI_Status_f2c", __LINE__, MPI_ERR_OTHER, "**notfstatignore", 0 );
return MPIR_Err_return_comm( 0, "MPI_Status_f2c", mpi_errno );
}
*c_status = *(MPI_Status *) f_status;
return MPI_SUCCESS;
}
| {'content_hash': '7be0f8881a68a9a820eb9e6f61426cb6', 'timestamp': '', 'source': 'github', 'line_count': 52, 'max_line_length': 76, 'avg_line_length': 29.653846153846153, 'alnum_prop': 0.6867704280155642, 'repo_name': 'wilseypa/llamaOS', 'id': '41872e386d6cfc69e84e5bd105f7da7c34234ebf', 'size': '1542', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'src/tools/mpich-3.0.4/src/binding/f77/statusf2c.c', 'mode': '33188', 'license': 'bsd-2-clause', 'language': [{'name': 'Assembly', 'bytes': '345125'}, {'name': 'Awk', 'bytes': '314'}, {'name': 'C', 'bytes': '21967143'}, {'name': 'C++', 'bytes': '7786827'}, {'name': 'FORTRAN', 'bytes': '1635479'}, {'name': 'Forth', 'bytes': '1728'}, {'name': 'Logos', 'bytes': '48433'}, {'name': 'Makefile', 'bytes': '484852'}, {'name': 'Objective-C', 'bytes': '271518'}, {'name': 'Shell', 'bytes': '9003'}, {'name': 'TeX', 'bytes': '17003'}]} |
<ServiceProvider>
<ApplicationID>6</ApplicationID>
<ApplicationName>am-store</ApplicationName>
<Description>APIM Store Service Provider</Description>
<IsSaaSApp>true</IsSaaSApp>
<InboundAuthenticationConfig>
<InboundAuthenticationRequestConfigs>
<InboundAuthenticationRequestConfig>
<InboundAuthKey>API_STORE</InboundAuthKey>
<InboundAuthType>samlsso</InboundAuthType>
<Properties></Properties>
</InboundAuthenticationRequestConfig>
</InboundAuthenticationRequestConfigs>
</InboundAuthenticationConfig>
<LocalAndOutBoundAuthenticationConfig>
<AuthenticationSteps>
<AuthenticationStep>
<StepOrder>1</StepOrder>
<LocalAuthenticatorConfigs>
<LocalAuthenticatorConfig>
<Name>BasicAuthenticator</Name>
<DisplayName>basicauth</DisplayName>
<IsEnabled>true</IsEnabled>
</LocalAuthenticatorConfig>
</LocalAuthenticatorConfigs>>
<SubjectStep>true</SubjectStep>
<AttributeStep>true</AttributeStep>
</AuthenticationStep>
</AuthenticationSteps>
</LocalAndOutBoundAuthenticationConfig>
<RequestPathAuthenticatorConfigs></RequestPathAuthenticatorConfigs>
<InboundProvisioningConfig></InboundProvisioningConfig>
<OutboundProvisioningConfig></OutboundProvisioningConfig>
<ClaimConfig>
<AlwaysSendMappedLocalSubjectId>true</AlwaysSendMappedLocalSubjectId>
<LocalClaimDialect>true</LocalClaimDialect><ClaimMappings><ClaimMapping><LocalClaim><ClaimUri>http://wso2.org/claims/givenname</ClaimUri></LocalClaim><RemoteClaim><ClaimUri>http://wso2.org/claims/givenName</ClaimUri>ClaimUri></RemoteClaim><RequestClaim>true</RequestClaim></ClaimMapping></ClaimMappings></ClaimConfig>
<PermissionAndRoleConfig></PermissionAndRoleConfig>
</ServiceProvider>
| {'content_hash': 'dc17146557fa2f591f08388f040e9644', 'timestamp': '', 'source': 'github', 'line_count': 39, 'max_line_length': 328, 'avg_line_length': 50.333333333333336, 'alnum_prop': 0.7086092715231788, 'repo_name': 'Prakhash/security-tools', 'id': 'c076bc7d0291910f04b78afa85b1728c04565fa3', 'size': '1963', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'internal/automation-scripts/wso2am-2.1.0-sso-config/am-sp-store.xml', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Shell', 'bytes': '39620'}, {'name': 'XSLT', 'bytes': '29511'}]} |
var redisClient = require('./redis_database').redisClient;
var TOKEN_EXPIRATION = 3600;
var TOKEN_EXPIRATION_SEC = TOKEN_EXPIRATION * 60;
// Middleware for token verification
exports.verifyToken = function (req, res, next) {
var token = getToken(req.headers);
redisClient.get(token, function (err, reply) {
if (err) {
//console.log(err);
return res.send(500);
}
if (reply) {
res.send(401);
}
else {
next();
}
});
};
exports.expireToken = function(headers) {
var token = getToken(headers);
if (token != null) {
redisClient.set(token, { is_expired: true });
redisClient.expire(token, TOKEN_EXPIRATION_SEC);
}
};
var getToken = function(headers) {
if (headers && headers.authorization) {
var authorization = headers.authorization;
var part = authorization.split(' ');
if (part.length == 2) {
var token = part[1];
return part[1];
}
else {
return null;
}
}
else {
return null;
}
};
exports.TOKEN_EXPIRATION = TOKEN_EXPIRATION;
exports.TOKEN_EXPIRATION_SEC = TOKEN_EXPIRATION_SEC; | {'content_hash': '02a818c0d403d7a45cc2ccbf214c25cf', 'timestamp': '', 'source': 'github', 'line_count': 54, 'max_line_length': 58, 'avg_line_length': 19.425925925925927, 'alnum_prop': 0.6587225929456625, 'repo_name': 'fauzita/PAUDku', 'id': 'add79fa3efffa706255b49b5bab40bb0c21c5856', 'size': '1049', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'app/server/config/token_manager.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '9430'}, {'name': 'JavaScript', 'bytes': '180643'}]} |
"""Package contenant la commande 'olist'.
"""
from primaires.interpreteur.commande.commande import Commande
class CmdOlist(Commande):
"""Commande 'olist'.
"""
def __init__(self):
"""Constructeur de la commande"""
Commande.__init__(self, "olist", "olist")
self.groupe = "administrateur"
self.nom_categorie = "batisseur"
self.schema = "(<message>)"
self.aide_courte = "affiche la liste des prototypes d'objets"
self.aide_longue = \
"Cette commande affiche une liste ordonnée des prototypes " \
"d'objets existant."
def interpreter(self, personnage, dic_masques):
"""Interprétation de la commande"""
cherchable = importeur.recherche.cherchables["probjet"]
if dic_masques["message"]:
chaine = dic_masques["message"].message
else:
chaine = ""
message = cherchable.trouver_depuis_chaine(chaine)
personnage << message
| {'content_hash': '4a87f95c044da39f88ba571248fde9a3', 'timestamp': '', 'source': 'github', 'line_count': 33, 'max_line_length': 73, 'avg_line_length': 30.636363636363637, 'alnum_prop': 0.5944609297725024, 'repo_name': 'stormi/tsunami', 'id': '138f9906f3845734e77f211faa2a5d9f74437dab', 'size': '2577', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/primaires/objet/commandes/olist/__init__.py', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Python', 'bytes': '7188300'}, {'name': 'Ruby', 'bytes': '373'}]} |
import { createElement, render } from 'rax';
import App from './App';
render(<App />, document.getElementById('root'));
if (module.hot) {
module.hot.accept();
}
| {'content_hash': 'aa3c78c62b98e6d30444213a1a544bd7', 'timestamp': '', 'source': 'github', 'line_count': 9, 'max_line_length': 49, 'avg_line_length': 18.444444444444443, 'alnum_prop': 0.6566265060240963, 'repo_name': 'jaredpalmer/react-production-starter', 'id': 'a8f82c62d72366e2ab00bd20404d8a959a98fc57', 'size': '166', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'examples/with-rax/src/client.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '517'}, {'name': 'JavaScript', 'bytes': '32266'}]} |
<?php
namespace Douglas\Request;
class Maker
{
public static function send($url, $jsessionid)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HEADER, true);
// Force JSON to be returned instead of XML
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json'));
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);
curl_setopt($ch, CURLOPT_TIMEOUT, 1500);
if ($jsessionid) {
curl_setopt($ch, CURLOPT_COOKIE, "JSESSIONID={$jsessionid}");
}
$response = curl_exec($ch);
$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
curl_close($ch);
return array($response, $header_size);
}
}
| {'content_hash': '6fbe186df7544bb1f7040e73154140d9', 'timestamp': '', 'source': 'github', 'line_count': 28, 'max_line_length': 80, 'avg_line_length': 31.0, 'alnum_prop': 0.5990783410138248, 'repo_name': 'adang1989/Douglas', 'id': 'c266c634191c8ae8bd8ba5cea4e74f1c4d8a5d0f', 'size': '868', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/Douglas/Request/Maker.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'PHP', 'bytes': '29273'}]} |
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); ?>
<?php $this->load->view('base/header'); ?>
<?php $this->load->view('base/head_base'); ?>
<div id="div_content">
<table class="table_info" id="setting_tb">
<tr>
<th>会员卡前缀:</th>
<td>
<input id="card_prefix" name="card_prefix" type="text" value="<?php echo empty($this_setting['card_prefix'])?'':$this_setting['card_prefix']; ?>">
<input type="hidden" id="last_card_prefix" value="<?php echo empty($this_setting['card_prefix'])?'':$this_setting['card_prefix']; ?>">
<span id="m_card_prefix" class="error-block"></span>
</td>
</tr>
<tr>
<th>会员卡递增值:</th>
<td>
<input id="card_addnum" name="card_addnum" type="text" value="<?php echo empty($this_setting['card_addnum'])?'':$this_setting['card_addnum']; ?>">
<input type="hidden" id="last_card_addnum" value="<?php echo empty($this_setting['card_addnum'])?'':$this_setting['card_addnum']; ?>">
<span id="m_card_addnum" class="error-block"></span>
</td>
</tr>
<tr>
<th>会员卡起增数:</th>
<td>
<input id="card_number" name="card_number" type="text" value="<?php echo empty($this_setting['card_number'])?'':$this_setting['card_number']; ?>">
<input type="hidden" id="last_card_number" value="<?php echo empty($this_setting['card_number'])?'':$this_setting['card_number']; ?>">
(当前为:<?php echo empty($this_setting['card_number'])?'':$this_setting['card_number']; ?>,修改的起增数必须大于或等于当前值)
<span id="m_card_number" class="error-block"></span>
</td>
</tr>
<tr>
<th>密码错误锁定次数:</th>
<td>
<input id="card_error_times" name="card_error_times" type="text" value="<?php echo empty($this_setting['card_error_times'])?'':$this_setting['card_error_times']; ?>">
<input type="hidden" id="last_card_error_times" value="<?php echo empty($this_setting['card_error_times'])?'':$this_setting['card_error_times']; ?>">
<span id="m_card_error_times" class="error-block"></span>
</td>
</tr>
</table>
</div>
<?php $this->load->view('setting/setting_js'); ?>
<?php $this->load->view('base/footer'); ?> | {'content_hash': '507674edef7bef265e4dc73f3954090c', 'timestamp': '', 'source': 'github', 'line_count': 43, 'max_line_length': 182, 'avg_line_length': 56.04651162790697, 'alnum_prop': 0.5336099585062241, 'repo_name': 'Jiumiking/qw', 'id': '3b23b572eac5ccb5511efd423cb4db31d83213b7', 'size': '2508', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'manage/views/setting/setting_card.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ApacheConf', 'bytes': '367'}, {'name': 'CSS', 'bytes': '144766'}, {'name': 'HTML', 'bytes': '8044917'}, {'name': 'JavaScript', 'bytes': '366038'}, {'name': 'PHP', 'bytes': '5388561'}]} |
import React, { Component } from 'react';
import { connect } from 'react-redux';
import ScheduleComponent from './ScheduleComponent';
import SettingsComponent from './SettingsComponent';
import AddProgramComponent from './AddProgramComponent'
import * as actionTypes from '../constants/actionTypes';
import { Actions } from 'react-native-router-flux';
import {
Container,
Content,
Tab,
Tabs,
Header,
Footer,
ScrollableTab,
Left,
Right,
Body,
Icon,
Button,
Title,
Spinner,
Text,
StyleProvider
} from 'native-base';
import getTheme from '../../native-base-theme/components';
import platform from '../../native-base-theme/variables/platform';
import { InteractionManager, View, Dimensions } from 'react-native';
import { fetchAllBookings } from '../actions/fetchBookings'
@connect((store) => {
return {
bookings: store.bookings,
programs: store.programs,
settings: store.settings,
autocomplete: store.autocomplete
}
})
export default class AllSchedules extends Component {
constructor(props, context) {
super(props, context);
this.state = {renderPlaceholderOnly: true};
}
componentDidMount() {
InteractionManager.runAfterInteractions(() => {
this.setState({renderPlaceholderOnly: false});
});
}
produceStuffToRender() {
let toRender;
let title;
const programs= this.props.programs;
if(programs.length === 0) {
const dimensions = Dimensions.get('window');
toRender = (
<Content>
<View style={{
flex:1,
height: dimensions.height,
width: dimensions.width,
flexDirection:'row',
alignItems:'center',
justifyContent:'center'
}}>
<Button
style={{ alignSelf: 'center' }}
info
rounded
onPress={() => {
Actions.AddPrograms();
}}
>
<Text>Lägg till schema</Text>
</Button>
</View>
</Content>
);
} else if(programs.length === 1) {
const program = programs[0];
const name = program.type === "PROGRAM" ? program.name : program.name.trim().slice(0, -1);
title = name;
toRender = (
<ScheduleComponent
specificProgram={program.name}
bookings={this.props.bookings}
programs={this.props.programs}
dispatch={this.props.dispatch}
settings={this.props.settings}
/>
)
} else if(this.props.settings.separateSchedules){
let swipes = [];
for(program of programs) {
title = "Scheman"
const name = program.type === "PROGRAM" ? program.name : program.name.trim().slice(0, -1);
swipes.push(
<Tab heading={name} key={name}>
<ScheduleComponent
specificProgram={program.name}
bookings={this.props.bookings}
programs={this.props.programs}
dispatch={this.props.dispatch}
settings={this.props.settings}
/>
</Tab>
)
toRender = (
<Tabs>
{swipes}
</Tabs>
);
}
} else {
title = "Alla scheman";
toRender = (
<ScheduleComponent
key="All_Schedules"
bookings={this.props.bookings}
programs={this.props.programs}
dispatch={this.props.dispatch}
settings={this.props.settings}
/>
)
}
let spinner = this.props.bookings.loading ?
<Spinner color='gray'/> :
(<Button
transparent
onPress={() => {
fetchAllBookings()
}}
>
<Icon name="refresh" />
</Button>)
return (
<StyleProvider style={getTheme(platform)}>
<Container>
<Header hasTabs=
{
this.props.programs.length > 1 &&
!this.props.settings.separateSchedules
}>
<Left>
{ spinner }
</Left>
<Body>
<Title>{title}</Title>
</Body>
<Right>
<Button
transparent
onPress={() => {
Actions.Settings();
}}
>
<Icon name="settings" />
</Button>
</Right>
</Header>
{toRender}
</Container>
</StyleProvider>
);
}
_renderPlaceholderView() {
return (
<StyleProvider style={getTheme(platform)}>
<Container>
<Header>
<Left>
</Left>
<Body>
<Title>Scheman</Title>
</Body>
<Right>
<Button
transparent
onPress={() => { Actions.Settings() }}
>
<Icon name="settings" />
</Button>
</Right>
</Header>
<Content>
<Body>
<Text>
Laddar...
</Text>
</Body>
</Content>
</Container>
</StyleProvider>
);
}
render() {
if (this.state.renderPlaceholderOnly) {
return this._renderPlaceholderView();
}
return this.produceStuffToRender();
}
}
| {'content_hash': '7149084361d12e84e3ef2506f30369d3', 'timestamp': '', 'source': 'github', 'line_count': 208, 'max_line_length': 98, 'avg_line_length': 25.66826923076923, 'alnum_prop': 0.5118936130361491, 'repo_name': 'Schwusch/mah-kronox-app', 'id': 'fe27cb4bd4a0a52baedb826e62913524c5723935', 'size': '5341', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'app/Components/AllSchedules.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '1633'}, {'name': 'JavaScript', 'bytes': '145782'}, {'name': 'Objective-C', 'bytes': '4505'}, {'name': 'Python', 'bytes': '1728'}, {'name': 'Shell', 'bytes': '194'}]} |
package com.yahoo.document.update;
import com.yahoo.document.datatypes.TensorFieldValue;
import com.yahoo.tensor.Tensor;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class TensorAddUpdateTest {
@Test
public void apply_add_update_operations() {
assertApplyTo("{{x:0,y:0}:1, {x:0,y:1}:2}", "{{x:0,y:2}:3}", "{{x:0,y:0}:1,{x:0,y:1}:2,{x:0,y:2}:3}");
}
private void assertApplyTo(String init, String update, String expected) {
String spec = "tensor(x{},y{})";
TensorFieldValue initialFieldValue = new TensorFieldValue(Tensor.from(spec, init));
TensorAddUpdate addUpdate = new TensorAddUpdate(new TensorFieldValue(Tensor.from(spec, update)));
Tensor updated = ((TensorFieldValue) addUpdate.applyTo(initialFieldValue)).getTensor().get();
assertEquals(Tensor.from(spec, expected), updated);
}
}
| {'content_hash': '1f3ed332d74e543e8479e4aaa33158ae', 'timestamp': '', 'source': 'github', 'line_count': 24, 'max_line_length': 110, 'avg_line_length': 37.166666666666664, 'alnum_prop': 0.6872197309417041, 'repo_name': 'vespa-engine/vespa', 'id': '64f8b31ad054ff878692e268d5915ebd80998e3d', 'size': '997', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'document/src/test/java/com/yahoo/document/update/TensorAddUpdateTest.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'ANTLR', 'bytes': '8130'}, {'name': 'C', 'bytes': '60315'}, {'name': 'C++', 'bytes': '29580035'}, {'name': 'CMake', 'bytes': '593981'}, {'name': 'Emacs Lisp', 'bytes': '91'}, {'name': 'GAP', 'bytes': '3312'}, {'name': 'Go', 'bytes': '560664'}, {'name': 'HTML', 'bytes': '54520'}, {'name': 'Java', 'bytes': '40814190'}, {'name': 'JavaScript', 'bytes': '73436'}, {'name': 'LLVM', 'bytes': '6152'}, {'name': 'Lex', 'bytes': '11499'}, {'name': 'Makefile', 'bytes': '5553'}, {'name': 'Objective-C', 'bytes': '12369'}, {'name': 'Perl', 'bytes': '23134'}, {'name': 'Python', 'bytes': '52392'}, {'name': 'Roff', 'bytes': '17506'}, {'name': 'Ruby', 'bytes': '10690'}, {'name': 'Shell', 'bytes': '268737'}, {'name': 'Yacc', 'bytes': '14735'}]} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_55) on Wed Jun 10 13:18:02 EDT 2015 -->
<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>io.fluo.api.observer Class Hierarchy (Fluo API 1.0.0-beta-1 API)</title>
<meta name="date" content="2015-06-10">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="io.fluo.api.observer Class Hierarchy (Fluo API 1.0.0-beta-1 API)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li>Class</li>
<li>Use</li>
<li class="navBarCell1Rev">Tree</li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-all.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../io/fluo/api/mini/package-tree.html">Prev</a></li>
<li><a href="../../../../io/fluo/api/types/package-tree.html">Next</a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?io/fluo/api/observer/package-tree.html" target="_top">Frames</a></li>
<li><a href="package-tree.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h1 class="title">Hierarchy For Package io.fluo.api.observer</h1>
<span class="strong">Package Hierarchies:</span>
<ul class="horizontal">
<li><a href="../../../../overview-tree.html">All Packages</a></li>
</ul>
</div>
<div class="contentContainer">
<h2 title="Class Hierarchy">Class Hierarchy</h2>
<ul>
<li type="circle">java.lang.<a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang"><span class="strong">Object</span></a>
<ul>
<li type="circle">io.fluo.api.observer.<a href="../../../../io/fluo/api/observer/AbstractObserver.html" title="class in io.fluo.api.observer"><span class="strong">AbstractObserver</span></a> (implements io.fluo.api.observer.<a href="../../../../io/fluo/api/observer/Observer.html" title="interface in io.fluo.api.observer">Observer</a>)</li>
<li type="circle">io.fluo.api.observer.<a href="../../../../io/fluo/api/observer/Observer.ObservedColumn.html" title="class in io.fluo.api.observer"><span class="strong">Observer.ObservedColumn</span></a></li>
</ul>
</li>
</ul>
<h2 title="Interface Hierarchy">Interface Hierarchy</h2>
<ul>
<li type="circle">io.fluo.api.observer.<a href="../../../../io/fluo/api/observer/Observer.html" title="interface in io.fluo.api.observer"><span class="strong">Observer</span></a></li>
<li type="circle">io.fluo.api.observer.<a href="../../../../io/fluo/api/observer/Observer.Context.html" title="interface in io.fluo.api.observer"><span class="strong">Observer.Context</span></a></li>
</ul>
<h2 title="Enum Hierarchy">Enum Hierarchy</h2>
<ul>
<li type="circle">java.lang.<a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang"><span class="strong">Object</span></a>
<ul>
<li type="circle">java.lang.<a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Enum.html?is-external=true" title="class or interface in java.lang"><span class="strong">Enum</span></a><E> (implements java.lang.<a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html?is-external=true" title="class or interface in java.lang">Comparable</a><T>, java.io.<a href="http://docs.oracle.com/javase/7/docs/api/java/io/Serializable.html?is-external=true" title="class or interface in java.io">Serializable</a>)
<ul>
<li type="circle">io.fluo.api.observer.<a href="../../../../io/fluo/api/observer/Observer.NotificationType.html" title="enum in io.fluo.api.observer"><span class="strong">Observer.NotificationType</span></a></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li>Class</li>
<li>Use</li>
<li class="navBarCell1Rev">Tree</li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-all.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../io/fluo/api/mini/package-tree.html">Prev</a></li>
<li><a href="../../../../io/fluo/api/types/package-tree.html">Next</a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?io/fluo/api/observer/package-tree.html" target="_top">Frames</a></li>
<li><a href="package-tree.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2015 <a href="http://www.fluo.io">Fluo IO</a>. All rights reserved.</small></p>
</body>
</html>
| {'content_hash': '75bbc635743a824bcc03cbf7a46f6da3', 'timestamp': '', 'source': 'github', 'line_count': 148, 'max_line_length': 540, 'avg_line_length': 44.41216216216216, 'alnum_prop': 0.6433896242202951, 'repo_name': 'mikewalch/incubator-fluo-website', 'id': '36a7dcc3e97edb2ca13b481fb920cc5ce421c8c4', 'size': '6573', 'binary': False, 'copies': '1', 'ref': 'refs/heads/gh-pages', 'path': 'apidocs/fluo/1.0.0-beta-1/io/fluo/api/observer/package-tree.html', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '68518'}, {'name': 'HTML', 'bytes': '9349884'}, {'name': 'JavaScript', 'bytes': '2481'}, {'name': 'Python', 'bytes': '5299'}, {'name': 'Ruby', 'bytes': '3473'}, {'name': 'Shell', 'bytes': '2867'}]} |
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Orchard.Core.XmlRpc.Models;
using Orchard.Core.XmlRpc.Services;
using Orchard.XmlRpc;
namespace Orchard.Core.XmlRpc.Controllers
{
public class HomeController : Controller
{
private readonly IXmlRpcWriter _writer;
private readonly IEnumerable<IXmlRpcHandler> _xmlRpcHandlers;
public HomeController(
IXmlRpcWriter writer,
IEnumerable<IXmlRpcHandler> xmlRpcHandlers,
ILogger<HomeController> logger)
{
_writer = writer;
_xmlRpcHandlers = xmlRpcHandlers;
Logger = logger;
}
ILogger Logger { get; }
[HttpPost, ActionName("Index")]
[IgnoreAntiforgeryToken]
public async Task<IActionResult> ServiceEndpoint([ModelBinder(BinderType = typeof(MethodCallModelBinder))]XRpcMethodCall methodCall)
{
if (Logger.IsEnabled(LogLevel.Debug))
{
Logger.LogDebug("XmlRpc methodName {0}", methodCall.MethodName);
}
var methodResponse = await DispatchAsync(methodCall);
if (methodResponse == null)
{
return StatusCode(500, "TODO: xmlrpc fault");
}
var settings = new XmlWriterSettings
{
Encoding = Encoding.UTF8,
OmitXmlDeclaration = false,
Indent = true
};
// save to an intermediate MemoryStream to preserve the encoding declaration
using (var stream = new MemoryStream())
{
using (XmlWriter w = XmlWriter.Create(stream, settings))
{
var result = _writer.MapMethodResponse(methodResponse);
result.Save(w);
}
var content = Encoding.UTF8.GetString(stream.ToArray());
return Content(content, "text/xml");
}
}
private async Task<XRpcMethodResponse> DispatchAsync(XRpcMethodCall request)
{
var context = new XmlRpcContext
{
Url = Url,
ControllerContext = ControllerContext,
HttpContext = HttpContext,
RpcMethodCall = request
};
try
{
foreach (var handler in _xmlRpcHandlers)
{
await handler.ProcessAsync(context);
}
}
catch (Exception e)
{
// if a core exception is raised, report the error message, otherwise signal a 500
context.RpcMethodResponse = context.RpcMethodResponse ?? new XRpcMethodResponse();
context.RpcMethodResponse.Fault = new XRpcFault(0, e.Message);
}
return context.RpcMethodResponse;
}
}
} | {'content_hash': 'a061afefe7f18b710301978cbc6c7e8b', 'timestamp': '', 'source': 'github', 'line_count': 97, 'max_line_length': 140, 'avg_line_length': 31.61855670103093, 'alnum_prop': 0.5653733289859798, 'repo_name': 'yiji/Orchard2', 'id': '59fe0abba97e26bb769147e4d26d8774b77831d0', 'size': '3069', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/OrchardCore.Modules/Orchard.XmlRpc/Controllers/HomeController.cs', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Batchfile', 'bytes': '104'}, {'name': 'C#', 'bytes': '2829259'}, {'name': 'CSS', 'bytes': '895614'}, {'name': 'HTML', 'bytes': '6663'}, {'name': 'JavaScript', 'bytes': '4304486'}]} |
{{ partial "head" . }}
{{ partial "nav" . }}
{{ partial "jumbotron" (dict "imageUrl" .Params.imageUrl "title" .Params.heading "subtitle" .Params.subtitle) }}
<div class="mw7 center ph3 pt4">
{{ .Content }}
</div>
{{ partial "footer" . }}
| {'content_hash': 'a9fa9226bb2c3d51998b815fbb916a62', 'timestamp': '', 'source': 'github', 'line_count': 10, 'max_line_length': 112, 'avg_line_length': 24.9, 'alnum_prop': 0.5983935742971888, 'repo_name': 'LinuxPay/linuxpay.org', 'id': '4783db861fdaf298a10129e21b71c650233b59b9', 'size': '249', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'site/layouts/_default/single.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '94394'}, {'name': 'HTML', 'bytes': '86900'}, {'name': 'JavaScript', 'bytes': '9334'}]} |
namespace Appleseed.Framework.Helpers
{
using System;
using System.Text;
using System.Text.RegularExpressions;
/// <summary>
/// Nice HTMLText helper. Contains both the HTML string
/// and a tag-free version of the same string.
/// by Manu
/// </summary>
public struct HTMLText
{
#region Constants and Fields
/// <summary>
/// The inner text.
/// </summary>
private string innerText; // Same as _InnerHTML but completely tag-free
/// <summary>
/// The inner xhtml.
/// </summary>
private string innerXhtml; // Same as _InnerHTML but converted to XHTML
#endregion
#region Constructors and Destructors
/// <summary>
/// Initializes a new instance of the <see cref="HTMLText"/> structure.
/// </summary>
/// <param name="myText">My text.</param>
public HTMLText(string myText)
: this()
{
this.InnerHTML = myText;
this.innerText = string.Empty;
this.innerXhtml = string.Empty;
}
#endregion
#region Properties
/// <summary>
/// InnerHTML
/// </summary>
/// <value>The inner HTML.</value>
public string InnerHTML { get; set; }
/// <summary>
/// InnerText
/// Same as InnerHTML but completely tag-free
/// </summary>
/// <value>The inner text.</value>
public string InnerText
{
get
{
this.innerText = CleanHTML(this.InnerHTML);
return this.innerText;
}
}
/// <summary>
/// Gets the inner XHTML.
/// </summary>
public string InnerXHTML
{
get
{
this.innerXhtml = GetXHtml(this.InnerHTML);
return this.innerXhtml;
}
}
#endregion
#region Operators
/// <summary>
/// Converts the struct to a string value
/// </summary>
/// <param name = "value">The value.</param>
/// <returns></returns>
public static implicit operator string(HTMLText value)
{
return value.InnerHTML;
}
/// <summary>
/// Converts the struct from a string value
/// </summary>
/// <param name = "value">The value.</param>
/// <returns></returns>
public static implicit operator HTMLText(string value)
{
var h = new HTMLText(value);
return h;
}
#endregion
#region Public Methods
/// <summary>
/// Gets an abstract HTML of maxLength characters maximum
/// </summary>
/// <param name="maxLength">
/// The max length.
/// </param>
/// <returns>
/// The get abstract html.
/// </returns>
public string GetAbstractHTML(int maxLength)
{
if (maxLength >= this.InnerHTML.Length || this.InnerHTML == string.Empty)
{
return this.InnerHTML;
}
var abstr = this.InnerHTML.Substring(0, maxLength);
abstr = abstr.Substring(0, abstr.LastIndexOf(' ')) + "...";
return abstr;
}
/// <summary>
/// Gets an abstract text (no HTML tags!) of maxLength characters maximum
/// </summary>
/// <param name="maxlength">
/// The max length.
/// </param>
/// <returns>
/// The get abstract text.
/// </returns>
public string GetAbstractText(int maxlength)
{
var abstr = this.InnerText;
if (maxlength >= abstr.Length || abstr == string.Empty)
{
return this.InnerText;
}
abstr = abstr.Substring(0, maxlength);
var l = abstr.LastIndexOf(' ');
l = (l > 0) ? l : abstr.Length;
abstr = abstr.Substring(0, l) + "...";
return abstr.Trim();
}
/// <summary>
/// Break the text in rows of row length characters maximum
/// using HTML content
/// </summary>
/// <param name="rowlength">
/// The row length.
/// </param>
/// <returns>
/// The get broken html.
/// </returns>
/// <remarks>
/// There is no such word as breaked. It is broken.
/// </remarks>
public string GetBreakedHTML(int rowlength)
{
return BreakThis(this.InnerHTML, rowlength);
}
/// <summary>
/// Break the text in rows of row length characters maximum,
/// using text content, useful for emails
/// </summary>
/// <param name="rowlength">
/// </param>
/// <returns>
/// The get broken text.
/// </returns>
public string GetBreakedText(int rowlength)
{
return BreakThis(this.InnerText, rowlength);
}
#endregion
#region Methods
/// <summary>
/// Breaks the this.
/// </summary>
/// <param name="input">
/// The input.
/// </param>
/// <param name="rowlength">
/// The row length.
/// </param>
/// <returns>
/// The break this.
/// </returns>
private static string BreakThis(string input, int rowlength)
{
// Clean up input
char[] removeChar = { ' ', '\n' };
input = input.Trim(removeChar);
var s = new StringBuilder();
string row;
var index = 0;
var len = input.Length;
var count = 0;
while (index <= len)
{
if ((index + rowlength) < len)
{
row = input.Substring(index, rowlength);
}
else
{
// Last row
s.Append(input.Substring(index));
s.Append(Environment.NewLine);
break;
}
// Search for end of line
var last = row.IndexOf('\n');
if (last == 0)
{
row = Environment.NewLine;
}
else if (last > 0)
{
row = row.Substring(0, last);
}
else
{
last = row.LastIndexOf(' ');
if (last > 0)
{
row = row.Substring(0, last) + Environment.NewLine;
}
}
s.Append(row);
index += row.Length;
count++;
// Avoid loop
if (row == string.Empty || index == len || count > len)
{
break;
}
}
// Clean up output
return s.ToString().Trim(removeChar);
}
/// <summary>
/// Removes any HTML tags
/// </summary>
/// <param name="input">
/// The input.
/// </param>
/// <returns>
/// The clean html.
/// </returns>
private static string CleanHTML(string input)
{
var output = Regex.Replace(input, @"(\<[^\<]*\>)", string.Empty);
output = output.Replace("<", "<");
output = output.Replace(">", ">");
return output;
}
/// <summary>
/// Returns XHTML
/// </summary>
/// <param name="input">
/// The input.
/// </param>
/// <returns>
/// The get x html.
/// </returns>
private static string GetXHtml(string input)
{
if (string.IsNullOrEmpty(input))
{
return string.Empty;
}
// Open tags (no attributes)
var regex = "<[A-Za-z0-9:]*[>,\\s]";
var output = Regex.Replace(input, regex, new MatchEvaluator(MatchToLower));
// Closed tags
regex = "</[A-Za-z0-9]*>";
output = Regex.Replace(output, regex, new MatchEvaluator(MatchToLower));
// Open tags (with attributes)
regex =
"<[a-zA-Z]+[a-zA-Z0-9:]*(\\s+[a-zA-Z]+[a-zA-Z0-9:]*((=[^\\s\"'<>]+)|(=\"[^\"]*\")|(='[^']*')|()))*\\s*\\/?\\s*>";
output = Regex.Replace(output, regex, new MatchEvaluator(ProcessAttribute));
// HR
output = output.Replace("<hr>", "<hr />");
// BR
output = output.Replace("<br>", "<br />");
return output;
}
/// <summary>
/// Transforms the match to lowercase
/// </summary>
/// <param name="m">
/// The m.
/// </param>
/// <returns>
/// The match to lower.
/// </returns>
private static string MatchToLower(Match m)
{
return m.ToString().ToLower();
}
/// <summary>
/// Processes the attribute.
/// </summary>
/// <param name="m">
/// The m.
/// </param>
/// <returns>
/// The process attribute.
/// </returns>
private static string ProcessAttribute(Match m)
{
// Attribute value (no quote) to Quoted Attribute Value
var output = "=([^\",^\\s,.]*)[\\s]";
var regex = Regex.Replace(m.ToString(), output, new MatchEvaluator(Quoteattribute));
// Attribute to lowercase
output = "\\s[^=\"]*=";
regex = Regex.Replace(regex, output, new MatchEvaluator(MatchToLower));
// Attribute value (no quote) to Quoted Attribute Value (end of tag)
output = "=([^\",^\\s,.]*)[>]";
return Regex.Replace(regex, output, new MatchEvaluator(QuoteattributeEnd));
}
/// <summary>
/// Quote the result
/// </summary>
/// <param name="m">
/// The m.
/// </param>
/// <returns>
/// The quote attribute.
/// </returns>
private static string Quoteattribute(Match m)
{
var str = m.ToString().Remove(0, 1).Trim();
return string.Format("=\"{0}\" ", str);
}
/// <summary>
/// Quote the result (end tag)
/// </summary>
/// <param name="m">
/// The m.
/// </param>
/// <returns>
/// The quote attribute end.
/// </returns>
private static string QuoteattributeEnd(Match m)
{
var str = m.ToString().Remove(0, 1);
str = str.Remove(str.Length - 1, 1);
return string.Format("=\"{0}\">", str);
}
#endregion
}
} | {'content_hash': '2e4d99649edcabc78980921d0ed897e6', 'timestamp': '', 'source': 'github', 'line_count': 387, 'max_line_length': 129, 'avg_line_length': 28.51937984496124, 'alnum_prop': 0.447494790250974, 'repo_name': 'Appleseed/portal', 'id': '63f4aeae5e58a4a1ce86ade7373e839cf0708b54', 'size': '11533', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Master/Appleseed/Projects/Appleseed.Framework.Core/Helpers/HTMLText.cs', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'ASP', 'bytes': '701416'}, {'name': 'Batchfile', 'bytes': '5824'}, {'name': 'C#', 'bytes': '5437355'}, {'name': 'CSS', 'bytes': '3097267'}, {'name': 'ColdFusion', 'bytes': '166069'}, {'name': 'Gherkin', 'bytes': '225'}, {'name': 'HTML', 'bytes': '1084272'}, {'name': 'JavaScript', 'bytes': '5781627'}, {'name': 'Lasso', 'bytes': '34435'}, {'name': 'PHP', 'bytes': '111194'}, {'name': 'PLpgSQL', 'bytes': '353788'}, {'name': 'Perl', 'bytes': '38719'}, {'name': 'Perl 6', 'bytes': '25708'}, {'name': 'PowerShell', 'bytes': '3737'}, {'name': 'Python', 'bytes': '46471'}, {'name': 'SQLPL', 'bytes': '6479'}, {'name': 'Smalltalk', 'bytes': '25790'}, {'name': 'XSLT', 'bytes': '39762'}]} |
concommand.Add("UD_InvitePlayer", function(ply, command, args)
local plyPlayer = player.GetByID(tonumber(args[1]))
if not IsValid(ply) or not IsValid(plyPlayer) then return false end
if #(ply.Squad or {}) >= 5 then return false end
plyPlayer:UpdateInvites(ply, 1)
end)
concommand.Add("UD_KickSquadPlayer", function(ply, command, args)
local plyPlayer = player.GetByID(tonumber(args[1]))
if not IsValid(ply) or not IsValid(plyPlayer) then return false end
if ply:GetNWEntity("SquadLeader") ~= ply or not ply:IsInSquad(plyPlayer) then return end
plyPlayer:SetNWEntity("SquadLeader", plyPlayer)
timer.Simple(0.5, function()
for _, plyPlayer in pairs(player.GetAll()) do
plyPlayer:UpdateSquadTable()
end
end)
end)
concommand.Add("UD_LeaveSquad", function(ply, command, args)
if not IsValid(ply) then return false end
ply:SetNWEntity("SquadLeader", ply)
timer.Simple(0.5, function()
for _, plyPlayer in pairs(player.GetAll()) do
plyPlayer:UpdateSquadTable()
end
end)
end)
concommand.Add("UD_AcceptInvite", function(ply, command, args)
local plyInviter = player.GetByID(tonumber(args[1]))
if not IsValid(ply) or not IsValid(plyInviter) then return false end
if not ply.Invites[plyInviter] == 1 then return end
plyInviter:SetNWEntity("SquadLeader", plyInviter)
ply:SetNWEntity("SquadLeader", plyInviter)
ply:UpdateInvites(plyInviter, 0)
timer.Simple(0.5, function()
for _, plyPlayer in pairs(player.GetAll()) do
plyPlayer:UpdateSquadTable()
end
end)
end) | {'content_hash': 'd1e9f980c09ba68bab8b0ed8ee23dbf8', 'timestamp': '', 'source': 'github', 'line_count': 39, 'max_line_length': 90, 'avg_line_length': 39.30769230769231, 'alnum_prop': 0.7292889758643183, 'repo_name': 'Polkm/underdone', 'id': 'e5a759006b1a00e56dfe7953b3cafcea5777eaed', 'size': '1533', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'gamemode/core/serverfiles/commands/squad_commands.lua', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Lua', 'bytes': '460221'}]} |
/*jshint strict: false */
/*global require, exports */
////////////////////////////////////////////////////////////////////////////////
/// @brief Arango Simple Query Language
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2012 triagens GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is triAGENS GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
/// @author Copyright 2012, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////
var arangosh = require("org/arangodb/arangosh");
var ArangoQueryCursor = require("org/arangodb/arango-query-cursor").ArangoQueryCursor;
var sq = require("org/arangodb/simple-query-common");
var GeneralArrayCursor = sq.GeneralArrayCursor;
var SimpleQueryAll = sq.SimpleQueryAll;
var SimpleQueryArray = sq.SimpleQueryArray;
var SimpleQueryByExample = sq.SimpleQueryByExample;
var SimpleQueryByCondition = sq.SimpleQueryByCondition;
var SimpleQueryFulltext = sq.SimpleQueryFulltext;
var SimpleQueryGeo = sq.SimpleQueryGeo;
var SimpleQueryNear = sq.SimpleQueryNear;
var SimpleQueryRange = sq.SimpleQueryRange;
var SimpleQueryWithin = sq.SimpleQueryWithin;
var SimpleQueryWithinRectangle = sq.SimpleQueryWithinRectangle;
// -----------------------------------------------------------------------------
// --SECTION-- SIMPLE QUERY ALL
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// --SECTION-- private functions
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @brief executes an all query
////////////////////////////////////////////////////////////////////////////////
SimpleQueryAll.prototype.execute = function (batchSize) {
if (this._execution === null) {
if (batchSize !== undefined && batchSize > 0) {
this._batchSize = batchSize;
}
var data = {
collection: this._collection.name()
};
if (this._limit !== null) {
data.limit = this._limit;
}
if (this._skip !== null) {
data.skip = this._skip;
}
if (this._batchSize !== null) {
data.batchSize = this._batchSize;
}
var requestResult = this._collection._database._connection.PUT(
"/_api/simple/all", JSON.stringify(data));
arangosh.checkRequestResult(requestResult);
this._execution = new ArangoQueryCursor(this._collection._database, requestResult);
if (requestResult.hasOwnProperty("count")) {
this._countQuery = requestResult.count;
}
}
};
// -----------------------------------------------------------------------------
// --SECTION-- QUERY BY EXAMPLE
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// --SECTION-- private functions
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @brief executes a query-by-example
////////////////////////////////////////////////////////////////////////////////
SimpleQueryByExample.prototype.execute = function (batchSize) {
if (this._execution === null) {
if (batchSize !== undefined && batchSize > 0) {
this._batchSize = batchSize;
}
var data = {
collection: this._collection.name(),
example: this._example
};
if (this._limit !== null) {
data.limit = this._limit;
}
if (this._skip !== null) {
data.skip = this._skip;
}
if (this._batchSize !== null) {
data.batchSize = this._batchSize;
}
var method = "by-example";
if (this.hasOwnProperty("_type")) {
data.index = this._index;
switch (this._type) {
case "hash":
method = "by-example-hash";
break;
case "skiplist":
method = "by-example-skiplist";
break;
}
}
var requestResult = this._collection._database._connection.PUT(
"/_api/simple/" + method, JSON.stringify(data));
arangosh.checkRequestResult(requestResult);
this._execution = new ArangoQueryCursor(this._collection._database, requestResult);
if (requestResult.hasOwnProperty("count")) {
this._countQuery = requestResult.count;
this._countTotal = requestResult.count;
}
}
};
// -----------------------------------------------------------------------------
// --SECTION-- QUERY BY CONDITION
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// --SECTION-- private functions
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @brief executes a query-by-condition
////////////////////////////////////////////////////////////////////////////////
SimpleQueryByCondition.prototype.execute = function (batchSize) {
if (this._execution === null) {
if (batchSize !== undefined && batchSize > 0) {
this._batchSize = batchSize;
}
var data = {
collection: this._collection.name(),
condition: this._condition
};
if (this._limit !== null) {
data.limit = this._limit;
}
if (this._skip !== null) {
data.skip = this._skip;
}
if (this._batchSize !== null) {
data.batchSize = this._batchSize;
}
var method = "by-condition";
if (this.hasOwnProperty("_type")) {
data.index = this._index;
switch (this._type) {
case "skiplist":
method = "by-condition-skiplist";
break;
}
}
var requestResult = this._collection._database._connection.PUT(
"/_api/simple/" + method, JSON.stringify(data));
arangosh.checkRequestResult(requestResult);
this._execution = new ArangoQueryCursor(this._collection._database, requestResult);
if (requestResult.hasOwnProperty("count")) {
this._countQuery = requestResult.count;
this._countTotal = requestResult.count;
}
}
};
// -----------------------------------------------------------------------------
// --SECTION-- RANGE QUERY
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// --SECTION-- private functions
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @brief executes a range query
////////////////////////////////////////////////////////////////////////////////
SimpleQueryRange.prototype.execute = function (batchSize) {
if (this._execution === null) {
if (batchSize !== undefined && batchSize > 0) {
this._batchSize = batchSize;
}
var data = {
collection: this._collection.name(),
attribute: this._attribute,
right: this._right,
left: this._left,
closed: this._type === 1
};
if (this._limit !== null) {
data.limit = this._limit;
}
if (this._skip !== null) {
data.skip = this._skip;
}
if (this._batchSize !== null) {
data.batchSize = this._batchSize;
}
var requestResult = this._collection._database._connection.PUT(
"/_api/simple/range", JSON.stringify(data));
arangosh.checkRequestResult(requestResult);
this._execution = new ArangoQueryCursor(this._collection._database, requestResult);
if (requestResult.hasOwnProperty("count")) {
this._countQuery = requestResult.count;
}
}
};
// -----------------------------------------------------------------------------
// --SECTION-- SIMPLE QUERY NEAR
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// --SECTION-- private functions
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @brief executes a near query
////////////////////////////////////////////////////////////////////////////////
SimpleQueryNear.prototype.execute = function (batchSize) {
if (this._execution === null) {
if (batchSize !== undefined && batchSize > 0) {
this._batchSize = batchSize;
}
var data = {
collection: this._collection.name(),
latitude: this._latitude,
longitude: this._longitude
};
if (this._limit !== null) {
data.limit = this._limit;
}
if (this._skip !== null) {
data.skip = this._skip;
}
if (this._index !== null) {
data.geo = this._index;
}
if (this._distance !== null) {
data.distance = this._distance;
}
if (this._batchSize !== null) {
data.batchSize = this._batchSize;
}
var requestResult = this._collection._database._connection.PUT(
"/_api/simple/near", JSON.stringify(data));
arangosh.checkRequestResult(requestResult);
this._execution = new ArangoQueryCursor(this._collection._database, requestResult);
if (requestResult.hasOwnProperty("count")) {
this._countQuery = requestResult.count;
}
}
};
// -----------------------------------------------------------------------------
// --SECTION-- SIMPLE QUERY WITHIN
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// --SECTION-- private functions
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @brief executes a within query
////////////////////////////////////////////////////////////////////////////////
SimpleQueryWithin.prototype.execute = function (batchSize) {
if (this._execution === null) {
if (batchSize !== undefined && batchSize > 0) {
this._batchSize = batchSize;
}
var data = {
collection: this._collection.name(),
latitude: this._latitude,
longitude: this._longitude,
radius: this._radius
};
if (this._limit !== null) {
data.limit = this._limit;
}
if (this._skip !== null) {
data.skip = this._skip;
}
if (this._index !== null) {
data.geo = this._index;
}
if (this._distance !== null) {
data.distance = this._distance;
}
if (this._batchSize !== null) {
data.batchSize = this._batchSize;
}
var requestResult = this._collection._database._connection.PUT(
"/_api/simple/within", JSON.stringify(data));
arangosh.checkRequestResult(requestResult);
this._execution = new ArangoQueryCursor(this._collection._database, requestResult);
if (requestResult.hasOwnProperty("count")) {
this._countQuery = requestResult.count;
}
}
};
// -----------------------------------------------------------------------------
// --SECTION-- SIMPLE QUERY WITHINRECTANGLE
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// --SECTION-- private functions
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @brief executes a withinRectangle query
////////////////////////////////////////////////////////////////////////////////
SimpleQueryWithinRectangle.prototype.execute = function (batchSize) {
if (this._execution === null) {
if (batchSize !== undefined && batchSize > 0) {
this._batchSize = batchSize;
}
var data = {
collection: this._collection.name(),
latitude1: this._latitude1,
longitude1: this._longitude1,
latitude2: this._latitude2,
longitude2: this._longitude2
};
if (this._limit !== null) {
data.limit = this._limit;
}
if (this._skip !== null) {
data.skip = this._skip;
}
if (this._index !== null) {
data.geo = this._index;
}
if (this._distance !== null) {
data.distance = this._distance;
}
if (this._batchSize !== null) {
data.batchSize = this._batchSize;
}
var requestResult = this._collection._database._connection.PUT(
"/_api/simple/within-rectangle", JSON.stringify(data));
arangosh.checkRequestResult(requestResult);
this._execution = new ArangoQueryCursor(this._collection._database, requestResult);
if (requestResult.hasOwnProperty("count")) {
this._countQuery = requestResult.count;
}
}
};
// -----------------------------------------------------------------------------
// --SECTION-- SIMPLE QUERY FULLTEXT
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// --SECTION-- private functions
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @brief executes a fulltext query
////////////////////////////////////////////////////////////////////////////////
SimpleQueryFulltext.prototype.execute = function (batchSize) {
if (this._execution === null) {
if (batchSize !== undefined && batchSize > 0) {
this._batchSize = batchSize;
}
var data = {
collection: this._collection.name(),
attribute: this._attribute,
query: this._query
};
if (this._limit !== null) {
data.limit = this._limit;
}
if (this._index !== null) {
data.index = this._index;
}
if (this._skip !== null) {
data.skip = this._skip;
}
if (this._batchSize !== null) {
data.batchSize = this._batchSize;
}
var requestResult = this._collection._database._connection.PUT(
"/_api/simple/fulltext", JSON.stringify(data));
arangosh.checkRequestResult(requestResult);
this._execution = new ArangoQueryCursor(this._collection._database, requestResult);
if (requestResult.hasOwnProperty("count")) {
this._countQuery = requestResult.count;
}
}
};
// -----------------------------------------------------------------------------
// --SECTION-- MODULE EXPORTS
// -----------------------------------------------------------------------------
exports.GeneralArrayCursor = GeneralArrayCursor;
exports.SimpleQueryAll = SimpleQueryAll;
exports.SimpleQueryArray = SimpleQueryArray;
exports.SimpleQueryByExample = SimpleQueryByExample;
exports.SimpleQueryByCondition = SimpleQueryByCondition;
exports.SimpleQueryFulltext = SimpleQueryFulltext;
exports.SimpleQueryGeo = SimpleQueryGeo;
exports.SimpleQueryNear = SimpleQueryNear;
exports.SimpleQueryRange = SimpleQueryRange;
exports.SimpleQueryWithin = SimpleQueryWithin;
exports.SimpleQueryWithinRectangle = SimpleQueryWithinRectangle;
// -----------------------------------------------------------------------------
// --SECTION-- END-OF-FILE
// -----------------------------------------------------------------------------
// Local Variables:
// mode: outline-minor
// outline-regexp: "^\\(/// @brief\\|/// @addtogroup\\|// --SECTION--\\|/// @page\\|/// @}\\)"
// End:
| {'content_hash': 'b95cf59fd178e83a66ebc3930e1d6a67', 'timestamp': '', 'source': 'github', 'line_count': 520, 'max_line_length': 94, 'avg_line_length': 32.598076923076924, 'alnum_prop': 0.4420978113385641, 'repo_name': 'morsdatum/ArangoDB', 'id': '501b8fbd76f77602c16614b128cf91e2e75e3794', 'size': '16951', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'js/client/modules/org/arangodb/simple-query.js', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Ada', 'bytes': '89080'}, {'name': 'Assembly', 'bytes': '141776'}, {'name': 'Bison', 'bytes': '143739'}, {'name': 'C', 'bytes': '12127588'}, {'name': 'C#', 'bytes': '55625'}, {'name': 'C++', 'bytes': '65923523'}, {'name': 'CLIPS', 'bytes': '5291'}, {'name': 'CSS', 'bytes': '1128009'}, {'name': 'CoffeeScript', 'bytes': '94'}, {'name': 'Emacs Lisp', 'bytes': '13142'}, {'name': 'Go', 'bytes': '1294927'}, {'name': 'JavaScript', 'bytes': '36312554'}, {'name': 'Lua', 'bytes': '13768'}, {'name': 'Makefile', 'bytes': '128022'}, {'name': 'Objective-C', 'bytes': '82137'}, {'name': 'Objective-C++', 'bytes': '1298'}, {'name': 'Pascal', 'bytes': '117802'}, {'name': 'Perl', 'bytes': '375029'}, {'name': 'Perl6', 'bytes': '2731'}, {'name': 'PowerShell', 'bytes': '84'}, {'name': 'Python', 'bytes': '2294399'}, {'name': 'Ruby', 'bytes': '1116843'}, {'name': 'SAS', 'bytes': '1847'}, {'name': 'Scheme', 'bytes': '10604'}, {'name': 'Shell', 'bytes': '524411'}, {'name': 'XSLT', 'bytes': '1145'}]} |
/**
*
* Emerald (kbi/elude @2015-2016)
*
*/
#ifndef AUDIO_DEVICE_H
#define AUDIO_DEVICE_H
#include "system/system_types.h"
typedef enum
{
/* not settable, bool */
AUDIO_DEVICE_PROPERTY_IS_ACTIVATED,
/* not settable, bool */
AUDIO_DEVICE_PROPERTY_IS_DEFAULT,
/* not settable, system_time.
*
* Meaningful value is associated at audio_device_activate() call time.
*/
AUDIO_DEVICE_PROPERTY_LATENCY,
/* not settable, const char* */
AUDIO_DEVICE_PROPERTY_NAME
} audio_device_property;
/** TODO.
*
* TODO: Once activated and associated with the specified window, the device cannot
* be unbound. This restriction may be lifted in the future.
*
* NOTE: Internal use only.
*/
PUBLIC bool audio_device_activate(audio_device device,
system_window owner_window);
/** TODO */
PUBLIC EMERALD_API bool audio_device_bind_to_thread(audio_device device);
/** TODO.
*
* NOTE: Internal use only.
*/
PUBLIC void audio_device_deinit();
/** TODO */
PUBLIC EMERALD_API audio_device audio_device_get_default_device();
/** TODO */
PUBLIC EMERALD_API void audio_device_get_property(audio_device device,
audio_device_property property,
void* out_result_ptr);
/** TODO.
*
* NOTE: Internal use only.
*/
PUBLIC void audio_device_init();
#endif /* AUDIO_DEVICE_H */
| {'content_hash': '70d8b790c0647f9afa9897c7749409be', 'timestamp': '', 'source': 'github', 'line_count': 65, 'max_line_length': 88, 'avg_line_length': 22.8, 'alnum_prop': 0.6045883940620783, 'repo_name': 'kbiElude/Emerald', 'id': '3887aab16df446c1397a4542222487b345e8aab9', 'size': '1482', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Emerald/include/audio/audio_device.h', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Assembly', 'bytes': '8314'}, {'name': 'Batchfile', 'bytes': '3816'}, {'name': 'C', 'bytes': '5398372'}, {'name': 'C++', 'bytes': '13949055'}, {'name': 'CMake', 'bytes': '83573'}, {'name': 'DIGITAL Command Language', 'bytes': '9957'}, {'name': 'HTML', 'bytes': '7869'}, {'name': 'M4', 'bytes': '23360'}, {'name': 'Makefile', 'bytes': '150360'}, {'name': 'Module Management System', 'bytes': '14415'}, {'name': 'Objective-C', 'bytes': '6717'}, {'name': 'Python', 'bytes': '183962'}, {'name': 'Roff', 'bytes': '218860'}, {'name': 'SAS', 'bytes': '13756'}, {'name': 'Shell', 'bytes': '700637'}, {'name': 'Smalltalk', 'bytes': '2661'}]} |
package com.yin.myproject.demo.socket.demo03;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
public class MainClient {
public static void main(String[] args) throws UnknownHostException, IOException {
System.out.println("客户端启动...");
System.out.println("当接收到服务器端字符为 \"OK\" 的时候, 客户端将终止\n");
while (true) {
Socket clientSocket = new Socket("127.0.0.1", 30000);
// 读取服务器端数据
String content = readFromServer(clientSocket);
System.out.println("接收到的数据为:" + content);
// 向服务器端发送
OutputStream os = clientSocket.getOutputStream();
DataOutputStream out = new DataOutputStream(os);
System.out.print("请输入: \t");
String str = new BufferedReader(new InputStreamReader(System.in)).readLine();
out.writeUTF(str);
}
}
private static String readFromServer(Socket clientSocket) {
try {
StringBuffer sb = new StringBuffer();
InputStream is = clientSocket.getInputStream();
int hasRead = 0;
byte[] bytes = new byte[1024];
while ((hasRead = is.read(bytes)) > 0) {
sb.append(new String(bytes, 0, hasRead));
}
return sb.toString();
} catch (IOException e) {
}
return null;
}
}
| {'content_hash': '12dee75f38903fea5c88875ea3236ea9', 'timestamp': '', 'source': 'github', 'line_count': 45, 'max_line_length': 82, 'avg_line_length': 30.511111111111113, 'alnum_prop': 0.6897305171158048, 'repo_name': 'SmallBadFish/demo', 'id': 'cad4d8562dba5144b85182c6b9a22220490b5f5e', 'size': '1473', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/main/java/com/yin/myproject/demo/socket/demo03/MainClient.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'HTML', 'bytes': '1843'}, {'name': 'Java', 'bytes': '243713'}]} |
module Scale
using Colors
using Compat
using Compose
using DataArrays
using DataStructures
using Gadfly
using Showoff
import Gadfly: element_aesthetics, isconcrete, concrete_length,
nonzero_length
import Distributions: Distribution
include("color_misc.jl")
# Return true if var is categorical.
function iscategorical(scales::Dict{Symbol, Gadfly.ScaleElement}, var::Symbol)
return haskey(scales, var) && isa(scales[var], DiscreteScale)
end
# Apply some scales to data in the given order.
#
# Args:
# scales: An iterable object of ScaleElements.
# aess: Aesthetics (of the same length as datas) to update with scaled data.
# datas: Zero or more data objects. (Yes, I know "datas" is not a real word.)
#
# Returns:
# nothing
#
function apply_scales(scales,
aess::Vector{Gadfly.Aesthetics},
datas::Gadfly.Data...)
for scale in scales
apply_scale(scale, aess, datas...)
end
for (aes, data) in zip(aess, datas)
aes.titles = data.titles
end
end
# Apply some scales to data in the given order.
#
# Args:
# scales: An iterable object of ScaleElements.
# datas: Zero or more data objects.
#
# Returns:
# A vector of Aesthetics of the same length as datas containing scaled data.
#
function apply_scales(scales, datas::Gadfly.Data...)
aess = Gadfly.Aesthetics[Gadfly.Aesthetics() for _ in datas]
apply_scales(scales, aess, datas...)
aess
end
# Transformations on continuous scales
immutable ContinuousScaleTransform
f::Function # transform function
finv::Function # f's inverse
# A function taking one or more values and returning an array of
# strings.
label::Function
end
function identity_formatter(xs::AbstractArray, format=:auto)
return showoff(xs, format)
end
const identity_transform =
ContinuousScaleTransform(identity, identity, identity_formatter)
function log10_formatter(xs::AbstractArray, format=:plain)
[@sprintf("10<sup>%s</sup>", x) for x in showoff(xs, format)]
end
const log10_transform =
ContinuousScaleTransform(log10, x -> 10^x, log10_formatter)
function log2_formatter(xs::AbstractArray, format=:plain)
[@sprintf("2<sup>%s</sup>", x) for x in showoff(xs, format)]
end
const log2_transform =
ContinuousScaleTransform(log2, x -> 2^x, log2_formatter)
function ln_formatter(xs::AbstractArray, format=:plain)
[@sprintf("e<sup>%s</sup>", x) for x in showoff(xs, format)]
end
const ln_transform =
ContinuousScaleTransform(log, exp, ln_formatter)
function asinh_formatter(xs::AbstractArray, format=:plain)
[@sprintf("asinh(%s)", x) for x in showoff(xs, format)]
end
const asinh_transform =
ContinuousScaleTransform(asinh, sinh, asinh_formatter)
function sqrt_formatter(xs::AbstractArray, format=:plain)
[@sprintf("%s<sup>2</sup>", x) for x in showoff(xs, format)]
end
const sqrt_transform = ContinuousScaleTransform(sqrt, x -> x^2, sqrt_formatter)
# Continuous scale maps data on a continuous scale simple by calling
# `convert(Float64, ...)`.
immutable ContinuousScale <: Gadfly.ScaleElement
vars::Vector{Symbol}
trans::ContinuousScaleTransform
minvalue
maxvalue
minticks
maxticks
labels::@compat(Union{(@compat Void), Function})
format
scalable
function ContinuousScale(vars::Vector{Symbol},
trans::ContinuousScaleTransform;
labels=nothing,
minvalue=nothing, maxvalue=nothing,
minticks=2, maxticks=10,
format=nothing,
scalable=true)
if minvalue != nothing && maxvalue != nothing && minvalue > maxvalue
error("Cannot construct a ContinuousScale with minvalue > maxvalue")
end
new(vars, trans, minvalue, maxvalue, minticks, maxticks, labels,
format, scalable)
end
end
function make_labeler(scale::ContinuousScale)
if scale.labels != nothing
function f(xs)
return [scale.labels(x) for x in xs]
end
elseif scale.format == nothing
scale.trans.label
else
function f(xs)
return scale.trans.label(xs, scale.format)
end
end
end
const x_vars = [:x, :xmin, :xmax, :xintercept, :xviewmin, :xviewmax]
const y_vars = [:y, :ymin, :ymax, :yintercept, :middle,
:upper_fence, :lower_fence, :upper_hinge, :lower_hinge,
:yviewmin, :yviewmax]
function continuous_scale_partial(vars::Vector{Symbol},
trans::ContinuousScaleTransform)
function f(; minvalue=nothing, maxvalue=nothing, labels=nothing, format=nothing, minticks=2,
maxticks=10, scalable=true)
ContinuousScale(vars, trans, minvalue=minvalue, maxvalue=maxvalue,
labels=labels, format=format, minticks=minticks,
maxticks=maxticks, scalable=scalable)
end
end
# Commonly used scales.
const x_continuous = continuous_scale_partial(x_vars, identity_transform)
const y_continuous = continuous_scale_partial(y_vars, identity_transform)
const x_log10 = continuous_scale_partial(x_vars, log10_transform)
const y_log10 = continuous_scale_partial(y_vars, log10_transform)
const x_log2 = continuous_scale_partial(x_vars, log2_transform)
const y_log2 = continuous_scale_partial(y_vars, log2_transform)
const x_log = continuous_scale_partial(x_vars, ln_transform)
const y_log = continuous_scale_partial(y_vars, ln_transform)
const x_asinh = continuous_scale_partial(x_vars, asinh_transform)
const y_asinh = continuous_scale_partial(y_vars, asinh_transform)
const x_sqrt = continuous_scale_partial(x_vars, sqrt_transform)
const y_sqrt = continuous_scale_partial(y_vars, sqrt_transform)
const size_continuous = continuous_scale_partial([:size], identity_transform)
function element_aesthetics(scale::ContinuousScale)
return scale.vars
end
# Apply a continuous scale.
#
# Args:
# scale: A continuos scale.
# datas: Zero or more data objects.
# aess: Aesthetics (of the same length as datas) to update with scaled data.
#
# Return:
# nothing
#
function apply_scale(scale::ContinuousScale,
aess::Vector{Gadfly.Aesthetics}, datas::Gadfly.Data...)
for (aes, data) in zip(aess, datas)
for var in scale.vars
vals = getfield(data, var)
if vals === nothing
continue
end
# special case for function arrays bound to :y
# pass the function values through and wait for the scale to
# be reapplied by Stat.func
if var == :y && eltype(vals) == Function
aes.y = vals
continue
end
# special case for Distribution values bound to :x or :y. wait for
# scale to be re-applied by Stat.qq
if in(var, [:x, :y]) && typeof(vals) <: Distribution
setfield!(aes, var, vals)
continue
end
T = Any
for d in vals
if isconcrete(d)
T = typeof(scale.trans.f(d))
break
end
end
ds = Gadfly.hasna(vals) ? DataArray(T, length(vals)) : Array(T, length(vals))
apply_scale_typed!(ds, vals, scale)
if var == :xviewmin || var == :xviewmax ||
var == :yviewmin || var == :yviewmax
setfield!(aes, var, ds[1])
else
setfield!(aes, var, ds)
end
if var in x_vars
label_var = :x_label
elseif var in y_vars
label_var = :y_label
else
label_var = symbol(@sprintf("%s_label", string(var)))
end
if in(label_var, Set(fieldnames(aes)))
setfield!(aes, label_var, make_labeler(scale))
end
end
if scale.minvalue != nothing
if scale.vars === x_vars
aes.xviewmin = scale.trans.f(scale.minvalue)
elseif scale.vars === y_vars
aes.yviewmin = scale.trans.f(scale.minvalue)
end
end
if scale.maxvalue != nothing
if scale.vars === x_vars
aes.xviewmax = scale.trans.f(scale.maxvalue)
elseif scale.vars === y_vars
aes.yviewmax = scale.trans.f(scale.maxvalue)
end
end
end
end
function apply_scale_typed!(ds, field, scale::ContinuousScale)
for i in 1:length(field)
d = field[i]
ds[i] = isconcrete(d) ? scale.trans.f(d) : d
end
end
# Reorder the levels of a pooled data array
function reorder_levels(da::PooledDataArray, order::AbstractVector)
level_values = levels(da)
if length(order) != length(level_values)
error("Discrete scale order is not of the same length as the data's levels.")
end
permute!(level_values, order)
return PooledDataArray(da, level_values)
end
function discretize_make_pda(values::Vector, levels=nothing)
if levels == nothing
return PooledDataArray(values)
else
return PooledDataArray(convert(Vector{eltype(levels)}, values), levels)
end
end
function discretize_make_pda(values::DataArray, levels=nothing)
if levels == nothing
return PooledDataArray(values)
else
return PooledDataArray(convert(DataArray{eltype(levels)}, values), levels)
end
end
function discretize_make_pda(values::Range, levels=nothing)
if levels == nothing
return PooledDataArray(collect(values))
else
return PooledDataArray(collect(values), levels)
end
end
function discretize_make_pda(values::PooledDataArray, levels=nothing)
if levels == nothing
return values
else
return PooledDataArray(values, convert(Vector{eltype(values)}, levels))
end
end
function discretize(values, levels=nothing, order=nothing,
preserve_order=true)
if levels == nothing
if preserve_order
levels = OrderedSet()
for value in values
push!(levels, value)
end
da = discretize_make_pda(values, collect(eltype(values), levels))
else
da = discretize_make_pda(values)
end
else
da = discretize_make_pda(values, levels)
end
if order != nothing
return reorder_levels(da, order)
else
return da
end
end
immutable DiscreteScaleTransform
f::Function
end
immutable DiscreteScale <: Gadfly.ScaleElement
vars::Vector{Symbol}
# Labels are either a function that takes an array of values and returns
# an array of string labels, a vector of string labels of the same length
# as the number of unique values in the discrete data, or nothing to use
# the default labels.
labels::@compat(Union{(@compat Void), Function})
# If non-nothing, give values for the scale. Order will be respected and
# anything in the data that's not represented in values will be set to NA.
levels::@compat(Union{(@compat Void), AbstractVector})
# If non-nothing, a permutation of the pool of values.
order::@compat(Union{(@compat Void), AbstractVector})
function DiscreteScale(vals::Vector{Symbol};
labels=nothing, levels=nothing, order=nothing)
new(vals, labels, levels, order)
end
end
const discrete = DiscreteScale
element_aesthetics(scale::DiscreteScale) = scale.vars
function x_discrete(; labels=nothing, levels=nothing, order=nothing)
return DiscreteScale(x_vars, labels=labels, levels=levels, order=order)
end
function y_discrete(; labels=nothing, levels=nothing, order=nothing)
return DiscreteScale(y_vars, labels=labels, levels=levels, order=order)
end
function group_discrete(; labels=nothing, levels=nothing, order=nothing)
return DiscreteScale([:group], labels=labels, levels=levels, order=order)
end
function apply_scale(scale::DiscreteScale, aess::Vector{Gadfly.Aesthetics},
datas::Gadfly.Data...)
for (aes, data) in zip(aess, datas)
for var in scale.vars
label_var = symbol(@sprintf("%s_label", string(var)))
if getfield(data, var) === nothing
continue
end
disc_data = discretize(getfield(data, var), scale.levels, scale.order)
setfield!(aes, var, PooledDataArray(round(Int64, disc_data.refs)))
# The leveler for discrete scales is a closure over the discretized data.
if scale.labels === nothing
function default_labeler(xs)
lvls = levels(disc_data)
vals = Any[1 <= x <= length(lvls) ? lvls[x] : "" for x in xs]
if all([isa(val, AbstractFloat) for val in vals])
return showoff(vals)
else
return [string(val) for val in vals]
end
end
labeler = default_labeler
else
function explicit_labeler(xs)
lvls = levels(disc_data)
return [string(scale.labels(lvls[x])) for x in xs]
end
labeler = explicit_labeler
end
if in(label_var, Set(fieldnames(aes)))
setfield!(aes, label_var, labeler)
end
end
end
end
immutable NoneColorScale <: Gadfly.ScaleElement
end
const color_none = NoneColorScale
function element_aesthetics(scale::NoneColorScale)
[:color]
end
function apply_scale(scale::NoneColorScale,
aess::Vector{Gadfly.Aesthetics}, datas::Gadfly.Data...)
for aes in aess
aes.color = nothing
end
end
immutable DiscreteColorScale <: Gadfly.ScaleElement
f::Function # A function f(n) that produces a vector of n colors.
# If non-nothing, give values for the scale. Order will be respected and
# anything in the data that's not represented in values will be set to NA.
levels::@compat(Union{(@compat Void), AbstractVector})
# If non-nothing, a permutation of the pool of values.
order::@compat(Union{(@compat Void), AbstractVector})
# If true, order levels as they appear in the data
preserve_order::Bool
function DiscreteColorScale(f::Function; levels=nothing, order=nothing,
preserve_order=true)
new(f, levels, order, preserve_order)
end
end
function element_aesthetics(scale::DiscreteColorScale)
[:color]
end
# Common discrete color scales
function color_discrete_hue(; levels=nothing, order=nothing,
preserve_order=true)
DiscreteColorScale(
h -> convert(Vector{Color},
distinguishable_colors(h, [LCHab(70, 60, 240)],
transform=c -> deuteranopic(c, 0.5),
lchoices=Float64[65, 70, 75, 80],
cchoices=Float64[0, 50, 60, 70],
hchoices=linspace(0, 330, 24))),
levels=levels, order=order, preserve_order=preserve_order)
end
@deprecate discrete_color_hue(; levels=nothing, order=nothing, preserve_order=true) color_discrete_hue(; levels=levels, order=order, preserve_order=preserve_order)
const color_discrete = color_discrete_hue
@deprecate discrete_color(; levels=nothing, order=nothing, preserve_order=true) color_discrete(; levels=levels, order=order, preserve_order=preserve_order)
color_discrete_manual(colors...; levels=nothing, order=nothing) = color_discrete_manual(map(Gadfly.parse_colorant, colors)...; levels=levels, order=order)
function color_discrete_manual(colors::Color...; levels=nothing, order=nothing)
cs = [colors...]
function f(n)
distinguishable_colors(n, cs)
end
DiscreteColorScale(f, levels=levels, order=order)
end
@deprecate discrete_color_manual(colors...; levels=nothing, order=nothing) color_discrete_manual(colors...; levels=levels, order=order)
function apply_scale(scale::DiscreteColorScale,
aess::Vector{Gadfly.Aesthetics}, datas::Gadfly.Data...)
levelset = OrderedSet()
for (aes, data) in zip(aess, datas)
if data.color === nothing
continue
end
for d in data.color
if !isna(d)
push!(levelset, d)
end
end
end
if scale.levels == nothing
scale_levels = [levelset...]
if !scale.preserve_order
sort!(scale_levels)
end
else
scale_levels = scale.levels
end
if scale.order != nothing
permute!(scale_levels, scale.order)
end
colors = convert(Vector{RGB{Float32}}, scale.f(length(scale_levels)))
color_map = @compat Dict([color => string(label)
for (label, color) in zip(scale_levels, colors)])
function labeler(xs)
[color_map[x] for x in xs]
end
for (aes, data) in zip(aess, datas)
if data.color === nothing
continue
end
ds = discretize(data.color, scale_levels)
colorvals = Array(RGB{Float32}, nonzero_length(ds.refs))
i = 1
for k in ds.refs
if k != 0
colorvals[i] = colors[k]
i += 1
end
end
colored_ds = PooledDataArray(colorvals, colors)
aes.color = colored_ds
aes.color_label = labeler
aes.color_key_colors = OrderedDict()
for (i, c) in enumerate(colors)
aes.color_key_colors[c] = i
end
end
end
immutable ContinuousColorScale <: Gadfly.ScaleElement
# A function of the form f(p) where 0 <= p <= 1, that returns a color.
f::Function
minvalue
maxvalue
function ContinuousColorScale(f::Function; minvalue=nothing, maxvalue=nothing)
new(f, minvalue, maxvalue)
end
end
element_aesthetics(::ContinuousColorScale) = [:color]
function color_continuous_gradient(;minvalue=nothing, maxvalue=nothing)
# TODO: this should be made more general purpose. I.e. define some
# more color scales.
function lch_diverge2(l0=30, l1=100, c=40, h0=260, h1=10, hmid=20, power=1.5)
lspan = l1 - l0
hspan1 = hmid - h0
hspan0 = h1 - hmid
function f(r)
r2 = 2r - 1
return LCHab(min(80, l1 - lspan * abs(r2)^power), max(10, c * abs(r2)),
(1-r)*h0 + r * h1)
end
end
ContinuousColorScale(
lch_diverge2(),
minvalue=minvalue, maxvalue=maxvalue)
end
@deprecate continuous_color_gradient(;minvalue=nothing, maxvalue=nothing) color_continuous_gradient(;minvalue=minvalue, maxvalue=maxvalue)
const color_continuous = color_continuous_gradient
@deprecate continuous_color(;minvalue=nothing, maxvalue=nothing) color_continuous(;minvalue=nothing, maxvalue=nothing)
function apply_scale(scale::ContinuousColorScale,
aess::Vector{Gadfly.Aesthetics}, datas::Gadfly.Data...)
cmin = Inf
cmax = -Inf
for data in datas
if data.color === nothing
continue
end
for c in data.color
if c === NA
continue
end
c = convert(Float64, c)
if c < cmin
cmin = c
end
if c > cmax
cmax = c
end
end
end
if cmin == Inf || cmax == -Inf
return nothing
end
if scale.minvalue != nothing
cmin = scale.minvalue
end
if scale.maxvalue != nothing
cmax = scale.maxvalue
end
cmin, cmax = promote(cmin, cmax)
ticks, viewmin, viewmax = Gadfly.optimize_ticks(cmin, cmax)
if ticks[1] == 0 && cmin >= 1
ticks[1] = 1
end
cmin = ticks[1]
cmax = ticks[end]
cspan = cmax != cmin ? cmax - cmin : 1.0
for (aes, data) in zip(aess, datas)
if data.color === nothing
continue
end
aes.color = DataArray(RGB{Float32}, length(data.color))
apply_scale_typed!(aes.color, data.color, scale, cmin, cspan)
color_key_colors = Dict{Color, Float64}()
color_key_labels = Dict{Color, AbstractString}()
tick_labels = identity_formatter(ticks)
for (i, j, label) in zip(ticks, ticks[2:end], tick_labels)
r = (i - cmin) / cspan
c = scale.f(r)
color_key_colors[c] = r
color_key_labels[c] = label
end
c = scale.f((ticks[end] - cmin) / cspan)
color_key_colors[c] = (ticks[end] - cmin) / cspan
color_key_labels[c] = tick_labels[end]
function labeler(xs)
[get(color_key_labels, x, "") for x in xs]
end
aes.color_function = scale.f
aes.color_label = labeler
aes.color_key_colors = color_key_colors
aes.color_key_continuous = true
end
end
function apply_scale_typed!(ds, field, scale::ContinuousColorScale,
cmin::Float64, cspan::Float64)
for (i, d) in enumerate(field)
if isconcrete(d)
ds[i] = convert(RGB{Float32}, scale.f((convert(Float64, d) - cmin) / cspan))
else
ds[i] = NA
end
end
end
# Label scale is always discrete, hence we call it 'label' rather
# 'label_discrete'.
immutable LabelScale <: Gadfly.ScaleElement
end
function apply_scale(scale::LabelScale,
aess::Vector{Gadfly.Aesthetics}, datas::Gadfly.Data...)
for (aes, data) in zip(aess, datas)
if data.label === nothing
continue
end
aes.label = discretize(data.label)
end
end
element_aesthetics(::LabelScale) = [:label]
const label = LabelScale
# Scale applied to grouping aesthetics.
immutable GroupingScale <: Gadfly.ScaleElement
var::Symbol
end
function xgroup(; labels=nothing, levels=nothing, order=nothing)
return DiscreteScale([:xgroup], labels=labels, levels=levels, order=order)
end
function ygroup(; labels=nothing, levels=nothing, order=nothing)
return DiscreteScale([:ygroup], labels=labels, levels=levels, order=order)
end
# Catchall scale for when no transformation of the data is necessary
immutable IdentityScale <: Gadfly.ScaleElement
var::Symbol
end
function element_aesthetics(scale::IdentityScale)
return [scale.var]
end
function apply_scale(scale::IdentityScale,
aess::Vector{Gadfly.Aesthetics}, datas::Gadfly.Data...)
for (aes, data) in zip(aess, datas)
if getfield(data, scale.var) === nothing
continue
end
setfield!(aes, scale.var, getfield(data, scale.var))
end
end
function z_func()
return IdentityScale(:z)
end
function y_func()
return IdentityScale(:y)
end
function x_distribution()
return IdentityScale(:x)
end
function y_distribution()
return IdentityScale(:y)
end
end # module Scale
| {'content_hash': 'e7e466db4cefe8db2d22d782e3a1b8c7', 'timestamp': '', 'source': 'github', 'line_count': 814, 'max_line_length': 163, 'avg_line_length': 28.555282555282556, 'alnum_prop': 0.6151264842540011, 'repo_name': 'Godisemo/Gadfly.jl', 'id': '6ba20e39527bd7cdff6dd2a4648d2b0f732b8a08', 'size': '23245', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/scale.jl', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '30495'}, {'name': 'Julia', 'bytes': '417942'}]} |
```zenscript
import mods.terrafirmacraft.Quern;Quern;
```
## 追加
```zenscript
Quern.addRecipe(String registryName, IIngredient input, IItemStack output);
```
## 削除
```zenscript
Quern.removeRecipe(IItemStack output);
Quern.removeRecipe(String registryName);
``` | {'content_hash': '5e77673af7a609b022c2387f763ca227', 'timestamp': '', 'source': 'github', 'line_count': 16, 'max_line_length': 75, 'avg_line_length': 16.4375, 'alnum_prop': 0.752851711026616, 'repo_name': 'jaredlll08/CraftTweaker-Documentation', 'id': '8ebb49c6d1dce9cf23c9bf42e221e1c5c8824f30', 'size': '291', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'translations/ja/docs/Mods/Terrafirmacraft/Recipes/Quern.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '195475'}, {'name': 'HTML', 'bytes': '11110'}, {'name': 'JavaScript', 'bytes': '155278'}]} |
@class FTFAlbumCategoryCollection;
@interface FTFAlbumSelectionMenuViewController : UITableViewController
- (void)fetchAlbumCategoryCollection;
@end
| {'content_hash': 'f90f8f379d48b862c303a25ebf627a03', 'timestamp': '', 'source': 'github', 'line_count': 7, 'max_line_length': 70, 'avg_line_length': 21.714285714285715, 'alnum_prop': 0.8618421052631579, 'repo_name': 'Gman9855/FiftyTwoFrames', 'id': '9d030bf961e4c23f896943108e9dd9c0ce834637', 'size': '340', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Fifty-Two Frames/FTFAlbumSelectionMenuViewController.h', 'mode': '33188', 'license': 'bsd-2-clause', 'language': [{'name': 'C++', 'bytes': '696'}, {'name': 'Objective-C', 'bytes': '1675692'}, {'name': 'Ruby', 'bytes': '400'}, {'name': 'Swift', 'bytes': '657'}]} |
package com.fruit.core.web.utils;
/**
* @author Vincent
* @time 2015/8/27 13:32
*/
public class ResultVO {
public ResultVO(boolean ok) {
this.ok = ok;
}
public ResultVO() {
}
private boolean ok;
private String msg;
private String url;
private Object data;
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
public boolean isOk() {
return ok;
}
public void setOk(boolean ok) {
this.ok = ok;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
| {'content_hash': '2c9a2ad54c22c85d492adceda6f62877', 'timestamp': '', 'source': 'github', 'line_count': 55, 'max_line_length': 38, 'avg_line_length': 14.636363636363637, 'alnum_prop': 0.537888198757764, 'repo_name': 'LittleLazyCat/TXEYXXK', 'id': 'f7233f2f8673f0b6bf3e553fef7ca96237cf13c7', 'size': '805', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'weixin_fruit/src/main/java/com/fruit/core/web/utils/ResultVO.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'ASP', 'bytes': '35841'}, {'name': 'ApacheConf', 'bytes': '768'}, {'name': 'Batchfile', 'bytes': '2067'}, {'name': 'C#', 'bytes': '16030'}, {'name': 'CSS', 'bytes': '3799756'}, {'name': 'FreeMarker', 'bytes': '33818'}, {'name': 'HTML', 'bytes': '4677568'}, {'name': 'Java', 'bytes': '13081066'}, {'name': 'JavaScript', 'bytes': '30072557'}, {'name': 'PHP', 'bytes': '38697'}, {'name': 'PLSQL', 'bytes': '13547'}, {'name': 'PLpgSQL', 'bytes': '5316'}, {'name': 'Shell', 'bytes': '1357'}]} |
using MetroRadiance.UI.Controls;
namespace SRNicoNico.Views {
public partial class ExitConfirmView : MetroWindow {
public ExitConfirmView() {
InitializeComponent();
}
}
}
| {'content_hash': '55eee69f802b4ba6d3a3d70fb394c84d', 'timestamp': '', 'source': 'github', 'line_count': 9, 'max_line_length': 56, 'avg_line_length': 23.22222222222222, 'alnum_prop': 0.6507177033492823, 'repo_name': 'mrtska/SRNicoNico', 'id': 'd0b263e9eedef1878d732850e9a8864c76f8a56f', 'size': '211', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'SRNicoNico/Views/ExitConfirmView.xaml.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C#', 'bytes': '936331'}, {'name': 'HTML', 'bytes': '500'}, {'name': 'JavaScript', 'bytes': '8376'}, {'name': 'SCSS', 'bytes': '477'}, {'name': 'TypeScript', 'bytes': '30425'}]} |
<!--
Copyright (c) 2014 Juniper Networks, Inc. All rights reserved.
-->
<!--
Access tag details
If the access tag is not there then every one can access the menu/menu items
If access tag is there then only the roles and orchestration models mentioned in the tags are allowed
If any role/orchModel tag is with negation(!) value then every one has access to menu/menu item except the one mentioned with negation
and need to add the iconClass tag wherever we need to show some icons
-->
<menu>
<items>
<item>
<label>Monitor</label>
<name>monitor</name>
<iconClass>icon-bar-chart</iconClass>
<items>
<item>
<label>Infrastructure</label>
<iconClass>icon-desktop</iconClass>
<resources>
<resource>
<rootDir>/monitor/storage-infra/common/ui</rootDir>
<js>monitor_infra_storage_constants.js</js>
<js>monitor_infra_storage_utils.js</js>
<css>contrail.storage.infra.css</css>
<view>monitor_infra_storage_common.view</view>
</resource>
</resources>
<access>
<roles>
<role>admin</role>
</roles>
<orchModels>
<model>openstack</model>
<model>cloudstack</model>
</orchModels>
</access>
<items>
<item>
<hash>mon_infra_dashboard</hash>
<label>Dashboard</label>
<resources>
<resource>
<rootDir>/monitor/storage-infra/dashboard/ui/</rootDir>
<js>monitor_infra_storage_dashboard.js</js>
<view>monitor_infra_storage_dashboard.view</view>
<class>infraMonitorStorageDashView</class>
</resource>
</resources>
<queryParams>
<tab>storageNode</tab>
</queryParams>
<searchStrings>Infrastructure Dashboard</searchStrings>
</item>
<item>
<hash>mon_infra_storage</hash>
<label>Storage Nodes</label>
<resources>
<resource>
<rootDir>/monitor/storage-infra/storagenode/ui</rootDir>
<js>monitor_infra_storagenode.js</js>
<view>monitor_infra_storagenode.view</view>
<class>storNodesView</class>
</resource>
</resources>
<searchStrings>Monitor Storage Nodes</searchStrings>
</item>
</items>
</item>
<item>
<name>storage</name>
<label>Storage</label>
<resources>
<resource>
<rootDir>/monitor/tenant-storage/common/ui</rootDir>
<js>tenant_monitor_storage_constants.js</js>
<js>tenant_monitor_storage_utils.js</js>
<js>tenant_monitor_storage.js</js>
<css>contrail.storage.css</css>
<view>tenant_monitor_storage.view</view>
</resource>
</resources>
<iconClass>icon-tasks</iconClass>
<access>
<roles>
<role>admin</role>
</roles>
<orchModels>
<model>openstack</model>
<model>cloudstack</model>
</orchModels>
</access>
<items>
<item>
<hash>mon_storage_dashboard</hash>
<label>Dashboard</label>
<resources>
<resource>
<rootDir>/monitor/tenant-storage/dashboard/ui</rootDir>
<js>tenant_monitor_storage_dashboard.js</js>
<view>tenant_monitor_storage_dashboard.view</view>
<class>tenantStorageDashboardView</class>
</resource>
</resources>
<searchStrings>Storage Dashboard</searchStrings>
</item>
<item>
<hash>mon_storage_disks</hash>
<label>Disks</label>
<resources>
<resource>
<rootDir>/monitor/tenant-storage/disks/ui</rootDir>
<js>tenant_monitor_storage_disks.js</js>
<view>tenant_monitor_storage_disks.view</view>
<class>tenantStorageDisksView</class>
</resource>
</resources>
<searchStrings>Storage Disks</searchStrings>
</item>
<item>
<hash>mon_storage_monitor</hash>
<label>Monitor</label>
<resources>
<resource>
<rootDir>/monitor/tenant-storage/monitor/ui</rootDir>
<js>tenant_monitor_storage_monitor.js</js>
<view>tenant_monitor_storage_monitor.view</view>
<class>tenantStorageMonitorView</class>
</resource>
</resources>
<searchStrings>Storage Monitor</searchStrings>
</item>
</items>
</item>
</items>
</item>
<item>
<name>configure</name>
<label>Configure</label>
<iconClass>icon-wrench</iconClass>
<items></items>
</item>
<item>
<label>Setting</label>
<name>setting</name>
<iconClass>icon-cog</iconClass>
<items></items>
</item>
<item>
<label>Query</label>
<name>query</name>
<iconClass>icon-search</iconClass>
<items></items>
</item>
</items>
</menu>
| {'content_hash': '5825e2c5612a506f9819da42f7adc5a3', 'timestamp': '', 'source': 'github', 'line_count': 157, 'max_line_length': 134, 'avg_line_length': 35.51592356687898, 'alnum_prop': 0.5166786226685797, 'repo_name': 'skizhak/contrail-web-storage', 'id': 'c304e221efde77f02174929a15aa06aa5707d8f9', 'size': '5576', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'webroot/menu.xml', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '8535'}, {'name': 'JavaScript', 'bytes': '338969'}]} |
/**
* @fileoverview Generating Cpp for mindstorms3 blocks.
* @author
*/
'use strict';
goog.provide('Blockly.Cpp.mindstorms3');
goog.require('Blockly.Cpp');
Blockly.Cpp['mindstorms3_speed_in'] = function(block) {
Blockly.Cpp.definitions_['include_mindstorms'] =
'#include <mindstorms.h>';
Blockly.Cpp.definitions_['include_mrobot3'] =
'CMindstorms m_robot3;';
var text_speed = block.getFieldValue('speed');
var dropdown_radius = block.getFieldValue('radius');
var code = 'm_robot3.' + 'setSpeed(' + text_speed + ', ' + dropdown_radius + ');\n';
return code;
};
Blockly.Cpp['mindstorms3_speed_cm'] = function(block) {
Blockly.Cpp.definitions_['include_mindstorms'] =
'#include <mindstorms.h>';
Blockly.Cpp.definitions_['include_mrobot3'] =
'CMindstorms m_robot3;';
var text_speed = block.getFieldValue('speed');
var dropdown_radius = block.getFieldValue('radius');
var code = 'm_robot3.' + 'setSpeed(' + text_speed + ', ' + dropdown_radius + ');\n';
return code;
};
Blockly.Cpp['mindstorms3_blink_LED'] = function(block) {
Blockly.Cpp.definitions_['include_mindstorms'] =
'#include <mindstorms.h>';
Blockly.Cpp.definitions_['include_mrobot3'] =
'CMindstorms m_robot3;';
var text_delay = block.getFieldValue('delay');
var text_numBlinks = block.getFieldValue('numBlinks');
var code = 'm_robot3.blinkLED(' + text_delay + ', ' + text_numBlinks + ');\n';
return code;
};
Blockly.Cpp['mindstorms3_delay'] = function(block) {
Blockly.Cpp.definitions_['include_mindstorms'] =
'#include <mindstorms.h>';
Blockly.Cpp.definitions_['include_mrobot3'] =
'CMindstorms m_robot3;';
var text_time = block.getFieldValue('time');
var code = 'm_robot3.delaySeconds(' + text_time + ');\n';
return code;
};
Blockly.Cpp['mindstorms3_move_joints'] = function(block) {
Blockly.Cpp.definitions_['include_mindstorms'] =
'#include <mindstorms.h>';
Blockly.Cpp.definitions_['include_mrobot3'] =
'CMindstorms m_robot3;';
var text_angle1 = block.getFieldValue('angle1');
var text_angle2 = block.getFieldValue('angle2');
var text_angle3 = block.getFieldValue('angle3');
var code = 'm_robot3.move(' + text_angle1 + ', ' + text_angle2 + ', ' + text_angle3 + ');\n';
return code;
};
Blockly.Cpp['mindstorms3_move_wait'] = function(block) {
Blockly.Cpp.definitions_['include_mindstorms'] =
'#include <mindstorms.h>';
Blockly.Cpp.definitions_['include_mrobot3'] =
'CMindstorms m_robot3;';
var code = 'm_robot3.moveWait();\n';
return code;
};
Blockly.Cpp['mindstorms3_traceon'] = function(block) {
Blockly.Cpp.definitions_['include_mindstorms'] =
'#include <mindstorms.h>';
Blockly.Cpp.definitions_['include_mrobot3'] =
'CMindstorms m_robot3;';
var code = 'm_robot3.traceOn();\n';
return code;
};
Blockly.Cpp['mindstorms3_traceoff'] = function(block) {
Blockly.Cpp.definitions_['include_mindstorms'] =
'#include <mindstorms.h>';
Blockly.Cpp.definitions_['include_mrobot3'] =
'CMindstorms m_robot3;';
var code = 'm_robot3.traceOff();\n';
return code;
};
Blockly.Cpp['mindstorms3_turn_in'] = function(block) {
Blockly.Cpp.definitions_['include_mindstorms'] =
'#include <mindstorms.h>';
Blockly.Cpp.definitions_['include_mrobot3'] =
'CMindstorms m_robot3;';
var dropdown_direction = block.getFieldValue('direction');
var angle_turn_direction = block.getFieldValue('turn direction');
var dropdown_radius = block.getFieldValue('radius');
var dropdown_width = block.getFieldValue('width');
var code = 'm_robot3.' + dropdown_direction + '(' + angle_turn_direction + ', ' + dropdown_radius + ', ' + dropdown_width + ');\n';
return code;
};
Blockly.Cpp['mindstorms3_turn_cm'] = function(block) {
Blockly.Cpp.definitions_['include_mindstorms'] =
'#include <mindstorms.h>';
Blockly.Cpp.definitions_['include_mrobot3'] =
'CMindstorms m_robot3;';
var dropdown_direction = block.getFieldValue('direction');
var angle_turn_direction = block.getFieldValue('turn direction');
var dropdown_radius = block.getFieldValue('radius');
var dropdown_width = block.getFieldValue('width');
var code = 'm_robot3.' + dropdown_direction + '(' + angle_turn_direction + ', ' + dropdown_radius + ', ' + dropdown_width + ');\n';
return code;
};
Blockly.Cpp['mindstorms3_drive_distance_in'] = function(block) {
Blockly.Cpp.definitions_['include_mindstorms'] =
'#include <mindstorms.h>';
Blockly.Cpp.definitions_['include_mrobot3'] =
'CMindstorms m_robot3;';
var text_distance = block.getFieldValue('distance');
var dropdown_radius = block.getFieldValue('radius');
var code = 'm_robot3.driveDistance(' + text_distance + ', ' + dropdown_radius + ');\n';
return code;
};
Blockly.Cpp['mindstorms3_drive_distance_cm'] = function(block) {
Blockly.Cpp.definitions_['include_mindstorms'] =
'#include <mindstorms.h>';
Blockly.Cpp.definitions_['include_mrobot3'] =
'CMindstorms m_robot3;';
var text_distance = block.getFieldValue('distance');
var dropdown_radius = block.getFieldValue('radius');
var code = 'm_robot3.driveDistance(' + text_distance + ', ' + dropdown_radius + ');\n';
return code;
};
Blockly.Cpp['mindstorms3_drive_time'] = function(block) {
Blockly.Cpp.definitions_['include_mindstorms'] =
'#include <mindstorms.h>';
Blockly.Cpp.definitions_['include_mrobot3'] =
'CMindstorms m_robot3;';
var text_time = block.getFieldValue('time');
var code = 'm_robot3.driveTime(' + text_time + ');\n';
return code;
};
Blockly.Cpp['mindstorms3_drive_angle'] = function(block) {
Blockly.Cpp.definitions_['include_mindstorms'] =
'#include <mindstorms.h>';
Blockly.Cpp.definitions_['include_mrobot3'] =
'CMindstorms m_robot3;';
var text_angle = block.getFieldValue('angle');
var code = 'm_robot3.driveAngle(' + text_angle + ');\n';
return code;
};
Blockly.Cpp['mindstorms3_reset'] = function(block) {
Blockly.Cpp.definitions_['include_mindstorms'] =
'#include <mindstorms.h>';
Blockly.Cpp.definitions_['include_mrobot3'] =
'CMindstorms m_robot3;';
var code = 'm_robot3.resetToZero();\n';
return code;
};
Blockly.Cpp['mindstorms3_turn_in_NB'] = function(block) {
Blockly.Cpp.definitions_['include_mindstorms'] =
'#include <mindstorms.h>';
Blockly.Cpp.definitions_['include_mrobot3'] =
'CMindstorms m_robot3;';
var dropdown_direction = block.getFieldValue('direction');
var angle_turn_direction = block.getFieldValue('turn direction');
var dropdown_radius = block.getFieldValue('radius');
var dropdown_width = block.getFieldValue('width');
var code = 'm_robot3.' + dropdown_direction + 'NB(' + angle_turn_direction + ', ' + dropdown_radius + ', ' + dropdown_width + ');\n';
return code;
};
Blockly.Cpp['mindstorms3_turn_cm_NB'] = function(block) {
Blockly.Cpp.definitions_['include_mindstorms'] =
'#include <mindstorms.h>';
Blockly.Cpp.definitions_['include_mrobot3'] =
'CMindstorms m_robot3;';
var dropdown_direction = block.getFieldValue('direction');
var angle_turn_direction = block.getFieldValue('turn direction');
var dropdown_radius = block.getFieldValue('radius');
var dropdown_width = block.getFieldValue('width');
var code = 'm_robot3.' + dropdown_direction + 'NB(' + angle_turn_direction + ', ' + dropdown_radius + ', ' + dropdown_width + ');\n';
return code;
};
Blockly.Cpp['mindstorms3_drive_distance_in_NB'] = function(block) {
Blockly.Cpp.definitions_['include_mindstorms'] =
'#include <mindstorms.h>';
Blockly.Cpp.definitions_['include_mrobot3'] =
'CMindstorms m_robot3;';
var text_distance = block.getFieldValue('distance');
var dropdown_radius = block.getFieldValue('radius');
var code = 'm_robot3.driveDistanceNB(' + text_distance + ', ' + dropdown_radius + ');\n';
return code;
};
Blockly.Cpp['mindstorms3_drive_distance_cm_NB'] = function(block) {
Blockly.Cpp.definitions_['include_mindstorms'] =
'#include <mindstorms.h>';
Blockly.Cpp.definitions_['include_mrobot3'] =
'CMindstorms m_robot3;';
var text_distance = block.getFieldValue('distance');
var dropdown_radius = block.getFieldValue('radius');
var code = 'm_robot3.driveDistanceNB(' + text_distance + ', ' + dropdown_radius + ');\n';
return code;
};
Blockly.Cpp['mindstorms3_drive_time_NB'] = function(block) {
Blockly.Cpp.definitions_['include_mindstorms'] =
'#include <mindstorms.h>';
Blockly.Cpp.definitions_['include_mrobot3'] =
'CMindstorms m_robot3;';
var text_time = block.getFieldValue('time');
var code = 'm_robot3.driveTimeNB(' + text_time + ');\n';
return code;
};
Blockly.Cpp['mindstorms3_drive_angle_NB'] = function(block) {
Blockly.Cpp.definitions_['include_mindstorms'] =
'#include <mindstorms.h>';
Blockly.Cpp.definitions_['include_mrobot3'] =
'CMindstorms m_robot3;';
var text_angle = block.getFieldValue('angle');
var code = 'm_robot3.driveAngleNB(' + text_angle + ');\n';
return code;
};
Blockly.Cpp['mindstorms3_reset_NB'] = function(block) {
Blockly.Cpp.definitions_['include_mindstorms'] =
'#include <mindstorms.h>';
Blockly.Cpp.definitions_['include_mrobot3'] =
'CMindstorms m_robot3;';
var code = 'm_robot3.resetToZeroNB();\n';
return code;
}; | {'content_hash': '79aec9d813f9ae48661bbd8ef6ef110a', 'timestamp': '', 'source': 'github', 'line_count': 247, 'max_line_length': 135, 'avg_line_length': 37.75708502024292, 'alnum_prop': 0.67016941882908, 'repo_name': 'rynguy/BlocklyRobotSimulation', 'id': '7b1914bf9775ca8e6d5fdfbc3c45941fbd6db8c4', 'size': '10002', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'generators/cpp/mindstorms3.js', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '10845'}, {'name': 'HTML', 'bytes': '6269054'}, {'name': 'JavaScript', 'bytes': '6442397'}, {'name': 'Python', 'bytes': '108779'}]} |
// PetaJson v0.5 - A simple but flexible Json library in a single .cs file.
//
// Copyright (C) 2014 Topten Software ([email protected]) All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this product
// 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.
// Define PETAJSON_NO_DYNAMIC to disable Expando support
// Define PETAJSON_NO_EMIT to disable Reflection.Emit
// Define PETAJSON_NO_DATACONTRACT to disable support for [DataContract]/[DataMember]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Reflection;
using System.Globalization;
using System.Collections;
using System.Threading;
#if !PETAJSON_NO_DYNAMIC
using System.Dynamic;
#endif
#if !PETAJSON_NO_EMIT
using System.Reflection.Emit;
#endif
#if !PETAJSON_NO_DATACONTRACT
using System.Runtime.Serialization;
#endif
namespace PetaJson
{
// Pass to format/write/parse functions to override defaults
[Flags]
internal enum JsonOptions
{
None = 0,
WriteWhitespace = 0x00000001,
DontWriteWhitespace = 0x00000002,
StrictParser = 0x00000004,
NonStrictParser = 0x00000008,
}
// API
internal static class Json
{
static Json()
{
WriteWhitespaceDefault = true;
StrictParserDefault = false;
#if !PETAJSON_NO_EMIT
Json.SetFormatterResolver(Emit.MakeFormatter);
Json.SetParserResolver(Emit.MakeParser);
Json.SetIntoParserResolver(Emit.MakeIntoParser);
#endif
}
// Pretty format default
public static bool WriteWhitespaceDefault
{
get;
set;
}
// Strict parser
public static bool StrictParserDefault
{
get;
set;
}
// Write an object to a text writer
public static void Write(TextWriter w, object o, JsonOptions options = JsonOptions.None)
{
var writer = new Writer(w, ResolveOptions(options));
writer.WriteValue(o);
}
static void DeleteFile(string filename)
{
try
{
System.IO.File.Delete(filename);
}
catch
{
// Don't care
}
}
// Write a file atomically by writing to a temp file and then renaming it - prevents corrupted files if crash
// in middle of writing file.
public static void WriteFileAtomic(string filename, object o, JsonOptions options = JsonOptions.None)
{
var tempName = filename + ".tmp";
try
{
// Write the temp file
WriteFile(tempName, o, options);
// Delete the original file
DeleteFile(filename);
// Rename the temp file
System.IO.File.Move(tempName, filename);
}
catch
{
DeleteFile(tempName);
throw;
}
}
// Write an object to a file
public static void WriteFile(string filename, object o, JsonOptions options = JsonOptions.None)
{
using (var w = new StreamWriter(filename))
{
Write(w, o, options);
}
}
// Format an object as a json string
public static string Format(object o, JsonOptions options = JsonOptions.None)
{
var sw = new StringWriter();
var writer = new Writer(sw, ResolveOptions(options));
writer.WriteValue(o);
return sw.ToString();
}
// Parse an object of specified type from a text reader
public static object Parse(TextReader r, Type type, JsonOptions options = JsonOptions.None)
{
Reader reader = null;
try
{
reader = new Reader(r, ResolveOptions(options));
var retv = reader.Parse(type);
reader.CheckEOF();
return retv;
}
catch (Exception x)
{
var loc = reader == null ? new JsonLineOffset() : reader.CurrentTokenPosition;
Console.WriteLine("Exception thrown while parsing JSON at {0}, context:{1}\n{2}", loc, reader.Context, x.ToString());
throw new JsonParseException(x, reader.Context, loc);
}
}
// Parse an object of specified type from a text reader
public static T Parse<T>(TextReader r, JsonOptions options = JsonOptions.None)
{
return (T)Parse(r, typeof(T), options);
}
// Parse from text reader into an already instantied object
public static void ParseInto(TextReader r, Object into, JsonOptions options = JsonOptions.None)
{
if (into == null)
throw new NullReferenceException();
if (into.GetType().IsValueType)
throw new InvalidOperationException("Can't ParseInto a value type");
Reader reader = null;
try
{
reader = new Reader(r, ResolveOptions(options));
reader.ParseInto(into);
reader.CheckEOF();
}
catch (Exception x)
{
var loc = reader == null ? new JsonLineOffset() : reader.CurrentTokenPosition;
Console.WriteLine("Exception thrown while parsing JSON at {0}, context:{1}\n{2}", loc, reader.Context, x.ToString());
throw new JsonParseException(x, reader.Context, loc);
}
}
// Parse an object of specified type from a file
public static object ParseFile(string filename, Type type, JsonOptions options = JsonOptions.None)
{
using (var r = new StreamReader(filename))
{
return Parse(r, type, options);
}
}
// Parse an object of specified type from a file
public static T ParseFile<T>(string filename, JsonOptions options = JsonOptions.None)
{
using (var r = new StreamReader(filename))
{
return Parse<T>(r, options);
}
}
// Parse from file into an already instantied object
public static void ParseFileInto(string filename, Object into, JsonOptions options = JsonOptions.None)
{
using (var r = new StreamReader(filename))
{
ParseInto(r, into, options);
}
}
// Parse an object from a string
public static object Parse(string data, Type type, JsonOptions options = JsonOptions.None)
{
return Parse(new StringReader(data), type, options);
}
// Parse an object from a string
public static T Parse<T>(string data, JsonOptions options = JsonOptions.None)
{
return (T)Parse<T>(new StringReader(data), options);
}
// Parse from string into an already instantiated object
public static void ParseInto(string data, Object into, JsonOptions options = JsonOptions.None)
{
ParseInto(new StringReader(data), into, options);
}
// Create a clone of an object
public static T Clone<T>(T source)
{
return (T)Reparse(source.GetType(), source);
}
// Create a clone of an object (untyped)
public static object Clone(object source)
{
return Reparse(source.GetType(), source);
}
// Clone an object into another instance
public static void CloneInto(object dest, object source)
{
ReparseInto(dest, source);
}
// Reparse an object by writing to a stream and re-reading (possibly
// as a different type).
public static object Reparse(Type type, object source)
{
if (source == null)
return null;
var ms = new MemoryStream();
try
{
// Write
var w = new StreamWriter(ms);
Json.Write(w, source);
w.Flush();
// Read
ms.Seek(0, SeekOrigin.Begin);
var r = new StreamReader(ms);
return Json.Parse(r, type);
}
finally
{
ms.Dispose();
}
}
// Typed version of above
public static T Reparse<T>(object source)
{
return (T)Reparse(typeof(T), source);
}
// Reparse one object into another object
public static void ReparseInto(object dest, object source)
{
var ms = new MemoryStream();
try
{
// Write
var w = new StreamWriter(ms);
Json.Write(w, source);
w.Flush();
// Read
ms.Seek(0, SeekOrigin.Begin);
var r = new StreamReader(ms);
Json.ParseInto(r, dest);
}
finally
{
ms.Dispose();
}
}
// Register a callback that can format a value of a particular type into json
public static void RegisterFormatter(Type type, Action<IJsonWriter, object> formatter)
{
Writer._formatters[type] = formatter;
}
// Typed version of above
public static void RegisterFormatter<T>(Action<IJsonWriter, T> formatter)
{
RegisterFormatter(typeof(T), (w, o) => formatter(w, (T)o));
}
// Register a parser for a specified type
public static void RegisterParser(Type type, Func<IJsonReader, Type, object> parser)
{
Reader._parsers.Set(type, parser);
}
// Register a typed parser
public static void RegisterParser<T>(Func<IJsonReader, Type, T> parser)
{
RegisterParser(typeof(T), (r, t) => parser(r, t));
}
// Simpler version for simple types
public static void RegisterParser(Type type, Func<object, object> parser)
{
RegisterParser(type, (r, t) => r.ReadLiteral(parser));
}
// Simpler and typesafe parser for simple types
public static void RegisterParser<T>(Func<object, T> parser)
{
RegisterParser(typeof(T), literal => parser(literal));
}
// Register an into parser
public static void RegisterIntoParser(Type type, Action<IJsonReader, object> parser)
{
Reader._intoParsers.Set(type, parser);
}
// Register an into parser
public static void RegisterIntoParser<T>(Action<IJsonReader, object> parser)
{
RegisterIntoParser(typeof(T), parser);
}
// Register a factory for instantiating objects (typically abstract classes)
// Callback will be invoked for each key in the dictionary until it returns an object
// instance and which point it will switch to serialization using reflection
public static void RegisterTypeFactory(Type type, Func<IJsonReader, string, object> factory)
{
Reader._typeFactories.Set(type, factory);
}
// Register a callback to provide a formatter for a newly encountered type
public static void SetFormatterResolver(Func<Type, Action<IJsonWriter, object>> resolver)
{
Writer._formatterResolver = resolver;
}
// Register a callback to provide a parser for a newly encountered value type
public static void SetParserResolver(Func<Type, Func<IJsonReader, Type, object>> resolver)
{
Reader._parserResolver = resolver;
}
// Register a callback to provide a parser for a newly encountered reference type
public static void SetIntoParserResolver(Func<Type, Action<IJsonReader, object>> resolver)
{
Reader._intoParserResolver = resolver;
}
public static bool WalkPath(this IDictionary<string, object> This, string Path, bool create, Func<IDictionary<string, object>, string, bool> leafCallback)
{
// Walk the path
var parts = Path.Split('.');
for (int i = 0; i < parts.Length - 1; i++)
{
object val;
if (!This.TryGetValue(parts[i], out val))
{
if (!create)
return false;
val = new Dictionary<string, object>();
This[parts[i]] = val;
}
This = (IDictionary<string, object>)val;
}
// Process the leaf
return leafCallback(This, parts[parts.Length - 1]);
}
public static bool PathExists(this IDictionary<string, object> This, string Path)
{
return This.WalkPath(Path, false, (dict, key) => dict.ContainsKey(key));
}
public static object GetPath(this IDictionary<string, object> This, Type type, string Path, object def)
{
This.WalkPath(Path, false, (dict, key) =>
{
object val;
if (dict.TryGetValue(key, out val))
{
if (val == null)
def = val;
else if (type.IsAssignableFrom(val.GetType()))
def = val;
else
def = Reparse(type, val);
}
return true;
});
return def;
}
// Ensure there's an object of type T at specified path
public static T GetObjectAtPath<T>(this IDictionary<string, object> This, string Path) where T : class, new()
{
T retVal = null;
This.WalkPath(Path, true, (dict, key) =>
{
object val;
dict.TryGetValue(key, out val);
retVal = val as T;
if (retVal == null)
{
retVal = val == null ? new T() : Reparse<T>(val);
dict[key] = retVal;
}
return true;
});
return retVal;
}
public static T GetPath<T>(this IDictionary<string, object> This, string Path, T def = default(T))
{
return (T)This.GetPath(typeof(T), Path, def);
}
public static void SetPath(this IDictionary<string, object> This, string Path, object value)
{
This.WalkPath(Path, true, (dict, key) => { dict[key] = value; return true; });
}
// Resolve passed options
static JsonOptions ResolveOptions(JsonOptions options)
{
JsonOptions resolved = JsonOptions.None;
if ((options & (JsonOptions.WriteWhitespace | JsonOptions.DontWriteWhitespace)) != 0)
resolved |= options & (JsonOptions.WriteWhitespace | JsonOptions.DontWriteWhitespace);
else
resolved |= WriteWhitespaceDefault ? JsonOptions.WriteWhitespace : JsonOptions.DontWriteWhitespace;
if ((options & (JsonOptions.StrictParser | JsonOptions.NonStrictParser)) != 0)
resolved |= options & (JsonOptions.StrictParser | JsonOptions.NonStrictParser);
else
resolved |= StrictParserDefault ? JsonOptions.StrictParser : JsonOptions.NonStrictParser;
return resolved;
}
}
// Called before loading via reflection
[Obfuscation(Exclude = true, ApplyToMembers = true)]
internal interface IJsonLoading
{
void OnJsonLoading(IJsonReader r);
}
// Called after loading via reflection
[Obfuscation(Exclude = true, ApplyToMembers = true)]
internal interface IJsonLoaded
{
void OnJsonLoaded(IJsonReader r);
}
// Called for each field while loading from reflection
// Return true if handled
[Obfuscation(Exclude = true, ApplyToMembers = true)]
internal interface IJsonLoadField
{
bool OnJsonField(IJsonReader r, string key);
}
// Called when about to write using reflection
[Obfuscation(Exclude = true, ApplyToMembers = true)]
internal interface IJsonWriting
{
void OnJsonWriting(IJsonWriter w);
}
// Called after written using reflection
[Obfuscation(Exclude = true, ApplyToMembers = true)]
internal interface IJsonWritten
{
void OnJsonWritten(IJsonWriter w);
}
// Describes the current literal in the json stream
internal enum LiteralKind
{
None,
String,
Null,
True,
False,
SignedInteger,
UnsignedInteger,
FloatingPoint,
}
// Passed to registered parsers
[Obfuscation(Exclude = true, ApplyToMembers = true)]
internal interface IJsonReader
{
object Parse(Type type);
T Parse<T>();
void ParseInto(object into);
object ReadLiteral(Func<object, object> converter);
void ParseDictionary(Action<string> callback);
void ParseArray(Action callback);
LiteralKind GetLiteralKind();
string GetLiteralString();
void NextToken();
}
// Passed to registered formatters
[Obfuscation(Exclude = true, ApplyToMembers = true)]
internal interface IJsonWriter
{
void WriteStringLiteral(string str);
void WriteRaw(string str);
void WriteArray(Action callback);
void WriteDictionary(Action callback);
void WriteValue(object value);
void WriteElement();
void WriteKey(string key);
void WriteKeyNoEscaping(string key);
}
// Exception thrown for any parse error
internal class JsonParseException : Exception
{
public JsonParseException(Exception inner, string context, JsonLineOffset position) :
base(string.Format("JSON parse error at {0}{1} - {2}", position, string.IsNullOrEmpty(context) ? "" : string.Format(", context {0}", context), inner.Message), inner)
{
Position = position;
Context = context;
}
public JsonLineOffset Position;
public string Context;
}
// Represents a line and character offset position in the source Json
internal struct JsonLineOffset
{
public int Line;
public int Offset;
public override string ToString()
{
return string.Format("line {0}, character {1}", Line + 1, Offset + 1);
}
}
// Used to decorate fields and properties that should be serialized
//
// - [Json] on class or struct causes all public fields and properties to be serialized
// - [Json] on a public or non-public field or property causes that member to be serialized
// - [JsonExclude] on a field or property causes that field to be not serialized
// - A class or struct with no [Json] attribute has all public fields/properties serialized
// - A class or struct with no [Json] attribute but a [Json] attribute on one or more members only serializes those members
//
// Use [Json("keyname")] to explicitly specify the key to be used
// [Json] without the keyname will be serialized using the name of the member with the first letter lowercased.
//
// [Json(KeepInstance=true)] causes container/subobject types to be serialized into the existing member instance (if not null)
//
// You can also use the system supplied DataContract and DataMember attributes. They'll only be used if there
// are no PetaJson attributes on the class or it's members. You must specify DataContract on the type and
// DataMember on any fields/properties that require serialization. There's no need for exclude attribute.
// When using DataMember, the name of the field or property is used as is - the first letter is left in upper case
//
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Property | AttributeTargets.Field)]
internal class JsonAttribute : Attribute
{
public JsonAttribute()
{
_key = null;
}
public JsonAttribute(string key)
{
_key = key;
}
// Key used to save this field/property
string _key;
public string Key
{
get { return _key; }
}
// If true uses ParseInto to parse into the existing object instance
// If false, creates a new instance as assigns it to the property
public bool KeepInstance
{
get;
set;
}
// If true, the property will be loaded, but not saved
// Use to upgrade deprecated persisted settings, but not
// write them back out again
public bool Deprecated
{
get;
set;
}
}
// See comments for JsonAttribute above
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)]
internal class JsonExcludeAttribute : Attribute
{
public JsonExcludeAttribute()
{
}
}
// Apply to enum values to specify which enum value to select
// if the supplied json value doesn't match any.
// If not found throws an exception
// eg, any unknown values in the json will be mapped to Fruit.unknown
//
// [JsonUnknown(Fruit.unknown)]
// enum Fruit
// {
// unknown,
// Apple,
// Pear,
// }
[AttributeUsage(AttributeTargets.Enum)]
internal class JsonUnknownAttribute : Attribute
{
public JsonUnknownAttribute(object unknownValue)
{
UnknownValue = unknownValue;
}
public object UnknownValue
{
get;
private set;
}
}
//namespace Internal
//{
[Obfuscation(Exclude = true, ApplyToMembers = true)]
internal enum Token
{
EOF,
Identifier,
Literal,
OpenBrace,
CloseBrace,
OpenSquare,
CloseSquare,
Equal,
Colon,
SemiColon,
Comma,
}
// Helper to create instances but include the type name in the thrown exception
internal static class DecoratingActivator
{
public static object CreateInstance(Type t)
{
try
{
return Activator.CreateInstance(t);
}
catch (Exception x)
{
throw new InvalidOperationException(string.Format("Failed to create instance of type '{0}'", t.FullName), x);
}
}
}
internal class Reader : IJsonReader
{
static Reader()
{
// Setup default resolvers
_parserResolver = ResolveParser;
_intoParserResolver = ResolveIntoParser;
Func<IJsonReader, Type, object> simpleConverter = (reader, type) =>
{
return reader.ReadLiteral(literal => Convert.ChangeType(literal, type, CultureInfo.InvariantCulture));
};
Func<IJsonReader, Type, object> numberConverter = (reader, type) =>
{
switch (reader.GetLiteralKind())
{
case LiteralKind.SignedInteger:
case LiteralKind.UnsignedInteger:
case LiteralKind.FloatingPoint:
object val = Convert.ChangeType(reader.GetLiteralString(), type, CultureInfo.InvariantCulture);
reader.NextToken();
return val;
}
throw new InvalidDataException("expected a numeric literal");
};
// Default type handlers
_parsers.Set(typeof(string), simpleConverter);
_parsers.Set(typeof(char), simpleConverter);
_parsers.Set(typeof(bool), simpleConverter);
_parsers.Set(typeof(byte), numberConverter);
_parsers.Set(typeof(sbyte), numberConverter);
_parsers.Set(typeof(short), numberConverter);
_parsers.Set(typeof(ushort), numberConverter);
_parsers.Set(typeof(int), numberConverter);
_parsers.Set(typeof(uint), numberConverter);
_parsers.Set(typeof(long), numberConverter);
_parsers.Set(typeof(ulong), numberConverter);
_parsers.Set(typeof(decimal), numberConverter);
_parsers.Set(typeof(float), numberConverter);
_parsers.Set(typeof(double), numberConverter);
_parsers.Set(typeof(DateTime), (reader, type) =>
{
return reader.ReadLiteral(literal => Utils.FromUnixMilliseconds((long)Convert.ChangeType(literal, typeof(long), CultureInfo.InvariantCulture)));
});
_parsers.Set(typeof(byte[]), (reader, type) =>
{
return reader.ReadLiteral(literal => Convert.FromBase64String((string)Convert.ChangeType(literal, typeof(string), CultureInfo.InvariantCulture)));
});
}
public Reader(TextReader r, JsonOptions options)
{
_tokenizer = new Tokenizer(r, options);
_options = options;
}
Tokenizer _tokenizer;
JsonOptions _options;
List<string> _contextStack = new List<string>();
public string Context
{
get
{
#if NET35
return string.Join(".", _contextStack.ToArray());
#else
return string.Join(".", _contextStack);
#endif
}
}
static Action<IJsonReader, object> ResolveIntoParser(Type type)
{
var ri = ReflectionInfo.GetReflectionInfo(type);
if (ri != null)
return ri.ParseInto;
else
return null;
}
static Func<IJsonReader, Type, object> ResolveParser(Type type)
{
// See if the Type has a static parser method - T ParseJson(IJsonReader)
var parseJson = ReflectionInfo.FindParseJson(type);
if (parseJson != null)
{
if (parseJson.GetParameters()[0].ParameterType == typeof(IJsonReader))
{
return (r, t) => parseJson.Invoke(null, new Object[] { r });
}
else
{
return (r, t) =>
{
if (r.GetLiteralKind() == LiteralKind.String)
{
var o = parseJson.Invoke(null, new Object[] { r.GetLiteralString() });
r.NextToken();
return o;
}
throw new InvalidDataException(string.Format("Expected string literal for type {0}", type.FullName));
};
}
}
return (r, t) =>
{
var into = DecoratingActivator.CreateInstance(type);
r.ParseInto(into);
return into;
};
}
public JsonLineOffset CurrentTokenPosition
{
get { return _tokenizer.CurrentTokenPosition; }
}
// ReadLiteral is implemented with a converter callback so that any
// errors on converting to the target type are thrown before the tokenizer
// is advanced to the next token. This ensures error location is reported
// at the start of the literal, not the following token.
public object ReadLiteral(Func<object, object> converter)
{
_tokenizer.Check(Token.Literal);
var retv = converter(_tokenizer.LiteralValue);
_tokenizer.NextToken();
return retv;
}
public void CheckEOF()
{
_tokenizer.Check(Token.EOF);
}
public object Parse(Type type)
{
// Null?
if (_tokenizer.CurrentToken == Token.Literal && _tokenizer.LiteralKind == LiteralKind.Null)
{
_tokenizer.NextToken();
return null;
}
// Handle nullable types
var typeUnderlying = Nullable.GetUnderlyingType(type);
if (typeUnderlying != null)
type = typeUnderlying;
// See if we have a reader
Func<IJsonReader, Type, object> parser;
if (Reader._parsers.TryGetValue(type, out parser))
{
return parser(this, type);
}
// See if we have factory
Func<IJsonReader, string, object> factory;
if (Reader._typeFactories.TryGetValue(type, out factory))
{
// Try first without passing dictionary keys
object into = factory(this, null);
if (into == null)
{
// This is a awkward situation. The factory requires a value from the dictionary
// in order to create the target object (typically an abstract class with the class
// kind recorded in the Json). Since there's no guarantee of order in a json dictionary
// we can't assume the required key is first.
// So, create a bookmark on the tokenizer, read keys until the factory returns an
// object instance and then rewind the tokenizer and continue
// Create a bookmark so we can rewind
_tokenizer.CreateBookmark();
// Skip the opening brace
_tokenizer.Skip(Token.OpenBrace);
// First pass to work out type
ParseDictionaryKeys(key =>
{
// Try to instantiate the object
into = factory(this, key);
return into == null;
});
// Move back to start of the dictionary
_tokenizer.RewindToBookmark();
// Quit if still didn't get an object from the factory
if (into == null)
throw new InvalidOperationException("Factory didn't create object instance (probably due to a missing key in the Json)");
}
// Second pass
ParseInto(into);
// Done
return into;
}
// Do we already have an into parser?
Action<IJsonReader, object> intoParser;
if (Reader._intoParsers.TryGetValue(type, out intoParser))
{
var into = DecoratingActivator.CreateInstance(type);
ParseInto(into);
return into;
}
// Enumerated type?
if (type.IsEnum)
{
if (type.GetCustomAttributes(typeof(FlagsAttribute), false).Any())
return ReadLiteral(literal => {
try
{
return Enum.Parse(type, (string)literal);
}
catch
{
return Enum.ToObject(type, literal);
}
});
else
return ReadLiteral(literal => {
try
{
return Enum.Parse(type, (string)literal);
}
catch (Exception)
{
var attr = type.GetCustomAttributes(typeof(JsonUnknownAttribute), false).FirstOrDefault();
if (attr == null)
throw;
return ((JsonUnknownAttribute)attr).UnknownValue;
}
});
}
// Array?
if (type.IsArray && type.GetArrayRank() == 1)
{
// First parse as a List<>
var listType = typeof(List<>).MakeGenericType(type.GetElementType());
var list = DecoratingActivator.CreateInstance(listType);
ParseInto(list);
return listType.GetMethod("ToArray").Invoke(list, null);
}
// Convert interfaces to concrete types
if (type.IsInterface)
type = Utils.ResolveInterfaceToClass(type);
// Untyped dictionary?
if (_tokenizer.CurrentToken == Token.OpenBrace && (type.IsAssignableFrom(typeof(IDictionary<string, object>))))
{
#if !PETAJSON_NO_DYNAMIC
var container = (new ExpandoObject()) as IDictionary<string, object>;
#else
var container = new Dictionary<string, object>();
#endif
ParseDictionary(key =>
{
container[key] = Parse(typeof(Object));
});
return container;
}
// Untyped list?
if (_tokenizer.CurrentToken == Token.OpenSquare && (type.IsAssignableFrom(typeof(List<object>))))
{
var container = new List<object>();
ParseArray(() =>
{
container.Add(Parse(typeof(Object)));
});
return container;
}
// Untyped literal?
if (_tokenizer.CurrentToken == Token.Literal && type.IsAssignableFrom(_tokenizer.LiteralType))
{
var lit = _tokenizer.LiteralValue;
_tokenizer.NextToken();
return lit;
}
// Call value type resolver
if (type.IsValueType)
{
var tp = _parsers.Get(type, () => _parserResolver(type));
if (tp != null)
{
return tp(this, type);
}
}
// Call reference type resolver
if (type.IsClass && type != typeof(object))
{
var into = DecoratingActivator.CreateInstance(type);
ParseInto(into);
return into;
}
// Give up
throw new InvalidDataException(string.Format("syntax error, unexpected token {0}", _tokenizer.CurrentToken));
}
// Parse into an existing object instance
public void ParseInto(object into)
{
if (into == null)
return;
if (_tokenizer.CurrentToken == Token.Literal && _tokenizer.LiteralKind == LiteralKind.Null)
{
throw new InvalidOperationException("can't parse null into existing instance");
//return;
}
var type = into.GetType();
// Existing parse into handler?
Action<IJsonReader, object> parseInto;
if (_intoParsers.TryGetValue(type, out parseInto))
{
parseInto(this, into);
return;
}
// Generic dictionary?
var dictType = Utils.FindGenericInterface(type, typeof(IDictionary<,>));
if (dictType != null)
{
// Get the key and value types
var typeKey = dictType.GetGenericArguments()[0];
var typeValue = dictType.GetGenericArguments()[1];
// Parse it
IDictionary dict = (IDictionary)into;
dict.Clear();
ParseDictionary(key =>
{
dict.Add(Convert.ChangeType(key, typeKey), Parse(typeValue));
});
return;
}
// Generic list
var listType = Utils.FindGenericInterface(type, typeof(IList<>));
if (listType != null)
{
// Get element type
var typeElement = listType.GetGenericArguments()[0];
// Parse it
IList list = (IList)into;
list.Clear();
ParseArray(() =>
{
list.Add(Parse(typeElement));
});
return;
}
// Untyped dictionary
var objDict = into as IDictionary;
if (objDict != null)
{
objDict.Clear();
ParseDictionary(key =>
{
objDict[key] = Parse(typeof(Object));
});
return;
}
// Untyped list
var objList = into as IList;
if (objList != null)
{
objList.Clear();
ParseArray(() =>
{
objList.Add(Parse(typeof(Object)));
});
return;
}
// Try to resolve a parser
var intoParser = _intoParsers.Get(type, () => _intoParserResolver(type));
if (intoParser != null)
{
intoParser(this, into);
return;
}
throw new InvalidOperationException(string.Format("Don't know how to parse into type '{0}'", type.FullName));
}
public T Parse<T>()
{
return (T)Parse(typeof(T));
}
public LiteralKind GetLiteralKind()
{
return _tokenizer.LiteralKind;
}
public string GetLiteralString()
{
return _tokenizer.String;
}
public void NextToken()
{
_tokenizer.NextToken();
}
// Parse a dictionary
public void ParseDictionary(Action<string> callback)
{
_tokenizer.Skip(Token.OpenBrace);
ParseDictionaryKeys(key => { callback(key); return true; });
_tokenizer.Skip(Token.CloseBrace);
}
// Parse dictionary keys, calling callback for each one. Continues until end of input
// or when callback returns false
private void ParseDictionaryKeys(Func<string, bool> callback)
{
// End?
while (_tokenizer.CurrentToken != Token.CloseBrace)
{
// Parse the key
string key = null;
if (_tokenizer.CurrentToken == Token.Identifier && (_options & JsonOptions.StrictParser) == 0)
{
key = _tokenizer.String;
}
else if (_tokenizer.CurrentToken == Token.Literal && _tokenizer.LiteralKind == LiteralKind.String)
{
key = (string)_tokenizer.LiteralValue;
}
else
{
throw new InvalidDataException("syntax error, expected string literal or identifier");
}
_tokenizer.NextToken();
_tokenizer.Skip(Token.Colon);
// Remember current position
var pos = _tokenizer.CurrentTokenPosition;
// Call the callback, quit if cancelled
_contextStack.Add(key);
bool doDefaultProcessing = callback(key);
_contextStack.RemoveAt(_contextStack.Count - 1);
if (!doDefaultProcessing)
return;
// If the callback didn't read anything from the tokenizer, then skip it ourself
if (pos.Line == _tokenizer.CurrentTokenPosition.Line && pos.Offset == _tokenizer.CurrentTokenPosition.Offset)
{
Parse(typeof(object));
}
// Separating/trailing comma
if (_tokenizer.SkipIf(Token.Comma))
{
if ((_options & JsonOptions.StrictParser) != 0 && _tokenizer.CurrentToken == Token.CloseBrace)
{
throw new InvalidDataException("Trailing commas not allowed in strict mode");
}
continue;
}
// End
break;
}
}
// Parse an array
public void ParseArray(Action callback)
{
_tokenizer.Skip(Token.OpenSquare);
int index = 0;
while (_tokenizer.CurrentToken != Token.CloseSquare)
{
_contextStack.Add(string.Format("[{0}]", index));
callback();
_contextStack.RemoveAt(_contextStack.Count - 1);
if (_tokenizer.SkipIf(Token.Comma))
{
if ((_options & JsonOptions.StrictParser) != 0 && _tokenizer.CurrentToken == Token.CloseSquare)
{
throw new InvalidDataException("Trailing commas not allowed in strict mode");
}
continue;
}
break;
}
_tokenizer.Skip(Token.CloseSquare);
}
// Yikes!
public static Func<Type, Action<IJsonReader, object>> _intoParserResolver;
public static Func<Type, Func<IJsonReader, Type, object>> _parserResolver;
public static ThreadSafeCache<Type, Func<IJsonReader, Type, object>> _parsers = new ThreadSafeCache<Type, Func<IJsonReader, Type, object>>();
public static ThreadSafeCache<Type, Action<IJsonReader, object>> _intoParsers = new ThreadSafeCache<Type, Action<IJsonReader, object>>();
public static ThreadSafeCache<Type, Func<IJsonReader, string, object>> _typeFactories = new ThreadSafeCache<Type, Func<IJsonReader, string, object>>();
}
internal class Writer : IJsonWriter
{
static Writer()
{
_formatterResolver = ResolveFormatter;
// Register standard formatters
_formatters.Add(typeof(string), (w, o) => w.WriteStringLiteral((string)o));
_formatters.Add(typeof(char), (w, o) => w.WriteStringLiteral(((char)o).ToString()));
_formatters.Add(typeof(bool), (w, o) => w.WriteRaw(((bool)o) ? "true" : "false"));
Action<IJsonWriter, object> convertWriter = (w, o) => w.WriteRaw((string)Convert.ChangeType(o, typeof(string), System.Globalization.CultureInfo.InvariantCulture));
_formatters.Add(typeof(int), convertWriter);
_formatters.Add(typeof(uint), convertWriter);
_formatters.Add(typeof(long), convertWriter);
_formatters.Add(typeof(ulong), convertWriter);
_formatters.Add(typeof(short), convertWriter);
_formatters.Add(typeof(ushort), convertWriter);
_formatters.Add(typeof(decimal), convertWriter);
_formatters.Add(typeof(byte), convertWriter);
_formatters.Add(typeof(sbyte), convertWriter);
_formatters.Add(typeof(DateTime), (w, o) => convertWriter(w, Utils.ToUnixMilliseconds((DateTime)o)));
_formatters.Add(typeof(float), (w, o) => w.WriteRaw(((float)o).ToString("R", System.Globalization.CultureInfo.InvariantCulture)));
_formatters.Add(typeof(double), (w, o) => w.WriteRaw(((double)o).ToString("R", System.Globalization.CultureInfo.InvariantCulture)));
_formatters.Add(typeof(byte[]), (w, o) =>
{
w.WriteRaw("\"");
w.WriteRaw(Convert.ToBase64String((byte[])o));
w.WriteRaw("\"");
});
}
public static Func<Type, Action<IJsonWriter, object>> _formatterResolver;
public static Dictionary<Type, Action<IJsonWriter, object>> _formatters = new Dictionary<Type, Action<IJsonWriter, object>>();
static Action<IJsonWriter, object> ResolveFormatter(Type type)
{
// Try `void FormatJson(IJsonWriter)`
var formatJson = ReflectionInfo.FindFormatJson(type);
if (formatJson != null)
{
if (formatJson.ReturnType == typeof(void))
return (w, obj) => formatJson.Invoke(obj, new Object[] { w });
if (formatJson.ReturnType == typeof(string))
return (w, obj) => w.WriteStringLiteral((string)formatJson.Invoke(obj, new Object[] { }));
}
var ri = ReflectionInfo.GetReflectionInfo(type);
if (ri != null)
return ri.Write;
else
return null;
}
public Writer(TextWriter w, JsonOptions options)
{
_writer = w;
_atStartOfLine = true;
_needElementSeparator = false;
_options = options;
}
private TextWriter _writer;
private int IndentLevel;
private bool _atStartOfLine;
private bool _needElementSeparator = false;
private JsonOptions _options;
private char _currentBlockKind = '\0';
// Move to the next line
public void NextLine()
{
if (_atStartOfLine)
return;
if ((_options & JsonOptions.WriteWhitespace) != 0)
{
WriteRaw("\n");
WriteRaw(new string('\t', IndentLevel));
}
_atStartOfLine = true;
}
// Start the next element, writing separators and white space
void NextElement()
{
if (_needElementSeparator)
{
WriteRaw(",");
NextLine();
}
else
{
NextLine();
IndentLevel++;
WriteRaw(_currentBlockKind.ToString());
NextLine();
}
_needElementSeparator = true;
}
// Write next array element
public void WriteElement()
{
if (_currentBlockKind != '[')
throw new InvalidOperationException("Attempt to write array element when not in array block");
NextElement();
}
// Write next dictionary key
public void WriteKey(string key)
{
if (_currentBlockKind != '{')
throw new InvalidOperationException("Attempt to write dictionary element when not in dictionary block");
NextElement();
WriteStringLiteral(key);
WriteRaw(((_options & JsonOptions.WriteWhitespace) != 0) ? ": " : ":");
}
// Write an already escaped dictionary key
public void WriteKeyNoEscaping(string key)
{
if (_currentBlockKind != '{')
throw new InvalidOperationException("Attempt to write dictionary element when not in dictionary block");
NextElement();
WriteRaw("\"");
WriteRaw(key);
WriteRaw("\"");
WriteRaw(((_options & JsonOptions.WriteWhitespace) != 0) ? ": " : ":");
}
// Write anything
public void WriteRaw(string str)
{
_atStartOfLine = false;
_writer.Write(str);
}
static int IndexOfEscapeableChar(string str, int pos)
{
int length = str.Length;
while (pos < length)
{
var ch = str[pos];
if (ch == '\\' || ch == '/' || ch == '\"' || (ch >= 0 && ch <= 0x1f) || (ch >= 0x7f && ch <= 0x9f) || ch == 0x2028 || ch == 0x2029)
return pos;
pos++;
}
return -1;
}
public void WriteStringLiteral(string str)
{
_atStartOfLine = false;
if (str == null)
{
_writer.Write("null");
return;
}
_writer.Write("\"");
int pos = 0;
int escapePos;
while ((escapePos = IndexOfEscapeableChar(str, pos)) >= 0)
{
if (escapePos > pos)
_writer.Write(str.Substring(pos, escapePos - pos));
switch (str[escapePos])
{
case '\"': _writer.Write("\\\""); break;
case '\\': _writer.Write("\\\\"); break;
case '/': _writer.Write("\\/"); break;
case '\b': _writer.Write("\\b"); break;
case '\f': _writer.Write("\\f"); break;
case '\n': _writer.Write("\\n"); break;
case '\r': _writer.Write("\\r"); break;
case '\t': _writer.Write("\\t"); break;
default:
_writer.Write(string.Format("\\u{0:x4}", (int)str[escapePos]));
break;
}
pos = escapePos + 1;
}
if (str.Length > pos)
_writer.Write(str.Substring(pos));
_writer.Write("\"");
}
// Write an array or dictionary block
private void WriteBlock(string open, string close, Action callback)
{
var prevBlockKind = _currentBlockKind;
_currentBlockKind = open[0];
var didNeedElementSeparator = _needElementSeparator;
_needElementSeparator = false;
callback();
if (_needElementSeparator)
{
IndentLevel--;
NextLine();
}
else
{
WriteRaw(open);
}
WriteRaw(close);
_needElementSeparator = didNeedElementSeparator;
_currentBlockKind = prevBlockKind;
}
// Write an array
public void WriteArray(Action callback)
{
WriteBlock("[", "]", callback);
}
// Write a dictionary
public void WriteDictionary(Action callback)
{
WriteBlock("{", "}", callback);
}
// Write any value
public void WriteValue(object value)
{
_atStartOfLine = false;
// Special handling for null
if (value == null)
{
_writer.Write("null");
return;
}
var type = value.GetType();
// Handle nullable types
var typeUnderlying = Nullable.GetUnderlyingType(type);
if (typeUnderlying != null)
type = typeUnderlying;
// Look up type writer
Action<IJsonWriter, object> typeWriter;
if (_formatters.TryGetValue(type, out typeWriter))
{
// Write it
typeWriter(this, value);
return;
}
// Enumerated type?
if (type.IsEnum)
{
if (type.GetCustomAttributes(typeof(FlagsAttribute), false).Any())
WriteRaw(Convert.ToUInt32(value).ToString(CultureInfo.InvariantCulture));
else
WriteStringLiteral(value.ToString());
return;
}
// Dictionary?
var d = value as System.Collections.IDictionary;
if (d != null)
{
WriteDictionary(() =>
{
foreach (var key in d.Keys)
{
WriteKey(key.ToString());
WriteValue(d[key]);
}
});
return;
}
// Dictionary?
var dso = value as IDictionary<string, object>;
if (dso != null)
{
WriteDictionary(() =>
{
foreach (var key in dso.Keys)
{
WriteKey(key.ToString());
WriteValue(dso[key]);
}
});
return;
}
// Array?
var e = value as System.Collections.IEnumerable;
if (e != null)
{
WriteArray(() =>
{
foreach (var i in e)
{
WriteElement();
WriteValue(i);
}
});
return;
}
// Resolve a formatter
var formatter = _formatterResolver(type);
if (formatter != null)
{
_formatters[type] = formatter;
formatter(this, value);
return;
}
// Give up
throw new InvalidDataException(string.Format("Don't know how to write '{0}' to json", value.GetType()));
}
}
// Information about a field or property found through reflection
internal class JsonMemberInfo
{
// The Json key for this member
public string JsonKey;
// True if should keep existing instance (reference types only)
public bool KeepInstance;
// True if deprecated
public bool Deprecated;
// Reflected member info
MemberInfo _mi;
public MemberInfo Member
{
get { return _mi; }
set
{
// Store it
_mi = value;
// Also create getters and setters
if (_mi is PropertyInfo)
{
GetValue = (obj) => ((PropertyInfo)_mi).GetValue(obj, null);
SetValue = (obj, val) => ((PropertyInfo)_mi).SetValue(obj, val, null);
}
else
{
GetValue = ((FieldInfo)_mi).GetValue;
SetValue = ((FieldInfo)_mi).SetValue;
}
}
}
// Member type
public Type MemberType
{
get
{
if (Member is PropertyInfo)
{
return ((PropertyInfo)Member).PropertyType;
}
else
{
return ((FieldInfo)Member).FieldType;
}
}
}
// Get/set helpers
public Action<object, object> SetValue;
public Func<object, object> GetValue;
}
// Stores reflection info about a type
internal class ReflectionInfo
{
// List of members to be serialized
public List<JsonMemberInfo> Members;
// Cache of these ReflectionInfos's
static ThreadSafeCache<Type, ReflectionInfo> _cache = new ThreadSafeCache<Type, ReflectionInfo>();
public static MethodInfo FindFormatJson(Type type)
{
if (type.IsValueType)
{
// Try `void FormatJson(IJsonWriter)`
var formatJson = type.GetMethod("FormatJson", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[] { typeof(IJsonWriter) }, null);
if (formatJson != null && formatJson.ReturnType == typeof(void))
return formatJson;
// Try `string FormatJson()`
formatJson = type.GetMethod("FormatJson", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[] { }, null);
if (formatJson != null && formatJson.ReturnType == typeof(string))
return formatJson;
}
return null;
}
public static MethodInfo FindParseJson(Type type)
{
// Try `T ParseJson(IJsonReader)`
var parseJson = type.GetMethod("ParseJson", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static, null, new Type[] { typeof(IJsonReader) }, null);
if (parseJson != null && parseJson.ReturnType == type)
return parseJson;
// Try `T ParseJson(string)`
parseJson = type.GetMethod("ParseJson", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static, null, new Type[] { typeof(string) }, null);
if (parseJson != null && parseJson.ReturnType == type)
return parseJson;
return null;
}
// Write one of these types
public void Write(IJsonWriter w, object val)
{
w.WriteDictionary(() =>
{
var writing = val as IJsonWriting;
if (writing != null)
writing.OnJsonWriting(w);
foreach (var jmi in Members.Where(x => !x.Deprecated))
{
w.WriteKeyNoEscaping(jmi.JsonKey);
w.WriteValue(jmi.GetValue(val));
}
var written = val as IJsonWritten;
if (written != null)
written.OnJsonWritten(w);
});
}
// Read one of these types.
// NB: Although PetaJson.JsonParseInto only works on reference type, when using reflection
// it also works for value types so we use the one method for both
public void ParseInto(IJsonReader r, object into)
{
var loading = into as IJsonLoading;
if (loading != null)
loading.OnJsonLoading(r);
r.ParseDictionary(key =>
{
ParseFieldOrProperty(r, into, key);
});
var loaded = into as IJsonLoaded;
if (loaded != null)
loaded.OnJsonLoaded(r);
}
// The member info is stored in a list (as opposed to a dictionary) so that
// the json is written in the same order as the fields/properties are defined
// On loading, we assume the fields will be in the same order, but need to
// handle if they're not. This function performs a linear search, but
// starts after the last found item as an optimization that should work
// most of the time.
int _lastFoundIndex = 0;
bool FindMemberInfo(string name, out JsonMemberInfo found)
{
for (int i = 0; i < Members.Count; i++)
{
int index = (i + _lastFoundIndex) % Members.Count;
var jmi = Members[index];
if (jmi.JsonKey == name)
{
_lastFoundIndex = index;
found = jmi;
return true;
}
}
found = null;
return false;
}
// Parse a value from IJsonReader into an object instance
public void ParseFieldOrProperty(IJsonReader r, object into, string key)
{
// IJsonLoadField
var lf = into as IJsonLoadField;
if (lf != null && lf.OnJsonField(r, key))
return;
// Find member
JsonMemberInfo jmi;
if (FindMemberInfo(key, out jmi))
{
// Try to keep existing instance
if (jmi.KeepInstance)
{
var subInto = jmi.GetValue(into);
if (subInto != null)
{
r.ParseInto(subInto);
return;
}
}
// Parse and set
var val = r.Parse(jmi.MemberType);
jmi.SetValue(into, val);
return;
}
}
// Get the reflection info for a specified type
public static ReflectionInfo GetReflectionInfo(Type type)
{
// Check cache
return _cache.Get(type, () =>
{
var allMembers = Utils.GetAllFieldsAndProperties(type);
// Does type have a [Json] attribute
bool typeMarked = type.GetCustomAttributes(typeof(JsonAttribute), true).OfType<JsonAttribute>().Any();
// Do any members have a [Json] attribute
bool anyFieldsMarked = allMembers.Any(x => x.GetCustomAttributes(typeof(JsonAttribute), false).OfType<JsonAttribute>().Any());
#if !PETAJSON_NO_DATACONTRACT
// Try with DataContract and friends
if (!typeMarked && !anyFieldsMarked && type.GetCustomAttributes(typeof(DataContractAttribute), true).OfType<DataContractAttribute>().Any())
{
var ri = CreateReflectionInfo(type, mi =>
{
// Get attributes
var attr = mi.GetCustomAttributes(typeof(DataMemberAttribute), false).OfType<DataMemberAttribute>().FirstOrDefault();
if (attr != null)
{
return new JsonMemberInfo()
{
Member = mi,
JsonKey = attr.Name ?? mi.Name, // No lower case first letter if using DataContract/Member
};
}
return null;
});
ri.Members.Sort((a, b) => String.CompareOrdinal(a.JsonKey, b.JsonKey)); // Match DataContractJsonSerializer
return ri;
}
#endif
{
// Should we serialize all public methods?
bool serializeAllPublics = typeMarked || !anyFieldsMarked;
// Build
var ri = CreateReflectionInfo(type, mi =>
{
// Explicitly excluded?
if (mi.GetCustomAttributes(typeof(JsonExcludeAttribute), false).Any())
return null;
// Get attributes
var attr = mi.GetCustomAttributes(typeof(JsonAttribute), false).OfType<JsonAttribute>().FirstOrDefault();
if (attr != null)
{
return new JsonMemberInfo()
{
Member = mi,
JsonKey = attr.Key ?? mi.Name.Substring(0, 1).ToLower() + mi.Name.Substring(1),
KeepInstance = attr.KeepInstance,
Deprecated = attr.Deprecated,
};
}
// Serialize all publics?
if (serializeAllPublics && Utils.IsPublic(mi))
{
return new JsonMemberInfo()
{
Member = mi,
JsonKey = mi.Name.Substring(0, 1).ToLower() + mi.Name.Substring(1),
};
}
return null;
});
return ri;
}
});
}
public static ReflectionInfo CreateReflectionInfo(Type type, Func<MemberInfo, JsonMemberInfo> callback)
{
// Work out properties and fields
var members = Utils.GetAllFieldsAndProperties(type).Select(x => callback(x)).Where(x => x != null).ToList();
// Anything with KeepInstance must be a reference type
var invalid = members.FirstOrDefault(x => x.KeepInstance && x.MemberType.IsValueType);
if (invalid != null)
{
throw new InvalidOperationException(string.Format("KeepInstance=true can only be applied to reference types ({0}.{1})", type.FullName, invalid.Member));
}
// Must have some members
if (!members.Any())
return null;
// Create reflection info
return new ReflectionInfo() { Members = members };
}
}
internal class ThreadSafeCache<TKey, TValue>
{
public ThreadSafeCache()
{
}
public TValue Get(TKey key, Func<TValue> createIt)
{
// Check if already exists
_lock.EnterReadLock();
try
{
TValue val;
if (_map.TryGetValue(key, out val))
return val;
}
finally
{
_lock.ExitReadLock();
}
// Nope, take lock and try again
_lock.EnterWriteLock();
try
{
// Check again before creating it
TValue val;
if (!_map.TryGetValue(key, out val))
{
// Store the new one
val = createIt();
_map[key] = val;
}
return val;
}
finally
{
_lock.ExitWriteLock();
}
}
public bool TryGetValue(TKey key, out TValue val)
{
_lock.EnterReadLock();
try
{
return _map.TryGetValue(key, out val);
}
finally
{
_lock.ExitReadLock();
}
}
public void Set(TKey key, TValue value)
{
_lock.EnterWriteLock();
try
{
_map[key] = value;
}
finally
{
_lock.ExitWriteLock();
}
}
Dictionary<TKey, TValue> _map = new Dictionary<TKey, TValue>();
ReaderWriterLockSlim _lock = new ReaderWriterLockSlim();
}
internal static class Utils
{
#if NET35
private static readonly FieldInfo[] _emptyFieldInfo = new FieldInfo[0];
#else
#endif
// Get all fields and properties of a type
public static IEnumerable<MemberInfo> GetAllFieldsAndProperties(Type t)
{
if (t == null)
#if NET35
return _emptyFieldInfo;
#else
return Enumerable.Empty<FieldInfo>();
#endif
BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly;
return t.GetMembers(flags).Where(x => x is FieldInfo || x is PropertyInfo).Concat(GetAllFieldsAndProperties(t.BaseType));
}
public static Type FindGenericInterface(Type type, Type tItf)
{
foreach (var t in type.GetInterfaces())
{
// Is this a generic list?
if (t.IsGenericType && t.GetGenericTypeDefinition() == tItf)
return t;
}
return null;
}
public static bool IsPublic(MemberInfo mi)
{
// Public field
var fi = mi as FieldInfo;
if (fi != null)
return fi.IsPublic;
// Public property
// (We only check the get method so we can work with anonymous types)
var pi = mi as PropertyInfo;
if (pi != null)
{
var gm = pi.GetGetMethod(true);
return (gm != null && gm.IsPublic);
}
return false;
}
public static Type ResolveInterfaceToClass(Type tItf)
{
// Generic type
if (tItf.IsGenericType)
{
var genDef = tItf.GetGenericTypeDefinition();
// IList<> -> List<>
if (genDef == typeof(IList<>))
{
return typeof(List<>).MakeGenericType(tItf.GetGenericArguments());
}
// IDictionary<string,> -> Dictionary<string,>
if (genDef == typeof(IDictionary<,>) && tItf.GetGenericArguments()[0] == typeof(string))
{
return typeof(Dictionary<,>).MakeGenericType(tItf.GetGenericArguments());
}
}
// IEnumerable -> List<object>
if (tItf == typeof(IEnumerable))
return typeof(List<object>);
// IDicitonary -> Dictionary<string,object>
if (tItf == typeof(IDictionary))
return typeof(Dictionary<string, object>);
return tItf;
}
public static long ToUnixMilliseconds(DateTime This)
{
return (long)This.Subtract(new DateTime(1970, 1, 1)).TotalMilliseconds;
}
public static DateTime FromUnixMilliseconds(long timeStamp)
{
return new DateTime(1970, 1, 1).AddMilliseconds(timeStamp);
}
}
internal class Tokenizer
{
public Tokenizer(TextReader r, JsonOptions options)
{
_underlying = r;
_options = options;
FillBuffer();
NextChar();
NextToken();
}
private JsonOptions _options;
private StringBuilder _sb = new StringBuilder();
private TextReader _underlying;
private char[] _buf = new char[4096];
private int _pos;
private int _bufUsed;
private StringBuilder _rewindBuffer;
private int _rewindBufferPos;
private JsonLineOffset _currentCharPos;
private char _currentChar;
private Stack<ReaderState> _bookmarks = new Stack<ReaderState>();
public JsonLineOffset CurrentTokenPosition;
public Token CurrentToken;
public LiteralKind LiteralKind;
public string String;
public object LiteralValue
{
get
{
if (CurrentToken != Token.Literal)
throw new InvalidOperationException("token is not a literal");
switch (LiteralKind)
{
case LiteralKind.Null: return null;
case LiteralKind.False: return false;
case LiteralKind.True: return true;
case LiteralKind.String: return String;
case LiteralKind.SignedInteger: return long.Parse(String, CultureInfo.InvariantCulture);
case LiteralKind.UnsignedInteger:
if (String.StartsWith("0x") || String.StartsWith("0X"))
return Convert.ToUInt64(String.Substring(2), 16);
else
return ulong.Parse(String, CultureInfo.InvariantCulture);
case LiteralKind.FloatingPoint: return double.Parse(String, CultureInfo.InvariantCulture);
}
return null;
}
}
public Type LiteralType
{
get
{
if (CurrentToken != Token.Literal)
throw new InvalidOperationException("token is not a literal");
switch (LiteralKind)
{
case LiteralKind.Null: return typeof(Object);
case LiteralKind.False: return typeof(Boolean);
case LiteralKind.True: return typeof(Boolean);
case LiteralKind.String: return typeof(string);
case LiteralKind.SignedInteger: return typeof(long);
case LiteralKind.UnsignedInteger: return typeof(ulong);
case LiteralKind.FloatingPoint: return typeof(double);
}
return null;
}
}
// This object represents the entire state of the reader and is used for rewind
struct ReaderState
{
public ReaderState(Tokenizer tokenizer)
{
_currentCharPos = tokenizer._currentCharPos;
_currentChar = tokenizer._currentChar;
_string = tokenizer.String;
_literalKind = tokenizer.LiteralKind;
_rewindBufferPos = tokenizer._rewindBufferPos;
_currentTokenPos = tokenizer.CurrentTokenPosition;
_currentToken = tokenizer.CurrentToken;
}
public void Apply(Tokenizer tokenizer)
{
tokenizer._currentCharPos = _currentCharPos;
tokenizer._currentChar = _currentChar;
tokenizer._rewindBufferPos = _rewindBufferPos;
tokenizer.CurrentToken = _currentToken;
tokenizer.CurrentTokenPosition = _currentTokenPos;
tokenizer.String = _string;
tokenizer.LiteralKind = _literalKind;
}
private JsonLineOffset _currentCharPos;
private JsonLineOffset _currentTokenPos;
private char _currentChar;
private Token _currentToken;
private LiteralKind _literalKind;
private string _string;
private int _rewindBufferPos;
}
// Create a rewind bookmark
public void CreateBookmark()
{
_bookmarks.Push(new ReaderState(this));
if (_rewindBuffer == null)
{
_rewindBuffer = new StringBuilder();
_rewindBufferPos = 0;
}
}
// Discard bookmark
public void DiscardBookmark()
{
_bookmarks.Pop();
if (_bookmarks.Count == 0)
{
_rewindBuffer = null;
_rewindBufferPos = 0;
}
}
// Rewind to a bookmark
public void RewindToBookmark()
{
_bookmarks.Pop().Apply(this);
}
// Fill buffer by reading from underlying TextReader
void FillBuffer()
{
_bufUsed = _underlying.Read(_buf, 0, _buf.Length);
_pos = 0;
}
// Get the next character from the input stream
// (this function could be extracted into a few different methods, but is mostly inlined
// for performance - yes it makes a difference)
public char NextChar()
{
if (_rewindBuffer == null)
{
if (_pos >= _bufUsed)
{
if (_bufUsed > 0)
{
FillBuffer();
}
if (_bufUsed == 0)
{
return _currentChar = '\0';
}
}
// Next
_currentCharPos.Offset++;
return _currentChar = _buf[_pos++];
}
if (_rewindBufferPos < _rewindBuffer.Length)
{
_currentCharPos.Offset++;
return _currentChar = _rewindBuffer[_rewindBufferPos++];
}
else
{
if (_pos >= _bufUsed && _bufUsed > 0)
FillBuffer();
_currentChar = _bufUsed == 0 ? '\0' : _buf[_pos++];
_rewindBuffer.Append(_currentChar);
_rewindBufferPos++;
_currentCharPos.Offset++;
return _currentChar;
}
}
// Read the next token from the input stream
// (Mostly inline for performance)
public void NextToken()
{
while (true)
{
// Skip whitespace and handle line numbers
while (true)
{
if (_currentChar == '\r')
{
if (NextChar() == '\n')
{
NextChar();
}
_currentCharPos.Line++;
_currentCharPos.Offset = 0;
}
else if (_currentChar == '\n')
{
if (NextChar() == '\r')
{
NextChar();
}
_currentCharPos.Line++;
_currentCharPos.Offset = 0;
}
else if (_currentChar == ' ')
{
NextChar();
}
else if (_currentChar == '\t')
{
NextChar();
}
else
break;
}
// Remember position of token
CurrentTokenPosition = _currentCharPos;
// Handle common characters first
switch (_currentChar)
{
case '/':
// Comments not support in strict mode
if ((_options & JsonOptions.StrictParser) != 0)
{
throw new InvalidDataException(string.Format("syntax error, unexpected character '{0}'", _currentChar));
}
// Process comment
NextChar();
switch (_currentChar)
{
case '/':
NextChar();
while (_currentChar != '\0' && _currentChar != '\r' && _currentChar != '\n')
{
NextChar();
}
break;
case '*':
bool endFound = false;
while (!endFound && _currentChar != '\0')
{
if (_currentChar == '*')
{
NextChar();
if (_currentChar == '/')
{
endFound = true;
}
}
NextChar();
}
break;
default:
throw new InvalidDataException("syntax error, unexpected character after slash");
}
continue;
case '\"':
case '\'':
{
_sb.Length = 0;
var quoteKind = _currentChar;
NextChar();
while (_currentChar != '\0')
{
if (_currentChar == '\\')
{
NextChar();
var escape = _currentChar;
switch (escape)
{
case '\"': _sb.Append('\"'); break;
case '\\': _sb.Append('\\'); break;
case '/': _sb.Append('/'); break;
case 'b': _sb.Append('\b'); break;
case 'f': _sb.Append('\f'); break;
case 'n': _sb.Append('\n'); break;
case 'r': _sb.Append('\r'); break;
case 't': _sb.Append('\t'); break;
case 'u':
var sbHex = new StringBuilder();
for (int i = 0; i < 4; i++)
{
NextChar();
sbHex.Append(_currentChar);
}
_sb.Append((char)Convert.ToUInt16(sbHex.ToString(), 16));
break;
default:
throw new InvalidDataException(string.Format("Invalid escape sequence in string literal: '\\{0}'", _currentChar));
}
}
else if (_currentChar == quoteKind)
{
String = _sb.ToString();
CurrentToken = Token.Literal;
LiteralKind = LiteralKind.String;
NextChar();
return;
}
else
{
_sb.Append(_currentChar);
}
NextChar();
}
throw new InvalidDataException("syntax error, unterminated string literal");
}
case '{': CurrentToken = Token.OpenBrace; NextChar(); return;
case '}': CurrentToken = Token.CloseBrace; NextChar(); return;
case '[': CurrentToken = Token.OpenSquare; NextChar(); return;
case ']': CurrentToken = Token.CloseSquare; NextChar(); return;
case '=': CurrentToken = Token.Equal; NextChar(); return;
case ':': CurrentToken = Token.Colon; NextChar(); return;
case ';': CurrentToken = Token.SemiColon; NextChar(); return;
case ',': CurrentToken = Token.Comma; NextChar(); return;
case '\0': CurrentToken = Token.EOF; return;
}
// Number?
if (char.IsDigit(_currentChar) || _currentChar == '-')
{
TokenizeNumber();
return;
}
// Identifier? (checked for after everything else as identifiers are actually quite rare in valid json)
if (Char.IsLetter(_currentChar) || _currentChar == '_' || _currentChar == '$')
{
// Find end of identifier
_sb.Length = 0;
while (Char.IsLetterOrDigit(_currentChar) || _currentChar == '_' || _currentChar == '$')
{
_sb.Append(_currentChar);
NextChar();
}
String = _sb.ToString();
// Handle special identifiers
switch (String)
{
case "true":
LiteralKind = LiteralKind.True;
CurrentToken = Token.Literal;
return;
case "false":
LiteralKind = LiteralKind.False;
CurrentToken = Token.Literal;
return;
case "null":
LiteralKind = LiteralKind.Null;
CurrentToken = Token.Literal;
return;
}
CurrentToken = Token.Identifier;
return;
}
// What the?
throw new InvalidDataException(string.Format("syntax error, unexpected character '{0}'", _currentChar));
}
}
// Parse a sequence of characters that could make up a valid number
// For performance, we don't actually parse it into a number yet. When using PetaJsonEmit we parse
// later, directly into a value type to avoid boxing
private void TokenizeNumber()
{
_sb.Length = 0;
// Leading negative sign
bool signed = false;
if (_currentChar == '-')
{
signed = true;
_sb.Append(_currentChar);
NextChar();
}
// Hex prefix?
bool hex = false;
if (_currentChar == '0' && (_options & JsonOptions.StrictParser) == 0)
{
_sb.Append(_currentChar);
NextChar();
if (_currentChar == 'x' || _currentChar == 'X')
{
_sb.Append(_currentChar);
NextChar();
hex = true;
}
}
// Process characters, but vaguely figure out what type it is
bool cont = true;
bool fp = false;
while (cont)
{
switch (_currentChar)
{
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
_sb.Append(_currentChar);
NextChar();
break;
case 'A':
case 'a':
case 'B':
case 'b':
case 'C':
case 'c':
case 'D':
case 'd':
case 'F':
case 'f':
if (!hex)
cont = false;
else
{
_sb.Append(_currentChar);
NextChar();
}
break;
case '.':
if (hex)
{
cont = false;
}
else
{
fp = true;
_sb.Append(_currentChar);
NextChar();
}
break;
case 'E':
case 'e':
if (!hex)
{
fp = true;
_sb.Append(_currentChar);
NextChar();
if (_currentChar == '+' || _currentChar == '-')
{
_sb.Append(_currentChar);
NextChar();
}
}
break;
default:
cont = false;
break;
}
}
if (char.IsLetter(_currentChar))
throw new InvalidDataException(string.Format("syntax error, invalid character following number '{0}'", _sb.ToString()));
// Setup token
String = _sb.ToString();
CurrentToken = Token.Literal;
// Setup literal kind
if (fp)
{
LiteralKind = LiteralKind.FloatingPoint;
}
else if (signed)
{
LiteralKind = LiteralKind.SignedInteger;
}
else
{
LiteralKind = LiteralKind.UnsignedInteger;
}
}
// Check the current token, throw exception if mismatch
public void Check(Token tokenRequired)
{
if (tokenRequired != CurrentToken)
{
throw new InvalidDataException(string.Format("syntax error, expected {0} found {1}", tokenRequired, CurrentToken));
}
}
// Skip token which must match
public void Skip(Token tokenRequired)
{
Check(tokenRequired);
NextToken();
}
// Skip token if it matches
public bool SkipIf(Token tokenRequired)
{
if (tokenRequired == CurrentToken)
{
NextToken();
return true;
}
return false;
}
}
#if !PETAJSON_NO_EMIT
static class Emit
{
// Generates a function that when passed an object of specified type, renders it to an IJsonReader
public static Action<IJsonWriter, object> MakeFormatter(Type type)
{
var formatJson = ReflectionInfo.FindFormatJson(type);
if (formatJson != null)
{
var method = new DynamicMethod("invoke_formatJson", null, new Type[] { typeof(IJsonWriter), typeof(Object) }, true);
var il = method.GetILGenerator();
if (formatJson.ReturnType == typeof(string))
{
// w.WriteStringLiteral(o.FormatJson())
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldarg_1);
il.Emit(OpCodes.Unbox, type);
il.Emit(OpCodes.Call, formatJson);
il.Emit(OpCodes.Callvirt, typeof(IJsonWriter).GetMethod("WriteStringLiteral"));
}
else
{
// o.FormatJson(w);
il.Emit(OpCodes.Ldarg_1);
il.Emit(type.IsValueType ? OpCodes.Unbox : OpCodes.Castclass, type);
il.Emit(OpCodes.Ldarg_0);
il.Emit(type.IsValueType ? OpCodes.Call : OpCodes.Callvirt, formatJson);
}
il.Emit(OpCodes.Ret);
return (Action<IJsonWriter, object>)method.CreateDelegate(typeof(Action<IJsonWriter, object>));
}
else
{
// Get the reflection info for this type
var ri = ReflectionInfo.GetReflectionInfo(type);
if (ri == null)
return null;
// Create a dynamic method that can do the work
var method = new DynamicMethod("dynamic_formatter", null, new Type[] { typeof(IJsonWriter), typeof(object) }, true);
var il = method.GetILGenerator();
// Cast/unbox the target object and store in local variable
var locTypedObj = il.DeclareLocal(type);
il.Emit(OpCodes.Ldarg_1);
il.Emit(type.IsValueType ? OpCodes.Unbox_Any : OpCodes.Castclass, type);
il.Emit(OpCodes.Stloc, locTypedObj);
// Get Invariant CultureInfo (since we'll probably be needing this)
var locInvariant = il.DeclareLocal(typeof(IFormatProvider));
il.Emit(OpCodes.Call, typeof(CultureInfo).GetProperty("InvariantCulture").GetGetMethod());
il.Emit(OpCodes.Stloc, locInvariant);
// These are the types we'll call .ToString(Culture.InvariantCulture) on
var toStringTypes = new Type[] {
typeof(int), typeof(uint), typeof(long), typeof(ulong),
typeof(short), typeof(ushort), typeof(decimal),
typeof(byte), typeof(sbyte)
};
// Theses types we also generate for
var otherSupportedTypes = new Type[] {
typeof(double), typeof(float), typeof(string), typeof(char)
};
// Call IJsonWriting if implemented
if (typeof(IJsonWriting).IsAssignableFrom(type))
{
if (type.IsValueType)
{
il.Emit(OpCodes.Ldloca, locTypedObj);
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Call, type.GetInterfaceMap(typeof(IJsonWriting)).TargetMethods[0]);
}
else
{
il.Emit(OpCodes.Ldloc, locTypedObj);
il.Emit(OpCodes.Castclass, typeof(IJsonWriting));
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Callvirt, typeof(IJsonWriting).GetMethod("OnJsonWriting", new Type[] { typeof(IJsonWriter) }));
}
}
// Process all members
foreach (var m in ri.Members)
{
// Dont save deprecated properties
if (m.Deprecated)
{
continue;
}
// Ignore write only properties
var pi = m.Member as PropertyInfo;
if (pi != null && pi.GetGetMethod(true) == null)
{
continue;
}
// Write the Json key
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldstr, m.JsonKey);
il.Emit(OpCodes.Callvirt, typeof(IJsonWriter).GetMethod("WriteKeyNoEscaping", new Type[] { typeof(string) }));
// Load the writer
il.Emit(OpCodes.Ldarg_0);
// Get the member type
var memberType = m.MemberType;
// Load the target object
if (type.IsValueType)
{
il.Emit(OpCodes.Ldloca, locTypedObj);
}
else
{
il.Emit(OpCodes.Ldloc, locTypedObj);
}
// Work out if we need the value or it's address on the stack
bool NeedValueAddress = (memberType.IsValueType && (toStringTypes.Contains(memberType) || otherSupportedTypes.Contains(memberType)));
if (Nullable.GetUnderlyingType(memberType) != null)
{
NeedValueAddress = true;
}
// Property?
if (pi != null)
{
// Call property's get method
if (type.IsValueType)
il.Emit(OpCodes.Call, pi.GetGetMethod(true));
else
il.Emit(OpCodes.Callvirt, pi.GetGetMethod(true));
// If we need the address then store in a local and take it's address
if (NeedValueAddress)
{
var locTemp = il.DeclareLocal(memberType);
il.Emit(OpCodes.Stloc, locTemp);
il.Emit(OpCodes.Ldloca, locTemp);
}
}
// Field?
var fi = m.Member as FieldInfo;
if (fi != null)
{
if (NeedValueAddress)
{
il.Emit(OpCodes.Ldflda, fi);
}
else
{
il.Emit(OpCodes.Ldfld, fi);
}
}
Label? lblFinished = null;
// Is it a nullable type?
var typeUnderlying = Nullable.GetUnderlyingType(memberType);
if (typeUnderlying != null)
{
// Duplicate the address so we can call get_HasValue() and then get_Value()
il.Emit(OpCodes.Dup);
// Define some labels
var lblHasValue = il.DefineLabel();
lblFinished = il.DefineLabel();
// Call has_Value
il.Emit(OpCodes.Call, memberType.GetProperty("HasValue").GetGetMethod());
il.Emit(OpCodes.Brtrue, lblHasValue);
// No value, write "null:
il.Emit(OpCodes.Pop);
il.Emit(OpCodes.Ldstr, "null");
il.Emit(OpCodes.Callvirt, typeof(IJsonWriter).GetMethod("WriteRaw", new Type[] { typeof(string) }));
il.Emit(OpCodes.Br_S, lblFinished.Value);
// Get it's value
il.MarkLabel(lblHasValue);
il.Emit(OpCodes.Call, memberType.GetProperty("Value").GetGetMethod());
// Switch to the underlying type from here on
memberType = typeUnderlying;
NeedValueAddress = (memberType.IsValueType && (toStringTypes.Contains(memberType) || otherSupportedTypes.Contains(memberType)));
// Work out again if we need the address of the value
if (NeedValueAddress)
{
var locTemp = il.DeclareLocal(memberType);
il.Emit(OpCodes.Stloc, locTemp);
il.Emit(OpCodes.Ldloca, locTemp);
}
}
// ToString()
if (toStringTypes.Contains(memberType))
{
// Convert to string
il.Emit(OpCodes.Ldloc, locInvariant);
il.Emit(OpCodes.Call, memberType.GetMethod("ToString", new Type[] { typeof(IFormatProvider) }));
il.Emit(OpCodes.Callvirt, typeof(IJsonWriter).GetMethod("WriteRaw", new Type[] { typeof(string) }));
}
// ToString("R")
else if (memberType == typeof(float) || memberType == typeof(double))
{
il.Emit(OpCodes.Ldstr, "R");
il.Emit(OpCodes.Ldloc, locInvariant);
il.Emit(OpCodes.Call, memberType.GetMethod("ToString", new Type[] { typeof(string), typeof(IFormatProvider) }));
il.Emit(OpCodes.Callvirt, typeof(IJsonWriter).GetMethod("WriteRaw", new Type[] { typeof(string) }));
}
// String?
else if (memberType == typeof(string))
{
il.Emit(OpCodes.Callvirt, typeof(IJsonWriter).GetMethod("WriteStringLiteral", new Type[] { typeof(string) }));
}
// Char?
else if (memberType == typeof(char))
{
il.Emit(OpCodes.Call, memberType.GetMethod("ToString", new Type[] { }));
il.Emit(OpCodes.Callvirt, typeof(IJsonWriter).GetMethod("WriteStringLiteral", new Type[] { typeof(string) }));
}
// Bool?
else if (memberType == typeof(bool))
{
var lblTrue = il.DefineLabel();
var lblCont = il.DefineLabel();
il.Emit(OpCodes.Brtrue_S, lblTrue);
il.Emit(OpCodes.Ldstr, "false");
il.Emit(OpCodes.Br_S, lblCont);
il.MarkLabel(lblTrue);
il.Emit(OpCodes.Ldstr, "true");
il.MarkLabel(lblCont);
il.Emit(OpCodes.Callvirt, typeof(IJsonWriter).GetMethod("WriteRaw", new Type[] { typeof(string) }));
}
// NB: We don't support DateTime as it's format can be changed
else
{
// Unsupported type, pass through
if (memberType.IsValueType)
{
il.Emit(OpCodes.Box, memberType);
}
il.Emit(OpCodes.Callvirt, typeof(IJsonWriter).GetMethod("WriteValue", new Type[] { typeof(object) }));
}
if (lblFinished.HasValue)
il.MarkLabel(lblFinished.Value);
}
// Call IJsonWritten
if (typeof(IJsonWritten).IsAssignableFrom(type))
{
if (type.IsValueType)
{
il.Emit(OpCodes.Ldloca, locTypedObj);
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Call, type.GetInterfaceMap(typeof(IJsonWritten)).TargetMethods[0]);
}
else
{
il.Emit(OpCodes.Ldloc, locTypedObj);
il.Emit(OpCodes.Castclass, typeof(IJsonWriting));
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Callvirt, typeof(IJsonWriting).GetMethod("OnJsonWritten", new Type[] { typeof(IJsonWriter) }));
}
}
// Done!
il.Emit(OpCodes.Ret);
var impl = (Action<IJsonWriter, object>)method.CreateDelegate(typeof(Action<IJsonWriter, object>));
// Wrap it in a call to WriteDictionary
return (w, obj) =>
{
w.WriteDictionary(() =>
{
impl(w, obj);
});
};
}
}
// Pseudo box lets us pass a value type by reference. Used during
// deserialization of value types.
interface IPseudoBox
{
object GetValue();
}
[Obfuscation(Exclude = true, ApplyToMembers = true)]
class PseudoBox<T> : IPseudoBox where T : struct
{
public T value = default(T);
object IPseudoBox.GetValue() { return value; }
}
// Make a parser for value types
public static Func<IJsonReader, Type, object> MakeParser(Type type)
{
System.Diagnostics.Debug.Assert(type.IsValueType);
// ParseJson method?
var parseJson = ReflectionInfo.FindParseJson(type);
if (parseJson != null)
{
if (parseJson.GetParameters()[0].ParameterType == typeof(IJsonReader))
{
var method = new DynamicMethod("invoke_ParseJson", typeof(Object), new Type[] { typeof(IJsonReader), typeof(Type) }, true);
var il = method.GetILGenerator();
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Call, parseJson);
il.Emit(OpCodes.Box, type);
il.Emit(OpCodes.Ret);
return (Func<IJsonReader, Type, object>)method.CreateDelegate(typeof(Func<IJsonReader, Type, object>));
}
else
{
var method = new DynamicMethod("invoke_ParseJson", typeof(Object), new Type[] { typeof(string) }, true);
var il = method.GetILGenerator();
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Call, parseJson);
il.Emit(OpCodes.Box, type);
il.Emit(OpCodes.Ret);
var invoke = (Func<string, object>)method.CreateDelegate(typeof(Func<string, object>));
return (r, t) =>
{
if (r.GetLiteralKind() == LiteralKind.String)
{
var o = invoke(r.GetLiteralString());
r.NextToken();
return o;
}
throw new InvalidDataException(string.Format("Expected string literal for type {0}", type.FullName));
};
}
}
else
{
// Get the reflection info for this type
var ri = ReflectionInfo.GetReflectionInfo(type);
if (ri == null)
return null;
// We'll create setters for each property/field
var setters = new Dictionary<string, Action<IJsonReader, object>>();
// Store the value in a pseudo box until it's fully initialized
var boxType = typeof(PseudoBox<>).MakeGenericType(type);
// Process all members
foreach (var m in ri.Members)
{
// Ignore write only properties
var pi = m.Member as PropertyInfo;
var fi = m.Member as FieldInfo;
if (pi != null && pi.GetSetMethod(true) == null)
{
continue;
}
// Create a dynamic method that can do the work
var method = new DynamicMethod("dynamic_parser", null, new Type[] { typeof(IJsonReader), typeof(object) }, true);
var il = method.GetILGenerator();
// Load the target
il.Emit(OpCodes.Ldarg_1);
il.Emit(OpCodes.Castclass, boxType);
il.Emit(OpCodes.Ldflda, boxType.GetField("value"));
// Get the value
GenerateGetJsonValue(m, il);
// Assign it
if (pi != null)
il.Emit(OpCodes.Call, pi.GetSetMethod(true));
if (fi != null)
il.Emit(OpCodes.Stfld, fi);
// Done
il.Emit(OpCodes.Ret);
// Store in the map of setters
setters.Add(m.JsonKey, (Action<IJsonReader, object>)method.CreateDelegate(typeof(Action<IJsonReader, object>)));
}
// Create helpers to invoke the interfaces (this is painful but avoids having to really box
// the value in order to call the interface).
Action<object, IJsonReader> invokeLoading = MakeInterfaceCall(type, typeof(IJsonLoading));
Action<object, IJsonReader> invokeLoaded = MakeInterfaceCall(type, typeof(IJsonLoaded));
Func<object, IJsonReader, string, bool> invokeField = MakeLoadFieldCall(type);
// Create the parser
Func<IJsonReader, Type, object> parser = (reader, Type) =>
{
// Create pseudobox (ie: new PseudoBox<Type>)
var box = DecoratingActivator.CreateInstance(boxType);
// Call IJsonLoading
if (invokeLoading != null)
invokeLoading(box, reader);
// Read the dictionary
reader.ParseDictionary(key =>
{
// Call IJsonLoadField
if (invokeField != null && invokeField(box, reader, key))
return;
// Get a setter and invoke it if found
Action<IJsonReader, object> setter;
if (setters.TryGetValue(key, out setter))
{
setter(reader, box);
}
});
// IJsonLoaded
if (invokeLoaded != null)
invokeLoaded(box, reader);
// Return the value
return ((IPseudoBox)box).GetValue();
};
// Done
return parser;
}
}
// Helper to make the call to a PsuedoBox value's IJsonLoading or IJsonLoaded
static Action<object, IJsonReader> MakeInterfaceCall(Type type, Type tItf)
{
// Interface supported?
if (!tItf.IsAssignableFrom(type))
return null;
// Resolve the box type
var boxType = typeof(PseudoBox<>).MakeGenericType(type);
// Create method
var method = new DynamicMethod("dynamic_invoke_" + tItf.Name, null, new Type[] { typeof(object), typeof(IJsonReader) }, true);
var il = method.GetILGenerator();
// Call interface method
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Castclass, boxType);
il.Emit(OpCodes.Ldflda, boxType.GetField("value"));
il.Emit(OpCodes.Ldarg_1);
il.Emit(OpCodes.Call, type.GetInterfaceMap(tItf).TargetMethods[0]);
il.Emit(OpCodes.Ret);
// Done
return (Action<object, IJsonReader>)method.CreateDelegate(typeof(Action<object, IJsonReader>));
}
// Similar to above but for IJsonLoadField
static Func<object, IJsonReader, string, bool> MakeLoadFieldCall(Type type)
{
// Interface supported?
var tItf = typeof(IJsonLoadField);
if (!tItf.IsAssignableFrom(type))
return null;
// Resolve the box type
var boxType = typeof(PseudoBox<>).MakeGenericType(type);
// Create method
var method = new DynamicMethod("dynamic_invoke_" + tItf.Name, typeof(bool), new Type[] { typeof(object), typeof(IJsonReader), typeof(string) }, true);
var il = method.GetILGenerator();
// Call interface method
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Castclass, boxType);
il.Emit(OpCodes.Ldflda, boxType.GetField("value"));
il.Emit(OpCodes.Ldarg_1);
il.Emit(OpCodes.Ldarg_2);
il.Emit(OpCodes.Call, type.GetInterfaceMap(tItf).TargetMethods[0]);
il.Emit(OpCodes.Ret);
// Done
return (Func<object, IJsonReader, string, bool>)method.CreateDelegate(typeof(Func<object, IJsonReader, string, bool>));
}
// Create an "into parser" that can parse from IJsonReader into a reference type (ie: a class)
public static Action<IJsonReader, object> MakeIntoParser(Type type)
{
System.Diagnostics.Debug.Assert(!type.IsValueType);
// Get the reflection info for this type
var ri = ReflectionInfo.GetReflectionInfo(type);
if (ri == null)
return null;
// We'll create setters for each property/field
var setters = new Dictionary<string, Action<IJsonReader, object>>();
// Process all members
foreach (var m in ri.Members)
{
// Ignore write only properties
var pi = m.Member as PropertyInfo;
var fi = m.Member as FieldInfo;
if (pi != null && pi.GetSetMethod(true) == null)
{
continue;
}
// Ignore read only properties that has KeepInstance attribute
if (pi != null && pi.GetGetMethod(true) == null && m.KeepInstance)
{
continue;
}
// Create a dynamic method that can do the work
var method = new DynamicMethod("dynamic_parser", null, new Type[] { typeof(IJsonReader), typeof(object) }, true);
var il = method.GetILGenerator();
// Load the target
il.Emit(OpCodes.Ldarg_1);
il.Emit(OpCodes.Castclass, type);
// Try to keep existing instance?
if (m.KeepInstance)
{
// Get existing existing instance
il.Emit(OpCodes.Dup);
if (pi != null)
il.Emit(OpCodes.Callvirt, pi.GetGetMethod(true));
else
il.Emit(OpCodes.Ldfld, fi);
var existingInstance = il.DeclareLocal(m.MemberType);
var lblExistingInstanceNull = il.DefineLabel();
// Keep a copy of the existing instance in a locale
il.Emit(OpCodes.Dup);
il.Emit(OpCodes.Stloc, existingInstance);
// Compare to null
il.Emit(OpCodes.Ldnull);
il.Emit(OpCodes.Ceq);
il.Emit(OpCodes.Brtrue_S, lblExistingInstanceNull);
il.Emit(OpCodes.Ldarg_0); // reader
il.Emit(OpCodes.Ldloc, existingInstance); // into
il.Emit(OpCodes.Callvirt, typeof(IJsonReader).GetMethod("ParseInto", new Type[] { typeof(Object) }));
il.Emit(OpCodes.Pop); // Clean up target left on stack (1)
il.Emit(OpCodes.Ret);
il.MarkLabel(lblExistingInstanceNull);
}
// Get the value from IJsonReader
GenerateGetJsonValue(m, il);
// Assign it
if (pi != null)
il.Emit(OpCodes.Callvirt, pi.GetSetMethod(true));
if (fi != null)
il.Emit(OpCodes.Stfld, fi);
// Done
il.Emit(OpCodes.Ret);
// Store the handler in map
setters.Add(m.JsonKey, (Action<IJsonReader, object>)method.CreateDelegate(typeof(Action<IJsonReader, object>)));
}
// Now create the parseInto delegate
Action<IJsonReader, object> parseInto = (reader, obj) =>
{
// Call IJsonLoading
var loading = obj as IJsonLoading;
if (loading != null)
loading.OnJsonLoading(reader);
// Cache IJsonLoadField
var lf = obj as IJsonLoadField;
// Read dictionary keys
reader.ParseDictionary(key =>
{
// Call IJsonLoadField
if (lf != null && lf.OnJsonField(reader, key))
return;
// Call setters
Action<IJsonReader, object> setter;
if (setters.TryGetValue(key, out setter))
{
setter(reader, obj);
}
});
// Call IJsonLoaded
var loaded = obj as IJsonLoaded;
if (loaded != null)
loaded.OnJsonLoaded(reader);
};
// Since we've created the ParseInto handler, we might as well register
// as a Parse handler too.
RegisterIntoParser(type, parseInto);
// Done
return parseInto;
}
// Registers a ParseInto handler as Parse handler that instantiates the object
// and then parses into it.
static void RegisterIntoParser(Type type, Action<IJsonReader, object> parseInto)
{
// Check type has a parameterless constructor
var con = type.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[0], null);
if (con == null)
return;
// Create a dynamic method that can do the work
var method = new DynamicMethod("dynamic_factory", typeof(object), new Type[] { typeof(IJsonReader), typeof(Action<IJsonReader, object>) }, true);
var il = method.GetILGenerator();
// Create the new object
var locObj = il.DeclareLocal(typeof(object));
il.Emit(OpCodes.Newobj, con);
il.Emit(OpCodes.Dup); // For return value
il.Emit(OpCodes.Stloc, locObj);
il.Emit(OpCodes.Ldarg_1); // parseinto delegate
il.Emit(OpCodes.Ldarg_0); // IJsonReader
il.Emit(OpCodes.Ldloc, locObj); // new object instance
il.Emit(OpCodes.Callvirt, typeof(Action<IJsonReader, object>).GetMethod("Invoke"));
il.Emit(OpCodes.Ret);
var factory = (Func<IJsonReader, Action<IJsonReader, object>, object>)method.CreateDelegate(typeof(Func<IJsonReader, Action<IJsonReader, object>, object>));
Json.RegisterParser(type, (reader, type2) =>
{
return factory(reader, parseInto);
});
}
// Generate the MSIL to retrieve a value for a particular field or property from a IJsonReader
private static void GenerateGetJsonValue(JsonMemberInfo m, ILGenerator il)
{
Action<string> generateCallToHelper = helperName =>
{
// Call the helper
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Call, typeof(Emit).GetMethod(helperName, new Type[] { typeof(IJsonReader) }));
// Move to next token
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Callvirt, typeof(IJsonReader).GetMethod("NextToken", new Type[] { }));
};
Type[] numericTypes = new Type[] {
typeof(int), typeof(uint), typeof(long), typeof(ulong),
typeof(short), typeof(ushort), typeof(decimal),
typeof(byte), typeof(sbyte),
typeof(double), typeof(float)
};
if (m.MemberType == typeof(string))
{
generateCallToHelper("GetLiteralString");
}
else if (m.MemberType == typeof(bool))
{
generateCallToHelper("GetLiteralBool");
}
else if (m.MemberType == typeof(char))
{
generateCallToHelper("GetLiteralChar");
}
else if (numericTypes.Contains(m.MemberType))
{
// Get raw number string
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Call, typeof(Emit).GetMethod("GetLiteralNumber", new Type[] { typeof(IJsonReader) }));
// Convert to a string
il.Emit(OpCodes.Call, typeof(CultureInfo).GetProperty("InvariantCulture").GetGetMethod());
il.Emit(OpCodes.Call, m.MemberType.GetMethod("Parse", new Type[] { typeof(string), typeof(IFormatProvider) }));
//
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Callvirt, typeof(IJsonReader).GetMethod("NextToken", new Type[] { }));
}
else
{
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldtoken, m.MemberType);
il.Emit(OpCodes.Call, typeof(Type).GetMethod("GetTypeFromHandle", new Type[] { typeof(RuntimeTypeHandle) }));
il.Emit(OpCodes.Callvirt, typeof(IJsonReader).GetMethod("Parse", new Type[] { typeof(Type) }));
il.Emit(m.MemberType.IsValueType ? OpCodes.Unbox_Any : OpCodes.Castclass, m.MemberType);
}
}
// Helper to fetch a literal bool from an IJsonReader
[Obfuscation(Exclude = true)]
public static bool GetLiteralBool(IJsonReader r)
{
switch (r.GetLiteralKind())
{
case LiteralKind.True:
return true;
case LiteralKind.False:
return false;
default:
throw new InvalidDataException("expected a boolean value");
}
}
// Helper to fetch a literal character from an IJsonReader
[Obfuscation(Exclude = true)]
public static char GetLiteralChar(IJsonReader r)
{
if (r.GetLiteralKind() != LiteralKind.String)
throw new InvalidDataException("expected a single character string literal");
var str = r.GetLiteralString();
if (str == null || str.Length != 1)
throw new InvalidDataException("expected a single character string literal");
return str[0];
}
// Helper to fetch a literal string from an IJsonReader
[Obfuscation(Exclude = true)]
public static string GetLiteralString(IJsonReader r)
{
switch (r.GetLiteralKind())
{
case LiteralKind.Null: return null;
case LiteralKind.String: return r.GetLiteralString();
}
throw new InvalidDataException("expected a string literal");
}
// Helper to fetch a literal number from an IJsonReader (returns the raw string)
[Obfuscation(Exclude = true)]
public static string GetLiteralNumber(IJsonReader r)
{
switch (r.GetLiteralKind())
{
case LiteralKind.SignedInteger:
case LiteralKind.UnsignedInteger:
case LiteralKind.FloatingPoint:
return r.GetLiteralString();
}
throw new InvalidDataException("expected a numeric literal");
}
}
#endif
//}
}
| {'content_hash': '13634e716186c97d8720d4ae440b1292', 'timestamp': '', 'source': 'github', 'line_count': 3338, 'max_line_length': 191, 'avg_line_length': 34.60545236668664, 'alnum_prop': 0.5125224000761819, 'repo_name': 'cyotek/MantisSharp', 'id': '5a0aec8e342aeba68db80739d4bec3e454092f02', 'size': '115515', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/PetaJson.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '885'}, {'name': 'C#', 'bytes': '272641'}, {'name': 'CSS', 'bytes': '4977'}]} |
package io.udash
package rest
import com.avsystem.commons.meta.MacroInstances
import com.avsystem.commons.meta.MacroInstances.materializeWith
import com.avsystem.commons.misc.ImplicitNotFound
import com.avsystem.commons.rpc.{AsRaw, AsReal}
import io.circe._
import io.circe.parser._
import io.circe.syntax._
import io.udash.rest.raw.{JsonValue, PlainValue}
import scala.annotation.implicitNotFound
import scala.concurrent.Future
trait CirceRestImplicits extends FloatingPointRestImplicits {
implicit def encoderBasedAsJson[T: Encoder]: AsRaw[JsonValue, T] =
v => JsonValue(v.asJson.noSpaces)
implicit def decoderBasedFromJson[T: Decoder]: AsReal[JsonValue, T] =
json => parse(json.value).fold(throw _, _.as[T].fold(throw _, identity))
implicit def keyEncoderBasedAsPlain[T: KeyEncoder]: AsRaw[PlainValue, T] =
v => PlainValue(KeyEncoder[T].apply(v))
implicit def keyDecoderBasedFromPlain[T: KeyDecoder]: AsReal[PlainValue, T] =
pv => KeyDecoder[T].apply(pv.value)
.getOrElse(throw new IllegalArgumentException(s"Invalid key: ${pv.value}"))
@implicitNotFound("#{forEncoder}")
implicit def asJsonNotFound[T](
implicit forEncoder: ImplicitNotFound[Encoder[T]]
): ImplicitNotFound[AsRaw[JsonValue, T]] = ImplicitNotFound()
@implicitNotFound("#{forDecoder}")
implicit def fromJsonNotFound[T](
implicit forDecoder: ImplicitNotFound[Decoder[T]]
): ImplicitNotFound[AsReal[JsonValue, T]] = ImplicitNotFound()
@implicitNotFound("#{forKeyEncoder}")
implicit def asPlainNotFound[T: KeyEncoder](
implicit forKeyEncoder: ImplicitNotFound[KeyEncoder[T]]
): ImplicitNotFound[AsRaw[PlainValue, T]] = ImplicitNotFound()
@implicitNotFound("#{forKeyDecoder}")
implicit def fromPlainNotFound[T: KeyDecoder](
implicit forKeyDecoder: ImplicitNotFound[KeyDecoder[T]]
): ImplicitNotFound[AsReal[PlainValue, T]] = ImplicitNotFound()
}
object CirceRestImplicits extends CirceRestImplicits
trait CirceInstances[T] {
@materializeWith(io.circe.derivation.`package`, "deriveEncoder")
def encoder: Encoder.AsObject[T]
@materializeWith(io.circe.derivation.`package`, "deriveDecoder")
def decoder: Decoder[T]
}
abstract class HasCirceCodec[T](
implicit instances: MacroInstances[Unit, CirceInstances[T]]
) {
implicit final lazy val objectEncoder: Encoder.AsObject[T] = instances((), this).encoder
implicit final lazy val decoder: Decoder[T] = instances((), this).decoder
}
trait CirceCustomizedInstances[T] {
@materializeWith(io.circe.derivation.`package`, "deriveEncoder")
def encoder(nameTransform: String => String, discriminator: Option[String]): Encoder.AsObject[T]
@materializeWith(io.circe.derivation.`package`, "deriveDecoder")
def decoder(nameTransform: String => String, useDefaults: Boolean, discriminator: Option[String]): Decoder[T]
}
abstract class HasCirceCustomizedCodec[T](
nameTransform: String => String,
useDefaults: Boolean = true,
discriminator: Option[String] = None
)(implicit instances: MacroInstances[Unit, CirceCustomizedInstances[T]]) {
implicit final lazy val objectEncoder: Encoder.AsObject[T] = instances((), this).encoder(nameTransform, discriminator)
implicit final lazy val decoder: Decoder[T] = instances((), this).decoder(nameTransform, useDefaults, discriminator)
}
case class CirceAddress(city: String, zip: String)
object CirceAddress extends HasCirceCustomizedCodec[CirceAddress](_.toUpperCase)
case class CircePerson(id: Long, name: String, address: Option[CirceAddress] = None)
object CircePerson extends HasCirceCodec[CircePerson]
abstract class CirceRestApiCompanion[T](
implicit instances: MacroInstances[(CirceRestImplicits, FutureRestImplicits), FullInstances[T]]
) extends RestApiCompanion[(CirceRestImplicits, FutureRestImplicits), T]((CirceRestImplicits, FutureRestImplicits))
trait CirceRestApi {
def createPerson(person: CircePerson): Future[String]
}
object CirceRestApi extends CirceRestApiCompanion[CirceRestApi]
| {'content_hash': '2f47d252aeaea2dafb8ad95151c31561', 'timestamp': '', 'source': 'github', 'line_count': 95, 'max_line_length': 120, 'avg_line_length': 41.67368421052632, 'alnum_prop': 0.7764587016923465, 'repo_name': 'UdashFramework/udash-core', 'id': '31406349c9eac21f49be90904222f5fadfa563e3', 'size': '3959', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'rest/src/test/scala/io/udash/rest/CirceRestApiTest.scala', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '2450'}, {'name': 'HTML', 'bytes': '4288'}, {'name': 'Less', 'bytes': '180'}, {'name': 'Scala', 'bytes': '2000448'}]} |
hacktoolkit
===========
[](https://travis-ci.org/hacktoolkit/hacktoolkit)
Hacktoolkit is the ONE open source project to rule them all (we try to, at least).
The spirit of this project is summarized in this tagline: _**Win hackathons by using refined APIs and bootstrap code to build complete websites and apps in 24 hours.**_
## About this `README`
This `README` is about the hacktoolkit library hosted at: https://github.com/hacktoolkit/hacktoolkit
For information about the project, see the website: http://hacktoolkit.com
* Code is organized into sub-folders or submodules, each with their own `README` files.
* **Always** read the `README` files in subdirectories before using the code so that your computer or mobile device doesn't blow up.
## Goals and Philosophy
* There will only be one main repository, ever, for Hacktoolkit (with the exception of submodules--more on this later)
* The goal is to be one repository that users can clone and immediately start using, not 47 different repositories.
* Easy to use; easy onboarding process
* Clean, robust code
* Find the best examples that are already existing (don't reinvent the wheel), and import them as submodules
* **We love skeletons and bootstrap code**
## Nomenclature
### Hacktoolkit vs hacktoolkit
Use **Hacktoolkit** (capital, proper name, one word, no spaces or hyphens) when referring to the project or code.
Use `hacktoolkit` (all lowercase) only when referring to the code, library, or package name.
### Names in code
* Java or Android package names, for example, should start with `com.hacktoolkit` and `com.hacktoolkit.android`, respectively
* `htk` is the preferred abbreviation for lowercase names
* Java class names can use the prefix `HTK`, e.g. `HTKUtils.java`, `HTKConstants.java`, `HTKSettings.java`
## Getting Started
Three simple steps:
1. **Clone the repository**
`git clone [email protected]:hacktoolkit/hacktoolkit.git`
2. **Update submodules**
`git submodule init` (inside the directory of the newly cloned repository; only run the first time)
`git submodule update` (Download the submodule codes the first time)
3. **Profit**
Start coding away with Hacktoolkit and share your delight with everyone else.
To get future updates, run: `git pull && git submodule update`
## Submodules
This project makes extensive use of Git Submodules.
For information on how to use Git Submodules, read <http://git-scm.com/book/en/Git-Tools-Submodules>.
In addition to the normal `git clone` or `git pull`, two commands are necessary to keep the submodules up-to-date:
1. `git submodule init` after cloning
2. `git submodule update` updates all the submodules
## Contributing
Hacktoolkit is always looking for help, whether you are a designer or a developer.
If you would like to be a maintainer for Hacktoolkit, contact Jonathan Tsai (<https://github.com/jontsai>).
The majority of people should probably just fork this repository and issue pull requests.
* Always include a `README`(`.md` is preferred) file in each directory, unless it is a leaf
* Follow the best practices and coding style guides for that language, platform, or API
* Use your best judgment and common sense, always.
* More coming...
| {'content_hash': '5b0ceb9d94462948b9bcf2df2c566de7', 'timestamp': '', 'source': 'github', 'line_count': 76, 'max_line_length': 168, 'avg_line_length': 43.44736842105263, 'alnum_prop': 0.7589339794064204, 'repo_name': 'clemfeelsgood/hackathontools', 'id': 'ab932c67913cc134a4e2abacb958e72d56066fb2', 'size': '3302', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'README.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '3033555'}, {'name': 'Java', 'bytes': '2367'}, {'name': 'JavaScript', 'bytes': '1014102'}, {'name': 'PHP', 'bytes': '19296'}, {'name': 'Perl', 'bytes': '22137'}, {'name': 'Python', 'bytes': '641911'}, {'name': 'Racket', 'bytes': '1826'}, {'name': 'Ruby', 'bytes': '11351'}, {'name': 'Shell', 'bytes': '392226'}]} |
/* eslint-disable react/prop-types */
import React from 'react';
import { mount } from 'enzyme';
import ColumnChooser from '.';
import { ListContext } from '../context';
import ColumnChooserButton from '../../Toolbar/ColumnChooserButton';
import getDefaultT from '../../../translate';
describe('ColumnChooser', () => {
let defaultContext;
beforeEach(() => {
defaultContext = {
columns: [
{ dataKey: 'foo', label: 'Foo' },
{ dataKey: 'bar', label: 'Bar' },
],
setVisibleColumns: jest.fn(),
t: getDefaultT(),
};
});
it('should render column chooser component', () => {
// when
const wrapper = mount(
<ListContext.Provider value={defaultContext}>
<ColumnChooser id="myColumnChooser" />
</ListContext.Provider>,
);
// then
expect(wrapper.find(ColumnChooserButton)).toBeDefined();
});
it('should update columns', () => {
// given
const wrapper = mount(
<ListContext.Provider value={defaultContext}>
<ColumnChooser id="myColumnChooser" />
</ListContext.Provider>,
);
const onSubmit = wrapper.find(ColumnChooserButton).prop('onSubmit');
// when
onSubmit(null, [
{ key: 'foo', hidden: true },
{ key: 'bar', hidden: false },
]);
// then
expect(defaultContext.setVisibleColumns).toBeCalledWith(['bar']);
});
it('should call props.onSubmit if exist', () => {
const onSubmit = jest.fn();
const wrapper = mount(
<ListContext.Provider value={defaultContext}>
<ColumnChooser id="myColumnChooser" onSubmit={onSubmit} />
</ListContext.Provider>,
);
const internalOnSubmit = wrapper.find(ColumnChooserButton).prop('onSubmit');
internalOnSubmit(null, [
{ key: 'foo', hidden: true },
{ key: 'bar', hidden: false },
]);
expect(onSubmit).toHaveBeenCalled();
});
});
| {'content_hash': 'a032642c190f0be6113508d3b7eaee57', 'timestamp': '', 'source': 'github', 'line_count': 71, 'max_line_length': 78, 'avg_line_length': 24.95774647887324, 'alnum_prop': 0.6478555304740407, 'repo_name': 'Talend/ui', 'id': '6e7c33886e3245ad37758785a84defe48b08f73d', 'size': '1772', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'packages/components/src/List/ListComposition/ColumnChooser/ColumnChooser.component.test.js', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '809'}, {'name': 'Groovy', 'bytes': '9150'}, {'name': 'HTML', 'bytes': '183895'}, {'name': 'Java', 'bytes': '338'}, {'name': 'JavaScript', 'bytes': '4781212'}, {'name': 'SCSS', 'bytes': '699775'}, {'name': 'Shell', 'bytes': '62'}, {'name': 'TypeScript', 'bytes': '1291286'}]} |
/**
* alert-extend.view.js
*
* @package AlertExtendView
* @category View
* @version 1.0
* @author Ricky Hurtado <[email protected]>
*/
define([
'message_view',
'message_module'
],
function(
MessageView
){
/**
* Init AlertExtendView class
*/
var AlertExtendView = MessageView.extend(
{
/**
* Initialize view
*/
initialize : function()
{
console.log('AlertView.AlertExtendView has been initialized.');
I.Message.Controller.setOptionAlertMessage('This alert message has been changed via AlertExtendView class.');
},
/**
* Display message
*/
displayMessage : function(message)
{
$(this.target.message).html('<p><strong>Message:</strong> ' + message + '<p></p><em>Message::displayMessage() function has been override via AlertExtendView class.</em></p>');
}
});
return AlertExtendView;
}); | {'content_hash': '3982f418537fc766aeec4d0b0b150952', 'timestamp': '', 'source': 'github', 'line_count': 41, 'max_line_length': 181, 'avg_line_length': 22.975609756097562, 'alnum_prop': 0.5987261146496815, 'repo_name': 'rickyhurtado/ironframework', 'id': '425c7995864cc80e9d3c12155134f8bd48e385fb', 'size': '942', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'demos/php/basic/assets/js/modules/alert-extend/dev/alert-extend.view.dev.js', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '636'}, {'name': 'JavaScript', 'bytes': '342362'}, {'name': 'PHP', 'bytes': '18719'}]} |
#pragma once
#include <aws/sagemaker/SageMaker_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>
namespace Aws
{
namespace Utils
{
namespace Json
{
class JsonValue;
class JsonView;
} // namespace Json
} // namespace Utils
namespace SageMaker
{
namespace Model
{
/**
* <p>The Amazon S3 location of the input data objects.</p><p><h3>See Also:</h3>
* <a
* href="http://docs.aws.amazon.com/goto/WebAPI/sagemaker-2017-07-24/LabelingJobS3DataSource">AWS
* API Reference</a></p>
*/
class AWS_SAGEMAKER_API LabelingJobS3DataSource
{
public:
LabelingJobS3DataSource();
LabelingJobS3DataSource(Aws::Utils::Json::JsonView jsonValue);
LabelingJobS3DataSource& operator=(Aws::Utils::Json::JsonView jsonValue);
Aws::Utils::Json::JsonValue Jsonize() const;
/**
* <p>The Amazon S3 location of the manifest file that describes the input data
* objects.</p>
*/
inline const Aws::String& GetManifestS3Uri() const{ return m_manifestS3Uri; }
/**
* <p>The Amazon S3 location of the manifest file that describes the input data
* objects.</p>
*/
inline bool ManifestS3UriHasBeenSet() const { return m_manifestS3UriHasBeenSet; }
/**
* <p>The Amazon S3 location of the manifest file that describes the input data
* objects.</p>
*/
inline void SetManifestS3Uri(const Aws::String& value) { m_manifestS3UriHasBeenSet = true; m_manifestS3Uri = value; }
/**
* <p>The Amazon S3 location of the manifest file that describes the input data
* objects.</p>
*/
inline void SetManifestS3Uri(Aws::String&& value) { m_manifestS3UriHasBeenSet = true; m_manifestS3Uri = std::move(value); }
/**
* <p>The Amazon S3 location of the manifest file that describes the input data
* objects.</p>
*/
inline void SetManifestS3Uri(const char* value) { m_manifestS3UriHasBeenSet = true; m_manifestS3Uri.assign(value); }
/**
* <p>The Amazon S3 location of the manifest file that describes the input data
* objects.</p>
*/
inline LabelingJobS3DataSource& WithManifestS3Uri(const Aws::String& value) { SetManifestS3Uri(value); return *this;}
/**
* <p>The Amazon S3 location of the manifest file that describes the input data
* objects.</p>
*/
inline LabelingJobS3DataSource& WithManifestS3Uri(Aws::String&& value) { SetManifestS3Uri(std::move(value)); return *this;}
/**
* <p>The Amazon S3 location of the manifest file that describes the input data
* objects.</p>
*/
inline LabelingJobS3DataSource& WithManifestS3Uri(const char* value) { SetManifestS3Uri(value); return *this;}
private:
Aws::String m_manifestS3Uri;
bool m_manifestS3UriHasBeenSet;
};
} // namespace Model
} // namespace SageMaker
} // namespace Aws
| {'content_hash': 'e5c72ee44bab379e55fb43e2f7c9df67', 'timestamp': '', 'source': 'github', 'line_count': 94, 'max_line_length': 127, 'avg_line_length': 30.28723404255319, 'alnum_prop': 0.6817702845100105, 'repo_name': 'jt70471/aws-sdk-cpp', 'id': '2ec8636a24945e372bad8021eb42e87d1fc3514f', 'size': '2966', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'aws-cpp-sdk-sagemaker/include/aws/sagemaker/model/LabelingJobS3DataSource.h', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '13452'}, {'name': 'C++', 'bytes': '278594037'}, {'name': 'CMake', 'bytes': '653931'}, {'name': 'Dockerfile', 'bytes': '5555'}, {'name': 'HTML', 'bytes': '4471'}, {'name': 'Java', 'bytes': '302182'}, {'name': 'Python', 'bytes': '110380'}, {'name': 'Shell', 'bytes': '4674'}]} |
.pil {
background: #ddd;
position: relative;
overflow: hidden;
}
.pil img:first-of-type {
display: block;
opacity: 0;
transition: opacity 0.5s ease-out;
}
.pil-loaded img:first-of-type { opacity: 1; }
.pil-thumb img {
position: absolute;
top: 0;
left: 0;
transition: opacity 0.3s ease-out;
-webkit-filter: blur(30px);
filter: blur(30px);
}
.pil-thumb.pil-thumb-loaded img { opacity: 1; }
.pil-loaded .pil-thumb img { opacity: 0; } | {'content_hash': 'c90d9dbf46031117ca57f8b0c39a6fe4', 'timestamp': '', 'source': 'github', 'line_count': 23, 'max_line_length': 47, 'avg_line_length': 19.304347826086957, 'alnum_prop': 0.6734234234234234, 'repo_name': 'gilbitron/Pil', 'id': '6ca88dc5ee0e4c4e3eac08ce2b2fe0271ca2d55b', 'size': '574', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'pil.css', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '574'}, {'name': 'JavaScript', 'bytes': '1827'}]} |
define(['backbone'], function(Backbone) {
return Backbone.Model.extend({
idAttribute: 'EXPERIMENTTYPEID',
urlRoot: '/exp/experiment/types',
validation: {
NAME: {
required: true,
pattern: 'wwdash',
},
}
})
})
| {'content_hash': '4491ee1c5cc5635149b117f7e3f8cfff', 'timestamp': '', 'source': 'github', 'line_count': 14, 'max_line_length': 41, 'avg_line_length': 18.428571428571427, 'alnum_prop': 0.5658914728682171, 'repo_name': 'DiamondLightSource/SynchWeb', 'id': '9800b933d856248239ebc3e72b05688fe39567a6', 'size': '258', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'client/src/js/modules/shipment/models/experimenttype.js', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '13914'}, {'name': 'HTML', 'bytes': '350320'}, {'name': 'Hack', 'bytes': '3508'}, {'name': 'JavaScript', 'bytes': '1782239'}, {'name': 'PHP', 'bytes': '1200208'}, {'name': 'Python', 'bytes': '20016'}, {'name': 'Ruby', 'bytes': '886'}, {'name': 'SCSS', 'bytes': '106898'}, {'name': 'Shell', 'bytes': '4656'}, {'name': 'Vue', 'bytes': '629967'}]} |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.11"/>
<title>ObjectDetectionSIFT: VisionManager Class Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/searchdata.js"></script>
<script type="text/javascript" src="search/search.js"></script>
<script type="text/javascript">
$(document).ready(function() { init_search(); });
</script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td id="projectlogo"><img alt="Logo" src="detection24.jpg"/></td>
<td id="projectalign" style="padding-left: 0.5em;">
<div id="projectname">ObjectDetectionSIFT
</div>
<div id="projectbrief">ENPM808X Midterm Project</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.11 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "search",false,'Search');
</script>
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li class="current"><a href="annotated.html"><span>Classes</span></a></li>
<li><a href="files.html"><span>Files</span></a></li>
<li>
<div id="MSearchBox" class="MSearchBoxInactive">
<span class="left">
<img id="MSearchSelect" src="search/mag_sel.png"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
alt=""/>
<input type="text" id="MSearchField" value="Search" accesskey="S"
onfocus="searchBox.OnSearchFieldFocus(true)"
onblur="searchBox.OnSearchFieldFocus(false)"
onkeyup="searchBox.OnSearchFieldChange(event)"/>
</span><span class="right">
<a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a>
</span>
</div>
</li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li><a href="annotated.html"><span>Class List</span></a></li>
<li><a href="classes.html"><span>Class Index</span></a></li>
<li><a href="hierarchy.html"><span>Class Hierarchy</span></a></li>
<li><a href="functions.html"><span>Class Members</span></a></li>
</ul>
</div>
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
</div><!-- top -->
<div class="header">
<div class="summary">
<a href="#pub-methods">Public Member Functions</a> |
<a href="#pub-static-methods">Static Public Member Functions</a> |
<a href="class_vision_manager-members.html">List of all members</a> </div>
<div class="headertitle">
<div class="title">VisionManager Class Reference</div> </div>
</div><!--header-->
<div class="contents">
<table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pub-methods"></a>
Public Member Functions</h2></td></tr>
<tr class="memitem:adcb5352baab5e4ce5a4723c83d855ac7"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="adcb5352baab5e4ce5a4723c83d855ac7"></a>
bool </td><td class="memItemRight" valign="bottom"><a class="el" href="class_vision_manager.html#adcb5352baab5e4ce5a4723c83d855ac7">initDetection</a> ()</td></tr>
<tr class="memdesc:adcb5352baab5e4ce5a4723c83d855ac7"><td class="mdescLeft"> </td><td class="mdescRight">public member function to initialize the object detection module. <br /></td></tr>
<tr class="separator:adcb5352baab5e4ce5a4723c83d855ac7"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a19e86478a5507255679aea74f0419e01"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a19e86478a5507255679aea74f0419e01"></a>
 </td><td class="memItemRight" valign="bottom"><a class="el" href="class_vision_manager.html#a19e86478a5507255679aea74f0419e01">~VisionManager</a> ()</td></tr>
<tr class="memdesc:a19e86478a5507255679aea74f0419e01"><td class="mdescLeft"> </td><td class="mdescRight">Vision Manager Destructor. <br /></td></tr>
<tr class="separator:a19e86478a5507255679aea74f0419e01"><td class="memSeparator" colspan="2"> </td></tr>
</table><table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pub-static-methods"></a>
Static Public Member Functions</h2></td></tr>
<tr class="memitem:aba19f4e02daa569658b59d63e12d2abe"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="aba19f4e02daa569658b59d63e12d2abe"></a>
static <a class="el" href="class_vision_manager.html">VisionManager</a> & </td><td class="memItemRight" valign="bottom"><a class="el" href="class_vision_manager.html#aba19f4e02daa569658b59d63e12d2abe">get</a> ()</td></tr>
<tr class="memdesc:aba19f4e02daa569658b59d63e12d2abe"><td class="mdescLeft"> </td><td class="mdescRight">static member function that returns singleton instance of the vision manager <br /></td></tr>
<tr class="separator:aba19f4e02daa569658b59d63e12d2abe"><td class="memSeparator" colspan="2"> </td></tr>
</table>
<hr/>The documentation for this class was generated from the following file:<ul>
<li>/home/viki/808XHw/midtermproject/cpp-boilerplate/include/<a class="el" href="_vision_manager_8h_source.html">VisionManager.h</a></li>
</ul>
</div><!-- contents -->
<!-- start footer part -->
<hr class="footer"/><address class="footer"><small>
Generated by  <a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/>
</a> 1.8.11
</small></address>
</body>
</html>
| {'content_hash': 'a9314bec690b14a509dd05055eb79eba', 'timestamp': '', 'source': 'github', 'line_count': 125, 'max_line_length': 230, 'avg_line_length': 53.584, 'alnum_prop': 0.6863242759032547, 'repo_name': 'rishabh1b/808XMidtermProject', 'id': 'c4c5683afd9fc28f784d89298dbce0588f164cdc', 'size': '6698', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'doc/html/class_vision_manager.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C++', 'bytes': '20037'}, {'name': 'CMake', 'bytes': '9573'}, {'name': 'Python', 'bytes': '5095'}]} |
import { RouteComponentProps } from 'react-router';
import { connect } from 'react-redux';
import { MembersPageDispatchProps, MembersPageStateProps, MembersPage as Component } from './MembersPage';
import { ApplicationState } from '../../state/ApplicationState';
import { Dispatch } from 'redux';
import * as React from 'react';
import { getPermissions } from '../../state/Selectors';
import { createSelector, Selector } from 'reselect';
import { flatten, map } from 'ramda';
import {
AddPermission,
FetchUserCountPerPermission,
PermissionLetterNode,
PermissionNode,
RemovePermission,
} from '../../actions';
const stateSelector: Selector<ApplicationState, MembersPageStateProps> = createSelector(
getPermissions,
state => state.permissions,
(permissions, permissionState) => ({
...permissionState,
canModify: flatten(map(perm => permissionState.allowableModifications[perm] || [], permissions)),
}),
);
export const MembersPage: React.ComponentType<RouteComponentProps<any>> = connect<
MembersPageStateProps,
MembersPageDispatchProps,
RouteComponentProps<any>
>(
stateSelector,
(dispatch: Dispatch): MembersPageDispatchProps => ({
fetchPermissionList: () => dispatch(FetchUserCountPerPermission.start()),
expandPermissionNode: (permission: string) => dispatch(PermissionNode.open(permission)),
expandLetterNode: (permission: string, letter: string) =>
dispatch(PermissionLetterNode.open({ permission, letter })),
collapsePermissionNode: (permission: string) => dispatch(PermissionNode.close(permission)),
collapseLetterNode: (permission: string, letter: string) =>
dispatch(PermissionLetterNode.close({ permission, letter })),
openAddPermission: (perm: string) => dispatch(AddPermission.openDialog(perm)),
openRemovePermission: (permission: string, username: string) =>
dispatch(RemovePermission.openDialog({ username, permission })),
}),
)(Component);
| {'content_hash': '2b99ff0008bd50c94a8a9bad33c1d340', 'timestamp': '', 'source': 'github', 'line_count': 45, 'max_line_length': 106, 'avg_line_length': 43.111111111111114, 'alnum_prop': 0.7422680412371134, 'repo_name': 'Eluinhost/hosts.uhc.gg', 'id': 'e2ab03ee3ecf97405e7c4a049aee04fc9bd7e76e', 'size': '1940', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'frontend/src/components/members/index.ts', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'HTML', 'bytes': '5833'}, {'name': 'JavaScript', 'bytes': '5022'}, {'name': 'SCSS', 'bytes': '99'}, {'name': 'Sass', 'bytes': '8389'}, {'name': 'Scala', 'bytes': '128564'}, {'name': 'Shell', 'bytes': '18'}, {'name': 'TypeScript', 'bytes': '305803'}]} |
ACCEPTED
#### According to
World Register of Marine Species
#### Published in
Eur J Protistol 28 (1): 49.
#### Original name
null
### Remarks
null | {'content_hash': 'fcedc13b456be74b6ece8d9fa5cc72de', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 32, 'avg_line_length': 11.538461538461538, 'alnum_prop': 0.6866666666666666, 'repo_name': 'mdoering/backbone', 'id': '82eabdb6fe99db02c5b59c85d35002dfa8935063', 'size': '212', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'life/Protozoa/Lobosa/Gruberellidae/Pernina/README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': []} |
"""Quiz what is missing."""
import os
import random
import textwrap
from typing import List
from .terminal import LineRepeater
from .data import bible
def explain() -> str:
"""Explain Person Action Object"""
return textwrap.dedent(
"""\
Missing game.
If you have an existing memory system for memorizing a series of information, then
you can try quizzing yourself when one of them are missing.
One way of doing this is to apply a particular attribute to the item in your
memory. Lets say you had a memory palace with all of the items in their proper
locations. When you see or hear the item, image that it is then on fire. You need
to really picture it burning. At the end, when you're asked which value is
missing, you traverse your memory palace until you find an item which is not on
fire. That is the answer.
"""
)
def say(phrase, voice="Tessa"):
"""Say the phrase out loud."""
# TODO: Support more platforms than just MacOS
if os.uname()[0] == "Darwin":
os.system("say -v %s %s" % (voice, phrase))
def quiz_missing(items: List[str], talk=False):
"""Leaving one out, print rest in random order, then ask for what is missing."""
try:
shuffled = items[:]
random.shuffle(shuffled)
total = len(shuffled)
last_item = shuffled.pop()
term = LineRepeater()
for n, item in enumerate(shuffled):
if talk:
say(item)
term.write(f"{n:2}/{total}: {item}")
if talk:
say("Okay, what is missing?")
ans = input("What is missing? ")
if ans.lower() == last_item.lower():
print("Well done!")
else:
print(f"Sorry, it was '{last_item}'")
except (EOFError, KeyboardInterrupt):
print("\nOkay, we can quiz another time.")
def quiz_bible_books(talk: bool = False):
"""Try to identify the missing book of the Bible."""
quiz_missing(bible.old_testament + bible.new_testament, talk=talk)
| {'content_hash': '270d25a486e718b1e5adcb868a1a3868', 'timestamp': '', 'source': 'github', 'line_count': 65, 'max_line_length': 90, 'avg_line_length': 31.984615384615385, 'alnum_prop': 0.6176046176046176, 'repo_name': 'patrickshuff/artofmemory', 'id': '37b279e3b98f771d95538d00cbd6671a59f60f86', 'size': '2079', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'artofmemory/missing.py', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Makefile', 'bytes': '75'}, {'name': 'Python', 'bytes': '17321'}]} |
'use strict';
exports.__esModule = true;
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
var _i18next = require('i18next');
var i18n = _interopRequireWildcard(_i18next);
var _aureliaDependencyInjection = require('aurelia-dependency-injection');
var _aureliaEventAggregator = require('aurelia-event-aggregator');
var _aureliaTemplating = require('aurelia-templating');
var _aureliaTemplatingResources = require('aurelia-templating-resources');
var _aureliaBinding = require('aurelia-binding');
var _aureliaLoader = require('aurelia-loader');
var translations = {
ar: {
translation: {
'now': 'الآن',
'second_ago': 'منذ __count__ ثانية',
'second_ago_plural': 'منذ __count__ ثواني',
'second_in': 'في __count__ ثانية',
'second_in_plural': 'في __count__ ثواني',
'minute_ago': 'منذ __count__ دقيقة',
'minute_ago_plural': 'منذ __count__ دقائق',
'minute_in': 'في __count__ دقيقة',
'minute_in_plural': 'في __count__ دقائق',
'hour_ago': 'منذ __count__ ساعة',
'hour_ago_plural': 'منذ __count__ ساعات',
'hour_in': 'في __count__ ساعة',
'hour_in_plural': 'في __count__ ساعات',
'day_ago': 'منذ __count__ يوم',
'day_ago_plural': 'منذ __count__ أيام',
'day_in': 'في __count__ يوم',
'day_in_plural': 'في __count__ أيام'
}
},
en: {
translation: {
'now': 'just now',
'second_ago': '__count__ second ago',
'second_ago_plural': '__count__ seconds ago',
'second_in': 'in __count__ second',
'second_in_plural': 'in __count__ seconds',
'minute_ago': '__count__ minute ago',
'minute_ago_plural': '__count__ minutes ago',
'minute_in': 'in __count__ minute',
'minute_in_plural': 'in __count__ minutes',
'hour_ago': '__count__ hour ago',
'hour_ago_plural': '__count__ hours ago',
'hour_in': 'in __count__ hour',
'hour_in_plural': 'in __count__ hours',
'day_ago': '__count__ day ago',
'day_ago_plural': '__count__ days ago',
'day_in': 'in __count__ day',
'day_in_plural': 'in __count__ days',
'month_ago': '__count__ month ago',
'month_ago_plural': '__count__ months ago',
'month_in': 'in __count__ month',
'month_in_plural': 'in __count__ months',
'year_ago': '__count__ year ago',
'year_ago_plural': '__count__ years ago',
'year_in': 'in __count__ year',
'year_in_plural': 'in __count__ years'
}
},
de: {
translation: {
'now': 'jetzt gerade',
'second_ago': 'vor __count__ Sekunde',
'second_ago_plural': 'vor __count__ Sekunden',
'second_in': 'in __count__ Sekunde',
'second_in_plural': 'in __count__ Sekunden',
'minute_ago': 'vor __count__ Minute',
'minute_ago_plural': 'vor __count__ Minuten',
'minute_in': 'in __count__ Minute',
'minute_in_plural': 'in __count__ Minuten',
'hour_ago': 'vor __count__ Stunde',
'hour_ago_plural': 'vor __count__ Stunden',
'hour_in': 'in __count__ Stunde',
'hour_in_plural': 'in __count__ Stunden',
'day_ago': 'vor __count__ Tag',
'day_ago_plural': 'vor __count__ Tagen',
'day_in': 'in __count__ Tag',
'day_in_plural': 'in __count__ Tagen',
'month_ago': 'vor __count__ Monat',
'month_ago_plural': 'vor __count__ Monaten',
'month_in': 'in __count__ Monat',
'month_in_plural': 'in __count__ Monaten',
'year_ago': 'vor __count__ Jahr',
'year_ago_plural': 'vor __count__ Jahren',
'year_in': 'in __count__ Jahr',
'year_in_plural': 'in __count__ Jahren'
}
},
nl: {
translation: {
'now': 'zonet',
'second_ago': '__count__ seconde geleden',
'second_ago_plural': '__count__ seconden geleden',
'second_in': 'in __count__ seconde',
'second_in_plural': 'in __count__ seconden',
'minute_ago': '__count__ minuut geleden',
'minute_ago_plural': '__count__ minuten geleden',
'minute_in': 'in __count__ minuut',
'minute_in_plural': 'in __count__ minuten',
'hour_ago': '__count__ uur geleden',
'hour_ago_plural': '__count__ uren geleden',
'hour_in': 'in __count__ uur',
'hour_in_plural': 'in __count__ uren',
'day_ago': '__count__ dag geleden',
'day_ago_plural': '__count__ dagen geleden',
'day_in': 'in __count__ dag',
'day_in_plural': 'in __count__ dagen',
'month_ago': '__count__ maand geleden',
'month_ago_plural': '__count__ maanden geleden',
'month_in': 'in __count__ maand',
'month_in_plural': 'in __count__ maanden',
'year_ago': '__count__ jaar geleden',
'year_ago_plural': '__count__ jaren geleden',
'year_in': 'in __count__ jaar',
'year_in_plural': 'in __count__ jaren'
}
},
fr: {
translation: {
'now': 'juste',
'second_ago': '__count__ seconde passé',
'second_ago_plural': '__count__ secondes passé',
'second_in': 'en __count__ seconde',
'second_in_plural': 'en __count__ secondes',
'minute_ago': '__count__ minute passé',
'minute_ago_plural': '__count__ minutes passé',
'minute_in': 'en __count__ minute',
'minute_in_plural': 'en __count__ minutes',
'hour_ago': '__count__ heure passé',
'hour_ago_plural': '__count__ heures passé',
'hour_in': 'en __count__ heure',
'hour_in_plural': 'en __count__ heures',
'day_ago': '__count__ jour passé',
'day_ago_plural': '__count__ jours passé',
'day_in': 'en __count__ jour',
'day_in_plural': 'en __count__ jours'
}
},
th: {
translation: {
'now': 'เมื่อกี้',
'second_ago': '__count__ วินาที ที่ผ่านมา',
'second_ago_plural': '__count__ วินาที ที่ผ่านมา',
'second_in': 'อีก __count__ วินาที',
'second_in_plural': 'อีก __count__ วินาที',
'minute_ago': '__count__ นาที ที่ผ่านมา',
'minute_ago_plural': '__count__ นาที ที่ผ่านมา',
'minute_in': 'อีก __count__ นาที',
'minute_in_plural': 'อีก __count__ นาที',
'hour_ago': '__count__ ชั่วโมง ที่ผ่านมา',
'hour_ago_plural': '__count__ ชั่วโมง ที่ผ่านมา',
'hour_in': 'อีก __count__ ชั่วโมง',
'hour_in_plural': 'อีก __count__ ชั่วโมง',
'day_ago': '__count__ วัน ที่ผ่านมา',
'day_ago_plural': '__count__ วัน ที่ผ่านมา',
'day_in': 'อีก __count__ วัน',
'day_in_plural': 'อีก __count__ วัน'
}
},
sv: {
translation: {
'now': 'just nu',
'second_ago': '__count__ sekund sedan',
'second_ago_plural': '__count__ sekunder sedan',
'second_in': 'om __count__ sekund',
'second_in_plural': 'om __count__ sekunder',
'minute_ago': '__count__ minut sedan',
'minute_ago_plural': '__count__ minuter sedan',
'minute_in': 'om __count__ minut',
'minute_in_plural': 'om __count__ minuter',
'hour_ago': '__count__ timme sedan',
'hour_ago_plural': '__count__ timmar sedan',
'hour_in': 'om __count__ timme',
'hour_in_plural': 'om __count__ timmar',
'day_ago': '__count__ dag sedan',
'day_ago_plural': '__count__ dagar sedan',
'day_in': 'om __count__ dag',
'day_in_plural': 'om __count__ dagar'
}
},
da: {
translation: {
'now': 'lige nu',
'second_ago': '__count__ sekunder siden',
'second_ago_plural': '__count__ sekunder siden',
'second_in': 'om __count__ sekund',
'second_in_plural': 'om __count__ sekunder',
'minute_ago': '__count__ minut siden',
'minute_ago_plural': '__count__ minutter siden',
'minute_in': 'om __count__ minut',
'minute_in_plural': 'om __count__ minutter',
'hour_ago': '__count__ time siden',
'hour_ago_plural': '__count__ timer siden',
'hour_in': 'om __count__ time',
'hour_in_plural': 'om __count__ timer',
'day_ago': '__count__ dag siden',
'day_ago_plural': '__count__ dage siden',
'day_in': 'om __count__ dag',
'day_in_plural': 'om __count__ dage'
}
},
no: {
translation: {
'now': 'akkurat nå',
'second_ago': '__count__ sekund siden',
'second_ago_plural': '__count__ sekunder siden',
'second_in': 'om __count__ sekund',
'second_in_plural': 'om __count__ sekunder',
'minute_ago': '__count__ minutt siden',
'minute_ago_plural': '__count__ minutter siden',
'minute_in': 'om __count__ minutt',
'minute_in_plural': 'om __count__ minutter',
'hour_ago': '__count__ time siden',
'hour_ago_plural': '__count__ timer siden',
'hour_in': 'om __count__ time',
'hour_in_plural': 'om __count__ timer',
'day_ago': '__count__ dag siden',
'day_ago_plural': '__count__ dager siden',
'day_in': 'om __count__ dag',
'day_in_plural': 'om __count__ dager'
}
},
jp: {
translation: {
'now': 'たった今',
'second_ago': '__count__ 秒前',
'second_ago_plural': '__count__ 秒前',
'second_in': 'あと __count__ 秒',
'second_in_plural': 'あと __count__ 秒',
'minute_ago': '__count__ 分前',
'minute_ago_plural': '__count__ 分前',
'minute_in': 'あと __count__ 分',
'minute_in_plural': 'あと __count__ 分',
'hour_ago': '__count__ 時間前',
'hour_ago_plural': '__count__ 時間前',
'hour_in': 'あと __count__ 時間',
'hour_in_plural': 'あと __count__ 時間',
'day_ago': '__count__ 日間前',
'day_ago_plural': '__count__ 日間前',
'day_in': 'あと __count__ 日間',
'day_in_plural': 'あと __count__ 日間'
}
}
};
exports.translations = translations;
var extend = function extend(destination, source) {
for (var property in source) {
destination[property] = source[property];
}
return destination;
};
exports.extend = extend;
var assignObjectToKeys = function assignObjectToKeys(root, obj) {
if (obj === undefined || obj === null) {
return obj;
}
var opts = {};
Object.keys(obj).map(function (key) {
if (typeof obj[key] === 'object') {
extend(opts, assignObjectToKeys(key, obj[key]));
} else {
opts[root !== '' ? root + '.' + key : key] = obj[key];
}
});
return opts;
};
exports.assignObjectToKeys = assignObjectToKeys;
var LazyOptional = (function () {
function LazyOptional(key) {
_classCallCheck(this, _LazyOptional);
this.key = key;
}
LazyOptional.prototype.get = function get(container) {
var _this = this;
return function () {
if (container.hasResolver(_this.key, false)) {
return container.get(_this.key);
}
return null;
};
};
LazyOptional.of = function of(key) {
return new LazyOptional(key);
};
var _LazyOptional = LazyOptional;
LazyOptional = _aureliaDependencyInjection.resolver()(LazyOptional) || LazyOptional;
return LazyOptional;
})();
exports.LazyOptional = LazyOptional;
var I18N = (function () {
function I18N(ea, signaler) {
_classCallCheck(this, I18N);
this.globalVars = {};
this.i18next = i18n;
this.ea = ea;
this.Intl = window.Intl;
this.signaler = signaler;
}
I18N.prototype.setup = function setup(options) {
var defaultOptions = {
resGetPath: 'locale/__lng__/__ns__.json',
lng: 'en',
getAsync: false,
sendMissing: false,
attributes: ['t', 'i18n'],
fallbackLng: 'en',
debug: false
};
i18n.init(options || defaultOptions);
if (i18n.options.attributes instanceof String) {
i18n.options.attributes = [i18n.options.attributes];
}
};
I18N.prototype.setLocale = function setLocale(locale) {
var _this2 = this;
return new Promise(function (resolve) {
var oldLocale = _this2.getLocale();
_this2.i18next.setLng(locale, function (tr) {
_this2.ea.publish('i18n:locale:changed', { oldValue: oldLocale, newValue: locale });
_this2.signaler.signal('aurelia-translation-signal');
resolve(tr);
});
});
};
I18N.prototype.getLocale = function getLocale() {
return this.i18next.lng();
};
I18N.prototype.nf = function nf(options, locales) {
return new this.Intl.NumberFormat(locales || this.getLocale(), options || {});
};
I18N.prototype.uf = function uf(number, locale) {
var nf = this.nf({}, locale || this.getLocale());
var comparer = nf.format(10000 / 3);
var thousandSeparator = comparer[1];
var decimalSeparator = comparer[5];
var result = number.replace(thousandSeparator, '').replace(/[^\d.,-]/g, '').replace(decimalSeparator, '.');
return Number(result);
};
I18N.prototype.df = function df(options, locales) {
return new this.Intl.DateTimeFormat(locales || this.getLocale(), options);
};
I18N.prototype.tr = function tr(key, options) {
var fullOptions = this.globalVars;
if (options !== undefined) {
fullOptions = Object.assign(Object.assign({}, this.globalVars), options);
}
return this.i18next.t(key, fullOptions);
};
I18N.prototype.registerGlobalVariable = function registerGlobalVariable(key, value) {
this.globalVars[key] = value;
};
I18N.prototype.unregisterGlobalVariable = function unregisterGlobalVariable(key) {
delete this.globalVars[key];
};
I18N.prototype.updateTranslations = function updateTranslations(el) {
var i = undefined;
var l = undefined;
var selector = [].concat(this.i18next.options.attributes);
for (i = 0, l = selector.length; i < l; i++) selector[i] = '[' + selector[i] + ']';
selector = selector.join(',');
var nodes = el.querySelectorAll(selector);
for (i = 0, l = nodes.length; i < l; i++) {
var node = nodes[i];
var keys = undefined;
for (var i2 = 0, l2 = this.i18next.options.attributes.length; i2 < l2; i2++) {
keys = node.getAttribute(this.i18next.options.attributes[i2]);
if (keys) break;
}
if (!keys) continue;
this.updateValue(node, keys);
}
};
I18N.prototype.updateValue = function updateValue(node, value, params) {
if (value === null || value === undefined) {
return;
}
var keys = value.split(';');
var i = keys.length;
while (i--) {
var key = keys[i];
var re = /\[([a-z\-]*)\]/g;
var m = undefined;
var attr = 'text';
if (node.nodeName === 'IMG') attr = 'src';
while ((m = re.exec(key)) !== null) {
if (m.index === re.lastIndex) {
re.lastIndex++;
}
if (m) {
key = key.replace(m[0], '');
attr = m[1];
}
}
if (!node._textContent) node._textContent = node.textContent;
if (!node._innerHTML) node._innerHTML = node.innerHTML;
switch (attr) {
case 'text':
node.textContent = this.tr(key, params);
break;
case 'prepend':
node.innerHTML = this.tr(key, params) + node._innerHTML.trim();
break;
case 'append':
node.innerHTML = node._innerHTML.trim() + this.tr(key, params);
break;
case 'html':
node.innerHTML = this.tr(key, params);
break;
default:
node.setAttribute(attr, this.tr(key, params));
break;
}
}
};
return I18N;
})();
exports.I18N = I18N;
var BaseI18N = (function () {
_createClass(BaseI18N, null, [{
key: 'inject',
value: [I18N, Element, _aureliaEventAggregator.EventAggregator],
enumerable: true
}]);
function BaseI18N(i18n, element, ea) {
var _this3 = this;
_classCallCheck(this, BaseI18N);
this.i18n = i18n;
this.element = element;
this.__i18nDisposer = ea.subscribe('i18n:locale:changed', function () {
_this3.i18n.updateTranslations(_this3.element);
});
}
BaseI18N.prototype.attached = function attached() {
this.i18n.updateTranslations(this.element);
};
BaseI18N.prototype.detached = function detached() {
this.__i18nDisposer.dispose();
};
return BaseI18N;
})();
exports.BaseI18N = BaseI18N;
var DfValueConverter = (function () {
DfValueConverter.inject = function inject() {
return [I18N];
};
function DfValueConverter(i18n) {
_classCallCheck(this, DfValueConverter);
this.service = i18n;
}
DfValueConverter.prototype.toView = function toView(value, formatOptions, locale, dateFormat) {
var df = dateFormat || this.service.df(formatOptions, locale || this.service.getLocale());
return df.format(value);
};
return DfValueConverter;
})();
exports.DfValueConverter = DfValueConverter;
var NfValueConverter = (function () {
NfValueConverter.inject = function inject() {
return [I18N];
};
function NfValueConverter(i18n) {
_classCallCheck(this, NfValueConverter);
this.service = i18n;
}
NfValueConverter.prototype.toView = function toView(value, formatOptions, locale, numberFormat) {
var nf = numberFormat || this.service.nf(formatOptions, locale || this.service.getLocale());
return nf.format(value);
};
return NfValueConverter;
})();
exports.NfValueConverter = NfValueConverter;
var RelativeTime = (function () {
RelativeTime.inject = function inject() {
return [I18N];
};
function RelativeTime(i18n) {
var _this4 = this;
_classCallCheck(this, RelativeTime);
this.service = i18n;
var trans = translations['default'] || translations;
Object.keys(trans).map(function (key) {
var translation = trans[key].translation;
var options = i18n.i18next.options;
if (options.interpolationPrefix !== '__' || options.interpolationSuffix !== '__') {
for (var subkey in translation) {
translation[subkey] = translation[subkey].replace('__count__', options.interpolationPrefix + 'count' + options.interpolationSuffix);
}
}
_this4.service.i18next.addResources(key, 'translation', translation);
});
}
RelativeTime.prototype.getRelativeTime = function getRelativeTime(time) {
var now = new Date();
var diff = now.getTime() - time.getTime();
var timeDiff = this.getTimeDiffDescription(diff, 'year', 31104000000);
if (!timeDiff) {
timeDiff = this.getTimeDiffDescription(diff, 'month', 2592000000);
if (!timeDiff) {
timeDiff = this.getTimeDiffDescription(diff, 'day', 86400000);
if (!timeDiff) {
timeDiff = this.getTimeDiffDescription(diff, 'hour', 3600000);
if (!timeDiff) {
timeDiff = this.getTimeDiffDescription(diff, 'minute', 60000);
if (!timeDiff) {
timeDiff = this.getTimeDiffDescription(diff, 'second', 1000);
if (!timeDiff) {
timeDiff = this.service.tr('now');
}
}
}
}
}
}
return timeDiff;
};
RelativeTime.prototype.getTimeDiffDescription = function getTimeDiffDescription(diff, unit, timeDivisor) {
var unitAmount = (diff / timeDivisor).toFixed(0);
if (unitAmount > 0) {
return this.service.tr(unit, { count: parseInt(unitAmount, 10), context: 'ago' });
} else if (unitAmount < 0) {
var abs = Math.abs(unitAmount);
return this.service.tr(unit, { count: abs, context: 'in' });
}
return null;
};
return RelativeTime;
})();
exports.RelativeTime = RelativeTime;
var TValueConverter = (function () {
TValueConverter.inject = function inject() {
return [I18N];
};
function TValueConverter(i18n) {
_classCallCheck(this, TValueConverter);
this.service = i18n;
}
TValueConverter.prototype.toView = function toView(value, options) {
return this.service.tr(value, options);
};
return TValueConverter;
})();
exports.TValueConverter = TValueConverter;
var TParamsCustomAttribute = (function () {
_createClass(TParamsCustomAttribute, null, [{
key: 'inject',
value: [Element],
enumerable: true
}]);
function TParamsCustomAttribute(element) {
_classCallCheck(this, _TParamsCustomAttribute);
this.element = element;
}
TParamsCustomAttribute.prototype.valueChanged = function valueChanged() {};
var _TParamsCustomAttribute = TParamsCustomAttribute;
TParamsCustomAttribute = _aureliaTemplating.customAttribute('t-params')(TParamsCustomAttribute) || TParamsCustomAttribute;
return TParamsCustomAttribute;
})();
exports.TParamsCustomAttribute = TParamsCustomAttribute;
var TCustomAttribute = (function () {
_createClass(TCustomAttribute, null, [{
key: 'inject',
value: [Element, I18N, _aureliaEventAggregator.EventAggregator, LazyOptional.of(TParamsCustomAttribute)],
enumerable: true
}]);
function TCustomAttribute(element, i18n, ea, tparams) {
_classCallCheck(this, _TCustomAttribute);
this.element = element;
this.service = i18n;
this.ea = ea;
this.lazyParams = tparams;
}
TCustomAttribute.prototype.bind = function bind() {
var _this5 = this;
this.params = this.lazyParams();
if (this.params) {
this.params.valueChanged = function (newParams, oldParams) {
_this5.paramsChanged(_this5.value, newParams, oldParams);
};
}
var p = this.params !== null ? this.params.value : undefined;
this.subscription = this.ea.subscribe('i18n:locale:changed', function () {
_this5.service.updateValue(_this5.element, _this5.value, p);
});
this.service.updateValue(this.element, this.value, p);
};
TCustomAttribute.prototype.paramsChanged = function paramsChanged(newValue, newParams) {
this.service.updateValue(this.element, newValue, newParams);
};
TCustomAttribute.prototype.valueChanged = function valueChanged(newValue) {
var p = this.params !== null ? this.params.value : undefined;
this.service.updateValue(this.element, newValue, p);
};
TCustomAttribute.prototype.unbind = function unbind() {
if (this.subscription) {
this.subscription.dispose();
}
};
var _TCustomAttribute = TCustomAttribute;
TCustomAttribute = _aureliaTemplating.customAttribute('t')(TCustomAttribute) || TCustomAttribute;
return TCustomAttribute;
})();
exports.TCustomAttribute = TCustomAttribute;
var TBindingBehavior = (function () {
_createClass(TBindingBehavior, null, [{
key: 'inject',
value: [_aureliaTemplatingResources.SignalBindingBehavior],
enumerable: true
}]);
function TBindingBehavior(signalBindingBehavior) {
_classCallCheck(this, TBindingBehavior);
this.signalBindingBehavior = signalBindingBehavior;
}
TBindingBehavior.prototype.bind = function bind(binding, source) {
this.signalBindingBehavior.bind(binding, source, 'aurelia-translation-signal');
var sourceExpression = binding.sourceExpression;
var expression = sourceExpression.expression;
sourceExpression.expression = new _aureliaBinding.ValueConverter(expression, 't', sourceExpression.args, [expression].concat(sourceExpression.args));
};
TBindingBehavior.prototype.unbind = function unbind(binding, source) {
binding.sourceExpression.expression = binding.sourceExpression.expression.expression;
this.signalBindingBehavior.unbind(binding, source);
};
return TBindingBehavior;
})();
exports.TBindingBehavior = TBindingBehavior;
var RtValueConverter = (function () {
RtValueConverter.inject = function inject() {
return [RelativeTime];
};
function RtValueConverter(relativeTime) {
_classCallCheck(this, RtValueConverter);
this.service = relativeTime;
}
RtValueConverter.prototype.toView = function toView(value) {
return this.service.getRelativeTime(value);
};
return RtValueConverter;
})();
exports.RtValueConverter = RtValueConverter;
function registerI18N(frameworkConfig, cb) {
var instance = new I18N(frameworkConfig.container.get(_aureliaEventAggregator.EventAggregator), frameworkConfig.container.get(_aureliaTemplatingResources.BindingSignaler));
frameworkConfig.container.registerInstance(I18N, instance);
var ret = cb(instance);
frameworkConfig.postTask(function () {
var resources = frameworkConfig.container.get(_aureliaTemplating.ViewResources);
var htmlBehaviorResource = resources.getAttribute('t');
var htmlParamsResource = resources.getAttribute('t-params');
var attributes = instance.i18next.options.attributes;
if (!attributes) {
attributes = ['t', 'i18n'];
}
attributes.forEach(function (alias) {
return resources.registerAttribute(alias, htmlBehaviorResource, 't');
});
attributes.forEach(function (alias) {
return resources.registerAttribute(alias + '-params', htmlParamsResource, 't-params');
});
});
return ret;
}
function configure(frameworkConfig, cb) {
if (cb === undefined || typeof cb !== 'function') {
var errorMsg = 'You need to provide a callback method to properly configure the library';
throw errorMsg;
}
frameworkConfig.globalResources('./t');
frameworkConfig.globalResources('./nf');
frameworkConfig.globalResources('./df');
frameworkConfig.globalResources('./rt');
if (window.Intl === undefined) {
var _ret = (function () {
var loader = frameworkConfig.container.get(_aureliaLoader.Loader);
return {
v: loader.normalize('aurelia-i18n').then(function (i18nName) {
return loader.normalize('intl', i18nName).then(function (intlName) {
return loader.loadModule(intlName).then(function (poly) {
window.Intl = poly;
return registerI18N(frameworkConfig, cb);
});
});
})
};
})();
if (typeof _ret === 'object') return _ret.v;
}
return Promise.resolve(registerI18N(frameworkConfig, cb));
}
exports.configure = configure;
exports.I18N = I18N;
exports.RelativeTime = RelativeTime;
exports.DfValueConverter = DfValueConverter;
exports.NfValueConverter = NfValueConverter;
exports.RtValueConverter = RtValueConverter;
exports.TValueConverter = TValueConverter;
exports.TBindingBehavior = TBindingBehavior;
exports.TCustomAttribute = TCustomAttribute;
exports.TParamsCustomAttribute = TParamsCustomAttribute;
exports.BaseI18N = BaseI18N;
exports.EventAggregator = _aureliaEventAggregator.EventAggregator; | {'content_hash': '1a3355d68d9e4b797f9b0c6329704858', 'timestamp': '', 'source': 'github', 'line_count': 859, 'max_line_length': 566, 'avg_line_length': 31.42142025611176, 'alnum_prop': 0.6143158830721351, 'repo_name': 'milunka/aurelia-i18next', 'id': '026e98eed548eba5d94aa9ad3134f8967c6f086a', 'size': '27588', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'dist/temp/aurelia-i18n.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'HTML', 'bytes': '949'}, {'name': 'JavaScript', 'bytes': '242080'}]} |
'use strict';
// MODULES //
var isArrayLikeObject = require( '@stdlib/assert/is-array-like-object' );
var isComplexLike = require( '@stdlib/assert/is-complex-like' );
var format = require( '@stdlib/string/format' );
var real = require( '@stdlib/complex/real' );
var imag = require( '@stdlib/complex/imag' );
// MAIN //
/**
* Returns an array of iterated values.
*
* @private
* @param {Object} it - iterator
* @param {Function} clbk - callback to invoke for each iterated value
* @param {*} thisArg - invocation context
* @returns {(Array|TypeError)} array or an error
*/
function fromIteratorMap( it, clbk, thisArg ) {
var out;
var v;
var z;
var i;
out = [];
i = -1;
while ( true ) {
v = it.next();
if ( v.done ) {
break;
}
i += 1;
z = clbk.call( thisArg, v.value, i );
if ( isArrayLikeObject( z ) && z.length >= 2 ) {
out.push( z[ 0 ], z[ 1 ] );
} else if ( isComplexLike( z ) ) {
out.push( real( z ), imag( z ) );
} else {
return new TypeError( format( 'invalid argument. Callback must return either a two-element array containing real and imaginary components or a complex number. Value: `%s`.', z ) );
}
}
return out;
}
// EXPORTS //
module.exports = fromIteratorMap;
| {'content_hash': '2f48b86678d821cdb7c54ef5cc640e14', 'timestamp': '', 'source': 'github', 'line_count': 54, 'max_line_length': 183, 'avg_line_length': 22.62962962962963, 'alnum_prop': 0.6292962356792144, 'repo_name': 'stdlib-js/stdlib', 'id': 'a8c45d5720a5d8c0e4a05c12c8d19760c787cd22', 'size': '1838', 'binary': False, 'copies': '1', 'ref': 'refs/heads/develop', 'path': 'lib/node_modules/@stdlib/array/complex128/lib/from_iterator_map.js', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Awk', 'bytes': '21739'}, {'name': 'C', 'bytes': '15336495'}, {'name': 'C++', 'bytes': '1349482'}, {'name': 'CSS', 'bytes': '58039'}, {'name': 'Fortran', 'bytes': '198059'}, {'name': 'HTML', 'bytes': '56181'}, {'name': 'Handlebars', 'bytes': '16114'}, {'name': 'JavaScript', 'bytes': '85975525'}, {'name': 'Julia', 'bytes': '1508654'}, {'name': 'Makefile', 'bytes': '4806816'}, {'name': 'Python', 'bytes': '3343697'}, {'name': 'R', 'bytes': '576612'}, {'name': 'Shell', 'bytes': '559315'}, {'name': 'TypeScript', 'bytes': '19309407'}, {'name': 'WebAssembly', 'bytes': '5980'}]} |
@interface DFVideoPlayController()
@property (nonatomic, strong) NSString *filePath;
@property (strong, nonatomic) AVPlayer *player;
@end
@implementation DFVideoPlayController
- (instancetype)initWithFile:(NSString *) filePath
{
self = [super init];
if (self) {
_filePath = filePath;
}
return self;
}
-(void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
[[UIApplication sharedApplication] setStatusBarHidden:YES];
[self addNotification];
[_player play];
}
-(void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
[self removeNotification];
[_player pause];
[[UIApplication sharedApplication] setStatusBarHidden:NO];
}
-(void)viewDidLoad
{
[super viewDidLoad];
self.navigationController.navigationBar.hidden = YES;
self.view.backgroundColor = [UIColor blackColor];
NSURL *fileUrl=[NSURL fileURLWithPath:_filePath];
AVPlayerItem *playerItem = [[AVPlayerItem alloc] initWithURL:fileUrl];
_player = [[AVPlayer alloc] initWithPlayerItem:playerItem];
AVPlayerLayer *layer = [AVPlayerLayer playerLayerWithPlayer:_player];
CGFloat x, y, width, height;
x=0;
width = self.view.frame.size.width;
height = width*0.7;
y = (self.view.frame.size.height - height)/2;
layer.frame = CGRectMake(x,y,width,height);
[self.view.layer addSublayer:layer];
layer.videoGravity=AVLayerVideoGravityResizeAspectFill;
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
[button addTarget:self action:@selector(close:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
}
-(void) close:(id) sender
{
[self dismissViewControllerAnimated:YES completion:^{
}];
}
-(void)addNotification{
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playbackFinished:) name:AVPlayerItemDidPlayToEndTimeNotification object:self.player.currentItem];
}
-(void)removeNotification{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
-(void)playbackFinished:(NSNotification *)notification{
[_player seekToTime:CMTimeMake(0, 1)];
[_player play];
}
@end
| {'content_hash': 'aae0a56f6c43265b555503535890d23c', 'timestamp': '', 'source': 'github', 'line_count': 92, 'max_line_length': 175, 'avg_line_length': 25.23913043478261, 'alnum_prop': 0.702411714039621, 'repo_name': 'anyunzhong/DFCommon', 'id': '4cc51448df71aca5bd6164b982ff700cc8bebf21', 'size': '2540', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'DFCommon/DFCommon/Lib/DFVideo/DFVideoPlayController.m', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '49484'}, {'name': 'Objective-C', 'bytes': '231668'}, {'name': 'Ruby', 'bytes': '1457'}]} |
<?php
declare(strict_types=1);
namespace BEAR\Sunday\Extension\Router;
class RouterMatch
{
/**
* Request method
*
* @var string
*/
public $method;
/**
* Request path
*
* @var string
*/
public $path;
/**
* Request query
*
* @var array
*/
public $query = [];
public function __toString()
{
$querySymbol = $this->query ? '?' : '';
return "{$this->method} {$this->path}{$querySymbol}" . \http_build_query($this->query);
}
}
| {'content_hash': 'd80dc09cd6ee05df59f5f74e2d9f7505', 'timestamp': '', 'source': 'github', 'line_count': 36, 'max_line_length': 95, 'avg_line_length': 14.972222222222221, 'alnum_prop': 0.49536178107606677, 'repo_name': 'BEARSunday/BEAR.Sunday', 'id': 'cf2c020450b57530fbfaddc5468f4394c4f00ab5', 'size': '539', 'binary': False, 'copies': '1', 'ref': 'refs/heads/1.x', 'path': 'src/Extension/Router/RouterMatch.php', 'mode': '33188', 'license': 'bsd-2-clause', 'language': [{'name': 'PHP', 'bytes': '35316'}]} |
const levenshtein = require('fast-levenshtein');
const utils = {
log(title, message) {
// title: string, message: object
console.log(`**** ${title}:`, JSON.stringify(message));
},
getClosestDevice(name, devices) {
// finds closest device by comparing device names to name provided. Uses https://en.wikipedia.org/wiki/Levenshtein_distance
let minimumDistance = Number.MAX_VALUE;
let closestDevice = null;
const cleanName = name.replace(/\s/g, '').toLowerCase(); // standardize format of name
for (let i = 0; i < devices.length; i += 1) {
const device = devices[i];
const cleanDeviceName = device.name.replace(/\s/g, '').toLowerCase(); // standardize format of device name
const distance = levenshtein.get(cleanName, cleanDeviceName);
if (distance < minimumDistance) {
// make this device the closestDevice if it has the shortest distance
minimumDistance = distance;
closestDevice = device;
}
}
console.log(name, minimumDistance, closestDevice.name, devices);
return closestDevice;
},
getDoors(devices) {
// finds all doors in a list of devices
if (!devices) {
return false;
}
const doors = [];
for (let i = 0; i < devices.length; i += 1) {
const device = devices[i];
if (device.typeId !== 3) {
doors.push(device);
}
}
return doors;
},
getLights(devices) {
// finds all lights in a list of devices
if (!devices) {
return false;
}
const lights = [];
for (let i = 0; i < devices.length; i += 1) {
const device = devices[i];
if (device.typeId === 3) {
lights.push(device);
}
}
return lights;
},
};
module.exports = utils;
| {'content_hash': '54391cadab9f97ffe28bb8006b953172', 'timestamp': '', 'source': 'github', 'line_count': 56, 'max_line_length': 127, 'avg_line_length': 31.232142857142858, 'alnum_prop': 0.6112064036592338, 'repo_name': 'thomasmunduchira/myq-home-alexa', 'id': 'aee3214887199b507294ee6fec05d53315421099', 'size': '1749', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'utils/utils.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '25100'}, {'name': 'Shell', 'bytes': '469'}]} |
module TestSeq
using FactCheck,
Bio.Seq,
YAML
import ..get_bio_fmt_specimens
# Return a random DNA/RNA sequence of the given length
function random_seq(n::Integer, nts, probs)
cumprobs = cumsum(probs)
x = Array(Char, n)
for i in 1:n
x[i] = nts[searchsorted(cumprobs, rand()).start]
end
return convert(AbstractString, x)
end
function random_array(n::Integer, elements, probs)
cumprobs = cumsum(probs)
x = Array(eltype(elements), n)
for i in 1:n
x[i] = elements[searchsorted(cumprobs, rand()).start]
end
return x
end
function random_dna(n, probs=[0.24, 0.24, 0.24, 0.24, 0.04])
return random_seq(n, ['A', 'C', 'G', 'T', 'N'], probs)
end
function random_rna(n, probs=[0.24, 0.24, 0.24, 0.24, 0.04])
return random_seq(n, ['A', 'C', 'G', 'U', 'N'], probs)
end
const codons = [
"AAA", "AAC", "AAG", "AAU",
"ACA", "ACC", "ACG", "ACU",
"AGA", "AGC", "AGG", "AGU",
"AUA", "AUC", "AUG", "AUU",
"CAA", "CAC", "CAG", "CAU",
"CCA", "CCC", "CCG", "CCU",
"CGA", "CGC", "CGG", "CGU",
"CUA", "CUC", "CUG", "CUU",
"GAA", "GAC", "GAG", "GAU",
"GCA", "GCC", "GCG", "GCU",
"GGA", "GGC", "GGG", "GGU",
"GUA", "GUC", "GUG", "GUU",
"UAC", "UAU", "UCA", "UCC",
"UCG", "UCU", "UGC", "UGG",
"UGU", "UUA", "UUC", "UUG",
"UUU",
# translatable ambiguities in the standard code
"CUN", "CCN", "CGN", "ACN",
"GUN", "GCN", "GGN", "UCN"
]
function random_translatable_rna(n)
probs = fill(1.0 / length(codons), length(codons))
cumprobs = cumsum(probs)
r = rand()
x = Array(AbstractString, n)
for i in 1:n
x[i] = codons[searchsorted(cumprobs, rand()).start]
end
return string(x...)
end
function random_dna_kmer(len)
return random_dna(len, [0.25, 0.25, 0.25, 0.25])
end
function random_rna_kmer(len)
return random_rna(len, [0.25, 0.25, 0.25, 0.25])
end
function random_dna_kmer_nucleotides(len)
return random_array(len, [DNA_A, DNA_C, DNA_G, DNA_T],
[0.25, 0.25, 0.25, 0.25])
end
function random_rna_kmer_nucleotides(len)
return random_array(len, [RNA_A, RNA_C, RNA_G, RNA_U],
[0.25, 0.25, 0.25, 0.25])
end
function random_aa(len)
return random_seq(len,
['A', 'R', 'N', 'D', 'C', 'Q', 'E', 'G', 'H', 'I',
'L', 'K', 'M', 'F', 'P', 'S', 'T', 'W', 'Y', 'V', 'X' ],
push!(fill(0.049, 20), 0.02))
end
function random_interval(minstart, maxstop)
start = rand(minstart:maxstop)
return start:rand(start:maxstop)
end
facts("Nucleotides") do
context("Conversions") do
context("UInt8") do
context("DNA conversions from UInt8") do
@fact convert(DNANucleotide, UInt8(0)) --> DNA_A
@fact convert(DNANucleotide, UInt8(1)) --> DNA_C
@fact convert(DNANucleotide, UInt8(2)) --> DNA_G
@fact convert(DNANucleotide, UInt8(3)) --> DNA_T
@fact convert(DNANucleotide, UInt8(4)) --> DNA_N
end
context("RNA conversions from UInt8") do
@fact convert(RNANucleotide, UInt8(0)) --> RNA_A
@fact convert(RNANucleotide, UInt8(1)) --> RNA_C
@fact convert(RNANucleotide, UInt8(2)) --> RNA_G
@fact convert(RNANucleotide, UInt8(3)) --> RNA_U
@fact convert(RNANucleotide, UInt8(4)) --> RNA_N
end
context("DNA conversions to UInt8") do
@fact convert(UInt8, DNA_A) --> UInt8(0)
@fact convert(UInt8, DNA_C) --> UInt8(1)
@fact convert(UInt8, DNA_G) --> UInt8(2)
@fact convert(UInt8, DNA_T) --> UInt8(3)
@fact convert(UInt8, DNA_N) --> UInt8(4)
end
context("RNA conversions to UInt8") do
@fact convert(UInt8, RNA_A) --> UInt8(0)
@fact convert(UInt8, RNA_C) --> UInt8(1)
@fact convert(UInt8, RNA_G) --> UInt8(2)
@fact convert(UInt8, RNA_U) --> UInt8(3)
@fact convert(UInt8, RNA_N) --> UInt8(4)
end
end
context("UInt64") do
context("DNA conversions from UInt64") do
@fact convert(DNANucleotide, UInt64(0)) --> DNA_A
@fact convert(DNANucleotide, UInt64(1)) --> DNA_C
@fact convert(DNANucleotide, UInt64(2)) --> DNA_G
@fact convert(DNANucleotide, UInt64(3)) --> DNA_T
@fact convert(DNANucleotide, UInt64(4)) --> DNA_N
end
context("RNA conversions from UInt64") do
@fact convert(RNANucleotide, UInt64(0)) --> RNA_A
@fact convert(RNANucleotide, UInt64(1)) --> RNA_C
@fact convert(RNANucleotide, UInt64(2)) --> RNA_G
@fact convert(RNANucleotide, UInt64(3)) --> RNA_U
@fact convert(RNANucleotide, UInt64(4)) --> RNA_N
end
context("DNA conversions to UInt64") do
@fact convert(UInt64, DNA_A) --> UInt64(0)
@fact convert(UInt64, DNA_C) --> UInt64(1)
@fact convert(UInt64, DNA_G) --> UInt64(2)
@fact convert(UInt64, DNA_T) --> UInt64(3)
@fact convert(UInt64, DNA_N) --> UInt64(4)
end
context("RNA conversions to UInt64") do
@fact convert(UInt64, RNA_A) --> UInt64(0)
@fact convert(UInt64, RNA_C) --> UInt64(1)
@fact convert(UInt64, RNA_G) --> UInt64(2)
@fact convert(UInt64, RNA_U) --> UInt64(3)
@fact convert(UInt64, RNA_N) --> UInt64(4)
end
end
context("Char") do
context("DNA conversions from Char") do
@fact convert(DNANucleotide, 'A') --> DNA_A
@fact convert(DNANucleotide, 'C') --> DNA_C
@fact convert(DNANucleotide, 'G') --> DNA_G
@fact convert(DNANucleotide, 'T') --> DNA_T
@fact convert(DNANucleotide, 'N') --> DNA_N
end
context("RNA conversions from Char") do
@fact convert(RNANucleotide, 'A') --> RNA_A
@fact convert(RNANucleotide, 'C') --> RNA_C
@fact convert(RNANucleotide, 'G') --> RNA_G
@fact convert(RNANucleotide, 'U') --> RNA_U
@fact convert(RNANucleotide, 'N') --> RNA_N
end
context("DNA conversions to Char") do
@fact convert(Char, DNA_A) --> 'A'
@fact convert(Char, DNA_C) --> 'C'
@fact convert(Char, DNA_G) --> 'G'
@fact convert(Char, DNA_T) --> 'T'
@fact convert(Char, DNA_N) --> 'N'
end
context("RNA conversions to Char") do
@fact convert(Char, RNA_A) --> 'A'
@fact convert(Char, RNA_C) --> 'C'
@fact convert(Char, RNA_G) --> 'G'
@fact convert(Char, RNA_U) --> 'U'
@fact convert(Char, RNA_N) --> 'N'
end
end
end
context("Show DNA") do
buf = IOBuffer()
for nt in [DNA_A, DNA_C, DNA_G, DNA_T, DNA_N]
show(buf, nt)
end
@fact takebuf_string(buf) --> "ACGTN"
end
context("Show RNA") do
buf = IOBuffer()
for nt in [RNA_A, RNA_C, RNA_G, RNA_U, RNA_N]
show(buf, nt)
end
@fact takebuf_string(buf) --> "ACGUN"
end
context("Sequences") do
function dna_complement(seq::AbstractString)
seqc = Array(Char, length(seq))
for (i, c) in enumerate(seq)
if c == 'A'
seqc[i] = 'T'
elseif c == 'C'
seqc[i] = 'G'
elseif c == 'G'
seqc[i] = 'C'
elseif c == 'T'
seqc[i] = 'A'
else
seqc[i] = 'N'
end
end
return convert(AbstractString, seqc)
end
function rna_complement(seq::AbstractString)
seqc = Array(Char, length(seq))
for (i, c) in enumerate(seq)
if c == 'A'
seqc[i] = 'U'
elseif c == 'C'
seqc[i] = 'G'
elseif c == 'G'
seqc[i] = 'C'
elseif c == 'U'
seqc[i] = 'A'
else
seqc[i] = 'N'
end
end
return convert(AbstractString, seqc)
end
function check_reversal(T, seq)
return reverse(seq) == convert(AbstractString, reverse(convert(T, seq)))
end
function check_dna_complement(T, seq)
return dna_complement(seq) ==
convert(AbstractString, complement(convert(T, seq)))
end
function check_rna_complement(T, seq)
return rna_complement(seq) ==
convert(AbstractString, complement(convert(T, seq)))
end
function check_dna_revcomp(T, seq)
return reverse(dna_complement(seq)) ==
convert(AbstractString, reverse_complement(convert(T, seq)))
end
function check_rna_revcomp(T, seq)
return reverse(rna_complement(seq)) ==
convert(AbstractString, reverse_complement(convert(T, seq)))
end
function check_mismatches(T, a, b)
count = 0
for (ca, cb) in zip(a, b)
if ca != cb
count += 1
end
end
return mismatches(convert(T, a), convert(T, b)) == count
end
context("Nucleotide Sequences") do
reps = 10
context("Construction and Conversions") do
context("Constructing empty sequences") do
# Check construction of empty nucleotide sequences
# using RNASequence and DNASequence functions
@fact RNASequence() --> NucleotideSequence(RNANucleotide)
@fact DNASequence() --> NucleotideSequence(DNANucleotide)
end
context("Conversion from/to Strings") do
# Check that sequences in strings survive round trip conversion:
# String → NucleotideSequence → String
function check_string_construction(T::Type, seq::AbstractString)
return convert(AbstractString, NucleotideSequence{T}(seq)) == uppercase(seq)
end
for len in [0, 1, 10, 32, 1000, 10000, 100000]
@fact all(Bool[check_string_construction(DNANucleotide, random_dna(len)) for _ in 1:reps]) --> true
@fact all(Bool[check_string_construction(RNANucleotide, random_rna(len)) for _ in 1:reps]) --> true
@fact all(Bool[check_string_construction(DNANucleotide, lowercase(random_dna(len))) for _ in 1:reps]) --> true
@fact all(Bool[check_string_construction(RNANucleotide, lowercase(random_rna(len))) for _ in 1:reps]) --> true
end
# Non-nucleotide characters should throw
@fact_throws DNASequence("ACCNNCATTTTTTAGATXATAG")
@fact_throws RNASequence("ACCNNCATTTTTTAGATXATAG")
end
context("Conversion between RNA and DNA") do
@fact convert(RNASequence, DNASequence("ACGTN")) --> rna"ACGUN"
@fact convert(DNASequence, RNASequence("ACGUN")) --> dna"ACGTN"
end
context("Construction from nucleotide vectors") do
function check_vector_construction(T::Type, seq::AbstractString)
xs = T[convert(T, c) for c in seq]
return NucleotideSequence{T}(xs) == NucleotideSequence{T}(seq)
end
for len in [0, 1, 10, 32, 1000, 10000, 100000]
@fact all(Bool[check_vector_construction(DNANucleotide, random_dna(len)) for _ in 1:reps]) --> true
@fact all(Bool[check_vector_construction(RNANucleotide, random_rna(len)) for _ in 1:reps]) --> true
end
end
context("Concatenation") do
function check_concatenation(::Type{DNANucleotide}, n)
chunks = [random_dna(rand(100:300)) for i in 1:n]
parts = Any[]
for i in 1:n
start = rand(1:length(chunks[i]))
stop = rand(start:length(chunks[i]))
push!(parts, start:stop)
end
str = string([chunk[parts[i]]
for (i, chunk) in enumerate(chunks)]...)
seq = *([DNASequence(chunk)[parts[i]]
for (i, chunk) in enumerate(chunks)]...)
return convert(AbstractString, seq) == uppercase(str)
end
@fact all(Bool[check_concatenation(DNANucleotide, rand(1:10)) for _ in 1:100]) --> true
end
context("Repetition") do
function check_repetition(::Type{DNANucleotide}, n)
chunk = random_dna(rand(100:300))
start = rand(1:length(chunk))
stop = rand(start:length(chunk))
str = chunk[start:stop] ^ n
seq = DNASequence(chunk)[start:stop] ^ n
return convert(AbstractString, seq) == uppercase(str)
end
@fact all(Bool[check_repetition(DNANucleotide, rand(1:10)) for _ in 1:100]) --> true
end
end
context("Equality") do
reps = 10
function check_seq_equality(len)
a = random_dna(len)
return a == copy(a)
end
for len in [1, 10, 32, 1000]
@fact all(Bool[check_seq_equality(len) for _ in 1:reps]) --> true
end
a = b = dna"ACTGN"
@fact ==(a, b) --> true
@fact ==(dna"ACTGN", dna"ACTGN") --> true
@fact ==(dna"ACTGN", dna"ACTGA") --> false
@fact ==(dna"ACTGN", dna"ACTG") --> false
@fact ==(dna"ACTG", dna"ACTGN") --> false
c = d = rna"ACUGN"
@fact ==(c, d) --> true
@fact ==(rna"ACUGN", rna"ACUGN") --> true
@fact ==(rna"ACUGN", rna"ACUGA") --> false
@fact ==(rna"ACUGN", rna"ACUG") --> false
@fact ==(rna"ACUG", rna"ACUGN") --> false
a = dna"ACGTNACGTN"
b = dna"""
ACGTN
ACGTN
"""
@fact ==(a, b) --> true
c = rna"ACUGNACUGN"
d = rna"""
ACUGN
ACUGN
"""
@fact ==(c, d) --> true
end
context("Length") do
for len in [0, 1, 10, 32, 1000, 10000, 100000]
@fact length(DNASequence(random_dna(len))) --> len
@fact endof(DNASequence(random_dna(len))) --> len
@fact length(DNASequence(random_dna(len))) --> len
@fact endof(DNASequence(random_dna(len))) --> len
end
end
context("Copy") do
function check_copy(T, seq)
return convert(AbstractString, copy(NucleotideSequence{T}(seq))) == seq
end
for len in [1, 10, 32, 1000, 10000, 100000]
@fact all(Bool[check_copy(DNANucleotide, random_dna(len)) for _ in 1:reps]) --> true
@fact all(Bool[check_copy(RNANucleotide, random_rna(len)) for _ in 1:reps]) --> true
end
end
context("Access and Iterations") do
dna_seq = dna"ACTG"
rna_seq = rna"ACUG"
context("Access DNA Sequence") do
# Access indexes out of bounds
@fact_throws dna_seq[-1]
@fact_throws dna_seq[0]
@fact_throws dna_seq[5]
@fact_throws getindex(dna_seq,-1)
@fact_throws getindex(dna_seq, 0)
@fact_throws getindex(dna_seq, 5)
end
context("Iteration through DNA Sequence") do
@fact start(dna"ACNTG") --> (1,3)
@fact start(dna"") --> (1,1)
@fact next(dna"ACTGN", (2,5)) --> (DNA_C, (3,5))
@fact next(dna"ACTGN", (5,5)) --> (DNA_N, (6,6))
@fact done(dna"", (1,1)) --> true
@fact done(dna"ACTGN", (2,5)) --> false
@fact done(dna"ACTGN", (5,5)) --> false
@fact done(dna"ACTGN", (6,5)) --> true
@fact done(dna"ACTGN", (0,5)) --> false
dna_vector = [DNA_A, DNA_C, DNA_T, DNA_G]
@fact all(Bool[nucleotide == dna_vector[i] for (i, nucleotide) in enumerate(dna_seq)]) --> true
end
context("Access RNA Sequence") do
# Access indexes out of bounds
@fact_throws rna_seq[-1]
@fact_throws rna_seq[0]
@fact_throws rna_seq[5]
@fact_throws getindex(rna_seq, -1)
@fact_throws getindex(rna_seq, 0)
@fact_throws getindex(rna_seq, 5)
end
context("Iteration through RNA Sequence") do
@fact start(rna"ACNUG") --> (1,3)
@fact start(rna"") --> (1,1)
@fact next(rna"ACUGN", (2,5)) --> (RNA_C, (3,5))
@fact next(rna"ACUGN", (5,5)) --> (RNA_N, (6,6))
@fact done(rna"", (1,1)) --> true
@fact done(rna"ACUGN", (2,5)) --> false
@fact done(rna"ACUGN", (5,5)) --> false
@fact done(rna"ACUGN", (6,5)) --> true
@fact done(rna"ACUGN", (0,5)) --> false
# Iteration through RNA Sequence
rna_vector = [RNA_A, RNA_C, RNA_U, RNA_G]
@fact all(Bool[nucleotide == rna_vector[i] for (i, nucleotide) in enumerate(rna_seq)]) --> true
end
context("Indexing with Ranges") do
@fact getindex(dna"ACTGNACTGN", 1:5) --> dna"ACTGN"
@fact getindex(rna"ACUGNACUGN", 1:5) --> rna"ACUGN"
@fact getindex(dna"ACTGNACTGN", 5:1) --> dna""
@fact getindex(rna"ACUGNACUGN", 5:1) --> rna""
end
end
context("Subsequence Construction") do
for len in [1, 10, 32, 1000, 10000, 100000]
seq = random_dna(len)
dnaseq = DNASequence(seq)
results = Bool[]
for _ in 1:reps
part = random_interval(1, length(seq))
push!(results, seq[part] == convert(AbstractString, dnaseq[part]))
end
@fact all(results) --> true
end
for len in [1, 10, 32, 1000, 10000, 100000]
seq = random_rna(len)
rnaseq = RNASequence(seq)
results = Bool[]
for _ in 1:reps
part = random_interval(1, length(seq))
push!(results, seq[part] == convert(AbstractString, rnaseq[part]))
end
@fact all(results) --> true
end
context("Subsequence Construction from Ranges") do
# Subsequence from range
@fact (RNASequence(rna"AUCGAUCG", 5:8) == RNASequence("AUCG")) --> true
@fact (DNASequence(dna"ATCGATCG", 5:8) == DNASequence("ATCG")) --> true
# Invalid ranges
@fact_throws RNASequence(rna"AUCGAUCG", 5:10)
@fact_throws DNASequence(dna"ATCGATCG", 5:10)
# Empty ranges
@fact (RNASequence(rna"AUCGAUCG", 5:4) == RNASequence()) --> true
@fact (DNASequence(dna"ATCGATCG", 5:4) == DNASequence()) --> true
# Subsequence of subsequence
@fact dna"ACGTAG"[4:end][1:2] == dna"TA" --> true
@fact dna"ACGTAG"[4:end][2:3] == dna"AG" --> true
@fact_throws dna"ACGTAG"[4:end][0:1]
@fact_throws dna"ACGTAG"[4:end][3:4]
end
end
context("Transformations") do
context("Reversal") do
for len in [0, 1, 10, 32, 1000, 10000, 100000]
@fact all(Bool[check_reversal(DNASequence, random_dna(len)) for _ in 1:reps]) --> true
@fact all(Bool[check_reversal(RNASequence, random_rna(len)) for _ in 1:reps]) --> true
end
end
context("Complement") do
for len in [1, 10, 32, 1000, 10000, 100000]
@fact all(Bool[check_dna_complement(DNASequence, random_dna(len)) for _ in 1:reps]) --> true
@fact all(Bool[check_rna_complement(RNASequence, random_rna(len)) for _ in 1:reps]) --> true
end
end
context("Reverse Complement") do
for len in [1, 10, 32, 1000, 10000, 100000]
@fact all(Bool[check_dna_revcomp(DNASequence, random_dna(len)) for _ in 1:reps]) --> true
@fact all(Bool[check_rna_revcomp(RNASequence, random_rna(len)) for _ in 1:reps]) --> true
end
end
end
context("Mismatches") do
for len in [1, 10, 32, 1000, 10000, 100000]
@fact all(Bool[check_mismatches(DNASequence, random_dna(len), random_dna(len))
for _ in 1:reps]) --> true
@fact all(Bool[check_mismatches(RNASequence, random_rna(len), random_rna(len))
for _ in 1:reps]) --> true
end
end
context("Mutability") do
seq = dna"ACGTACGT"
@fact ismutable(seq) --> false
@fact_throws seq[1] = DNA_C
seq2 = seq[1:4]
@fact ismutable(seq2) --> false
mutable!(seq)
@fact ismutable(seq) --> true
seq[1] = DNA_C
@fact seq[1] --> DNA_C
@fact seq2[1] --> DNA_A
seq[2] = DNA_N
@fact seq[2] --> DNA_N
@fact seq2[2] --> DNA_C
seq[2] = DNA_G
@fact seq[2] --> DNA_G
immutable!(seq)
@fact_throws seq[1] = DNA_A
seq = dna"ACGTACGT"
mutable!(seq)
rnaseq = convert(RNASequence, seq)
@fact ismutable(rnaseq) --> true
@fact_throws rnaseq[1] = DNA_C
rnaseq[1] = RNA_C
@fact seq --> dna"ACGTACGT"
@fact rnaseq --> rna"CCGUACGU"
end
end
context("SequenceNIterator") do
function check_ns(T, seq)
expected = Int[]
for i in 1:length(seq)
if seq[i] == 'N'
push!(expected, i)
end
end
collect(npositions(T(seq))) == expected
end
reps = 10
for len in [1, 10, 32, 1000, 10000, 100000]
@fact all(Bool[check_ns(DNASequence, random_dna(len)) for _ in 1:reps]) --> true
@fact all(Bool[check_ns(RNASequence, random_rna(len)) for _ in 1:reps]) --> true
end
dna_seq = dna"ANANANA"
dna_niter = npositions(dna_seq)
@fact start(dna_niter) --> 2
@fact next(dna_niter, 2) --> (2,4)
@fact done(dna_niter, 6) --> false
@fact done(dna_niter, 8) --> true
ns = [2,4,6]
for (i, n) in enumerate(dna_niter)
@fact n --> ns[i]
end
rna_seq = rna"ANANANA"
rna_niter = npositions(rna_seq)
@fact start(rna_niter) --> 2
@fact next(rna_niter, 2) --> (2,4)
@fact done(rna_niter, 6) --> false
@fact done(rna_niter, 8) --> true
ns = [2,4,6]
for (i, n) in enumerate(rna_niter)
@fact n --> ns[i]
end
end
context("Kmer") do
reps = 100
context("Construction and Conversions") do
# Check that kmers in strings survive round trip conversion:
# UInt64 → Kmer → UInt64
function check_uint64_convertion(T::Type, n::UInt64, len::Int)
return convert(UInt64, convert(Kmer{T, len}, n)) === n
end
# Check that kmers in strings survive round trip conversion:
# String → Kmer → String
function check_string_construction(T::Type, seq::AbstractString)
return convert(AbstractString, convert(Kmer{T}, seq)) == uppercase(seq)
end
# Check that dnakmers can be constructed from a DNASequence
# DNASequence → Kmer → DNASequence
function check_dnasequence_construction(seq::DNASequence)
return convert(DNASequence, convert(DNAKmer, seq)) == seq
end
# Check that rnakmers can be constructed from a RNASequence
# RNASequence → Kmer → RNASequence
function check_rnasequence_construction(seq::RNASequence)
return convert(RNASequence, convert(RNAKmer, seq)) == seq
end
# Check that kmers can be constructed from a NucleotideSequence
# NucleotideSequence → Kmer → NucleotideSequence
function check_nucsequence_construction(seq::NucleotideSequence)
return convert(NucleotideSequence, convert(Kmer, seq)) == seq
end
# Check that kmers can be constructed from an array of nucleotides
# Vector{Nucleotide} → Kmer → Vector{Nucleotide}
function check_nucarray_kmer{T <: Nucleotide}(seq::Vector{T})
return convert(AbstractString, [convert(Char, c) for c in seq]) ==
convert(AbstractString, kmer(seq...))
end
# Check that kmers in strings survive round trip conversion:
# String → NucleotideSequence → Kmer → NucleotideSequence → String
function check_roundabout_construction(T::Type, seq::AbstractString)
return convert(AbstractString,
convert(NucleotideSequence{T},
convert(Kmer,
convert(NucleotideSequence{T}, seq)))) == uppercase(seq)
end
for len in [0, 1, 16, 32]
# UInt64 conversions
@fact all(Bool[check_uint64_convertion(DNANucleotide, rand(UInt64), len)
for _ in 1:reps]) --> true
@fact all(Bool[check_uint64_convertion(RNANucleotide, rand(UInt64), len)
for _ in 1:reps]) --> true
# String construction
@fact all(Bool[check_string_construction(DNANucleotide, random_dna_kmer(len))
for _ in 1:reps]) --> true
@fact all(Bool[check_string_construction(RNANucleotide, random_rna_kmer(len))
for _ in 1:reps]) --> true
# DNA/RNASequence Constructions
@fact all(Bool[check_dnasequence_construction(DNASequence(random_dna_kmer(len))) for _ in 1:reps]) --> true
@fact all(Bool[check_rnasequence_construction(RNASequence(random_rna_kmer(len))) for _ in 1:reps]) --> true
# NucleotideSequence Construction
@fact all(Bool[check_nucsequence_construction(DNASequence(random_dna_kmer(len))) for _ in 1:reps]) --> true
@fact all(Bool[check_nucsequence_construction(RNASequence(random_rna_kmer(len))) for _ in 1:reps]) --> true
# Construction from nucleotide arrays
if len > 0
@fact all(Bool[check_nucarray_kmer(random_dna_kmer_nucleotides(len))
for _ in 1:reps]) --> true
@fact all(Bool[check_nucarray_kmer(random_rna_kmer_nucleotides(len))
for _ in 1:reps]) --> true
end
# Roundabout conversions
@fact all(Bool[check_roundabout_construction(DNANucleotide, random_dna_kmer(len))
for _ in 1:reps]) --> true
@fact all(Bool[check_roundabout_construction(RNANucleotide, random_rna_kmer(len))
for _ in 1:reps]) --> true
end
@fact_throws kmer() # can't construct 0-mer using `kmer()`
@fact_throws kmer(RNA_A, RNA_C, RNA_G, RNA_N, RNA_U) # no Ns in kmers
@fact_throws kmer(DNA_A, DNA_C, DNA_G, DNA_N, DNA_T) # no Ns in kmers
@fact_throws kmer(rna"ACGNU")# no Ns in kmers
@fact_throws rnmakmer(rna"ACGNU")# no Ns in kmers
@fact_throws kmer(dna"ACGNT") # no Ns in kmers
@fact_throws dnmakmer(dna"ACGNT") # no Ns in kmers
@fact_throws kmer(RNA_A, DNA_A) # no mixing of RNA and DNA
@fact_throws kmer(random_rna(33)) # no kmer larger than 32nt
@fact_throws kmer(random_dna(33)) # no kmer larger than 32nt
@fact_throws kmer(RNA_A, RNA_C, RNA_G, RNA_U, # no kmer larger than 32nt
RNA_A, RNA_C, RNA_G, RNA_U,
RNA_A, RNA_C, RNA_G, RNA_U,
RNA_A, RNA_C, RNA_G, RNA_U,
RNA_A, RNA_C, RNA_G, RNA_U,
RNA_A, RNA_C, RNA_G, RNA_U,
RNA_A, RNA_C, RNA_G, RNA_U,
RNA_A, RNA_C, RNA_G, RNA_U,
RNA_A, RNA_C, RNA_G, RNA_U)
@fact_throws kmer(DNA_A, DNA_C, DNA_G, DNA_T, # no kmer larger than 32nt
DNA_A, DNA_C, DNA_G, DNA_T,
DNA_A, DNA_C, DNA_G, DNA_T,
DNA_A, DNA_C, DNA_G, DNA_T,
DNA_A, DNA_C, DNA_G, DNA_T,
DNA_A, DNA_C, DNA_G, DNA_T,
DNA_A, DNA_C, DNA_G, DNA_T,
DNA_A, DNA_C, DNA_G, DNA_T,
DNA_A, DNA_C, DNA_G, DNA_T)
context("From strings") do
@fact dnakmer("ACTG") --> convert(Kmer, DNASequence("ACTG"))
@fact rnakmer("ACUG") --> convert(Kmer, RNASequence("ACUG"))
# N is not allowed in Kmers
@fact_throws dnakmer("ACGTNACGT")
@fact_throws rnakmer("ACGUNACGU")
end
end
context("Comparisons") do
context("Equality") do
function check_seq_kmer_equality(len)
a = dnakmer(random_dna_kmer(len))
b = convert(DNASequence, a)
return a == b && b == a
end
for len in [1, 10, 32]
@fact all(Bool[check_seq_kmer_equality(len) for _ in 1:reps]) --> true
end
# True negatives
@fact (dnakmer("ACG") == rnakmer("ACG")) --> false
@fact (dnakmer("T") == rnakmer("U")) --> false
@fact (dnakmer("AC") == dnakmer("AG")) --> false
@fact (rnakmer("AC") == rnakmer("AG")) --> false
@fact (dnakmer("ACG") == rna"ACG") --> false
@fact (dnakmer("T") == rna"U") --> false
@fact (dnakmer("AC") == dna"AG") --> false
@fact (rnakmer("AC") == rna"AG") --> false
@fact (rna"ACG" == dnakmer("ACG")) --> false
@fact (rna"U" == dnakmer("T")) --> false
@fact (dna"AG" == dnakmer("AC")) --> false
@fact (rna"AG" == rnakmer("AC")) --> false
end
context("Inequality") do
for len in [1, 10, 32]
@fact isless(convert(DNAKmer{1}, UInt64(0)), convert(DNAKmer{1}, UInt64(1))) --> true
@fact isless(convert(DNAKmer{1}, UInt64(0)), convert(DNAKmer{1}, UInt64(0))) --> false
@fact isless(convert(DNAKmer{1}, UInt64(1)), convert(DNAKmer{1}, UInt64(0))) --> false
@fact isless(convert(RNAKmer{1}, UInt64(0)), convert(RNAKmer{1}, UInt64(1))) --> true
@fact isless(convert(RNAKmer{1}, UInt64(0)), convert(RNAKmer{1}, UInt64(0))) --> false
@fact isless(convert(RNAKmer{1}, UInt64(1)), convert(RNAKmer{1}, UInt64(0))) --> false
end
end
end
context("Length") do
for len in [0, 1, 16, 32]
@fact length(dnakmer(random_dna_kmer(len))) --> len
@fact length(rnakmer(random_rna_kmer(len))) --> len
end
end
context("Access and Iterations") do
dna_kmer = dnakmer("ACTG")
rna_kmer = rnakmer("ACUG")
context("Access DNA Kmer") do
@fact dna_kmer[1] --> DNA_A
@fact dna_kmer[2] --> DNA_C
@fact dna_kmer[3] --> DNA_T
@fact dna_kmer[4] --> DNA_G
# Access indexes out of bounds
@fact_throws dna_kmer[-1]
@fact_throws dna_kmer[0]
@fact_throws dna_kmer[5]
@fact_throws getindex(dna_kmer,-1)
@fact_throws getindex(dna_kmer, 0)
@fact_throws getindex(dna_kmer, 5)
end
context("Iteration through DNA Kmer") do
@fact start(dnakmer("ACTG")) --> 1
@fact start(dnakmer("")) --> 1
@fact next(dnakmer("ACTG"), 1) --> (DNA_A, 2)
@fact next(dnakmer("ACTG"), 4) --> (DNA_G, 5)
@fact done(dnakmer(""), 1) --> true
@fact done(dnakmer("ACTG"), 1) --> false
@fact done(dnakmer("ACTG"), 4) --> false
@fact done(dnakmer("ACTG"), 5) --> true
@fact done(dnakmer("ACTG"), -1) --> false
dna_kmer_vector = [DNA_A, DNA_C, DNA_T, DNA_G]
@fact all(Bool[nucleotide == dna_kmer_vector[i] for (i, nucleotide) in enumerate(dna_kmer)]) --> true
end
context("Access RNA Kmer") do
@fact rna_kmer[1] --> RNA_A
@fact rna_kmer[2] --> RNA_C
@fact rna_kmer[3] --> RNA_U
@fact rna_kmer[4] --> RNA_G
# Access indexes out of bounds
@fact_throws rna_kmer[-1]
@fact_throws rna_kmer[0]
@fact_throws rna_kmer[5]
@fact_throws getindex(rna_kmer, -1)
@fact_throws getindex(rna_kmer, 0)
@fact_throws getindex(rna_kmer, 5)
end
context("Iteration through RNA Kmer") do
@fact start(rnakmer("ACUG")) --> 1
@fact start(rnakmer("")) --> 1
@fact next(rnakmer("ACUG"), 1) --> (RNA_A, 2)
@fact next(rnakmer("ACUG"), 4) --> (RNA_G, 5)
@fact done(rnakmer(""), 1) --> true
@fact done(rnakmer("ACUG"), 1) --> false
@fact done(rnakmer("ACUG"), 4) --> false
@fact done(rnakmer("ACUG"), 5) --> true
@fact done(rnakmer("ACUG"), -1) --> false
rna_kmer_vector = [RNA_A, RNA_C, RNA_U, RNA_G]
@fact all(Bool[nucleotide == rna_kmer_vector[i] for (i, nucleotide) in enumerate(rna_kmer)]) --> true
end
end
reps = 10
context("Transformations") do
context("Reversal") do
for len in [0, 1, 16, 32]
@fact all(Bool[check_reversal(DNAKmer, random_dna_kmer(len)) for _ in 1:reps]) --> true
@fact all(Bool[check_reversal(RNAKmer, random_rna_kmer(len)) for _ in 1:reps]) --> true
end
end
context("Complement") do
for len in [0, 1, 16, 32]
@fact all(Bool[check_dna_complement(DNAKmer, random_dna_kmer(len)) for _ in 1:reps]) --> true
@fact all(Bool[check_rna_complement(RNAKmer, random_rna_kmer(len)) for _ in 1:reps]) --> true
end
end
context("Reverse Complement") do
for len in [0, 1, 16, 32]
@fact all(Bool[check_dna_revcomp(DNAKmer, random_dna_kmer(len)) for _ in 1:reps]) --> true
@fact all(Bool[check_rna_revcomp(RNAKmer, random_rna_kmer(len)) for _ in 1:reps]) --> true
end
end
end
context("Mismatches") do
for len in [0, 1, 16, 32]
@fact all(Bool[check_mismatches(DNAKmer, random_dna_kmer(len), random_dna_kmer(len))
for _ in 1:reps]) --> true
@fact all(Bool[check_mismatches(RNAKmer, random_rna_kmer(len), random_rna_kmer(len))
for _ in 1:reps]) --> true
end
end
end
context("EachKmer") do
function string_eachkmer(seq::AbstractString, k, step=1)
kmers = AbstractString[]
i = 1
for i in 1:step:length(seq) - k + 1
subseq = seq[i:i + k - 1]
if !in('N', subseq)
push!(kmers, subseq)
end
end
return kmers
end
function check_eachkmer(T, seq::AbstractString, k, step=1)
xs = [convert(AbstractString, x) for (i, x) in collect(each(Kmer{T, k}, NucleotideSequence{T}(seq), step))]
ys = string_eachkmer(seq, k, step)
return xs == ys
end
reps = 10
len = 10000
for k in [1, 3, 16, 32]
@fact all(Bool[check_eachkmer(DNANucleotide, random_dna(len), k) for _ in 1:reps]) --> true
@fact all(Bool[check_eachkmer(RNANucleotide, random_rna(len), k) for _ in 1:reps]) --> true
end
for k in [1, 3, 16, 32]
@fact all(Bool[check_eachkmer(DNANucleotide, random_dna(len), k, 3) for _ in 1:reps]) --> true
@fact all(Bool[check_eachkmer(RNANucleotide, random_rna(len), k, 3) for _ in 1:reps]) --> true
end
@fact isempty(collect(each(DNAKmer{1}, dna""))) --> true
@fact isempty(collect(each(DNAKmer{1}, dna"NNNNNNNNNN"))) --> true
@fact isempty(collect(each(DNAKmer{0}, dna"ACGT"))) --> true
@fact_throws each(DNAKmer{-1}, dna"ACGT")
@fact_throws each(DNAKmer{33}, dna"ACGT")
end
context("Nucleotide Counting") do
function string_nucleotide_count(::Type{DNANucleotide}, seq::AbstractString)
counts = Dict{DNANucleotide, Int}(
DNA_A => 0,
DNA_C => 0,
DNA_G => 0,
DNA_T => 0,
DNA_N => 0 )
for c in seq
counts[convert(DNANucleotide, c)] += 1
end
return counts
end
function string_nucleotide_count(::Type{RNANucleotide}, seq::AbstractString)
counts = Dict{RNANucleotide, Int}(
RNA_A => 0,
RNA_C => 0,
RNA_G => 0,
RNA_U => 0,
RNA_N => 0 )
for c in seq
counts[convert(RNANucleotide, c)] += 1
end
return counts
end
function check_nucleotide_count(::Type{DNANucleotide}, seq::AbstractString)
string_counts = string_nucleotide_count(DNANucleotide, seq)
seq_counts = NucleotideCounts(DNASequence(seq))
return string_counts[DNA_A] == seq_counts[DNA_A] &&
string_counts[DNA_C] == seq_counts[DNA_C] &&
string_counts[DNA_G] == seq_counts[DNA_G] &&
string_counts[DNA_T] == seq_counts[DNA_T] &&
string_counts[DNA_N] == seq_counts[DNA_N]
end
function check_nucleotide_count(::Type{RNANucleotide}, seq::AbstractString)
string_counts = string_nucleotide_count(RNANucleotide, seq)
seq_counts = NucleotideCounts(RNASequence(seq))
return string_counts[RNA_A] == seq_counts[RNA_A] &&
string_counts[RNA_C] == seq_counts[RNA_C] &&
string_counts[RNA_G] == seq_counts[RNA_G] &&
string_counts[RNA_U] == seq_counts[RNA_U] &&
string_counts[RNA_N] == seq_counts[RNA_N]
end
function check_kmer_nucleotide_count(::Type{DNANucleotide}, seq::AbstractString)
string_counts = string_nucleotide_count(DNANucleotide, seq)
kmer_counts = NucleotideCounts(dnakmer(seq))
return string_counts[DNA_A] == kmer_counts[DNA_A] &&
string_counts[DNA_C] == kmer_counts[DNA_C] &&
string_counts[DNA_G] == kmer_counts[DNA_G] &&
string_counts[DNA_T] == kmer_counts[DNA_T] &&
string_counts[DNA_N] == kmer_counts[DNA_N]
end
function check_kmer_nucleotide_count(::Type{RNANucleotide}, seq::AbstractString)
string_counts = string_nucleotide_count(RNANucleotide, seq)
kmer_counts = NucleotideCounts(rnakmer(seq))
return string_counts[RNA_A] == kmer_counts[RNA_A] &&
string_counts[RNA_C] == kmer_counts[RNA_C] &&
string_counts[RNA_G] == kmer_counts[RNA_G] &&
string_counts[RNA_U] == kmer_counts[RNA_U] &&
string_counts[RNA_N] == kmer_counts[RNA_N]
end
reps = 10
for len in [1, 10, 32, 1000, 10000, 100000]
@fact all(Bool[check_nucleotide_count(DNANucleotide, random_dna(len))
for _ in 1:reps]) --> true
@fact all(Bool[check_nucleotide_count(RNANucleotide, random_rna(len))
for _ in 1:reps]) --> true
end
for len in [1, 10, 32]
@fact all(Bool[check_kmer_nucleotide_count(DNANucleotide, random_dna_kmer(len))
for _ in 1:reps]) --> true
@fact all(Bool[check_kmer_nucleotide_count(RNANucleotide, random_rna_kmer(len))
for _ in 1:reps]) --> true
end
end
context("Kmer Counting") do
function string_kmer_count{T <: Nucleotide}(::Type{T}, seq::AbstractString, k, step)
counts = Dict{Kmer{T, k}, Int}()
for x in UInt64(0):UInt64(4^k-1)
counts[convert(Kmer{T, k}, x)] = 0
end
for i in 1:step:(length(seq)-k+1)
s = seq[i:i+k-1]
if 'N' in s
continue
end
counts[convert(Kmer{T, k}, s)] += 1
end
return counts
end
function check_kmer_count{T <: Nucleotide}(::Type{T}, seq::AbstractString, k, step)
string_counts = string_kmer_count(T, seq, k, step)
kmer_counts = KmerCounts{T, k}(convert(NucleotideSequence{T}, seq), step)
for y in UInt64(0):UInt64(4^k-1)
x = convert(Kmer{T, k}, y)
if string_counts[x] != kmer_counts[x]
return false
end
end
return true
end
reps = 10
for len in [1, 10, 32, 1000, 10000]
for k in [1, 2, 5]
for step in [1, 3]
@fact all(Bool[check_kmer_count(DNANucleotide, random_dna(len), k, step)
for _ in 1:reps]) --> true
@fact all(Bool[check_kmer_count(RNANucleotide, random_rna(len), k, step)
for _ in 1:reps]) --> true
end
end
end
end
end
end
facts("Aminoacids") do
context("AminoAcid Sequences") do
reps = 10
context("Construction") do
# Non-aa characters should throw
@fact_throws AminoAcidSequence("ATGHLMYZZACAGNM")
# Check that sequences in strings survive round trip conversion:
# String → AminoAcidSequence → String
function check_string_construction(seq::AbstractString)
return convert(AbstractString, AminoAcidSequence(seq)) == uppercase(seq)
end
for len in [0, 1, 10, 32, 1000, 10000, 100000]
@fact all(Bool[check_string_construction(random_aa(len)) for _ in 1:reps]) --> true
@fact all(Bool[check_string_construction(lowercase(random_aa(len))) for _ in 1:reps]) --> true
end
# Check creation of empty
end
context("Conversion") do
seq = aa"ARNDCQEGHILKMFPSTWYVX"
@fact convert(AminoAcidSequence, [aa for aa in seq]) --> seq
@fact convert(Vector{AminoAcid}, seq) --> [aa for aa in seq]
@fact_throws convert(AminoAcidSequence, [convert(AminoAcid, UInt8(30))])
end
context("Concatenation") do
function check_concatenation(n)
chunks = [random_aa(rand(100:300)) for i in 1:n]
parts = Any[]
for i in 1:n
start = rand(1:length(chunks[i]))
stop = rand(start:length(chunks[i]))
push!(parts, start:stop)
end
str = string([chunk[parts[i]]
for (i, chunk) in enumerate(chunks)]...)
seq = *([AminoAcidSequence(chunk)[parts[i]]
for (i, chunk) in enumerate(chunks)]...)
return convert(AbstractString, seq) == uppercase(str)
end
@fact all(Bool[check_concatenation(rand(1:10)) for _ in 1:100]) --> true
end
context("Equality") do
seq = aa"ARNDCQEGHILKMFPSTWYVX"
@fact ==(seq, aa"ARNDCQEGHILKMFPSTWYVX") --> true
@fact ==(seq, aa"ARNDCQEGHILKMFPSTWYXV") --> false
@fact ==(seq, aa"ARNDCQEGHLKMFPSTWYVX") --> false
seq′ = aa"""
ARNDCQEGHI
LKMFPSTWYV
X
"""
@fact ==(seq, seq′) --> true
end
context("Repetition") do
function check_repetition(n)
chunk = random_aa(rand(100:300))
start = rand(1:length(chunk))
stop = rand(start:length(chunk))
str = chunk[start:stop] ^ n
seq = AminoAcidSequence(chunk)[start:stop] ^ n
return convert(AbstractString, seq) == uppercase(str)
end
@fact all(Bool[check_repetition(rand(1:10)) for _ in 1:100]) --> true
end
context("Copy") do
function check_copy(seq)
return convert(AbstractString, copy(AminoAcidSequence(seq))) == uppercase(seq)
end
for len in [1, 10, 32, 1000, 10000, 100000]
@fact all(Bool[check_copy(random_aa(len)) for _ in 1:reps]) --> true
end
end
context("Subsequence Construction") do
for len in [1, 10, 32, 1000, 10000, 100000]
seq = random_aa(len)
aaseq = AminoAcidSequence(seq)
results = Bool[]
for _ in 1:reps
part = random_interval(1, length(seq))
push!(results, seq[part] == convert(AbstractString, aaseq[part]))
end
@fact all(results) --> true
end
end
context("Mutability") do
seq = aa"ARNDCQEGHILKMFPSTWYVX"
@fact ismutable(seq) --> false
@fact_throws seq[1] = AA_C
seq2 = seq[1:4]
@fact ismutable(seq2) --> false
mutable!(seq)
@fact ismutable(seq) --> true
seq[1] = AA_C
@fact seq[1] --> AA_C
@fact seq2[1] --> AA_A
immutable!(seq)
@fact_throws seq[1] = AA_A
end
end
context("Parsers") do
context("Valid Cases") do
# case-insensitive and ignores spaces
@fact parse(AminoAcid, "a") --> AA_A
@fact parse(AminoAcid, "Ala") --> AA_A
@fact parse(AminoAcid, "aLa ") --> AA_A
@fact parse(AminoAcid, " alA ") --> AA_A
@fact parse(AminoAcid, "\tAlA\n") --> AA_A
@fact parse(AminoAcid, "x") --> AA_X
@fact parse(AminoAcid, "X") --> AA_X
aas = [
("A", "ALA", AA_A),
("R", "ARG", AA_R),
("N", "ASN", AA_N),
("D", "ASP", AA_D),
("C", "CYS", AA_C),
("E", "GLU", AA_E),
("Q", "GLN", AA_Q),
("G", "GLY", AA_G),
("H", "HIS", AA_H),
("I", "ILE", AA_I),
("L", "LEU", AA_L),
("K", "LYS", AA_K),
("M", "MET", AA_M),
("F", "PHE", AA_F),
("P", "PRO", AA_P),
("S", "SER", AA_S),
("T", "THR", AA_T),
("W", "TRP", AA_W),
("Y", "TYR", AA_Y),
("V", "VAL", AA_V),
]
@fact length(aas) --> 20
for (one, three, aa) in aas
@fact parse(AminoAcid, one) --> aa
@fact parse(AminoAcid, three) --> aa
end
end
context("Invalid Cases") do
@fact_throws parse(AminoAcid, "")
@fact_throws parse(AminoAcid, "AL")
@fact_throws parse(AminoAcid, "LA")
@fact_throws parse(AminoAcid, "ALAA")
end
end
end
facts("Translation") do
# crummy string translation to test against
standard_genetic_code_dict = Dict{AbstractString, Char}(
"AAA" => 'K', "AAC" => 'N', "AAG" => 'K', "AAU" => 'N',
"ACA" => 'T', "ACC" => 'T', "ACG" => 'T', "ACU" => 'T',
"AGA" => 'R', "AGC" => 'S', "AGG" => 'R', "AGU" => 'S',
"AUA" => 'I', "AUC" => 'I', "AUG" => 'M', "AUU" => 'I',
"CAA" => 'Q', "CAC" => 'H', "CAG" => 'Q', "CAU" => 'H',
"CCA" => 'P', "CCC" => 'P', "CCG" => 'P', "CCU" => 'P',
"CGA" => 'R', "CGC" => 'R', "CGG" => 'R', "CGU" => 'R',
"CUA" => 'L', "CUC" => 'L', "CUG" => 'L', "CUU" => 'L',
"GAA" => 'E', "GAC" => 'D', "GAG" => 'E', "GAU" => 'D',
"GCA" => 'A', "GCC" => 'A', "GCG" => 'A', "GCU" => 'A',
"GGA" => 'G', "GGC" => 'G', "GGG" => 'G', "GGU" => 'G',
"GUA" => 'V', "GUC" => 'V', "GUG" => 'V', "GUU" => 'V',
"UAA" => '*', "UAC" => 'Y', "UAG" => '*', "UAU" => 'Y',
"UCA" => 'S', "UCC" => 'S', "UCG" => 'S', "UCU" => 'S',
"UGA" => '*', "UGC" => 'C', "UGG" => 'W', "UGU" => 'C',
"UUA" => 'L', "UUC" => 'F', "UUG" => 'L', "UUU" => 'F',
# translatable ambiguities in the standard code
"CUN" => 'L', "CCN" => 'P', "CGN" => 'R', "ACN" => 'T',
"GUN" => 'V', "GCN" => 'A', "GGN" => 'G', "UCN" => 'S'
)
function string_translate(seq::AbstractString)
@assert length(seq) % 3 == 0
aaseq = Array(Char, div(length(seq), 3))
for i in 1:3:length(seq) - 3 + 1
aaseq[div(i, 3) + 1] = standard_genetic_code_dict[seq[i:i+2]]
end
return convert(AbstractString, aaseq)
end
function check_translate(seq::AbstractString)
return string_translate(seq) == convert(AbstractString, translate(RNASequence(seq)))
end
reps = 10
#for len in [1, 10, 32, 1000, 10000, 100000]
for len in [1, 10, 32]
@fact all(Bool[check_translate(random_translatable_rna(len)) for _ in 1:reps]) --> true
end
@fact_throws translate(dna"ACGTACGTA") # can't translate DNA
@fact_throws translate(rna"ACGUACGU") # can't translate non-multiples of three
@fact_throws translate(rna"ACGUACGNU") # can't translate N
end
facts("Sequence Parsing") do
context("FASTA Parsing") do
get_bio_fmt_specimens()
function check_fasta_parse(filename)
# Reading from a stream
for seqrec in open(filename, FASTA)
end
# Reading from a memory mapped file
for seqrec in open(filename, FASTA, memory_map=true)
end
# Check round trip
output = IOBuffer()
expected_entries = Any[]
for seqrec in open(filename, FASTA)
write(output, seqrec)
push!(expected_entries, seqrec)
end
read_entries = Any[]
for seqrec in open(takebuf_array(output), FASTA)
push!(read_entries, seqrec)
end
return expected_entries == read_entries
end
path = Pkg.dir("Bio", "test", "BioFmtSpecimens", "FASTA")
for specimen in YAML.load_file(joinpath(path, "index.yml"))
tags = specimen["tags"]
valid = get(specimen, "valid", true)
# currently unsupported features
if contains(tags, "gaps") || contains(tags, "comments") || contains(tags, "ambiguity")
continue
end
if valid
@fact check_fasta_parse(joinpath(path, specimen["filename"])) --> true
else
@fact_throws check_fasta_parse(joinpath(path, specimen["filename"]))
end
end
end
context("FASTQ Parsing") do
get_bio_fmt_specimens()
function check_fastq_parse(filename)
# Reading from a stream
for seqrec in open(filename, FASTQ)
end
# Reading from a memory mapped file
for seqrec in open(filename, FASTQ, memory_map=true)
end
# Check round trip
output = IOBuffer()
expected_entries = Any[]
for seqrec in open(filename, FASTQ)
write(output, seqrec)
push!(expected_entries, seqrec)
end
read_entries = Any[]
for seqrec in open(takebuf_array(output), FASTQ)
push!(read_entries, seqrec)
end
return expected_entries == read_entries
end
path = Pkg.dir("Bio", "test", "BioFmtSpecimens", "FASTQ")
for specimen in YAML.load_file(joinpath(path, "index.yml"))
tags = get(specimen, "tags", "")
valid = get(specimen, "valid", true)
# currently unsupported features
if contains(tags, "rna") || contains(tags, "gaps") ||
contains(tags, "comments") || contains(tags, "ambiguity")
continue
end
if valid
@fact check_fastq_parse(joinpath(path, specimen["filename"])) --> true
else
@fact_throws check_fastq_parse(joinpath(path, specimen["filename"]))
end
end
end
end
facts("Quality scores") do
using Bio.Seq: encode_quality_string!,
encode_quality_string,
decode_quality_string!,
decode_quality_string,
ILLUMINA13_QUAL_ENCODING,
ILLUMINA15_QUAL_ENCODING,
ILLUMINA18_QUAL_ENCODING,
SANGER_QUAL_ENCODING,
SOLEXA_QUAL_ENCODING
context("Decoding PHRED scores") do
function test_decode(encoding, values, expected)
result = Array(Int8, length(expected))
decode_quality_string!(encoding, values, result, 1,
length(result))
@fact result --> expected
# Without start and end does the entire string
decode_quality_string!(encoding, values, result)
@fact result --> expected
# Non in-place version of the above
result = decode_quality_string(encoding, values, 1, length(result))
@fact result --> expected
resutlt = decode_quality_string(encoding, values)
@fact result --> expected
end
test_decode(SANGER_QUAL_ENCODING,
UInt8['!', '#', '$', '%', '&', 'I', '~'],
Int8[0, 2, 3, 4, 5, 40, 93])
test_decode(SOLEXA_QUAL_ENCODING,
UInt8[';', 'B', 'C', 'D', 'E', 'h', '~'],
Int8[-5, 2, 3, 4, 5, 40, 62])
test_decode(ILLUMINA13_QUAL_ENCODING,
UInt8['@', 'B', 'C', 'D', 'E', 'h', '~'],
Int8[0, 2, 3, 4, 5, 40, 62])
test_decode(ILLUMINA15_QUAL_ENCODING,
UInt8['C', 'D', 'E', 'h', '~'],
Int8[3, 4, 5, 40, 62])
test_decode(ILLUMINA18_QUAL_ENCODING,
UInt8['!', '#', '$', '%', '&', 'I', '~'],
Int8[0, 2, 3, 4, 5, 40, 93])
end
context("Encoding PHRED scores") do
function test_encode(encoding, values, expected)
# With start & end
result = Array(UInt8, length(expected))
encode_quality_string!(encoding, values, result, 1,
length(result))
@fact result --> expected
# Without start & end means the entire length
encode_quality_string!(encoding, values, result)
@fact result --> expected
result = encode_quality_string(encoding, values, 1, length(result))
@fact result --> expected
result = encode_quality_string(encoding, values)
@fact result --> expected
end
test_encode(SANGER_QUAL_ENCODING,
Int8[0, 2, 3, 4, 5, 40, 93],
UInt8['!', '#', '$', '%', '&', 'I', '~'])
test_encode(SOLEXA_QUAL_ENCODING,
Int8[-5, 2, 3, 4, 5, 40, 62],
UInt8[';', 'B', 'C', 'D', 'E', 'h', '~'])
test_encode(ILLUMINA13_QUAL_ENCODING,
Int8[0, 2, 3, 4, 5, 40, 62],
UInt8['@', 'B', 'C', 'D', 'E', 'h', '~'])
test_encode(ILLUMINA15_QUAL_ENCODING,
Int8[3, 4, 5, 40, 62],
UInt8['C', 'D', 'E', 'h', '~'])
test_encode(ILLUMINA18_QUAL_ENCODING,
Int8[0, 2, 3, 4, 5, 40, 93],
UInt8['!', '#', '$', '%', '&', 'I', '~'])
end
context("Sequence Writing") do
context("FASTA writing") do
dna_seq1 = random_dna(79 * 3) # full lines
dna_seq2 = random_dna(50) # short line
seq_name1 = "Sequence 1"
seq_name2 = "Sequence 2"
seq_description1 = "Description 1"
seq_description2 = "Description 2"
wrapped_seq1 = join([dna_seq1[1:79], dna_seq1[80:158], dna_seq1[159:end]], "\n")
expected_seq1 = string(">", seq_name1, " ", seq_description1, "\n", wrapped_seq1, "\n")
expected_seq2 = string(">", seq_name2, " ", seq_description2, "\n", dna_seq2, "\n")
expected = string(expected_seq1, expected_seq2)
fasta_seq1 = Seq.FASTADNASeqRecord(
seq_name1, DNASequence(dna_seq1), Seq.FASTAMetadata(seq_description1))
fasta_seq2 = Seq.FASTADNASeqRecord(
seq_name2, DNASequence(dna_seq2), Seq.FASTAMetadata(seq_description2))
sequences = [fasta_seq1, fasta_seq2]
output = IOBuffer()
for seq in sequences
write(output, seq)
end
@fact takebuf_string(output) --> expected
end
end
end
end # TestSeq
| {'content_hash': '82fe224b341b89b130c77ccde213cd94', 'timestamp': '', 'source': 'github', 'line_count': 1556, 'max_line_length': 134, 'avg_line_length': 40.45179948586118, 'alnum_prop': 0.4615922342436808, 'repo_name': 'dcjones/Bio.jl', 'id': '9f40983cf643181b92fd5d8d707f604175223e9f', 'size': '62987', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'test/seq/TestSeq.jl', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Julia', 'bytes': '352277'}, {'name': 'Makefile', 'bytes': '978'}, {'name': 'Ragel in Ruby Host', 'bytes': '25806'}]} |
sample app of Apache Camel
# build
```
cd camelSample
mvn clean install
```
you use target/geo-XXX-jar-with-dependencies.jar as below
`
java -jar geo-XXX-jar-with-dependencies.jar
`
# develop
you can use the followings maven commands.
```
mvn camel:run
```
if you want to run with hawtio.
```
mvn hawtio:camel
```
| {'content_hash': '19d89ed1ca5022499f24a8ddc089e412', 'timestamp': '', 'source': 'github', 'line_count': 27, 'max_line_length': 57, 'avg_line_length': 11.925925925925926, 'alnum_prop': 0.7080745341614907, 'repo_name': 'JunNakamura/camelSample', 'id': 'dc903ba94efef37a5282e49c2b959282c1450af0', 'size': '336', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '3991'}]} |
Volt.configure do |config|
# Setup your global app config here.
# Your app secret is used for signing things like the user cookie so it can't
# be tampered with. A random value is generated on new projects that will work
# without the need to customize. Make sure this value doesn't leave your server.
config.app_secret = 'Ak5icDj0iYykCJbvmeyDCeV5qYkGHUx3YY0IuFsBSgDVeWlD8YVtfqeuBVdbWn9B2aU'
# Database config all start with db_ and can be set either in the config
# file or with an environment variable (DB_NAME for example).
config.db_driver = 'mongo'
config.db_name = (config.app_name + '_' + Volt.env.to_s)
config.db_host = 'localhost'
config.db_port = 27017
# Compression options
# If you are not running behind something like nginx in production, you can
# have rack deflate all files.
# config.deflate = true
# Public configurations
# Anything under config.public will be sent to the client as well as the server,
# so be sure no private data ends up under public
# Use username instead of email as the login
# config.public.auth.use_username = true
end | {'content_hash': '24d9b579af2aaab38c2c63fcc969c4c8', 'timestamp': '', 'source': 'github', 'line_count': 30, 'max_line_length': 91, 'avg_line_length': 37.0, 'alnum_prop': 0.7378378378378379, 'repo_name': 'danielpclark/M3uGen', 'id': '7e9982f89920ba55d8b8a22a34ad86d5a6474cbf', 'size': '1110', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'config/app.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '27'}, {'name': 'Ruby', 'bytes': '8221'}]} |
This repo contains the slides for my talk on Professional JavaScript, originally
given at Houston Techfest, Sep 2013.
## License
[MIT LICENSE](LICENSE.md)
| {'content_hash': 'f6e8b6bbcd487780f0dad1d5d3a3c409', 'timestamp': '', 'source': 'github', 'line_count': 6, 'max_line_length': 80, 'avg_line_length': 26.333333333333332, 'alnum_prop': 0.7784810126582279, 'repo_name': 'oakmac/professional-javascript-short', 'id': '89df126d1ea51a422161ed36652c629893e4228a', 'size': '190', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'README.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '11337'}, {'name': 'HTML', 'bytes': '25804'}, {'name': 'JavaScript', 'bytes': '69335'}]} |
package com.intellij.execution.impl;
import com.intellij.execution.ExecutionManager;
import com.intellij.execution.process.ProcessHandler;
import com.intellij.execution.process.ScriptRunnerUtil;
import com.intellij.execution.ui.RunContentDescriptor;
import com.intellij.openapi.util.Conditions;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;
import org.junit.Assert;
import java.util.List;
import java.util.Objects;
public class ExecutionTestUtil {
private ExecutionTestUtil() {
}
@NotNull
public static RunContentDescriptor getSingleRunContentDescriptor(@NotNull ExecutionManager executionManager) {
List<RunContentDescriptor> descriptors = ((ExecutionManagerImpl)executionManager).getRunningDescriptors(Conditions.alwaysTrue());
String actualDescriptorsMsg = stringifyDescriptors(descriptors);
Assert.assertEquals(actualDescriptorsMsg, 1, descriptors.size());
RunContentDescriptor descriptor = ContainerUtil.getFirstItem(descriptors);
return Objects.requireNonNull(descriptor);
}
public static void terminateAllRunningDescriptors(@NotNull ExecutionManager executionManager) {
List<RunContentDescriptor> descriptors = ((ExecutionManagerImpl)executionManager).getRunningDescriptors(Conditions.alwaysTrue());
for (RunContentDescriptor descriptor : descriptors) {
ProcessHandler processHandler = descriptor.getProcessHandler();
if (processHandler != null) {
ScriptRunnerUtil.terminateProcessHandler(processHandler, 0, null);
}
}
}
@NotNull
private static String stringifyDescriptors(@NotNull List<? extends RunContentDescriptor> descriptors) {
return "Actual descriptors: " + StringUtil.join(descriptors, descriptor -> {
if (descriptor == null) {
return "null";
}
ProcessHandler processHandler = descriptor.getProcessHandler();
return String.format("[%s, %s]",
descriptor.getDisplayName(),
processHandler != null ? processHandler.getClass().getName() : null);
}, ", ");
}
}
| {'content_hash': 'ae732799d861e59eeecb96f39fdbdf56', 'timestamp': '', 'source': 'github', 'line_count': 51, 'max_line_length': 133, 'avg_line_length': 42.07843137254902, 'alnum_prop': 0.7567567567567568, 'repo_name': 'leafclick/intellij-community', 'id': 'b047ffb07c979eb612c23784d7d4512d6f230060', 'size': '2287', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'platform/lang-impl/testSources/com/intellij/execution/impl/ExecutionTestUtil.java', 'mode': '33188', 'license': 'apache-2.0', 'language': []} |
<?xml version="1.0" encoding="UTF-8"?>
<catalog>
<feature>
<name>vendor-bb-uib-buttons</name>
<contextItemName>[BBHOST]</contextItemName>
<properties>
<property name="title" label="Title" viewHint="admin,designModeOnly">
<value type="string">Bootstrap UI Buttons</value>
</property>
<property name="version" label="Version" viewHint="admin,designModeOnly">
<value type="string">1.3.3-bb.3</value>
</property>
<property name="path" label="Path" readonly="true" viewHint="designModeOnly">
<value type="string">$(itemRoot)/scripts/vendor-bb-uib-buttons.js</value>
</property>
<property name="feature.vendor-bb-angular" label="Feature Vendor Bb Angular" readonly="true" viewHint="">
<value type="string">vendor-bb-angular</value>
</property>
</properties>
</feature>
</catalog> | {'content_hash': '30350e6504e8f7793091de886a35aa11', 'timestamp': '', 'source': 'github', 'line_count': 21, 'max_line_length': 117, 'avg_line_length': 46.333333333333336, 'alnum_prop': 0.5878725590955807, 'repo_name': 'lenin-anzen/bb-widgets', 'id': '48eb10635b6092dd9778028c139d625064b18e70', 'size': '973', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'target/backbase/00033_vendor-bb-uib-buttons.extract/model.xml', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '247393'}, {'name': 'HTML', 'bytes': '23695'}, {'name': 'JavaScript', 'bytes': '76316'}, {'name': 'RAML', 'bytes': '917'}]} |
<TEI xmlns="http://www.tei-c.org/ns/1.0">
<teiHeader>
<fileDesc>
<titleStmt>
<title>Ode on His Majesty's recovery: by the author of Sympathy and humanity.</title>
<author>Pratt, Mr. (Samuel Jackson), 1749-1814.</author>
</titleStmt>
<extent>10 600dpi bitonal TIFF page images and SGML/XML encoded text</extent>
<publicationStmt>
<publisher>University of Michigan Library</publisher>
<pubPlace>Ann Arbor, Michigan</pubPlace>
<date when="2009-10">2009 October</date>
<idno type="DLPS">004853298</idno>
<idno type="ESTC">T85345</idno>
<idno type="DOCNO">CW113803360</idno>
<idno type="TCP">K069565.000</idno>
<idno type="GALEDOCNO">CW3313803360</idno>
<idno type="CONTENTSET">ECLL</idno>
<idno type="IMAGESETID">0670901100</idno>
<availability>
<p>This keyboarded and encoded edition of the
work described above is co-owned by the institutions
providing financial support to the Early English Books
Online Text Creation Partnership. This Phase I text is
available for reuse, according to the terms of <ref target="https://creativecommons.org/publicdomain/zero/1.0/">Creative
Commons 0 1.0 Universal</ref>. The text can be copied,
modified, distributed and performed, even for
commercial purposes, all without asking permission.</p>
</availability>
</publicationStmt>
<sourceDesc>
<biblFull>
<titleStmt>
<title>Ode on His Majesty's recovery: by the author of Sympathy and humanity.</title>
<author>Pratt, Mr. (Samuel Jackson), 1749-1814.</author>
</titleStmt>
<extent>[4],7,[1]p. ; 4⁰.</extent>
<publicationStmt>
<publisher>printed at the Logographic Press; and sold by J. Watter,</publisher>
<pubPlace>London :</pubPlace>
<date>1789.</date>
</publicationStmt>
<notesStmt>
<note>Author of Sympathy and humanity = Samuel Jackson Pratt.</note>
<note>With a half-title.</note>
<note>Reproduction of original from the British Library.</note>
<note>English Short Title Catalog, ESTCT85345.</note>
<note>Electronic data. Farmington Hills, Mich. : Thomson Gale, 2003. Page image (PNG). Digitized image of the microfilm version produced in Woodbridge, CT by Research Publications, 1982-2002 (later known as Primary Source Microfilm, an imprint of the Gale Group).</note>
</notesStmt>
</biblFull>
</sourceDesc>
</fileDesc>
<encodingDesc>
<projectDesc>
<p>Created by converting TCP files to TEI P5 using tcp2tei.xsl,
TEI @ Oxford.
</p>
</projectDesc>
<editorialDecl>
<p>EEBO-TCP is a partnership between the Universities of Michigan and Oxford and the publisher ProQuest to create accurately transcribed and encoded texts based on the image sets published by ProQuest via their Early English Books Online (EEBO) database (http://eebo.chadwyck.com). The general aim of EEBO-TCP is to encode one copy (usually the first edition) of every monographic English-language title published between 1473 and 1700 available in EEBO.</p>
<p>EEBO-TCP aimed to produce large quantities of textual data within the usual project restraints of time and funding, and therefore chose to create diplomatic transcriptions (as opposed to critical editions) with light-touch, mainly structural encoding based on the Text Encoding Initiative (http://www.tei-c.org).</p>
<p>The EEBO-TCP project was divided into two phases. The 25,363 texts created during Phase 1 of the project have been released into the public domain as of 1 January 2015. Anyone can now take and use these texts for their own purposes, but we respectfully request that due credit and attribution is given to their original source.</p>
<p>Users should be aware of the process of creating the TCP texts, and therefore of any assumptions that can be made about the data.</p>
<p>Text selection was based on the New Cambridge Bibliography of English Literature (NCBEL). If an author (or for an anonymous work, the title) appears in NCBEL, then their works are eligible for inclusion. Selection was intended to range over a wide variety of subject areas, to reflect the true nature of the print record of the period. In general, first editions of a works in English were prioritized, although there are a number of works in other languages, notably Latin and Welsh, included and sometimes a second or later edition of a work was chosen if there was a compelling reason to do so.</p>
<p>Image sets were sent to external keying companies for transcription and basic encoding. Quality assurance was then carried out by editorial teams in Oxford and Michigan. 5% (or 5 pages, whichever is the greater) of each text was proofread for accuracy and those which did not meet QA standards were returned to the keyers to be redone. After proofreading, the encoding was enhanced and/or corrected and characters marked as illegible were corrected where possible up to a limit of 100 instances per text. Any remaining illegibles were encoded as <gap>s. Understanding these processes should make clear that, while the overall quality of TCP data is very good, some errors will remain and some readable characters will be marked as illegible. Users should bear in mind that in all likelihood such instances will never have been looked at by a TCP editor.</p>
<p>The texts were encoded and linked to page images in accordance with level 4 of the TEI in Libraries guidelines.</p>
<p>Copies of the texts have been issued variously as SGML (TCP schema; ASCII text with mnemonic sdata character entities); displayable XML (TCP schema; characters represented either as UTF-8 Unicode or text strings within braces); or lossless XML (TEI P5, characters represented either as UTF-8 Unicode or TEI g elements).</p>
<p>Keying and markup guidelines are available at the <ref target="http://www.textcreationpartnership.org/docs/.">Text Creation Partnership web site</ref>.</p>
</editorialDecl>
<listPrefixDef>
<prefixDef ident="tcp"
matchPattern="([0-9\-]+):([0-9IVX]+)"
replacementPattern="https://data.historicaltexts.jisc.ac.uk/view?pubId=ecco-$1&index=ecco&pageId=ecco-$1-$20"/>
<prefixDef ident="char"
matchPattern="(.+)"
replacementPattern="https://raw.githubusercontent.com/textcreationpartnership/Texts/master/tcpchars.xml#$1"/>
</listPrefixDef>
</encodingDesc>
<profileDesc>
<langUsage>
<language ident="eng">eng</language>
</langUsage>
</profileDesc>
</teiHeader>
<text xml:lang="eng">
<front>
<div type="half_title">
<pb facs="tcp:0670901100:1" rendition="simple:additions"/>
<p>ODE ON <hi>HIS MAJESTY'S RECOVERY.</hi>
</p>
</div>
<div type="title_page">
<pb facs="tcp:0670901100:2" rendition="simple:additions"/>
<pb facs="tcp:0670901100:3"/>
<p>ODE ON <hi>HIS MAJESTY'S RECOVERY;</hi> BY THE AUTHOR OF SYMPATHY AND HUMANITY.</p>
<p>
<hi>LONDON:</hi> PRINTED AT THE <hi>LOGOGRAPHIC PRESS;</hi> AND SOLD BY J. WALTER, No. 169, OPPOSITE OLD BOND-STREET, PICCADILLY.</p>
<p>M.DCC.LXXXIX.</p>
</div>
</front>
<body>
<div type="ode">
<pb facs="tcp:0670901100:4"/>
<head>ODE.</head>
<lg>
<l>AVAUNT, ye Deities <hi>profane,</hi>
</l>
<l>And all ye ſhadowy Powers,</l>
<l>Imagination's airy Train,</l>
<l>That dwell in fabled Bowers!</l>
</lg>
<lg>
<l>Thou Heliconian Fount,</l>
<l>Whence Poeſy's rich Torrents flow;</l>
<l>And thou, Parnaſſian Mount,</l>
<l>Where Fancy ſees her Myrtles blow!</l>
</lg>
<lg>
<pb n="2" facs="tcp:0670901100:5"/>
<l>I bear no votive Off'ring to your Shrine,</l>
<l>No Incenſe to the bard-created Nine.</l>
<l>Nor e'en to thee, O Jove, whoſe high-thron'd State,</l>
<l>The Muſe of Greece has drawn ſublimely great,</l>
<l>High o'er the Pagan Heav'n, whilſt the bleſt Synod near,</l>
<l>Hymn the dread Thunderer's Name throughout th' ima<g ref="char:EOLhyphen"/>gin'd Sphere!</l>
</lg>
<lg>
<l>Thee, holy Power! whoſe awe-impreſſing Sway,</l>
<l>Earth, Air, and Sea, and Heav'n's bright Realms obey;</l>
<l>ESSENCE OF TRUTH! Thee, in thy bleſt Abode,</l>
<l>Sole we invoke—the ſole, the LIVING GOD!</l>
</lg>
<lg>
<l>O LIVING GOD! from Thee alone,</l>
<l>Bright beaming from thy Sapphire Throne,</l>
<l>Can heav'nly Inſpiration flow,</l>
<l>And give our melting Hearts with holy Flames to glow!</l>
</lg>
<lg>
<pb n="3" facs="tcp:0670901100:6"/>
<l>For, ah! not Touch of Wizard Wand,</l>
<l>Nor wild Romance from Legends old,</l>
<l>Nor moon-light Spell of Elfin Band,</l>
<l>Nor Spectre-Tales, by Poets told;</l>
</lg>
<lg>
<l>Nor Necromancer's magic Skill,</l>
<l>Whoſe Voice the <hi>Hero's</hi> Blood can chill;</l>
<l>Nor Knights, in terrible Array,</l>
<l>Did e'er ſuch wond'rous Acts diſplay,</l>
<l>As thoſe which late Britannia ſaw,</l>
<l>Her trembling Heart deep ſtruck with pious Awe,</l>
<l>Now to Agony oppreſt,</l>
<l>And now to Rapture bleſt,</l>
<l>When with her Parent King ſhe felt th' Almighty Rod,</l>
<l>And the reſtoring Arm, of Thee the LIVING GOD!</l>
</lg>
<lg>
<l>Yes, GOD of Gods! 'twas thine to try—</l>
<l>Judgment and Righteouſneſs thy Throne uphold,</l>
<l>Tho' Clouds and Darkneſs are around Thee roll'd,</l>
<l>—A choſen Nation's Sympathy.</l>
</lg>
<lg>
<pb n="4" facs="tcp:0670901100:7"/>
<l>Deſtiny thy dread Command,</l>
<l>As erſt in Iſrael's Land,</l>
<l>Obey'd, and came from Heav'n to prove,</l>
<l>A mighty People's Loyalty and Love.</l>
</lg>
<lg>
<l>Streaming oft from Beauty's Eye,</l>
<l>O filial Love! thy graceful Tear was ſeen,</l>
<l>Thy Pray'r was heard—and many a Sigh,</l>
<l>Broke from the faithful Boſom of a QUEEN:</l>
<l>From Breaſt to Breaſt the Softneſs ſtole,</l>
<l>And Sorrow touch'd the PRINCELY Soul;</l>
<l>PUBLIC ALLEGIANCE join'd the Pray'r,</l>
<l>With FEALTY unchang'd, amidſt ſevere Deſpair!</l>
</lg>
<lg>
<l>
<hi>Then,</hi> LIVING GOD, 'twas Thine to prove,</l>
<l>By Grief ſincere, an Empire's Love!</l>
<l>Thine by Adverſity to try,</l>
<l>A mighty People's Loyalty.</l>
<l>
<pb n="5" facs="tcp:0670901100:8"/>And who, Thou GOD of Gods, ſave Thee, can tell,</l>
<l>How Albion to her inmoſt Heart was cheer'd;</l>
<l>Ah! who but Thou her Extacy reveal,</l>
<l>When thy RESTORING CHERUBIM appear'd?</l>
</lg>
<lg>
<l>Not Egypt's ſuff'ring Tribe of yore,</l>
<l>Plague-ſtruck, a keener Anguiſh bore,</l>
<l>When, with our Parent King, we felt th' Almighty Rod;</l>
<l>Nor ſuch ſoul-born Tranſport knew,</l>
<l>In the Hour the Peſt withdrew,</l>
<l>As when that King was ſav'd by Thee the LIVING GOD!</l>
</lg>
<lg>
<l>Strike the Lyre to bliſsful Meaſure,</l>
<l>Albion holds once more her Treaſure;</l>
<l>Brunſwick's illuſtrious Star now ſhines again!</l>
<l>Let the Notes thro' Earth reſound,</l>
<l>Waft them, triumphant Winds, acroſs the Main,</l>
<l>'Till ev'ry Land returns the Sound:</l>
<l>
<pb n="6" facs="tcp:0670901100:9"/>For ev'ry Land—O Theme without Alloy!—</l>
<l>
<hi>In one full Chorus joins Britannia's Joy!</hi>
</l>
</lg>
<lg>
<l>Now ſwell the Chords, and in ſublimer Numbers own,</l>
<l>The mighty Bleſſing comes from Heaven alone!</l>
</lg>
<lg>
<l>Avaunt! ye Deities <hi>profane,</hi>
</l>
<l>And all ye ſhadowy Powers;</l>
<l>Imagination's airy Train,</l>
<l>That dwell in fabled Bowers!</l>
</lg>
<lg>
<l>We know 'tis GOD, the LIVING GOD that giveth</l>
<l>To our Pray'rs a Parent King;</l>
<l>We know, we know, that "OUR REDEEMER liveth,"</l>
<l>TO HIM—the MIGHTY ONE we ſing!</l>
</lg>
<lg>
<l>O for the heav'n-inſtructed David's Lyre!</l>
<l>O for the wrapt Iſaiah's hallow'd Fire!</l>
<l>
<pb n="7" facs="tcp:0670901100:10"/>That ſo the ſacred <hi>Airs</hi> of Harmony may riſe,</l>
<l>And waft a Nation's Incenſe to the Skies,</l>
<l>'Till Angels catch the Strain, and with Arch-angels ſing,</l>
<l>GLORY TO GOD ON HIGH—TO HEAV'N'S ETERNAL KING!</l>
</lg>
<trailer>THE END.</trailer>
</div>
</body>
</text>
</TEI>
| {'content_hash': '0dfd35e308002f93116d1384ab85f54f', 'timestamp': '', 'source': 'github', 'line_count': 244, 'max_line_length': 878, 'avg_line_length': 59.90163934426229, 'alnum_prop': 0.5742337164750958, 'repo_name': 'benjaminpauley/RBSDigitalApproaches', 'id': 'd17432aa8d97a808a1e9506ef2a4c1a5fc7edd67', 'size': '14710', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'TCP-texts/K069565.000.xml', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '125733'}, {'name': 'Python', 'bytes': '2798'}]} |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="msvalidate.01" content="C3BF2C67B92C75F2DEAA096973652038" />
<link rel="shortcut icon" href="http://www.apiman.io/latest/resources/images/favicon.ico">
<title>Re-Publishing Your API(s) | apiman Open Source API Management</title>
<meta name="description" content="An early design decision we made in apiman was to not allow APIs to bere-published to the Gateway. The reasoning was that Client Apps may haveestablished Co...">
<!-- CSS -->
<link href="http://www.apiman.io/latest/resources/bootstrap-3.3.0/css/bootstrap.min.css" rel="stylesheet">
<link href="http://www.apiman.io/latest/resources/patternfly-1.0.5/css/patternfly.min.css" rel="stylesheet">
<link href="http://static.jboss.org/css/rhbar.css" media="screen" rel="stylesheet">
<link href="http://www.apiman.io/latest/resources/css/apiman-web.css?v=1.2.7.Final" rel="stylesheet">
<link href="http://www.apiman.io/latest/resources/css/apiman-web.responsive.css?v=1.2.7.Final" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet">
<link href="/blog/css/highlight.css" rel="stylesheet">
<link href="/blog/css/main.css" rel="stylesheet">
<link href="/blog/css/coderay-asciidoctor.css" rel="stylesheet">
<!-- Scripts -->
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
<script src="http://www.apiman.io/latest/resources/jquery-1.11.1/js/jquery.min.js"></script>
<script src="http://www.apiman.io/latest/resources/bootstrap-3.3.0/js/bootstrap.min.js"></script>
<script id="dsq-count-scr" src="//apiman.disqus.com/count.js" async></script>
<!-- Canonical URL -->
<link rel="canonical" href="http://apiman.io/blog/apiman/1.2.x/gateway/2016/02/24/republishing.html">
<link rel="alternate" type="application/rss+xml" title="apiman Blog | Open Source API Management" href="http://apiman.io/blog/feed.xml" />
<!-- Google Analytics -->
<script>
$(document).ready(function() {
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-56678850-1', 'auto');
ga('send', 'pageview');
});
</script>
</head>
<body class="blog">
<div id="rhbar">
<a class="jbdevlogo" href="http://www.jboss.org/projects/about" rel="nofollow" target="_blank"></a>
<a class="rhlogo" href="http://www.redhat.com/" rel="nofollow" target="_blank"></a>
</div>
<nav id="top-nav" class="navbar navbar-inverse" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="http://www.apiman.io/latest/index.html">apiman</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav navbar-right">
<li class="top-menu-item menu-item"><a href="http://www.apiman.io/latest/index.html">Overview</a></li>
<li class="top-menu-item menu-item"><a href="http://www.apiman.io/latest/download.html">Download</a></li>
<li class="top-menu-item menu-item"><a href="http://www.apiman.io/latest/roadmap.html">Roadmap</a></li>
<li class="top-menu-item menu-item active"><a href="http://www.apiman.io/blog/">Blog</a></li>
<li class="top-menu-item menu-item dropdown">
<a href="" class="dropdown-toggle" data-toggle="dropdown">Get Involved<b class="caret"></b></a>
<ul class="dropdown-menu">
<li class="menu-item">
<a href="https://issues.jboss.org/browse/APIMAN">Report a Bug</a>
</li>
<li class="menu-item">
<a href="http://www.apiman.io/latest/chat.html">Chat on IRC</a>
</li>
<li class="menu-item">
<a href="https://twitter.com/apiman_io" rel="nofollow" target="_blank">Twitter Feed</a>
</li>
<li class="menu-item">
<a href="https://lists.jboss.org/mailman/listinfo/apiman-user" rel="nofollow" target="_blank">Mailing List</a>
</li>
<li class="divider"></li>
<li class="menu-item">
<a href="http://www.apiman.io/latest/contributors.html">Contributors List</a>
</li>
</ul>
</li>
<li class="top-menu-item menu-item dropdown">
<a href="" class="dropdown-toggle" data-toggle="dropdown">Learn More<b class="caret"></b></a>
<ul class="dropdown-menu">
<li class="menu-item">
<a href="http://www.apiman.io/latest/tutorials.html">Tutorials & Walkthroughs</a>
</li>
<li class="menu-item">
<a href="http://www.apiman.io/latest/crash-course.html">Crash Course!</a>
</li>
<li class="divider"></li>
<li class="menu-item">
<a href="http://www.apiman.io/latest/installation-guide.html">Installation Guide</a>
</li>
<li class="menu-item">
<a href="http://www.apiman.io/latest/user-guide.html">User Guide</a>
</li>
<li class="menu-item">
<a href="http://www.apiman.io/latest/developer-guide.html">Developer Guide</a>
</li>
<li class="menu-item">
<a href="http://www.apiman.io/latest/production-guide.html">Production Guide</a>
</li>
<li class="divider"></li>
<li class="menu-item">
<a href="http://www.apiman.io/latest/api-manager-restdocs.html">API Manager REST Endpoints</a>
</li>
</ul>
</li>
</ul>
</div><!--/.nav-collapse -->
</div>
</nav>
<div class="container" id="blog">
<div class="blog-content">
<div class="post">
<header class="post-header" style="margin-top: 25px">
<h1 style="color: #666; font-weight: bold" class="post-title section-header">Re-Publishing Your API(s)</h1>
<span style="color: #243446; font-size: 13px"><i class="fa fa-calendar"></i> Feb 24, 2016</span>
<span style="color: #243446; margin-left: 15px; font-size: 13px"><i class="fa fa-user"></i> <a href="https://www.github.com/ericwittmann">Eric Wittmann</a></span>
<span style="color: #243446; margin-left: 15px; font-size: 13px"><i class="fa fa-tags"></i> apiman, 1.2.x, and gateway</span>
</header>
<article class="post-content"
style="margin-top: 20px; font-size: 14px; line-height: 20px">
<p>An early design decision we made in apiman was to not allow APIs to be
re-published to the Gateway. The reasoning was that Client Apps may have
established Contracts with the API, and thus have agreed to specific terms
and conditions (whether implicit or explicit). Therefore, we shouldn’t
allow the API provider to modify those terms and re-publish the API, as it
may violate the agreement.</p>
<p>However, we later added the concept of a Public API, which allows any
client to invoke it without first creating a Contract. It is clear that
API providers should be able to re-publish a Public API (presumably after
changing the API’s configuration).</p>
<!--more-->
<h2 id="when-can-i-re-publish">When Can I Re-Publish?</h2>
<p>An API can be re-published to the Gateway when the following criteria is
met:</p>
<ul>
<li>It is a Public API</li>
<li>The API is in the <em>Published</em> state</li>
<li>The API has been modified in some way</li>
</ul>
<p>Additionally, if the Public API has been retired (is currently in the
<em>Retired</em> state) then the user can Re-Publish it regardless of whether
it has since been modified.</p>
<h2 id="how-do-i-re-publish">How Do I Re-Publish?</h2>
<p>When an API meets the above criteria, a <strong>Re-Publish</strong> button will be
available in the user interface (right where the “Publish” button is
typically located).</p>
<p><img src="/blog/images/2016-02-24/re-publish.png" alt="Image: Republish Button" /></p>
<p>As soon as you’re comfortable with the changes you’ve made to your API,
simply click the button and you should be all set!</p>
<h2 id="why-is-there-still-versioning">Why Is There Still Versioning?</h2>
<p>This feature does not take the place of API versioning. Versioning
is still very important because you may want to publish multiple
versions of the same API at the same time (for example, if you
actually need to support multiple versions of a live API). In
addition, if an API is not public, then you will still need to
use versioning if you want to change the policy configuration for
your API.</p>
<h2 id="conclusion">Conclusion</h2>
<p>As always, a goal of apiman is to make the system as easy to use as
possible, while still being useful and powerful. We think that this
approach is a reasonable compromise. You still can’t re-publish an
API if there are established Contracts with Client Apps, but if you’re
only using Public APIs, then there’s no reason to prevent changes from
being republished!</p>
<p>/post</p>
</article>
<div id="disqus_thread"></div>
<script>
var disqus_config = function () {
this.page.url = '';
this.page.identifier = '/apiman/1.2.x/gateway/2016/02/24/republishing';
};
(function() { // DON'T EDIT BELOW THIS LINE
var d = document, s = d.createElement('script');
s.src = '//apiman.disqus.com/embed.js';
s.setAttribute('data-timestamp', +new Date());
(d.head || d.body).appendChild(s);
})();
</script>
<noscript>Please enable JavaScript to view the <a href="https://disqus.com/?ref_noscript" rel="nofollow">comments powered by Disqus.</a></noscript>
</div>
</div>
<div class="blog-footer">
<footer role="contentinfo">
<div id="inner-footer" class="clearfix row">
<div id="widget-footer" class="clearfix">
<hr>
<div class="widget col-sm-6 col-md-6 widget_text">
<div class="textwidget">
<p>
Copyright © 2017 Red Hat, Inc. All rights reserved.<br>
apiman code is open source and released under <a href="http://www.apache.org/licenses/LICENSE-2.0.html" rel="nofollow" target="_blank">Apache License, v2.0</a>.<br>
<a href="/latest/disclosure.html">Open Source Disclosure</a>
</p>
</div>
</div>
<div class="widget col-sm-6 col-md-6 widget_text" style="text-align: right">
<a href="http://www.redhat.com" rel="nofollow" target="_blank"><img src="http://static.jboss.org/theme/images/common/redhat_logo.png" alt="Red Hat"></a>
</div>
</div>
<nav class="clearfix"></nav>
</div>
<!-- Adobe Analytics -->
<script src="//www.redhat.com/j/s_code.js" />
<script>
/**
* Adobe Analytics
*
* Variables reported to Adobe Analytics:
* -pageName
* -server
* -channel
* -first minor section
* -second minor section (if available)
* -third minor section (if available)
* -full URL (domain + path + query string)
* -base URL (domain + path)
* -language
* -country
*
*/
/**
* Additional JS files to be loaded BEFORE adobe-analytics.js:
*
* - http://www.redhat.com/j/s_code.js
*
* Additional JS files to be loaded AFTER adobe-analytics.js
*
* - http://www.redhat.com/j/rh_omni_footer.js
*/
(function() {
// Load the path name, without its initial /
var arr = location.pathname.substr(1, location.pathname.length).toLowerCase().split('/');
// If the path ends in index.html or whitespace, trim the array
if (arr[arr.length - 1] == "index.html" || arr[arr.length - 1] == "" ) {
arr.pop();
}
/*
* Assign values to Adobe Analytics properties
*/
s.channel = "apiman | "; // The channel is our top level classification
s.server = "apiman"; // The server is ???
s.pageName = "apiman | | " + (arr[arr.length -1] || "homepage"); // pageName is apiman | <Channel> | {page_name}. {page_name} has index.html removed
s.prop2 = s.eVar22 = "en"; // prop2/eVar22 is the ISO 639-1 language code
s.prop4 = s.eVar23 = encodeURI(location.search); //prop4/eVar23 is the query string of the page
// Pad the array as needed, so we can shift away later
for (var i = arr.length; i < 3; i++) {
arr[i] = "";
}
s.prop14 = s.eVar27 = arr.shift(); // prop14/eVar27 is the first minor section (normally /{minor_section_1})
s.prop15 = s.eVar28 = arr.shift(); // prop15/eVar28 is the second minor section (normally /a/{minor_section_2})
s.prop16 = s.eVar29 = arr.shift(); // prop16/eVar29 is the third minor section (normally /a/b/{minor_section_3})
s.prop21 = s.eVar18 = encodeURI(location.hostname+location.pathname).toLowerCase(); // prop21/eVar18 is the URL, less any query strings or fragments
})();
</script>
<script src="//www.redhat.com/assets/js/tracking/rh_omni_footer.js"/>
</footer>
</div>
</div>
</body>
</html>
| {'content_hash': '7f1948cfbe0cac1ca57c1f703b5894cc', 'timestamp': '', 'source': 'github', 'line_count': 324, 'max_line_length': 198, 'avg_line_length': 45.08641975308642, 'alnum_prop': 0.6057639649507119, 'repo_name': 'msavy/apiman.github.io', 'id': 'dfe0b6335c19c16f32698c1f404e40bb89ca168a', 'size': '14626', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'blog/apiman/1.2.x/gateway/2016/02/24/republishing.html', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '370572'}, {'name': 'HTML', 'bytes': '2816865'}, {'name': 'JavaScript', 'bytes': '1288764'}, {'name': 'Ruby', 'bytes': '7627'}, {'name': 'Shell', 'bytes': '862'}]} |
Features:
* Active Record relations (N:1 - Product/Categories, N:N - Product/Tags, N:N Products/Orders)
* Dynamic list in forms (Adding tags to products)
* Conditional validation (Product's discount depends on product's price)
* Concers (Indexable, Loggable)
* Embeded forms (Editing catgories from product's form)
* Helpers (product helper)
* Subscribers (LogSubscriber)
* Factory Girl (test/fixtures), Faker gem
* Testing (test/), shoulda gem, database cleaner gem
* Byebug gem
* Better errors gem
* Cucumber (features/)
* Database seeds
* Generating excel spreadsheets
* Localizations (i18n, l10n)
* Routing (resources + regular expressions)
* Devise, CanCan + abilities (https://github.com/ryanb/cancan/wiki/authorizing-controller-actions)
* Capistrano
* Custom Rake tasks: http://railsguides.net/how-to-generate-rake-task/, http://cobwwweb.com/how-to-write-a-custom-rake-task
| {'content_hash': '1911521ce4c35aab1f35b319ac337db8', 'timestamp': '', 'source': 'github', 'line_count': 22, 'max_line_length': 123, 'avg_line_length': 41.13636363636363, 'alnum_prop': 0.7436464088397791, 'repo_name': 'factorlabs/rails-ecommerce', 'id': 'cf5d2a09b720787f5f3d92bb0b2dafba15e3b38a', 'size': '905', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'README.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '2071'}, {'name': 'CoffeeScript', 'bytes': '422'}, {'name': 'Gherkin', 'bytes': '225'}, {'name': 'HTML', 'bytes': '11243'}, {'name': 'JavaScript', 'bytes': '661'}, {'name': 'Ruby', 'bytes': '79554'}]} |
package edu.kpi.comsys.dis.lab.services.exceptions;
public class StoryNotFoundException extends EntityNotFoundException {
private final Long storyId;
public StoryNotFoundException(Long storyId) {
super("Story with id \"" + storyId + "\" not found");
this.storyId = storyId;
}
public StoryNotFoundException(String message, Long storyId) {
super(message);
this.storyId = storyId;
}
public StoryNotFoundException(String message, Throwable cause, Long storyId) {
super(message, cause);
this.storyId = storyId;
}
public StoryNotFoundException(Throwable cause, Long storyId) {
super("Story with id \"" + storyId + "\" not found", cause);
this.storyId = storyId;
}
public Long getStoryId() {
return storyId;
}
}
| {'content_hash': 'b5c3ae63095fae873a5c595d95d82ea3', 'timestamp': '', 'source': 'github', 'line_count': 31, 'max_line_length': 82, 'avg_line_length': 26.741935483870968, 'alnum_prop': 0.6513872135102533, 'repo_name': 'NightmaresSeller/dis-lab-work-samples', 'id': '16bbf24be5bb764c536c1df90e1c6b37e6511097', 'size': '829', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'spring-data/src/main/java/edu/kpi/comsys/dis/lab/services/exceptions/StoryNotFoundException.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '92492'}]} |
<?xml version="1.0" encoding="UTF-8"?>
<?eclipse version="3.0"?>
<!--
~ Licensed to the Apache Software Foundation (ASF) under one or more
~ contributor license agreements. See the NOTICE file distributed with
~ this work for additional information regarding copyright ownership.
~ The ASF licenses this file to You under the Apache License, Version 2.0
~ (the "License"); you may not use this file except in compliance with
~ the License. You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing, software
~ distributed under the License is distributed on an "AS IS" BASIS,
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
~ See the License for the specific language governing permissions and
~ limitations under the License.
-->
<!-- $Rev$ $Date$ -->
<plugin>
<extension point="org.apache.geronimo.st.ui.loader">
<loader class="org.apache.geronimo.st.v21.ui.editors.GeronimoFormContentLoader" version="2.2"/>
</extension>
<!--
|
| Map the action defined for the "Geronimo Deployment" project-facet to a specific class
|
-->
<extension point="org.eclipse.wst.common.project.facet.ui.wizardPages">
<wizard-pages action="geronimo.plan.install.v22">
<page class="org.apache.geronimo.st.v21.ui.wizards.FacetInstallPage"/>
</wizard-pages>
</extension>
</plugin>
| {'content_hash': '67c12888e19d2b24ad235718ba19c616', 'timestamp': '', 'source': 'github', 'line_count': 39, 'max_line_length': 103, 'avg_line_length': 38.43589743589744, 'alnum_prop': 0.6911274182788526, 'repo_name': 'apache/geronimo-devtools', 'id': '9c950fc565d1d151a088caf8c8a09d09efedd773', 'size': '1499', 'binary': False, 'copies': '2', 'ref': 'refs/heads/trunk', 'path': 'plugins/org.apache.geronimo.st.v22.ui/plugin.xml', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '1057218'}]} |
package org.wso2.cep.integration.common.utils;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.impl.builder.StAXOMBuilder;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.simple.parser.JSONParser;
import org.wso2.appserver.integration.common.clients.*;
import org.wso2.carbon.automation.engine.context.AutomationContext;
import org.wso2.carbon.automation.engine.context.TestUserMode;
import org.wso2.carbon.automation.engine.frameworkutils.FrameworkPathUtil;
import org.wso2.carbon.integration.common.utils.LoginLogoutClient;
import org.wso2.carbon.integration.common.utils.mgt.ServerConfigurationManager;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import javax.xml.xpath.XPathExpressionException;
import java.io.*;
import java.util.regex.Matcher;
public abstract class CEPIntegrationTest {
private static final Log log = LogFactory.getLog(CEPIntegrationTest.class);
protected AutomationContext cepServer;
protected String backendURL;
protected ConfigurationUtil configurationUtil;
protected EventProcessorAdminServiceClient eventProcessorAdminServiceClient;
protected EventStreamManagerAdminServiceClient eventStreamManagerAdminServiceClient;
protected EventReceiverAdminServiceClient eventReceiverAdminServiceClient;
protected EventPublisherAdminServiceClient eventPublisherAdminServiceClient;
protected ExecutionManagerAdminServiceClient executionManagerAdminServiceClient;
protected EventSimulatorAdminServiceClient eventSimulatorAdminServiceClient;
protected void init() throws Exception {
init(TestUserMode.SUPER_TENANT_ADMIN);
}
protected void init(TestUserMode testUserMode) throws Exception {
cepServer = new AutomationContext("CEP", testUserMode);
configurationUtil = ConfigurationUtil.getConfigurationUtil();
backendURL = cepServer.getContextUrls().getBackEndUrl();
}
protected String getSessionCookie() throws Exception {
LoginLogoutClient loginLogoutClient = new LoginLogoutClient(cepServer);
return loginLogoutClient.login();
}
protected void cleanup() {
cepServer = null;
configurationUtil = null;
}
protected String getServiceUrl(String serviceName) throws XPathExpressionException {
return cepServer.getContextUrls().getServiceUrl() + "/" + serviceName;
}
protected String getServiceUrlHttps(String serviceName) throws XPathExpressionException {
return cepServer.getContextUrls().getSecureServiceUrl() + "/" + serviceName;
}
protected String getTestArtifactLocation() {
return FrameworkPathUtil.getSystemResourceLocation();
}
protected void gracefullyRestartServer() throws Exception {
ServerConfigurationManager serverConfigurationManager = new ServerConfigurationManager(cepServer);
serverConfigurationManager.restartGracefully();
}
/**
* @param testCaseFolderName Name of the folder created under /artifacts/CEP for the particular test case.
* @param configFileName Name of the XML config-file created under above folder.
* @return The above XML-configuration, as a string
* @throws Exception
*/
protected String getXMLArtifactConfiguration(String testCaseFolderName, String configFileName)
throws Exception {
String relativeFilePath = getTestArtifactLocation() + "/artifacts/CEP/"+testCaseFolderName+"/"+configFileName;
relativeFilePath = relativeFilePath.replaceAll("[\\\\/]", Matcher.quoteReplacement(File.separator));
OMElement configElement = loadClasspathResourceXML(relativeFilePath);
return configElement.toString();
}
/**
* @param testCaseFolderName testCaseFolderName Name of the folder created under /artifacts/CEP for the particular test case.
* @param configFileName Name of the JSON config-file created under above folder.
* @return The above JSON-configuration, as a string
* @throws Exception
*/
protected String getJSONArtifactConfiguration(String testCaseFolderName, String configFileName)
throws Exception {
String relativeFilePath = getTestArtifactLocation() + "/artifacts/CEP/"+testCaseFolderName+"/"+configFileName;
relativeFilePath = relativeFilePath.replaceAll("[\\\\/]", Matcher.quoteReplacement(File.separator));
JSONParser jsonParser = new JSONParser();
return jsonParser.parse(new FileReader(relativeFilePath)).toString();
}
/**
* Returns the execution plan, read from the given file path.
* @param testCaseFolderName testCaseFolderName Name of the folder created under /artifacts/CEP for the particular test case.
* @param executionPlanFileName Execution plan file name, relative to the test artifacts folder.
* @return execution plan as a string.
* @throws Exception
*/
protected String getExecutionPlanFromFile(String testCaseFolderName, String executionPlanFileName)
throws Exception {
String relativeFilePath = getTestArtifactLocation() + "/artifacts/CEP/"+testCaseFolderName+"/"+executionPlanFileName;
relativeFilePath = relativeFilePath.replaceAll("[\\\\/]", Matcher.quoteReplacement(File.separator));
return ConfigurationUtil.readFile(relativeFilePath) ;
}
public OMElement loadClasspathResourceXML(String path) throws FileNotFoundException, XMLStreamException {
OMElement documentElement = null;
FileInputStream inputStream = null;
XMLStreamReader parser = null;
StAXOMBuilder builder = null;
File file = new File(path);
if (file.exists()) {
try {
inputStream = new FileInputStream(file);
parser = XMLInputFactory.newInstance().createXMLStreamReader(inputStream);
//create the builder
builder = new StAXOMBuilder(parser);
//get the root element (in this case the envelope)
documentElement = builder.getDocumentElement().cloneOMElement();
} finally {
if (builder != null) {
builder.close();
}
if (parser != null) {
try {
parser.close();
} catch (XMLStreamException e) {
//ignore
}
}
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
//ignore
}
}
}
} else {
throw new FileNotFoundException("File does not exist at " + path);
}
return documentElement;
}
}
| {'content_hash': '591a42cda8102ee2fededeb63deae611', 'timestamp': '', 'source': 'github', 'line_count': 156, 'max_line_length': 129, 'avg_line_length': 44.33974358974359, 'alnum_prop': 0.7001590284805551, 'repo_name': 'manoramahp/product-cep', 'id': '25eb2c9ecca2c66a6723a806ffd9e3f4058777c9', 'size': '7557', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'modules/integration/tests-common/integration-test-utils/src/main/java/org/wso2/cep/integration/common/utils/CEPIntegrationTest.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '9422'}, {'name': 'CSS', 'bytes': '153211'}, {'name': 'HTML', 'bytes': '62982'}, {'name': 'Handlebars', 'bytes': '2864'}, {'name': 'Java', 'bytes': '753672'}, {'name': 'JavaScript', 'bytes': '2525120'}, {'name': 'Shell', 'bytes': '13293'}]} |
title: Cloudcraft - visualise AWS environment as isometric architecture diagrams
date: 2018-08-14 10:05:03
tags:
---

References
----------
* CloudCraft, <https://cloudcraft.co/> | {'content_hash': '16e2ff3c21898a3cbb0c75f799bf2762', 'timestamp': '', 'source': 'github', 'line_count': 11, 'max_line_length': 150, 'avg_line_length': 30.09090909090909, 'alnum_prop': 0.7613293051359517, 'repo_name': 'TerrenceMiao/blog', 'id': '93b775bd7d0633488753d18a2b9be5c30304e5f5', 'size': '335', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'source/_posts/Cloudcraft-visualise-AWS-environment-as-isometric-architecture-diagrams.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '3182'}, {'name': 'EJS', 'bytes': '12518'}, {'name': 'JavaScript', 'bytes': '25679'}, {'name': 'Pug', 'bytes': '29989'}, {'name': 'Stylus', 'bytes': '52711'}]} |
/*!
* Fancytree "awesome" skin.
*
* DON'T EDIT THE CSS FILE DIRECTLY, since it is automatically generated from
* the LESS templates.
*/
/*******************************************************************************
* Common Styles for Fancytree Skins.
*
* This section is automatically generated from the `skin-common.less` template.
******************************************************************************/
/*------------------------------------------------------------------------------
* Helpers
*----------------------------------------------------------------------------*/
.ui-helper-hidden {
display: none;
}
/*------------------------------------------------------------------------------
* Container and UL / LI
*----------------------------------------------------------------------------*/
ul.fancytree-container {
font-family: tahoma, arial, helvetica;
font-size: 10pt;
white-space: nowrap;
padding: 3px;
margin: 0;
background-color: white;
border: 1px dotted gray;
overflow: auto;
min-height: 0%;
position: relative;
}
ul.fancytree-container ul {
padding: 0 0 0 16px;
margin: 0;
}
ul.fancytree-container ul > li:before {
content: none;
}
ul.fancytree-container li {
list-style-image: none;
list-style-position: outside;
list-style-type: none;
-moz-background-clip: border;
-moz-background-inline-policy: continuous;
-moz-background-origin: padding;
background-attachment: scroll;
background-color: transparent;
background-position: 0em 0em;
background-repeat: repeat-y;
background-image: none;
margin: 0;
}
ul.fancytree-container li.fancytree-lastsib {
background-image: none;
}
ul.fancytree-no-connector > li {
background-image: none;
}
.ui-fancytree-disabled ul.fancytree-container {
opacity: 0.5;
background-color: silver;
}
/*------------------------------------------------------------------------------
* Common icon definitions
*----------------------------------------------------------------------------*/
span.fancytree-empty,
span.fancytree-vline,
span.fancytree-expander,
span.fancytree-icon,
span.fancytree-checkbox,
span.fancytree-radio,
span.fancytree-drag-helper-img,
#fancytree-drop-marker {
width: 1em;
height: 1em;
display: inline-block;
vertical-align: top;
background-repeat: no-repeat;
background-position: left;
background-position: 0em 0em;
}
span.fancytree-icon,
span.fancytree-checkbox,
span.fancytree-expander,
span.fancytree-radio,
span.fancytree-custom-icon {
margin-top: 0px;
}
/* Used by icon option: */
span.fancytree-custom-icon {
width: 1em;
height: 1em;
display: inline-block;
margin-left: 0.5em;
background-position: 0em 0em;
}
/* Used by 'icon' node option: */
img.fancytree-icon {
width: 1em;
height: 1em;
margin-left: 0.5em;
margin-top: 0px;
vertical-align: top;
border-style: none;
}
/*------------------------------------------------------------------------------
* Expander icon
*
* Note: IE6 doesn't correctly evaluate multiples class names,
* so we create combined class names that can be used in the CSS.
*
* Prefix: fancytree-exp-
* 1st character: 'e': expanded, 'c': collapsed, 'n': no children
* 2nd character (optional): 'd': lazy (Delayed)
* 3rd character (optional): 'l': Last sibling
*----------------------------------------------------------------------------*/
span.fancytree-expander {
cursor: pointer;
}
.fancytree-exp-n span.fancytree-expander,
.fancytree-exp-nl span.fancytree-expander {
background-image: none;
cursor: default;
}
/* Fade out expanders, when container is not hovered or active */
.fancytree-fade-expander span.fancytree-expander {
transition: opacity 1.5s;
opacity: 0;
}
.fancytree-fade-expander:hover span.fancytree-expander,
.fancytree-fade-expander.fancytree-treefocus span.fancytree-expander,
.fancytree-fade-expander .fancytree-treefocus span.fancytree-expander,
.fancytree-fade-expander [class*='fancytree-statusnode-'] span.fancytree-expander {
transition: opacity 0.6s;
opacity: 1;
}
/*------------------------------------------------------------------------------
* Checkbox icon
*----------------------------------------------------------------------------*/
span.fancytree-checkbox {
margin-left: 0.5em;
}
.fancytree-unselectable span.fancytree-checkbox {
opacity: 0.4;
filter: alpha(opacity=40);
}
/*------------------------------------------------------------------------------
* Radiobutton icon
* This is a customization, that may be activated by overriding the 'checkbox'
* class name as 'fancytree-radio' in the tree options.
*----------------------------------------------------------------------------*/
/*------------------------------------------------------------------------------
* Node type icon
* Note: IE6 doesn't correctly evaluate multiples class names,
* so we create combined class names that can be used in the CSS.
*
* Prefix: fancytree-ico-
* 1st character: 'e': expanded, 'c': collapsed
* 2nd character (optional): 'f': folder
*----------------------------------------------------------------------------*/
span.fancytree-icon {
margin-left: 0.5em;
}
/* Documents */
/* Folders */
.fancytree-loading span.fancytree-expander,
.fancytree-loading span.fancytree-expander:hover,
.fancytree-statusnode-loading span.fancytree-icon,
.fancytree-statusnode-loading span.fancytree-icon:hover {
background-image: url("loading.gif");
}
/* Status node icons */
/*------------------------------------------------------------------------------
* Node titles and highlighting
*----------------------------------------------------------------------------*/
span.fancytree-node {
/* See #117 */
display: inherit;
width: 100%;
margin-top: 1px;
min-height: 1em;
}
span.fancytree-title {
color: black;
cursor: pointer;
display: inline-block;
vertical-align: top;
min-height: 1em;
padding: 0 3px 0 3px;
margin: 0px 0 0 0.5em;
border: 1px solid transparent;
-webkit-border-radius: 0px;
-moz-border-radius: 0px;
-ms-border-radius: 0px;
-o-border-radius: 0px;
border-radius: 0px;
}
span.fancytree-node.fancytree-error span.fancytree-title {
color: red;
}
/*------------------------------------------------------------------------------
* Drag'n'drop support
*----------------------------------------------------------------------------*/
div.fancytree-drag-helper span.fancytree-childcounter,
div.fancytree-drag-helper span.fancytree-dnd-modifier {
display: inline-block;
color: #fff;
background: #337ab7;
border: 1px solid gray;
min-width: 10px;
height: 10px;
line-height: 1;
vertical-align: baseline;
border-radius: 10px;
padding: 2px;
text-align: center;
font-size: 9px;
}
div.fancytree-drag-helper span.fancytree-childcounter {
position: absolute;
top: -6px;
right: -6px;
}
div.fancytree-drag-helper span.fancytree-dnd-modifier {
background: #5cb85c;
border: none;
font-weight: bolder;
}
/*** Drop marker icon *********************************************************/
#fancytree-drop-marker {
width: 2em;
position: absolute;
margin: 0;
}
#fancytree-drop-marker.fancytree-drop-after,
#fancytree-drop-marker.fancytree-drop-before {
width: 4em;
}
/*** Source node while dragging ***********************************************/
span.fancytree-drag-source.fancytree-drag-remove {
opacity: 0.15;
}
/*** Target node while dragging cursor is over it *****************************/
/*------------------------------------------------------------------------------
* 'table' extension
*----------------------------------------------------------------------------*/
table.fancytree-ext-table {
border-collapse: collapse;
}
table.fancytree-ext-table span.fancytree-node {
display: inline-block;
box-sizing: border-box;
}
/*------------------------------------------------------------------------------
* 'columnview' extension
*----------------------------------------------------------------------------*/
table.fancytree-ext-columnview tbody tr td {
position: relative;
border: 1px solid gray;
vertical-align: top;
overflow: auto;
}
table.fancytree-ext-columnview tbody tr td > ul {
padding: 0;
}
table.fancytree-ext-columnview tbody tr td > ul li {
list-style-image: none;
list-style-position: outside;
list-style-type: none;
-moz-background-clip: border;
-moz-background-inline-policy: continuous;
-moz-background-origin: padding;
background-attachment: scroll;
background-color: transparent;
background-position: 0em 0em;
background-repeat: repeat-y;
background-image: none;
/* no v-lines */
margin: 0;
}
table.fancytree-ext-columnview span.fancytree-node {
position: relative;
/* allow positioning of embedded spans */
display: inline-block;
}
table.fancytree-ext-columnview span.fancytree-node.fancytree-expanded {
background-color: #CBE8F6;
}
table.fancytree-ext-columnview .fancytree-has-children span.fancytree-cv-right {
position: absolute;
right: 3px;
}
/*------------------------------------------------------------------------------
* 'filter' extension
*----------------------------------------------------------------------------*/
.fancytree-ext-filter-dimm span.fancytree-node span.fancytree-title {
color: silver;
font-weight: lighter;
}
.fancytree-ext-filter-dimm tr.fancytree-submatch span.fancytree-title,
.fancytree-ext-filter-dimm span.fancytree-node.fancytree-submatch span.fancytree-title {
color: black;
font-weight: normal;
}
.fancytree-ext-filter-dimm tr.fancytree-match span.fancytree-title,
.fancytree-ext-filter-dimm span.fancytree-node.fancytree-match span.fancytree-title {
color: black;
font-weight: bold;
}
.fancytree-ext-filter-hide tr.fancytree-hide,
.fancytree-ext-filter-hide span.fancytree-node.fancytree-hide {
display: none;
}
.fancytree-ext-filter-hide tr.fancytree-submatch span.fancytree-title,
.fancytree-ext-filter-hide span.fancytree-node.fancytree-submatch span.fancytree-title {
color: silver;
font-weight: lighter;
}
.fancytree-ext-filter-hide tr.fancytree-match span.fancytree-title,
.fancytree-ext-filter-hide span.fancytree-node.fancytree-match span.fancytree-title {
color: black;
font-weight: normal;
}
.fancytree-ext-childcounter span.fancytree-icon,
.fancytree-ext-filter span.fancytree-icon {
position: relative;
}
.fancytree-ext-childcounter span.fancytree-childcounter,
.fancytree-ext-filter span.fancytree-childcounter {
color: #fff;
background: #777;
border: 1px solid gray;
position: absolute;
top: -6px;
right: -6px;
min-width: 10px;
height: 10px;
line-height: 1;
vertical-align: baseline;
border-radius: 10px;
padding: 2px;
text-align: center;
font-size: 9px;
}
/*------------------------------------------------------------------------------
* 'wide' extension
*----------------------------------------------------------------------------*/
ul.fancytree-ext-wide {
position: relative;
min-width: 100%;
z-index: 2;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
ul.fancytree-ext-wide span.fancytree-node > span {
position: relative;
z-index: 2;
}
ul.fancytree-ext-wide span.fancytree-node span.fancytree-title {
position: absolute;
z-index: 1;
left: 0px;
width: 100%;
margin-left: 0;
margin-right: 0;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
/*******************************************************************************
* Styles specific to this skin.
*
* This section is automatically generated from the `ui-fancytree.less` template.
******************************************************************************/
ul.fancytree-container ul {
padding: 0.3em 0 0 1em;
margin: 0;
} | {'content_hash': '3d21fbd7d92b3ab431e75f7adfed6041', 'timestamp': '', 'source': 'github', 'line_count': 380, 'max_line_length': 88, 'avg_line_length': 30.91578947368421, 'alnum_prop': 0.5680966973101804, 'repo_name': 'deevis/business_rules', 'id': '86597e69de966de57845ed8fa9a47ff938b6b65e', 'size': '11748', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'vendor/assets/stylesheets/fancytree-awesome.css', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '15030'}, {'name': 'HTML', 'bytes': '97324'}, {'name': 'JavaScript', 'bytes': '1852858'}, {'name': 'Ruby', 'bytes': '315630'}, {'name': 'Shell', 'bytes': '561'}]} |
import { applyPromoCodeRequest, getPromoCodesRequest, applyPromoCodeToScheduleRequest } from '../requests/coupons';
import { setScheduleAction, fetchingScheduleList } from './scheduleTutor';
import { getDashboardRequest } from './teacher';
import { pendingTask, begin, end } from 'react-redux-spinner';
import Alert from 'react-s-alert';
const setStatusRequestFalse = () => ({
type: 'SET_STATUS_REQUEST',
payload: false,
[ pendingTask ]: end,
});
const setStatusRequestTrue = () => ({
type: 'SET_STATUS_REQUEST',
payload: true,
[ pendingTask ]: begin,
});
const setCoupons = (coupons) => ({
type: 'SET_COUPONS',
payload: coupons,
});
const setCoupon = (coupon) => ({
type: 'SET_COUPON',
payload: coupon,
});
const reqApplyCode = (code) => {
return (dispatch) => {
dispatch(setStatusRequestTrue());
applyPromoCodeRequest(code)
.then(successReqApplyCode);
function successReqApplyCode(response) {
const msg = response && response.data && response.data.coupons;
dispatch(setCoupon(''));
if (msg) Alert.success(msg);
dispatch(setStatusRequestFalse());
dispatch(reqGetCoupons());
}
};
};
const reqApplyCodeToSchedule = (scheduleId, couponId) => {
return (dispatch) => {
dispatch(setStatusRequestTrue());
applyPromoCodeToScheduleRequest(scheduleId, couponId)
.then(successReqApplyCodeToSchedule);
function successReqApplyCodeToSchedule(response) {
const msg = response && response.data && response.data.coupons;
if (msg) {
Alert.success(msg);
dispatch(getDashboardRequest('student', null));
dispatch(fetchingScheduleList('student', '', 1));
dispatch(setScheduleAction({ action: '', scheduleId: '' }));
}
dispatch(setStatusRequestFalse());
dispatch(reqGetCoupons());
}
};
};
const reqGetCoupons = () => {
return (dispatch) => {
dispatch(setStatusRequestTrue());
getPromoCodesRequest()
.then(successReqGetCoupons);
function successReqGetCoupons({ data: { coupons } }) {
dispatch(setCoupons(coupons));
dispatch(setStatusRequestFalse());
}
};
};
export {
reqApplyCode,
reqGetCoupons,
setCoupon,
reqApplyCodeToSchedule,
};
| {'content_hash': '483e0e2da2e63049b5d2e7822e2f2c7e', 'timestamp': '', 'source': 'github', 'line_count': 84, 'max_line_length': 115, 'avg_line_length': 25.357142857142858, 'alnum_prop': 0.6995305164319249, 'repo_name': 'jlmonroy13/brainstutor-client', 'id': '7177c6a6170f204299a5b8f5a9ba6e469b81b8bf', 'size': '2130', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/actions/coupons.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '171857'}, {'name': 'HTML', 'bytes': '6677'}, {'name': 'JavaScript', 'bytes': '225340'}]} |
@class NSColor, NSMutableArray, NSString, SKBitmapFont, SKSpriteNode;
@interface SKLabelNode : SKNode
{
float _fontSize;
CDStruct_83984b6f _fontColor;
NSString *_fontName;
NSString *_text;
SKBitmapFont *_bmf;
NSMutableArray *_textSprites;
NSColor *_labelColor;
float _labelColorBlend;
long long _labelBlendMode;
SKSpriteNode *_textSprite;
long long _horizontalAlignmentMode;
long long _verticalAlignmentMode;
struct CGRect _textRect;
}
+ (id)labelNodeWithFontNamed:(id)arg1;
+ (id)labelNodeWithText:(id)arg1;
+ (id)_labelNodeWithFontTexture:(id)arg1 fontDataString:(id)arg2;
+ (id)_labelNodeWithFontNamed:(id)arg1;
- (id).cxx_construct;
- (void).cxx_destruct;
- (id)description;
@property(copy, nonatomic) NSString *text;
- (void)createSpritesForText;
- (void)_scaleFactorChangedFrom:(float)arg1 to:(float)arg2;
- (void)_flippedChangedFrom:(BOOL)arg1 to:(BOOL)arg2;
- (void)createBitmapSpritesForText;
- (struct CGRect)frame;
- (id)nodeAtPoint:(struct CGPoint)arg1 recursive:(BOOL)arg2;
- (id)nodesAtPoint:(struct CGPoint)arg1;
- (id)childrenInRect:(struct CGRect)arg1;
- (id)copyWithZone:(struct _NSZone *)arg1;
- (id)copy;
@property(nonatomic) long long blendMode;
@property(nonatomic) double colorBlendFactor;
@property(retain, nonatomic) NSColor *color;
@property(retain, nonatomic) NSColor *fontColor;
@property(nonatomic) double fontSize;
@property(copy, nonatomic) NSString *fontName;
@property(nonatomic) long long horizontalAlignmentMode;
@property(nonatomic) long long verticalAlignmentMode;
- (id)initWithFontNamed:(id)arg1;
- (void)encodeWithCoder:(id)arg1;
- (BOOL)isEqualToNode:(id)arg1;
- (id)initWithCoder:(id)arg1;
- (void)_initialize;
- (id)init;
- (id)_getTextSprites;
@end
| {'content_hash': 'e43b177e18e7c12843dcfca53d8a69cc', 'timestamp': '', 'source': 'github', 'line_count': 55, 'max_line_length': 69, 'avg_line_length': 31.8, 'alnum_prop': 0.7478559176672385, 'repo_name': 'wczekalski/Distraction-Free-Xcode-plugin', 'id': '0910d152e6dbd3e7c94bdbddbd667871b0c6bfef', 'size': '1918', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Archived/v1/WCDistractionFreeXcodePlugin/Headers/SharedFrameworks/SpriteKit/SKLabelNode.h', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '81011'}, {'name': 'C++', 'bytes': '588495'}, {'name': 'DTrace', 'bytes': '1835'}, {'name': 'Objective-C', 'bytes': '10151940'}, {'name': 'Ruby', 'bytes': '1105'}]} |
namespace gpopt
{
using namespace gpos;
//---------------------------------------------------------------------------
// @class:
// CXformSimplifySelectWithSubquery
//
// @doc:
// Simplify Select with subquery
//
//---------------------------------------------------------------------------
class CXformSimplifySelectWithSubquery : public CXformSimplifySubquery
{
private:
// private copy ctor
CXformSimplifySelectWithSubquery(const CXformSimplifySelectWithSubquery &);
public:
// ctor
explicit
CXformSimplifySelectWithSubquery
(
CMemoryPool *mp
)
:
// pattern
CXformSimplifySubquery
(
GPOS_NEW(mp) CExpression
(
mp,
GPOS_NEW(mp) CLogicalSelect(mp),
GPOS_NEW(mp) CExpression(mp, GPOS_NEW(mp) CPatternLeaf(mp)), // relational child
GPOS_NEW(mp) CExpression(mp, GPOS_NEW(mp) CPatternTree(mp)) // predicate tree
)
)
{}
// dtor
virtual
~CXformSimplifySelectWithSubquery()
{}
// Compatibility function for simplifying aggregates
virtual
BOOL FCompatible
(
CXform::EXformId exfid
)
{
return (CXform::ExfSimplifySelectWithSubquery != exfid);
}
// ident accessors
virtual
EXformId Exfid() const
{
return ExfSimplifySelectWithSubquery;
}
// return a string for xform name
virtual
const CHAR *SzId() const
{
return "CXformSimplifySelectWithSubquery";
}
// is transformation a subquery unnesting (Subquery To Apply) xform?
virtual
BOOL FSubqueryUnnesting() const
{
return true;
}
}; // class CXformSimplifySelectWithSubquery
}
#endif // !GPOPT_CXformSimplifySelectWithSubquery_H
// EOF
| {'content_hash': '8649a23fcadd041a061c1990ea3c207e', 'timestamp': '', 'source': 'github', 'line_count': 85, 'max_line_length': 86, 'avg_line_length': 19.96470588235294, 'alnum_prop': 0.6063641720683559, 'repo_name': 'jmcatamney/gpdb', 'id': '0731d95413d64bd617aaed4e764892afe9fd78e6', 'size': '2309', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'src/backend/gporca/libgpopt/include/gpopt/xforms/CXformSimplifySelectWithSubquery.h', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Assembly', 'bytes': '3724'}, {'name': 'Awk', 'bytes': '836'}, {'name': 'Batchfile', 'bytes': '12854'}, {'name': 'C', 'bytes': '42498841'}, {'name': 'C++', 'bytes': '14366259'}, {'name': 'CMake', 'bytes': '38452'}, {'name': 'Csound Score', 'bytes': '223'}, {'name': 'DTrace', 'bytes': '3873'}, {'name': 'Dockerfile', 'bytes': '11932'}, {'name': 'Emacs Lisp', 'bytes': '3488'}, {'name': 'Fortran', 'bytes': '14863'}, {'name': 'GDB', 'bytes': '576'}, {'name': 'Gherkin', 'bytes': '335208'}, {'name': 'HTML', 'bytes': '53484'}, {'name': 'JavaScript', 'bytes': '23969'}, {'name': 'Lex', 'bytes': '229556'}, {'name': 'M4', 'bytes': '111147'}, {'name': 'Makefile', 'bytes': '496239'}, {'name': 'Objective-C', 'bytes': '38376'}, {'name': 'PLpgSQL', 'bytes': '8009512'}, {'name': 'Perl', 'bytes': '798767'}, {'name': 'PowerShell', 'bytes': '422'}, {'name': 'Python', 'bytes': '3000118'}, {'name': 'Raku', 'bytes': '698'}, {'name': 'Roff', 'bytes': '32437'}, {'name': 'Ruby', 'bytes': '77585'}, {'name': 'SCSS', 'bytes': '339'}, {'name': 'Shell', 'bytes': '451713'}, {'name': 'XS', 'bytes': '6983'}, {'name': 'Yacc', 'bytes': '674092'}, {'name': 'sed', 'bytes': '1231'}]} |
layout: page
title: Clayton Electronics Party
date: 2016-05-24
author: Katherine Bartlett
tags: weekly links, java
status: published
summary: Suspendisse imperdiet velit mauris, malesuada eleifend elit viverra.
banner: images/banner/office-01.jpg
booking:
startDate: 11/12/2019
endDate: 11/13/2019
ctyhocn: DALHSHX
groupCode: CEP
published: true
---
Morbi nec imperdiet erat. Phasellus vitae congue risus. Nam suscipit augue metus. Phasellus suscipit auctor diam, a suscipit ligula aliquam sed. Suspendisse at ultricies lorem, non porttitor massa. Ut id sem urna. Praesent et turpis sed est luctus viverra ut ut justo. Ut interdum lectus eu mi facilisis, eu aliquam orci ultricies. Quisque maximus viverra sapien, in tincidunt metus ornare sed. Morbi ligula mi, pretium dignissim dui id, dapibus cursus libero. Cras maximus lacinia ipsum. Suspendisse pellentesque est a dolor commodo luctus. Morbi quis libero id leo volutpat blandit sed et sapien. Sed vel sem dignissim dolor pretium dapibus nec id tellus. Duis a ex eget augue aliquet fringilla. Aliquam consequat euismod nibh, eu scelerisque nisl ullamcorper ac.
* Vestibulum vitae metus eu risus varius accumsan
* Fusce porta lectus in libero viverra ultricies.
Suspendisse ac neque interdum, tincidunt dui sit amet, commodo ex. Suspendisse pulvinar ante mauris, et placerat eros egestas quis. Nullam cursus a velit a pretium. Nullam gravida diam et leo varius, a venenatis arcu ornare. In pulvinar non lacus ac tincidunt. Aliquam nec tellus consequat, varius diam ut, mattis quam. Pellentesque eu auctor risus.
| {'content_hash': '0221260449b59ea33227c5962e1ef05c', 'timestamp': '', 'source': 'github', 'line_count': 21, 'max_line_length': 765, 'avg_line_length': 75.04761904761905, 'alnum_prop': 0.8052030456852792, 'repo_name': 'KlishGroup/prose-pogs', 'id': '10ed0409e23b5469add81360824f38f982ed9204', 'size': '1580', 'binary': False, 'copies': '1', 'ref': 'refs/heads/gh-pages', 'path': 'pogs/D/DALHSHX/CEP/index.md', 'mode': '33188', 'license': 'mit', 'language': []} |
class Agent : public rcsc::PlayerAgent {
public:
Agent();
virtual ~Agent();
virtual FieldEvaluator::ConstPtr getFieldEvaluator() const;
// Returns the feature extractor corresponding to the feature_set_t
static FeatureExtractor* getFeatureExtractor(hfo::feature_set_t feature_set,
int num_teammates,
int num_opponents,
bool playing_offense);
inline long statusUpdateTime() { return lastStatusUpdateTime; }
// Process incoming trainer messages. Used to update the game status.
void ProcessTrainerMessages();
// Process incoming teammate messages.
void ProcessTeammateMessages();
// Update the state features from the world model.
void UpdateFeatures();
protected:
// You can override this method. But you must call
// PlayerAgent::initImpl() in this method.
virtual bool initImpl(rcsc::CmdLineParser& cmd_parser);
// main decision
virtual void actionImpl();
// communication decision
virtual void communicationImpl();
virtual void handleActionStart();
virtual void handleActionEnd();
virtual void handleServerParam();
virtual void handlePlayerParam();
virtual void handlePlayerType();
virtual FieldEvaluator::ConstPtr createFieldEvaluator() const;
virtual ActionGenerator::ConstPtr createActionGenerator() const;
protected:
hfo::feature_set_t feature_set; // Requested feature set
FeatureExtractor* feature_extractor; // Extracts the features
long lastTrainerMessageTime; // Last time the trainer sent a message
long lastTeammateMessageTime; // Last time a teammate sent a message
long lastStatusUpdateTime; // Last time we got a status update
hfo::status_t game_status; // Current status of the game
hfo::Player player_on_ball; // Player in posession of the ball
std::vector<float> state; // Vector of current state features
std::string say_msg, hear_msg; // Messages to/from teammates
hfo::action_t requested_action; // Currently requested action
std::vector<float> params; // Parameters of current action
public:
inline const std::vector<float>& getState() { return state; }
inline hfo::status_t getGameStatus() { return game_status; }
inline const hfo::Player& getPlayerOnBall() { return player_on_ball; }
inline const std::string& getHearMsg() { return hear_msg; }
int getUnum(); // Returns the uniform number of the player
inline void setFeatureSet(hfo::feature_set_t fset) { feature_set = fset; }
inline std::vector<float>* mutable_params() { return ¶ms; }
inline void setAction(hfo::action_t a) { requested_action = a; }
inline void setSayMsg(const std::string& message) { say_msg = message; }
private:
bool doPreprocess();
bool doSmartKick();
bool doShoot();
bool doPass();
bool doPassTo(int receiver);
bool doDribble();
bool doMove();
bool doForceKick();
bool doHeardPassReceive();
bool doMarkPlayer(int unum);
bool doMarkPlayerNearIndex(int near_index);
bool doReduceAngleToGoal();
bool doDefendGoal();
bool doGoToBall();
bool doNewAction1();
Communication::Ptr M_communication;
FieldEvaluator::ConstPtr M_field_evaluator;
ActionGenerator::ConstPtr M_action_generator;
};
#endif
| {'content_hash': '97d2cf02d455cf5bf87e692685073621', 'timestamp': '', 'source': 'github', 'line_count': 88, 'max_line_length': 78, 'avg_line_length': 38.17045454545455, 'alnum_prop': 0.693361119380768, 'repo_name': 'UNiQ10/HFO', 'id': 'd4b569cb0595beb558319bc64809e4a39a17de0b', 'size': '3589', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/agent.h', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C++', 'bytes': '1219063'}, {'name': 'CMake', 'bytes': '6351'}, {'name': 'Python', 'bytes': '37973'}, {'name': 'Shell', 'bytes': '18707'}]} |
namespace NetMud.DataStructure.Linguistic
{
/// <summary>
/// Rules that identify when words convert to other words based on placement
/// </summary>
public interface IDictataTransformationRule
{
/// <summary>
/// The word to be transformed
/// </summary>
IDictata Origin { get; set; }
/// <summary>
/// A specific word that follows the first
/// </summary>
IDictata SpecificFollowing { get; set; }
/// <summary>
/// Only when the following word ends with this string
/// </summary>
string EndsWith { get; set; }
/// <summary>
/// Only when the following word begins with this string
/// </summary>
string BeginsWith { get; set; }
/// <summary>
/// The word this turns into
/// </summary>
IDictata TransformedWord { get; set; }
}
}
| {'content_hash': '89a1f77798b0dde70d55c4b0dcdaf22b', 'timestamp': '', 'source': 'github', 'line_count': 33, 'max_line_length': 80, 'avg_line_length': 27.90909090909091, 'alnum_prop': 0.5494028230184582, 'repo_name': 'SwiftAusterity/NetMud', 'id': 'cb037d69cf209e18273731e988c9834e5d995115', 'size': '923', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'NetMud.DataStructure/Linguistic/IDictataTransformationRule.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ASP', 'bytes': '202'}, {'name': 'C', 'bytes': '8930665'}, {'name': 'C#', 'bytes': '1968762'}, {'name': 'C++', 'bytes': '458'}, {'name': 'CSS', 'bytes': '152651'}, {'name': 'HTML', 'bytes': '5127'}, {'name': 'JavaScript', 'bytes': '1180842'}, {'name': 'Makefile', 'bytes': '2304'}]} |
@implementation GZCVCBaseViewConfig
@end
| {'content_hash': 'a5390853d1d1dcc3e579c26cdbcd6b18', 'timestamp': '', 'source': 'github', 'line_count': 5, 'max_line_length': 35, 'avg_line_length': 8.8, 'alnum_prop': 0.8181818181818182, 'repo_name': 'gzhongcheng/GZCFramework', 'id': 'e9155f41033f3dd0d26958bb58004bd7ba411e5e', 'size': '232', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'GZCFrameWork/BaseClass/GZCVCBaseViewConfig.m', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Objective-C', 'bytes': '581449'}, {'name': 'Ruby', 'bytes': '745'}]} |
package net.outman.hipda.ui;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.List;
/**
* Key and Value Array Adapter
*
* @param <T>
*/
public class KeyValueArrayAdapter extends ArrayAdapter<KeyValueArrayAdapter.KeyValue> {
/**
* Key and Value
*/
public class KeyValue {
public String key;
public String value;
/**
* @param key
* @param value
*/
public KeyValue(final String key, final String value) {
super();
this.key = key;
this.value = value;
}
}
/**
* @param context
* @param resource
* @param textViewResourceId
* @param objects
*/
public KeyValueArrayAdapter(final Context context, final int resource,
final int textViewResourceId,
final KeyValue[] objects) {
super(context, resource, textViewResourceId, objects);
}
/**
* @param context
* @param resource
* @param textViewResourceId
* @param objects
*/
public KeyValueArrayAdapter(final Context context, final int resource,
final int textViewResourceId,
final List<KeyValue> objects) {
super(context, resource, textViewResourceId, objects);
}
/**
* @param context
* @param resource
* @param textViewResourceId
*/
public KeyValueArrayAdapter(final Context context, final int resource,
final int textViewResourceId) {
super(context, resource, textViewResourceId);
}
/**
* @param context
* @param textViewResourceId
* @param objects
*/
public KeyValueArrayAdapter(final Context context, final int textViewResourceId,
final KeyValue[] objects) {
super(context, textViewResourceId, objects);
}
/**
* @param context
* @param textViewResourceId
* @param objects
*/
public KeyValueArrayAdapter(final Context context, final int textViewResourceId,
final List<KeyValue> objects) {
super(context, textViewResourceId, objects);
}
/**
* @param context
* @param textViewResourceId
*/
public KeyValueArrayAdapter(final Context context, final int textViewResourceId) {
super(context, textViewResourceId);
}
/**
* Change the string value of the TextView with the value of the KeyValue.
*/
@Override
public View getView(final int position, final View convertView, final ViewGroup parent) {
final TextView view = (TextView) super.getView(position, convertView, parent);
view.setText(getItem(position).value);
return view;
}
/**
* Change the string value of the TextView with the value of the KeyValue.
*/
@Override
public View getDropDownView(final int position, final View convertView, final ViewGroup parent) {
final TextView view = (TextView) super.getDropDownView(position, convertView, parent);
view.setText(getItem(position).value);
return view;
}
/**
* Set the specified Collection at the array.
*
* @param keys
* @param vaules
*/
public void setKeyValue(final String[] keys, final String[] vaules) {
if (keys.length != vaules.length) {
throw new RuntimeException("The length of keys and values is not in agreement.");
}
final int N = keys.length;
for (int i = 0; i < N; i++) {
add(new KeyValue(keys[i], vaules[i]));
}
}
/**
* Set the specified Collection at the array.
*
* @param keysVaules
*/
public void setKeyValue(final String[][] keysVaules) {
final int N = keysVaules.length;
for (int i = 0; i < N; i++) {
add(new KeyValue(keysVaules[i][0], keysVaules[i][1]));
}
}
private String[] entries;
private String[] entryValues;
/**
* Set the specified Collection at the array.
*
* @param entries
*/
public void setEntries(final String[] entries) {
this.entries = entries;
if (entryValues != null) {
setKeyValue(entryValues, entries);
}
}
/**
* Set the specified Collection at the array.
*
* @param entryValues
*/
public void setEntryValues(final String[] entryValues) {
this.entryValues = entryValues;
if (entries != null) {
setKeyValue(entryValues, entries);
}
}
/**
* Get the value of the KeyValue with the specified position in the data set.
*
* @param position
* @return
*/
public String getValue(final int position) {
return getItem(position).value;
}
/**
* Get the key of the KeyValue with the specified position in the data set.
*
* @param position
* @return
*/
public String getKey(final int position) {
return getItem(position).key;
}
/**
* Get the entry of the KeyValue with the specified position in the data set.
*
* @param position
* @return
*/
public String getEntry(final int position) {
return getValue(position);
}
/**
* Get the entry value of the KeyValue with the specified position in the data set.
*
* @param position
* @return
*/
public String getEntryValue(final int position) {
return getKey(position);
}
} | {'content_hash': '6938d7c2f2d7fad09354a1b1f5e02cab', 'timestamp': '', 'source': 'github', 'line_count': 218, 'max_line_length': 101, 'avg_line_length': 26.238532110091743, 'alnum_prop': 0.5870629370629371, 'repo_name': 'outman-zhou/android-hipda-client', 'id': 'ddc96942a4b5f8d17ae902653ca4bf9b39b5c90f', 'size': '6340', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'hipda/src/main/java/net/outman/hipda/ui/KeyValueArrayAdapter.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'HTML', 'bytes': '1387'}, {'name': 'Java', 'bytes': '377810'}]} |
//
// JavascriptInterface.h
// JavascriptInterface
//
// Created by 7heaven on 16/7/14.
// Copyright © 2016年 7heaven. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "IWebView.h"
#import "InterfaceProvider.h"
@interface JavascriptInterface : NSObject
@property (unsafe_unretained, nonatomic) id<IWebView> webView;
@property (unsafe_unretained, nonatomic) id<InterfaceProvider> interfaceProvider;
/**
* @brief javascriptinterface名称,JS端调用的时候格式为{interfaceName}.{方法名}\n 例如:当前interfaceName为"nativeCommon", 方法为"callNative", 则JS的调用方式为nativeCommon.callNative();
*
*/
@property (strong, nonatomic) NSString *interfaceName;
/**
* @brief 注入JS方法,对应的原生方法和原生方法的JS端名称由InterfaceProvider提供
*
*/
- (void) injectJSMethod;
/**
* @brief 检查当前的URL是否为注入的JS方法的实际调用形式
*
* @param url 需要验证的url
*
* @return YES表示当前URL的格式符合JS方法对原生的实际调用
*/
- (BOOL) checkUpcomingRequestURL:(NSURL *) url;
/**
* @brief 处理当前的URL并执行对应的原生方法
*
* @param url 传入的url
*
* @return YES表示当前url被作为JS对原生的调用处理,NO表示当前url格式不符合JS对原生调用或者未找到原生对应的方法
*/
- (BOOL) handleInjectedJSMethod:(NSURL *) url;
@end
| {'content_hash': '29a7e7900d96509ed50ac18b4b0c3e9f', 'timestamp': '', 'source': 'github', 'line_count': 48, 'max_line_length': 154, 'avg_line_length': 22.583333333333332, 'alnum_prop': 0.7472324723247232, 'repo_name': '7heaven/SHJavascriptInterface', 'id': '4df61cd8b7c19549a103a6db7bc0a5dfea957e2b', 'size': '1403', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'library/JavascriptInterface.h', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Objective-C', 'bytes': '23391'}, {'name': 'Ruby', 'bytes': '473'}]} |
package income
import (
"context"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestIncomeGetArchiveByDate(t *testing.T) {
convey.Convey("GetArchiveByDate", t, func(ctx convey.C) {
var (
c = context.Background()
aid = "av_id"
table = "av_income"
date = "2018-06-24"
id = int64(0)
limit = int(100)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
archives, err := d.GetArchiveByDate(c, aid, table, date, id, limit)
ctx.Convey("Then err should be nil.archives should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(archives, convey.ShouldNotBeNil)
})
})
})
}
func TestIncomeGetBgmIncomeByDate(t *testing.T) {
convey.Convey("GetBgmIncomeByDate", t, func(ctx convey.C) {
var (
c = context.Background()
date = "2018-06-24"
id = int64(0)
limit = int(100)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
archives, err := d.GetBgmIncomeByDate(c, date, id, limit)
ctx.Convey("Then err should be nil.archives should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(archives, convey.ShouldNotBeNil)
})
})
})
}
| {'content_hash': '7297501c9f27342504685da12a06e706', 'timestamp': '', 'source': 'github', 'line_count': 46, 'max_line_length': 88, 'avg_line_length': 26.304347826086957, 'alnum_prop': 0.6537190082644628, 'repo_name': 'LQJJ/demo', 'id': 'c0c15cd14e8574e67113cff7a68bfa19fa58b1b9', 'size': '1210', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': '126-go-common-master/app/job/main/growup/dao/income/archive_test.go', 'mode': '33261', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '5910716'}, {'name': 'C++', 'bytes': '113072'}, {'name': 'CSS', 'bytes': '10791'}, {'name': 'Dockerfile', 'bytes': '934'}, {'name': 'Go', 'bytes': '40121403'}, {'name': 'Groovy', 'bytes': '347'}, {'name': 'HTML', 'bytes': '359263'}, {'name': 'JavaScript', 'bytes': '545384'}, {'name': 'Makefile', 'bytes': '6671'}, {'name': 'Mathematica', 'bytes': '14565'}, {'name': 'Objective-C', 'bytes': '14900720'}, {'name': 'Objective-C++', 'bytes': '20070'}, {'name': 'PureBasic', 'bytes': '4152'}, {'name': 'Python', 'bytes': '4490569'}, {'name': 'Ruby', 'bytes': '44850'}, {'name': 'Shell', 'bytes': '33251'}, {'name': 'Swift', 'bytes': '463286'}, {'name': 'TSQL', 'bytes': '108861'}]} |
package cf
import (
"bytes"
"code.cloudfoundry.org/commandrunner"
"os/exec"
)
type CF interface {
DisplayCfVersion() (string, error)
}
type cf struct {
commandRunner commandrunner.CommandRunner
}
func New(commandRunner commandrunner.CommandRunner) CF {
return &cf{commandRunner: commandRunner}
}
func (cf *cf) DisplayCfVersion() (string, error) {
var stdout bytes.Buffer
cmd := exec.Command("cf", "-v")
cmd.Stdout = &stdout
err := cf.commandRunner.Run(cmd)
if err != nil {
return "", err
}
return stdout.String(), err
}
| {'content_hash': '600c36802f2f7dac7d1e67a4b09c4522', 'timestamp': '', 'source': 'github', 'line_count': 32, 'max_line_length': 56, 'avg_line_length': 16.9375, 'alnum_prop': 0.7047970479704797, 'repo_name': 'glyn/ergo', 'id': 'd2b4da006aa63b932d1ee9f33e3b9b35e41f8d4d', 'size': '542', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'cf/cf.go', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Go', 'bytes': '3210'}, {'name': 'HTML', 'bytes': '87'}, {'name': 'Shell', 'bytes': '739'}, {'name': 'Smarty', 'bytes': '1931'}]} |
package org.hisp.dhis.dataset.hibernate;
import java.util.List;
import com.google.common.collect.Lists;
import org.hibernate.criterion.Restrictions;
import org.hisp.dhis.common.hibernate.HibernateIdentifiableObjectStore;
import org.hisp.dhis.dataentryform.DataEntryForm;
import org.hisp.dhis.dataset.DataSet;
import org.hisp.dhis.dataset.DataSetStore;
import org.hisp.dhis.organisationunit.OrganisationUnit;
import org.hisp.dhis.period.PeriodService;
import org.hisp.dhis.period.PeriodType;
/**
* @author Kristian Nordal
*/
public class HibernateDataSetStore
extends HibernateIdentifiableObjectStore<DataSet>
implements DataSetStore
{
// -------------------------------------------------------------------------
// Dependencies
// -------------------------------------------------------------------------
private PeriodService periodService;
public void setPeriodService( PeriodService periodService )
{
this.periodService = periodService;
}
// -------------------------------------------------------------------------
// DataSet
// -------------------------------------------------------------------------
@Override
public int save( DataSet dataSet )
{
PeriodType periodType = periodService.reloadPeriodType( dataSet.getPeriodType() );
dataSet.setPeriodType( periodType );
return super.save( dataSet );
}
@Override
public void update( DataSet dataSet )
{
PeriodType periodType = periodService.reloadPeriodType( dataSet.getPeriodType() );
dataSet.setPeriodType( periodType );
super.update( dataSet );
}
@Override
@SuppressWarnings("unchecked")
public List<DataSet> getDataSetsByPeriodType( PeriodType periodType )
{
periodType = periodService.reloadPeriodType( periodType );
return getCriteria( Restrictions.eq( "periodType", periodType ) ).list();
}
@Override
@SuppressWarnings("unchecked")
public List<DataSet> getDataSetsForMobile( OrganisationUnit source )
{
String hql = "from DataSet d where :source in elements(d.sources) and d.mobile = true";
return getQuery( hql ).setEntity( "source", source ).list();
}
@Override
@SuppressWarnings( "unchecked" )
public List<DataSet> getDataSetsByDataEntryForm( DataEntryForm dataEntryForm )
{
if ( dataEntryForm == null )
{
return Lists.newArrayList();
}
final String hql = "from DataSet d where d.dataEntryForm = :dataEntryForm";
return getQuery( hql ).setEntity( "dataEntryForm", dataEntryForm ).list();
}
}
| {'content_hash': '993e969caabedf8d1183115b48076d64', 'timestamp': '', 'source': 'github', 'line_count': 90, 'max_line_length': 95, 'avg_line_length': 30.622222222222224, 'alnum_prop': 0.5928882438316401, 'repo_name': 'vmluan/dhis2-core', 'id': '043502a78259b1e83e3ea68fb6497f5acac574b2', 'size': '4338', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/dataset/hibernate/HibernateDataSetStore.java', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'CSS', 'bytes': '443851'}, {'name': 'Game Maker Language', 'bytes': '20893'}, {'name': 'HTML', 'bytes': '96135'}, {'name': 'Java', 'bytes': '16791545'}, {'name': 'JavaScript', 'bytes': '2077563'}, {'name': 'Ruby', 'bytes': '1011'}, {'name': 'Shell', 'bytes': '394'}, {'name': 'XSLT', 'bytes': '8281'}]} |
'use babel'
import {
createGroupButtons,
createButton,
createIcon,
createIconFromPath,
createText,
createTextEditor,
createElement,
insertElement,
attachEventFromObject
} from './element'
import { InspectorView } from './InspectorView'
import { EventEmitter } from 'events'
const { CompositeDisposable } = require('atom')
import { parse } from 'path'
export interface CallStackFrame {
name: string,
columnNumber: number,
lineNumber: number,
filePath: string
}
export type CallStackFrames = Array<CallStackFrame>
export interface DebugAreaOptions {
didPause?: Function,
didResume?: Function,
didStepOver?: Function,
didStepInto?: Function,
didStepOut?: Function,
didBreak?: Function,
didOpenFile?: Function,
didRequestProperties?: Function,
didEvaluateExpression?: Function,
didOpenFrame?: Function
}
export class DebugAreaView {
private element: HTMLElement
private callStackContentElement: HTMLElement
private watchExpressionContentElement: HTMLElement
private watchExpressionsContentElement: HTMLElement
private scopeContentElement: HTMLElement
private breakpointContentElement: HTMLElement
private resizeElement: HTMLElement
private pauseButton: HTMLElement
private resumeButton: HTMLElement
private events: EventEmitter
private projectPath: string
private subscriptions:any = new CompositeDisposable()
constructor (options?: DebugAreaOptions) {
this.events = new EventEmitter()
this.pauseButton = createButton({
click: () => {
this.events.emit('didPause')
}
}, [createIcon('pause'), createText('Pause')])
this.resumeButton = createButton({
click: () => {
this.events.emit('didResume')
}
}, [createIcon('resume'), createText('Resume')])
this.togglePause(false)
let watchInputElement: any = createTextEditor({
placeholder: 'Add watch expression',
keyEvents: {
'13': () => createExpression(),
'27': () => resetExpression()
}
})
var resetExpression = () => {
watchInputElement.getModel().setText('')
watchInputElement.style.display = 'none'
}
var createExpression = () => {
let watchExpressionText = watchInputElement.getModel().getText()
if (watchExpressionText.trim().length > 0) {
this.createExpressionLine(watchExpressionText)
}
resetExpression()
}
watchInputElement.addEventListener('blur', createExpression)
resetExpression()
this.watchExpressionsContentElement = createElement('div')
this.element = createElement('xatom-debug-area')
this.watchExpressionContentElement = createElement('xatom-debug-group-content', {
className: 'watch',
elements: [ watchInputElement, this.watchExpressionsContentElement ]
})
this.scopeContentElement = createElement('xatom-debug-group-content', {
className: 'scope'
})
this.callStackContentElement = createElement('xatom-debug-group-content', {
className: 'callstack'
})
this.breakpointContentElement = createElement('xatom-debug-group-content', {
className: 'breakpoint'
})
this.resizeElement = createElement('xatom-debug-resize', {
className: 'resize-left'
})
insertElement(this.element, [
this.resizeElement,
createElement('xatom-debug-controls', {
elements: [
this.pauseButton,
this.resumeButton,
createButton({
tooltip: {
subscriptions: this.subscriptions,
title: 'Step Over'
},
click: () => {
this.events.emit('didStepOver')
}
}, [createIcon('step-over')]),
createButton({
tooltip: {
subscriptions: this.subscriptions,
title: 'Step Into'
},
click: () => {
this.events.emit('didStepInto')
}
}, [createIcon('step-into')]),
createButton({
tooltip: {
subscriptions: this.subscriptions,
title: 'Step Out'
},
click: () => {
this.events.emit('didStepOut')
}
}, [createIcon('step-out')])
]
}),
createElement('xatom-debug-group', {
elements: [
createElement('xatom-debug-group-header', {
elements: [
createText('Watch Expressions'),
createButton({
click: () => {
watchInputElement.style.display = null
watchInputElement.focus()
}
}, createIcon('add')),
createButton({
click: () => {
// refresh
}
}, createIcon('refresh'))
]
}),
this.watchExpressionContentElement
]
}),
createElement('xatom-debug-group', {
elements: [
createElement('xatom-debug-group-header', {
elements: [createText('Variables')]
}),
this.scopeContentElement
]
}),
createElement('xatom-debug-group', {
elements: [
createElement('xatom-debug-group-header', {
elements: [createText('Call Stack')]
}),
this.callStackContentElement
]
}),
createElement('xatom-debug-group', {
elements: [
createElement('xatom-debug-group-header', {
elements: [createText('Breakpoints')]
}),
this.breakpointContentElement
]
})
])
attachEventFromObject(this.events, [
'didPause',
'didResume',
'didStepOver',
'didStepInto',
'didStepOut',
'didBreak',
'didOpenFile',
'didRequestProperties',
'didEvaluateExpression',
'didOpenFrame'
], options)
window.addEventListener('resize', () => this.adjustDebugArea())
setTimeout(() => this.adjustDebugArea(), 0)
this.resizeDebugArea()
}
adjustDebugArea () {
let ignoreElements = ['xatom-debug-controls', 'xatom-debug-group xatom-debug-group-header']
let reduce = ignoreElements.reduce((value, query): number => {
let el = this.element.querySelectorAll(query)
Array.from(el).forEach((child: HTMLElement) => {
value += child.clientHeight
})
return value
}, 6)
let contents = this.element.querySelectorAll('xatom-debug-group xatom-debug-group-content')
let items = Array.from(contents)
let availableHeight = (this.element.clientHeight - reduce) / items.length
items.forEach((el: HTMLElement) => {
el.style.height = `${availableHeight}px`
})
}
resizeDebugArea () {
let initialEvent
let resize = (targetEvent) => {
let offset = initialEvent.screenX - targetEvent.screenX
let width = this.element.clientWidth + offset
if (width > 240 && width < 600) {
this.element.style.width = `${width}px`
}
initialEvent = targetEvent
}
this.resizeElement.addEventListener('mousedown', (e) => {
initialEvent = e
document.addEventListener('mousemove', resize)
document.addEventListener('mouseup', () => {
document.removeEventListener('mouseup', resize)
document.removeEventListener('mousemove', resize)
})
})
}
togglePause (status: boolean) {
this.resumeButton.style.display = status ? null : 'none'
this.pauseButton.style.display = status ? 'none' : null
}
// Debug
createFrameLine (frame: CallStackFrame, indicate: boolean) {
let file = parse(frame.filePath)
let indicator = createIcon(indicate ? 'arrow-right-solid' : '')
if (indicate) {
indicator.classList.add('active')
}
return createElement('xatom-debug-group-item', {
options: {
click: () => {
this.events.emit('didOpenFrame', frame)
this.events.emit('didOpenFile',
frame.filePath,
frame.lineNumber,
frame.columnNumber)
}
},
elements: [
createElement('span', {
elements: [indicator, createText(frame.name || '(anonymous)')]
}),
createElement('span', {
className: 'file-reference',
elements: [
createText(file.base),
createElement('span', {
className: 'file-position',
elements: [ createText(`${frame.lineNumber + 1}${ frame.columnNumber > 0 ? ':' + frame.columnNumber : '' }`) ]
})
]
})
]
})
}
getBreakpointId (filePath: string, lineNumber: number) {
let token = btoa(`${filePath}${lineNumber}`)
return `breakpoint-${token}`
}
setWorkspace (projectPath) {
this.projectPath = projectPath
}
createExpressionLine (expressionText: string) {
let expressionValue = createElement('span')
let expressionResult = createElement('span')
insertElement(expressionValue, createText(expressionText))
// this.watchExpressionsContentElement
insertElement(this.watchExpressionsContentElement, createElement('xatom-debug-group-item', {
options: {
click () {}
},
elements: [
expressionValue,
expressionResult
]
}))
// if is running...
this.events.emit('didEvaluateExpression', expressionText, {
insertFromResult: (result) => {
if (result.type === 'object') {
result = [{
value: result
}]
}
let inspector = new InspectorView({
result,
didRequestProperties: (result, inspectorView) => {
this.events.emit('didRequestProperties', result, inspectorView)
}
})
insertElement(expressionResult, inspector.getElement())
}
})
}
createBreakpointLine (filePath: string, lineNumber: number) {
// let file = parse(filePath)
let shortName = filePath
if (this.projectPath) {
shortName = filePath.replace(this.projectPath, '')
}
insertElement(this.breakpointContentElement, createElement('xatom-debug-group-item', {
id: this.getBreakpointId(filePath, lineNumber),
options: {
click: () => {
this.events.emit('didOpenFile', filePath, lineNumber, 0)
}
},
elements: [
createIcon('break'),
createElement('span', {
// className: 'file-reference',
elements: [
createElement('span', {
className: 'file-position',
elements: [ createText(String(lineNumber + 1)) ]
}),
createText(shortName)
]
})
]
}))
}
removeBreakpointLine (filePath: string, lineNumber: number) {
let id = this.getBreakpointId(filePath, lineNumber)
let element = this.breakpointContentElement.querySelector(`[id='${id}']`)
if (element) {
element.remove()
}
}
clearBreakpoints () {
this.breakpointContentElement.innerHTML = ''
}
insertCallStackFromFrames (frames: CallStackFrames) {
this.clearCallStack()
frames.forEach((frame, index) => {
return insertElement(this.callStackContentElement,
this.createFrameLine(frame, index === 0))
})
}
clearCallStack () {
this.callStackContentElement.innerHTML = ''
}
insertScopeVariables (scope) {
if (scope) {
// render scope variables
this.clearScope()
let inspector = new InspectorView({
result: scope,
didRequestProperties: (result, inspectorView) => {
this.events.emit('didRequestProperties', result, inspectorView)
}
})
insertElement(this.scopeContentElement, inspector.getElement())
// update watch expressions
}
}
clearScope () {
this.scopeContentElement.innerHTML = ''
}
getElement () {
return this.element
}
// Destroy all
destroy () {
this.element.remove()
this.subscriptions.dispose()
window.removeEventListener('resize', () => this.adjustDebugArea())
}
}
| {'content_hash': '2270f8b6f926e1a8c13186fe01d12289', 'timestamp': '', 'source': 'github', 'line_count': 415, 'max_line_length': 124, 'avg_line_length': 29.10843373493976, 'alnum_prop': 0.6010761589403973, 'repo_name': 'willyelm/xatom-debug', 'id': '8be9dd966309577095f183d2588e8868228ff6a4', 'size': '12184', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/DebugAreaView.ts', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '48729'}, {'name': 'TypeScript', 'bytes': '132865'}]} |
package com.panda.videolivecore.utils;
import java.security.NoSuchAlgorithmException;
import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class AESUtils {
public static final String TAG = "AESUtils";
private Cipher cipher;
private String iv = "995d1b5ebbac3761";
private IvParameterSpec ivspec = new IvParameterSpec(this.iv.getBytes());
private SecretKeySpec keyspec;
public AESUtils(String seckey) {
this.keyspec = new SecretKeySpec(seckey.getBytes(), "AES");
try {
this.cipher = Cipher.getInstance("AES/CBC/NoPadding");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e2) {
e2.printStackTrace();
}
}
public byte[] encrypt(String text) throws Exception {
if (text == null || text.length() == 0) {
throw new Exception("Empty string");
}
try {
int blockSize = this.cipher.getBlockSize();
byte[] dataBytes = text.getBytes();
int plaintextLength = dataBytes.length;
if (plaintextLength % blockSize != 0) {
plaintextLength += blockSize - (plaintextLength % blockSize);
}
byte[] plaintext = new byte[plaintextLength];
System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length);
this.cipher.init(1, this.keyspec, this.ivspec);
return this.cipher.doFinal(plaintext);
} catch (Exception e) {
throw new Exception("[encrypt] " + e.getMessage());
}
}
public byte[] decrypt(String code) throws Exception {
if (code == null || code.length() == 0) {
throw new Exception("Empty string");
}
try {
this.cipher.init(2, this.keyspec, this.ivspec);
return this.cipher.doFinal(hexToBytes(code));
} catch (Exception e) {
throw new Exception("[decrypt] " + e.getMessage());
}
}
public static String bytesToHex(byte[] data) {
if (data == null) {
return null;
}
int len = data.length;
String str = "";
for (int i = 0; i < len; i++) {
if ((data[i] & 255) < 16) {
str = str + "0" + Integer.toHexString(data[i] & 255);
} else {
str = str + Integer.toHexString(data[i] & 255);
}
}
return str;
}
public static byte[] hexToBytes(String str) {
byte[] bArr = null;
if (str != null && str.length() >= 2) {
int len = str.length() / 2;
bArr = new byte[len];
for (int i = 0; i < len; i++) {
bArr[i] = (byte) Integer.parseInt(str.substring(i * 2, (i * 2) + 2), 16);
}
}
return bArr;
}
}
| {'content_hash': '1056609fa34ce073edfd3ebfe88fce0c', 'timestamp': '', 'source': 'github', 'line_count': 86, 'max_line_length': 89, 'avg_line_length': 35.383720930232556, 'alnum_prop': 0.5359842260926717, 'repo_name': 'chenstrace/Videoliveplatform', 'id': 'a2bec5fe49491f94f0f62140c1fcf5aa70b5ee42', 'size': '3043', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'app/src/main/java/com/panda/videolivecore/utils/AESUtils.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '1022198'}, {'name': 'Makefile', 'bytes': '1030956'}, {'name': 'Shell', 'bytes': '410'}]} |
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<android.support.v7.widget.RecyclerView
android:layout_alignParentBottom="true"
android:id="@+id/password_recyclerview"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
</RelativeLayout> | {'content_hash': '7d27838c692fb1efd23a961cc8153c6b', 'timestamp': '', 'source': 'github', 'line_count': 19, 'max_line_length': 74, 'avg_line_length': 33.26315789473684, 'alnum_prop': 0.6772151898734177, 'repo_name': 'trustratch/GPP-prototype', 'id': 'ef15667d06753b6707bf6e9767703e646363a39e', 'size': '632', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'app/src/main/res/layout/activity_passface.xml', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '78205'}]} |
namespace invalidation {
class InvalidationLogger;
} // namespace invalidation
// The implementation for the chrome://invalidations page.
class InvalidationsMessageHandler
: public content::WebUIMessageHandler,
public invalidation::InvalidationLoggerObserver {
public:
InvalidationsMessageHandler();
InvalidationsMessageHandler(const InvalidationsMessageHandler&) = delete;
InvalidationsMessageHandler& operator=(const InvalidationsMessageHandler&) =
delete;
~InvalidationsMessageHandler() override;
// Implementation of InvalidationLoggerObserver.
void OnRegistrationChange(
const std::set<std::string>& registered_handlers) override;
void OnStateChange(const invalidation::InvalidatorState& new_state,
const base::Time& last_change_timestamp) override;
void OnUpdatedTopics(
const std::string& handler_name,
const invalidation::TopicCountMap& topics_counts) override;
void OnDebugMessage(const base::DictionaryValue& details) override;
void OnInvalidation(
const invalidation::TopicInvalidationMap& new_invalidations) override;
void OnDetailedStatus(const base::DictionaryValue& network_details) override;
// Implementation of WebUIMessageHandler.
void RegisterMessages() override;
void OnJavascriptDisallowed() override;
// Triggers the logger to send the current state and objects ids.
void UpdateContent(const base::ListValue* args);
// Called by the javascript whenever the page is ready to receive messages.
void UIReady(const base::ListValue* args);
// Calls the InvalidationService for any internal details.
void HandleRequestDetailedStatus(const base::ListValue* args);
private:
// The pointer to the internal InvalidatorService InvalidationLogger.
// Used to get the information necessary to display to the JS and to
// register ourselves as Observers for any notifications.
raw_ptr<invalidation::InvalidationLogger> logger_;
base::WeakPtrFactory<InvalidationsMessageHandler> weak_ptr_factory_{this};
};
#endif // CHROME_BROWSER_UI_WEBUI_INVALIDATIONS_INVALIDATIONS_MESSAGE_HANDLER_H_
| {'content_hash': '47996711b9ff27ee87a81d6d086baf6d', 'timestamp': '', 'source': 'github', 'line_count': 53, 'max_line_length': 81, 'avg_line_length': 40.0377358490566, 'alnum_prop': 0.7770970782280867, 'repo_name': 'scheib/chromium', 'id': '5a3da7f33b01fb170b6fd5a21eb846b61363a530', 'size': '2751', 'binary': False, 'copies': '1', 'ref': 'refs/heads/main', 'path': 'chrome/browser/ui/webui/invalidations/invalidations_message_handler.h', 'mode': '33188', 'license': 'bsd-3-clause', 'language': []} |
package graphql.execution;
import com.google.common.collect.ImmutableList;
import graphql.GraphQLError;
import graphql.PublicApi;
import graphql.execution.instrumentation.parameters.InstrumentationFieldCompleteParameters;
import java.util.List;
import java.util.function.Consumer;
/**
* Note: This is returned by {@link InstrumentationFieldCompleteParameters#getFetchedValue()}
* and therefore part of the public despite never used in a method signature.
*/
@PublicApi
public class FetchedValue {
private final Object fetchedValue;
private final Object rawFetchedValue;
private final Object localContext;
private final ImmutableList<GraphQLError> errors;
private FetchedValue(Object fetchedValue, Object rawFetchedValue, ImmutableList<GraphQLError> errors, Object localContext) {
this.fetchedValue = fetchedValue;
this.rawFetchedValue = rawFetchedValue;
this.errors = errors;
this.localContext = localContext;
}
/*
* the unboxed value meaning not Optional, not DataFetcherResult etc
*/
public Object getFetchedValue() {
return fetchedValue;
}
public Object getRawFetchedValue() {
return rawFetchedValue;
}
public List<GraphQLError> getErrors() {
return errors;
}
public Object getLocalContext() {
return localContext;
}
public FetchedValue transform(Consumer<Builder> builderConsumer) {
Builder builder = newFetchedValue(this);
builderConsumer.accept(builder);
return builder.build();
}
@Override
public String toString() {
return "FetchedValue{" +
"fetchedValue=" + fetchedValue +
", rawFetchedValue=" + rawFetchedValue +
", localContext=" + localContext +
", errors=" + errors +
'}';
}
public static Builder newFetchedValue() {
return new Builder();
}
public static Builder newFetchedValue(FetchedValue otherValue) {
return new Builder()
.fetchedValue(otherValue.getFetchedValue())
.rawFetchedValue(otherValue.getRawFetchedValue())
.errors(otherValue.getErrors())
.localContext(otherValue.getLocalContext())
;
}
public static class Builder {
private Object fetchedValue;
private Object rawFetchedValue;
private Object localContext;
private ImmutableList<GraphQLError> errors = ImmutableList.of();
public Builder fetchedValue(Object fetchedValue) {
this.fetchedValue = fetchedValue;
return this;
}
public Builder rawFetchedValue(Object rawFetchedValue) {
this.rawFetchedValue = rawFetchedValue;
return this;
}
public Builder localContext(Object localContext) {
this.localContext = localContext;
return this;
}
public Builder errors(List<GraphQLError> errors) {
this.errors = ImmutableList.copyOf(errors);
return this;
}
public FetchedValue build() {
return new FetchedValue(fetchedValue, rawFetchedValue, errors, localContext);
}
}
} | {'content_hash': '3b54366fc86637a06b34201c636b30fa', 'timestamp': '', 'source': 'github', 'line_count': 108, 'max_line_length': 128, 'avg_line_length': 30.203703703703702, 'alnum_prop': 0.65113427345187, 'repo_name': 'graphql-java/graphql-java', 'id': '28d2ce6da60e6ebf5acf1dba959e99dd2c442dc3', 'size': '3262', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/main/java/graphql/execution/FetchedValue.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ANTLR', 'bytes': '8546'}, {'name': 'Groovy', 'bytes': '2276282'}, {'name': 'HTML', 'bytes': '4949'}, {'name': 'Java', 'bytes': '3031418'}]} |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.