text:
"""Xception V1 model for Keras.

On ImageNet, this model gets to a top-1 validation accuracy of 0.790
and a top-5 validation accuracy of 0.945.

Do note that the input image format for this model is different than for
the VGG16 and ResNet models (299x299 instead of 224x224),
and that the input preprocessing function
is also different (same as Inception V3).

Also do note that this model is only available for the TensorFlow backend,
due to its reliance on `SeparableConvolution` layers.

# Reference

- [Xception: Deep Learning with Depthwise Separable
Convolutions](https://arxiv.org/abs/1610.02357)

"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import os

from tensorflow.python.keras._impl.keras import backend as K
from tensorflow.python.keras._impl.keras import layers
from tensorflow.python.keras._impl.keras.applications import imagenet_utils
from tensorflow.python.keras._impl.keras.applications.imagenet_utils import _obtain_input_shape
from tensorflow.python.keras._impl.keras.applications.imagenet_utils import decode_predictions  # pylint: disable=unused-import
from tensorflow.python.keras._impl.keras.engine.topology import get_source_inputs
from tensorflow.python.keras._impl.keras.layers import Activation
from tensorflow.python.keras._impl.keras.layers import BatchNormalization
from tensorflow.python.keras._impl.keras.layers import Conv2D
from tensorflow.python.keras._impl.keras.layers import Dense
from tensorflow.python.keras._impl.keras.layers import GlobalAveragePooling2D
from tensorflow.python.keras._impl.keras.layers import GlobalMaxPooling2D
from tensorflow.python.keras._impl.keras.layers import Input
from tensorflow.python.keras._impl.keras.layers import MaxPooling2D
from tensorflow.python.keras._impl.keras.layers import SeparableConv2D
from tensorflow.python.keras._impl.keras.models import Model
from tensorflow.python.keras._impl.keras.utils.data_utils import get_file
from tensorflow.python.platform import tf_logging as logging

TF_WEIGHTS_PATH = 'https://github.com/fchollet/deep-learning-models/releases/download/v0.4/xception_weights_tf_dim_ordering_tf_kernels.h5'
TF_WEIGHTS_PATH_NO_TOP = 'https://github.com/fchollet/deep-learning-models/releases/download/v0.4/xception_weights_tf_dim_ordering_tf_kernels_notop.h5'

def Xception(include_top=True,
             weights='imagenet',
             input_tensor=None,
             input_shape=None,
             pooling=None,
             classes=1000):
  """Instantiates the Xception architecture.

  Optionally loads weights pre-trained
  on ImageNet. This model is available for TensorFlow only,
  and can only be used with inputs following the TensorFlow
  data format `(width, height, channels)`.
  You should set `image_data_format="channels_last"` in your Keras config
  located at ~/.keras/keras.json.

  Note that the default input image size for this model is 299x299.

  Arguments:
      include_top: whether to include the fully-connected
          layer at the top of the network.
      weights: one of `None` (random initialization),
          'imagenet' (pre-training on ImageNet),
          or the path to the weights file to be loaded.
      input_tensor: optional Keras tensor (i.e. output of `layers.Input()`)
          to use as image input for the model.
      input_shape: optional shape tuple, only to be specified
          if `include_top` is False (otherwise the input shape
          has to be `(299, 299, 3)`.
          It should have exactly 3 input channels,
          and width and height should be no smaller than 71.
          E.g. `(150, 150, 3)` would be one valid value.
      pooling: Optional pooling mode for feature extraction
          when `include_top` is `False`.
          - `None` means that the output of the model will be
              the 4D tensor output of the
              last convolutional layer.
          - `avg` means that global average pooling
              will be applied to the output of the
              last convolutional layer, and thus
              the output of the model will be a 2D tensor.
          - `max` means that global max pooling will
              be applied.
      classes: optional number of classes to classify images
          into, only to be specified if `include_top` is True, and
          if no `weights` argument is specified.

  Returns:
      A Keras model instance.

  Raises:
      ValueError: in case of invalid argument for `weights`,
          or invalid input shape.
      RuntimeError: If attempting to run this model with a
          backend that does not support separable convolutions.
  """
  if not (weights in {'imagenet', None} or os.path.exists(weights)):
    raise ValueError('The `weights` argument should be either '
                     '`None` (random initialization), `imagenet` '
                     '(pre-training on ImageNet), '
                     'or the path to the weights file to be loaded.')

  if weights == 'imagenet' and include_top and classes != 1000:
    raise ValueError('If using `weights` as imagenet with `include_top`'
                     ' as true, `classes` should be 1000')

  if K.backend() != 'tensorflow':
    raise RuntimeError('The Xception model is only available with '
                       'the TensorFlow backend.')
  if K.image_data_format() != 'channels_last':
    logging.warning(
        'The Xception model is only available for the '
        'input data format "channels_last" '
        '(width, height, channels). '
        'However your settings specify the default '
        'data format "channels_first" (channels, width, height). '
        'You should set `image_data_format="channels_last"` in your Keras '
        'config located at ~/.keras/keras.json. '
        'The model being returned right now will expect inputs '
        'to follow the "channels_last" data format.')
    K.set_image_data_format('channels_last')
    old_data_format = 'channels_first'
  else:
    old_data_format = None

  # Determine proper input shape
  input_shape = _obtain_input_shape(
      input_shape,
      default_size=299,
      min_size=71,
      data_format=K.image_data_format(),
      require_flatten=False,
      weights=weights)

  if input_tensor is None:
    img_input = Input(shape=input_shape)
  else:
    img_input = Input(tensor=input_tensor, shape=input_shape)

  x = Conv2D(
      32, (3, 3), strides=(2, 2), use_bias=False,
      name='block1_conv1')(img_input)
  x = BatchNormalization(name='block1_conv1_bn')(x)
  x = Activation('relu', name='block1_conv1_act')(x)
  x = Conv2D(64, (3, 3), use_bias=False, name='block1_conv2')(x)
  x = BatchNormalization(name='block1_conv2_bn')(x)
  x = Activation('relu', name='block1_conv2_act')(x)

  residual = Conv2D(
      128, (1, 1), strides=(2, 2), padding='same', use_bias=False)(x)
  residual = BatchNormalization()(residual)

  x = SeparableConv2D(
      128, (3, 3), padding='same', use_bias=False, name='block2_sepconv1')(x)
  x = BatchNormalization(name='block2_sepconv1_bn')(x)
  x = Activation('relu', name='block2_sepconv2_act')(x)
  x = SeparableConv2D(
      128, (3, 3), padding='same', use_bias=False, name='block2_sepconv2')(x)
  x = BatchNormalization(name='block2_sepconv2_bn')(x)

  x = MaxPooling2D(
      (3, 3), strides=(2, 2), padding='same', name='block2_pool')(x)
  x = layers.add([x, residual])

  residual = Conv2D(
      256, (1, 1), strides=(2, 2), padding='same', use_bias=False)(x)
  residual = BatchNormalization()(residual)

  x = Activation('relu', name='block3_sepconv1_act')(x)
  x = SeparableConv2D(
      256, (3, 3), padding='same', use_bias=False, name='block3_sepconv1')(x)
  x = BatchNormalization(name='block3_sepconv1_bn')(x)
  x = Activation('relu', name='block3_sepconv2_act')(x)
  x = SeparableConv2D(
      256, (3, 3), padding='same', use_bias=False, name='block3_sepconv2')(x)
  x = BatchNormalization(name='block3_sepconv2_bn')(x)

  x = MaxPooling2D(
      (3, 3), strides=(2, 2), padding='same', name='block3_pool')(x)
  x = layers.add([x, residual])

  residual = Conv2D(
      728, (1, 1), strides=(2, 2), padding='same', use_bias=False)(x)
  residual = BatchNormalization()(residual)

  x = Activation('relu', name='block4_sepconv1_act')(x)
  x = SeparableConv2D(
      728, (3, 3), padding='same', use_bias=False, name='block4_sepconv1')(x)
  x = BatchNormalization(name='block4_sepconv1_bn')(x)
  x = Activation('relu', name='block4_sepconv2_act')(x)
  x = SeparableConv2D(
      728, (3, 3), padding='same', use_bias=False, name='block4_sepconv2')(x)
  x = BatchNormalization(name='block4_sepconv2_bn')(x)

  x = MaxPooling2D(
      (3, 3), strides=(2, 2), padding='same', name='block4_pool')(x)
  x = layers.add([x, residual])

  for i in range(8):
    residual = x
    prefix = 'block' + str(i + 5)

    x = Activation('relu', name=prefix + '_sepconv1_act')(x)
    x = SeparableConv2D(
        728, (3, 3), padding='same', use_bias=False,
        name=prefix + '_sepconv1')(x)
    x = BatchNormalization(name=prefix + '_sepconv1_bn')(x)
    x = Activation('relu', name=prefix + '_sepconv2_act')(x)
    x = SeparableConv2D(
        728, (3, 3), padding='same', use_bias=False,
        name=prefix + '_sepconv2')(x)
    x = BatchNormalization(name=prefix + '_sepconv2_bn')(x)
    x = Activation('relu', name=prefix + '_sepconv3_act')(x)
    x = SeparableConv2D(
        728, (3, 3), padding='same', use_bias=False,
        name=prefix + '_sepconv3')(x)
    x = BatchNormalization(name=prefix + '_sepconv3_bn')(x)

    x = layers.add([x, residual])

  residual = Conv2D(
      1024, (1, 1), strides=(2, 2), padding='same', use_bias=False)(x)
  residual = BatchNormalization()(residual)

  x = Activation('relu', name='block13_sepconv1_act')(x)
  x = SeparableConv2D(
      728, (3, 3), padding='same', use_bias=False, name='block13_sepconv1')(x)
  x = BatchNormalization(name='block13_sepconv1_bn')(x)
  x = Activation('relu', name='block13_sepconv2_act')(x)
  x = SeparableConv2D(
      1024, (3, 3), padding='same', use_bias=False, name='block13_sepconv2')(x)
  x = BatchNormalization(name='block13_sepconv2_bn')(x)

  x = MaxPooling2D(
      (3, 3), strides=(2, 2), padding='same', name='block13_pool')(x)
  x = layers.add([x, residual])

  x = SeparableConv2D(
      1536, (3, 3), padding='same', use_bias=False, name='block14_sepconv1')(x)
  x = BatchNormalization(name='block14_sepconv1_bn')(x)
  x = Activation('relu', name='block14_sepconv1_act')(x)

  x = SeparableConv2D(
      2048, (3, 3), padding='same', use_bias=False, name='block14_sepconv2')(x)
  x = BatchNormalization(name='block14_sepconv2_bn')(x)
  x = Activation('relu', name='block14_sepconv2_act')(x)

  if include_top:
    x = GlobalAveragePooling2D(name='avg_pool')(x)
    x = Dense(classes, activation='softmax', name='predictions')(x)
  else:
    if pooling == 'avg':
      x = GlobalAveragePooling2D()(x)
    elif pooling == 'max':
      x = GlobalMaxPooling2D()(x)

  # Ensure that the model takes into account
  # any potential predecessors of `input_tensor`.
  if input_tensor is not None:
    inputs = get_source_inputs(input_tensor)
  else:
    inputs = img_input
  # Create model.
  model = Model(inputs, x, name='xception')

  # load weights
  if weights == 'imagenet':
    if include_top:
      weights_path = get_file(
          'xception_weights_tf_dim_ordering_tf_kernels.h5',
          TF_WEIGHTS_PATH,
          cache_subdir='models',
          file_hash='0a58e3b7378bc2990ea3b43d5981f1f6')
    else:
      weights_path = get_file(
          'xception_weights_tf_dim_ordering_tf_kernels_notop.h5',
          TF_WEIGHTS_PATH_NO_TOP,
          cache_subdir='models',
          file_hash='b0042744bf5b25fce3cb969f33bebb97')
    model.load_weights(weights_path)

  if old_data_format:
    K.set_image_data_format(old_data_format)
  elif weights is not None:
    model.load_weights(weights)
  return model

def preprocess_input(x):
  """Preprocesses a numpy array encoding a batch of images.

  Arguments:
      x: a 4D numpy array consists of RGB values within [0, 255].

  Returns:
      Preprocessed array.
  """
  return imagenet_utils.preprocess_input(x, mode='tf')


text:
<!doctype html>

<title>CodeMirror: Bi-directional Text Demo</title>
<meta charset="utf-8"/>
<link rel=stylesheet href="../doc/docs.css">

<link rel="stylesheet" href="../lib/codemirror.css">

CodeMirror

Home

Manual

Code

Bi-directional Text

Bi-directional Text Demo

<form><textarea id="code" name="code">

value (string or Doc)

قيمة البداية المحرر. يمكن أن تكون سلسلة، أو. كائن مستند.

mode (string or object)

وضع الاستخدام. عندما لا تعطى، وهذا الافتراضي إلى الطريقة الاولى
  التي تم تحميلها. قد يكون من سلسلة، والتي إما أسماء أو ببساطة هو وضع
  MIME نوع المرتبطة اسطة. بدلا من ذلك، قد يكون من كائن يحتوي على
  خيارات التكوين لواسطة، مع name الخاصية التي وضع أسماء
  (على سبيل المثال {name: "javascript", json: true}).
  صفحات التجريبي لكل وضع تحتوي على معلومات حول ما معلمات تكوين وضع
  يدعمها. يمكنك أن تطلب CodeMirror التي تم تعريفها طرق وأنواع MIME
  الكشف على CodeMirror.modes
  و CodeMirror.mimeModes الكائنات. وضع خرائط الأسماء
  الأولى لمنشئات الخاصة بهم، وخرائط لأنواع MIME 2 المواصفات
  واسطة.

theme (string)

موضوع لنمط المحرر مع. يجب عليك التأكد من الملف CSS تحديد
  المقابلة .cm-s-[name] يتم تحميل أنماط (انظر
  theme الدليل في التوزيع).
  الافتراضي هو "default" ، والتي تم تضمينها في
  الألوان codemirror.css. فمن الممكن استخدام فئات متعددة
  في تطبيق السمات مرة واحدة على سبيل المثال "foo bar"
  سيتم تعيين كل من cm-s-foo و cm-s-bar
  الطبقات إلى المحرر.

</textarea>
  <fieldset>
    Editor default direction:
    <input type="radio" id="ltr" name="direction"/>LTR
    <input type="radio" id="rtl" name="direction"/>RTL
  </fieldset>
  <fieldset>
    HTML document direction:
    <input type="radio" id="htmlltr" name="htmldirection"/>LTR
    <input type="radio" id="htmlrtl" name="htmldirection"/>RTL
  </fieldset>
  <fieldset>
    <input type="checkbox" id="rtlMoveVisually"/>Use visual order for arrow key movement.
  </fieldset>
</form>

Demonstration of bi-directional text support. See
  the related
  blog post for more background.

redpajama_set_name: RedPajamaGithub


text:
ZF2 Simple Acl
===========
Simple acl module.

Restrict ROUTES
----------------
Only one thing you need to start is to define routes which you want to restrict and the strategy which you would like
to use for other not defined routes. Strategy might be 'permissive' or 'strict'. If value 'permissive' it will mean
"allow all from all" so then you will have to restrict all resources which you want to be restricted.
If value 'strict' it is will mean "deny all from all" so then you will have to allow every resource which you want to be available
```
'restriction_strategy' => 'permissive',

'routes' => array(
  'main' => array(true)
)
```

Smart redirection
-----------------
Provide smart redirection according on path/module where user requested restricted resource.
It is can be used for restricting few modules with on ACL library.
```
'redirect_route' => array('/frontend.*?/'=>'frontend/user/login',
                          '/backend.*?/'=>'backend/user/login')
```
It is very usefull if you have authorization on your frontend and backend modules,
and you would like to redirect user who requested backend resource to the backend/user/login route and
users who requested frontend restricted resource to the frontend/user/login.

Recognizers
----------------
It is very simple ability to authorize user by some token. Now supports authorization only thru token defined in COOKIE.
I've added this feature only because from time to time i need user role which can acces
to the special resources but without real authorization thru login form. In my example it was a cron script.
```
wget http://$1/generate/sitemap --no-cookies --header "Cookie: cron=a23b4cdg76fb38a5d48b83e22f0e79df" -o /dev/null -O /tmp/sitemap.generated
```
you should specify recognizer:
```
'recognizers' => array('cron'),
```
and role :
```
  'roles' => array(array('name'=>'cron',
                         'id'=>2,
                         'data' => array(
                             'type'=>'cron',
                             // It is authorization token, value will be compared with
                             // token inside $_COOKIE['cron'] and will decide that this is
                             // cron role.
                             'token'=>'a23b4cdg76fb38a5d48b83e22f0e79df'
  )))
```


text:
extern "C" {
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <unistd.h>
#include <strings.h>
#include <fcntl.h>
}

#include <string>

#include <libflog/proto/internet.hpp>

#include "ssl_wrapper.hpp"

namespace flog {
namespace socket {

struct Address {
  Address(socklen_t s)
    : size(s), status(true)
  { }
  Address(const Address& a)
    : size(a.size), status(a.status), error(a.error)
  { }
  virtual ~Address() {}

  virtual const sockaddr* generic_address() const = 0;
  virtual sockaddr* generic_address() = 0;
  socklen_t* generic_address_size();
  virtual int type() const = 0;
  virtual bool match(const net::Address& rhs) const = 0;

  virtual Address* defcons() const = 0;
  virtual Address* copy() const = 0;
  virtual std::string to_string() const = 0;

  operator bool() const { return status; }

  socklen_t size;
  bool status;
  std::string error;
};

struct IPv4 : Address {
  IPv4();
  IPv4(const ipv4::Address& a, uint16_t p);
  IPv4(const std::string& ip, uint16_t p);
  IPv4(const IPv4& ip);

  const sockaddr* generic_address() const;
  sockaddr* generic_address();
  socklen_t* generic_address_size();
  int type() const;
  bool match(const net::Address& rhs) const;

  IPv4* defcons() const;
  IPv4* copy() const;
  std::string to_string() const;

  sockaddr_in addr;
};

struct IPv6 : Address {
  IPv6();
  IPv6(const ipv6::Address& a, uint16_t p);
  IPv6(const std::string& ip, uint16_t p);
  IPv6(const IPv6& ip);

  const sockaddr* generic_address() const;
  sockaddr* generic_address();
  socklen_t* generic_address_size();
  int type() const;
  bool match(const net::Address& rhs) const;

  IPv6* defcons() const;
  IPv6* copy() const;
  std::string to_string() const;

  sockaddr_in6 addr;
};

Address* make_address(const net::Address& a);

struct Socket {
  Socket(const net::Address& a);
  Socket(net::Transport t, const Address& l);
  Socket(net::Transport t, Address* l);
  Socket(net::Transport t, Address* l, Address* p, int f);
  Socket(Socket&& s);
  ~Socket();

  Socket& bind();
  Socket& listen();
  Socket& connect(const net::Address& p);
  Socket& connect(const Address& p);
  Socket accept();

  bool match(const net::Address& addr) const;

  net::Transport transport;
  Address* local;
  Address* peer;
  int fd;

  operator bool() const { return status; }

  bool status;
  std::string error;
};

int to_domain(net::Transport t);

std::string to_string(const Socket& s);

inline socklen_t*
Address::generic_address_size()
{
  return &size;
}

inline
IPv4::IPv4()
  : Address(sizeof(sockaddr_in))
{
  bzero(&addr, sizeof(sockaddr_in));
  addr.sin_family = AF_INET;
  addr.sin_addr.s_addr = INADDR_ANY;
}

inline
IPv4::IPv4(const ipv4::Address& a, uint16_t p)
  : Address(sizeof(sockaddr_in))
{
  bzero(&addr, sizeof(sockaddr_in));
  addr.sin_family = AF_INET;
  addr.sin_addr.s_addr = htonl(a.addr);
  addr.sin_port = htons(p);
}

inline
IPv4::IPv4(const IPv4& ip)
  : Address(ip), addr(ip.addr)
{ }

inline const sockaddr*
IPv4::generic_address() const
{
  return reinterpret_cast<const sockaddr*>(&addr);
}

inline sockaddr*
IPv4::generic_address()
{
  return reinterpret_cast<sockaddr*>(&addr);
}

inline int
IPv4::type() const
{
  return AF_INET;
}

inline bool
IPv4::match(const net::Address& rhs) const
{
  return rhs.network == net::IPv4 and
         rhs.v4.addr == addr.sin_addr.s_addr and
         rhs.port == addr.sin_port;
}

inline IPv4*
IPv4::defcons() const
{
  return new IPv4();
}

inline IPv4*
IPv4::copy() const
{
  return new IPv4(*this);
}

inline
IPv6::IPv6()
  : Address(sizeof(sockaddr_in6))
{
  bzero(&addr, sizeof(sockaddr_in6));
  addr.sin6_family = AF_INET6;
  addr.sin6_addr = in6addr_any;
}

inline
IPv6::IPv6(const ipv6::Address& a, uint16_t p)
  : Address(sizeof(sockaddr_in6))
{
  bzero(&addr, sizeof(sockaddr_in6));
  addr.sin6_family = AF_INET6;
  std::copy(a.addr, a.addr+16, addr.sin6_addr.s6_addr);
  addr.sin6_port = htons(p);
}

inline
IPv6::IPv6(const IPv6& ip)
  : Address(ip), addr(ip.addr)
{ }

inline const sockaddr*
IPv6::generic_address() const
{
  return reinterpret_cast<const sockaddr*>(&addr);
}

inline sockaddr*
IPv6::generic_address()
{
  return reinterpret_cast<sockaddr*>(&addr);
}

inline int
IPv6::type() const
{
  return AF_INET6;
}

inline bool
IPv6::match(const net::Address& rhs) const
{
  return rhs.network == net::IPv6 and
         std::equal(rhs.v6.addr, rhs.v6.addr+16, addr.sin6_addr.s6_addr) and
         rhs.port == addr.sin6_port;
}

inline IPv6*
IPv6::defcons() const
{
  return new IPv6();
}

inline IPv6*
IPv6::copy() const
{
  return new IPv6(*this);
}

inline
Socket::Socket(const net::Address& a)
  : transport(a.transport), local(make_address(a)), peer(nullptr),
    fd(::socket(local->type(), to_domain(a.transport), 0)), status(true)
{
  int flags;
  if (fd < 0) {
    status = false;
    error = strerror(errno);
  } else {
    flags = ::fcntl(fd, F_GETFD);
    if (flags < 0) {
      status = false;
      error = strerror(errno);
    } else {
      flags = ::fcntl(fd, F_SETFD, flags|O_NONBLOCK);
      if (flags < 0) {
        status = false;
        error = strerror(errno);
      } else
        this->bind();
    }
  }
}

inline
Socket::Socket(net::Transport t, const Address& l)
  : transport(t), local(l.copy()), peer(nullptr),
    fd(::socket(l.type(), to_domain(t), 0)), status(true)
{
  int flags;
  if (fd < 0) {
    status = false;
    error = strerror(errno);
  } else {
    flags = ::fcntl(fd, F_GETFD);
    if (flags < 0) {
      status = false;
      error = strerror(errno);
    } else {
      flags = ::fcntl(fd, F_SETFD, flags|O_NONBLOCK);
      if (flags < 0) {
        status = false;
        error = strerror(errno);
      } else
        this->bind();
    }
  }
}

inline
Socket::Socket(net::Transport t, Address* l)
  : transport(t), local(l), peer(nullptr),
    fd(::socket(l->type(), to_domain(t), 0)), status(true)
{
  int flags;
  if (fd < 0) {
    status = false;
    error = strerror(errno);
  } else {
    flags = ::fcntl(fd, F_GETFD);
    if (flags < 0) {
      status = false;
      error = strerror(errno);
    } else {
      flags = ::fcntl(fd, F_SETFD, flags|O_NONBLOCK);
      if (flags < 0) {
        status = false;
        error = strerror(errno);
      } else
        this->bind();
    }
  }
}

inline
Socket::Socket(net::Transport t, Address* l, Address* p, int f)
  : transport(t), local(l), peer(p), fd(f), status(true)
{ }

inline
Socket::Socket(Socket&& s)
  : transport(s.transport), local(s.local), peer(s.peer),
    fd(s.fd), status(s.status), error(s.error)
{
  s.local = nullptr;
  s.peer = nullptr;
  s.fd = -1;
  s.status = false;
  s.error = "moved from";
}

inline
Socket::~Socket()
{
  if(fd > -1) ::close(fd);
  if(local) delete local;
  if(peer) delete peer;
}

inline bool
Socket::match(const net::Address& rhs) const {
  if(rhs.transport != transport)
    return false;
  return local->match(rhs);
}

inline int
to_domain(net::Transport t)
{
  switch(t) {
    case net::TLS:
    case net::TCP:
      return SOCK_STREAM;
    case net::UDP:
      return SOCK_DGRAM;
    default:
      return -1;
  }
}

inline Socket&
Socket::bind()
{
  auto r = ::bind(fd, local->generic_address(), *local->generic_address_size());
  if( r < 0) {
    status = false;
    error = strerror(errno);
  }
  return *this;
}

inline Socket&
Socket::listen()
{
  auto r = ::listen(fd, SOMAXCONN);
  if (r < 0) {
    status = false;
    error = strerror(errno);
  }
  return *this;
}

inline Socket&
Socket::connect(const net::Address& p)
{
  if(peer) delete peer;
  peer = make_address(p);

  // connect to the peer address
  auto r = ::connect(fd, peer->generic_address(),
                     *peer->generic_address_size());
  if (r < 0) {
    status = false;
    error = strerror(errno);
  }

  return *this;
}

inline Socket&
Socket::connect(const Address& p)
{
  // copy the peer address
  if(peer) delete peer;
  peer = p.copy();

  // connect to the peer address
  auto r = ::connect(fd, peer->generic_address(),
                     *peer->generic_address_size());
  if (r < 0) {
    status = false;
    error = strerror(errno);
  }
  return *this;
}

inline Socket
Socket::accept()
{
  Address* new_peer = local->defcons();
  auto r = ::accept(fd, new_peer->generic_address(),
                    new_peer->generic_address_size());
  if (r < 0) {
    status = false;
    error = strerror(errno);
  }
  return Socket(transport, local->copy(), new_peer, r);
}

} // namespace socket
} // namespace flog

#endif


text:
package org.ovirt.engine.core.bll;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyList;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.runners.MockitoJUnitRunner;
import org.mockito.stubbing.Answer;
import org.ovirt.engine.core.bll.snapshots.SnapshotsValidator;
import org.ovirt.engine.core.bll.validator.VmValidator;
import org.ovirt.engine.core.bll.validator.storage.StorageDomainValidator;
import org.ovirt.engine.core.common.action.AddVmFromSnapshotParameters;
import org.ovirt.engine.core.common.businessentities.Snapshot;
import org.ovirt.engine.core.common.businessentities.StorageDomain;
import org.ovirt.engine.core.common.businessentities.VM;
import org.ovirt.engine.core.common.businessentities.storage.DiskImage;
import org.ovirt.engine.core.common.businessentities.storage.DiskInterface;
import org.ovirt.engine.core.common.businessentities.storage.ImageStatus;
import org.ovirt.engine.core.common.errors.EngineMessage;
import org.ovirt.engine.core.compat.Guid;

@RunWith(MockitoJUnitRunner.class)
public class AddVmFromSnapshotCommandTest extends AddVmCommandTest{

    /**
     * The command under test.
     */
    protected AddVmFromSnapshotCommand<AddVmFromSnapshotParameters> command;

    private SnapshotsValidator snapshotsValidator;

    @Override
    @Test
    public void validateSpaceAndThreshold() {
        initCommand();
        doReturn(ValidationResult.VALID).when(storageDomainValidator).isDomainWithinThresholds();
        doReturn(ValidationResult.VALID).when(storageDomainValidator).hasSpaceForClonedDisks(anyList());
        doReturn(storageDomainValidator).when(command).createStorageDomainValidator(any(StorageDomain.class));
        mockGetAllSnapshots();
        assertTrue(command.validateSpaceRequirements());
        verify(storageDomainValidator, times(TOTAL_NUM_DOMAINS)).hasSpaceForClonedDisks(anyList());
        verify(storageDomainValidator, never()).hasSpaceForNewDisks(anyList());
    }

    @Override
    @Test
    public void validateSpaceNotEnough() throws Exception {
        initCommand();
        doReturn(ValidationResult.VALID).when(storageDomainValidator).isDomainWithinThresholds();
        doReturn(new ValidationResult(EngineMessage.ACTION_TYPE_FAILED_DISK_SPACE_LOW_ON_STORAGE_DOMAIN)).
                when(storageDomainValidator).hasSpaceForClonedDisks(anyList());
        doReturn(storageDomainValidator).when(command).createStorageDomainValidator(any(StorageDomain.class));
        mockGetAllSnapshots();
        assertFalse(command.validateSpaceRequirements());
        //The following is mocked to fail, should happen only once.
        verify(storageDomainValidator).hasSpaceForClonedDisks(anyList());
        verify(storageDomainValidator, never()).hasSpaceForNewDisks(anyList());
    }

    @Override
    @Test
    public void validateSpaceNotWithinThreshold() throws Exception {
        initCommand();
        doReturn(new ValidationResult(EngineMessage.ACTION_TYPE_FAILED_DISK_SPACE_LOW_ON_STORAGE_DOMAIN)).
                when(storageDomainValidator).isDomainWithinThresholds();
        doReturn(storageDomainValidator).when(command).createStorageDomainValidator(any(StorageDomain.class));
        assertFalse(command.validateSpaceRequirements());
    }

    @Test
    public void testCannotDisableVirtioScsi() {
        initCommand();
        command.getParameters().setVirtioScsiEnabled(false);

        doReturn(snapshotsValidator).when(command).createSnapshotsValidator();
        doReturn(ValidationResult.VALID).when(snapshotsValidator).snapshotExists(any(Snapshot.class));
        doReturn(ValidationResult.VALID).when(snapshotsValidator).vmNotDuringSnapshot(any(Guid.class));

        VM vm = new VM();
        Snapshot snapshot = new Snapshot();
        doReturn(vm).when(command).getVmFromConfiguration();
        doReturn(snapshot).when(command).getSnapshot();

        DiskImage disk = new DiskImage();
        disk.setDiskInterface(DiskInterface.VirtIO_SCSI);
        disk.setPlugged(true);
        doReturn(Collections.singletonList(disk)).when(command).getAdjustedDiskImagesFromConfiguration();

        VmValidator vmValidator = spy(new VmValidator(vm));
        doReturn(vmValidator).when(command).createVmValidator(vm);

        assertFalse(command.checkCanDisableVirtIoScsi());
        ValidateTestUtils.assertValidationMessages("Validation should prevent disabling of virtIO-scsi.",
                command,
                EngineMessage.CANNOT_DISABLE_VIRTIO_SCSI_PLUGGED_DISKS);
    }

    @Override
    protected List<DiskImage> createDiskSnapshot(Guid diskId, int numOfImages) {
        List<DiskImage> disksList = new ArrayList<>();
        for (int i = 0; i < numOfImages; ++i) {
            DiskImage diskImage = new DiskImage();
            diskImage.setActive(false);
            diskImage.setId(diskId);
            diskImage.setImageId(Guid.newGuid());
            diskImage.setParentId(Guid.newGuid());
            diskImage.setImageStatus(ImageStatus.OK);
            disksList.add(diskImage);
        }
        return disksList;
    }

    private void mockGetAllSnapshots() {
        doAnswer(new Answer<List<DiskImage>>() {
            @Override
            public List<DiskImage> answer(InvocationOnMock invocation) throws Throwable {
                Object[] args = invocation.getArguments();
                DiskImage arg = (DiskImage) args[0];
                List<DiskImage> list  = createDiskSnapshot(arg.getId(), 3);
                return list;
            }
        }).when(command).getAllImageSnapshots(any(DiskImage.class));
    }

    private void initCommand() {
        final Guid sourceSnapshotId = Guid.newGuid();
        command = setupCanAddVmFromSnapshotTests(0, sourceSnapshotId);
        generateStorageToDisksMap(command);
        initDestSDs(command);
        storageDomainValidator = mock(StorageDomainValidator.class);
        snapshotsValidator = mock(SnapshotsValidator.class);
    }
}


text:
Steam > Library > Counter-Strike: Global Offensive (right-click) > Properties > Set Launch Options:

-novid -high -threads 4 -freq 144 -refresh 144 -tickrate 128 -nojoy -nod3d9ex +exec autoexec.cfg


text:
import os
from http.cookiejar import CookieJar
import requests
from lxml import html

PIXHOST_HOMEPAGE_URL = 'http://www.pixhost.org/'
PIXHOST_UPLOAD_URL = 'http://www.pixhost.org/classic-upload/'

def upload(images, adult=False):
    source_images = images if isinstance(images, list) else [images]

    params = {
        'content_type': int(adult),
        'tos': 'on'
    }

    # fake headers
    headers = {
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.125 Safari/537.36',
        'Referer': 'http://www.pixhost.org/classic-upload/',
        'Origin': 'http://www.pixhost.org',
        'Host': 'www.pixhost.org',
    }

    files = []
    # add images to parameter lists
    for img in source_images:
        if os.path.getsize(img) > pow(10, 7):
            raise TooLargeImageFormat()

        files.append(('img[]', (os.path.basename(img), open(img, 'rb'))))

    # make first request to the homepage to fill cookie jar with default cookies
    jar = CookieJar()
    requests.post(PIXHOST_HOMEPAGE_URL, cookies=jar, headers=headers)

    # upload images
    response = requests.post(PIXHOST_UPLOAD_URL, data=params, cookies=jar, headers=headers, files=files)

    for file in files:
        file[1][1].close()

    if response.status_code != 200:
        raise UploadFailed(response)

    # urls for uploaded images
    image_urls = []

    root = html.fromstring(response.text)

    main_div = root.xpath('//div[@id="text"]')

    # fetch small thumbnails
    all_small_thumbs = main_div[0].xpath('./a')

    for thumb_elm in all_small_thumbs:
        # we need to download the page with fullsize image
        full_size_preview_url = thumb_elm.attrib['href']
        preview_response = requests.get(full_size_preview_url, headers=headers, cookies=jar)
        preview_root = html.fromstring(preview_response.text)

        image_urls.append({
            'thumb_image': thumb_elm.xpath('./img')[0].attrib['src'],
            'full_size_image': preview_root.xpath('//img[@id="show_image"]')[0].attrib['src'],
            'page_url': full_size_preview_url  # you probably won't need this
        })

    return image_urls if isinstance(images, list) else image_urls[0]

class UploadFailed(Exception):
    pass

class TooLargeImageFormat(Exception):
    pass


text:
#include "compactblockprocessor.h"
#include "compactthin.h"
#include "blockencodings.h"
#include "thinblock.h"
#include "streams.h"
#include "util.h" // LogPrintf
#include "net.h"
#include "netmessagemaker.h"
#include "utilprocessmsg.h"
#include "consensus/validation.h"
#include "compacttxfinder.h"

void CompactBlockProcessor::operator()(CDataStream& vRecv, const CTxMemPool& mempool,
        uint64_t currMaxBlockSize, int activeChainHeight)
{
    CompactBlock block;
    vRecv >> block;

    const uint256 hash = block.header.GetHash();

    LogPrintf("received compactblock %s from peer=%d\n",
            hash.ToString(), worker.nodeID());

    try {
        validateCompactBlock(block, currMaxBlockSize);
    }
    catch (const std::exception& e) {
        LogPrint(Log::BLOCK, "Invalid compact block %s\n", e.what());
        rejectBlock(hash, e.what(), 20);
        return;
    }

    // We (may) have requested node to announce blocks to us and it will
    // continue to do so even if we haven't kept up. Don't misbehave it for
    // sending us unconnected headers.
    bool bumpUnconnecting = false;
    if (requestConnectHeaders(block.header, bumpUnconnecting)) {
        worker.stopWork(hash);
        return;
    }

    if (!setToWork(block.header, activeChainHeight))
        return;

    from.AddInventoryKnown(CInv(MSG_CMPCT_BLOCK, hash));

    std::unique_ptr<CompactStub> stub;
    try {
        CompactTxFinder txfinder(mempool,
                block.shorttxidk0, block.shorttxidk1);

        stub.reset(new CompactStub(block));
        worker.buildStub(*stub, txfinder, connman, from);
    }
    catch (const thinblock_error& e) {
        rejectBlock(hash, e.what(), 10);
        return;
    }

    if (!worker.isWorkingOn(hash)) {
        // Stub had enough data to finish
        // the block.
        return;
    }

    // Request missing
    std::vector<std::pair<int, ThinTx> > missing = worker.getTxsMissing(hash);

    CompactReRequest req;
    req.blockhash = hash;

    for (auto& t : missing)
        req.indexes.push_back(t.first /* index in block */);

    LogPrint(Log::BLOCK, "re-requesting %d compact txs for %s peer=%d\n",
            req.indexes.size(), hash.ToString(), from.id);
    connman.PushMessage(&from, NetMsg(&from, NetMsgType::GETBLOCKTXN, req));
}


text:
'use strict';
const {expect} = require('chai');
const sinon = require('sinon');
const proxyquire = require('proxyquire').noCallThru().noPreserveCache();

const modulePath = '../../../../lib/commands/doctor/index';

describe('Unit: Commands > Doctor', function () {
    it('doesn\'t do anything if there are no checks to run (with log)', function () {
        const listrStub = sinon.stub().resolves();
        const logStub = sinon.stub();
        const hookStub = sinon.stub().resolves([]);
        const DoctorCommand = proxyquire(modulePath, {
            './checks': []
        });
        const instance = new DoctorCommand({listr: listrStub, log: logStub}, {hook: hookStub});

        return instance.run({}).then(() => {
            expect(listrStub.called).to.be.false;
            expect(hookStub.calledOnce).to.be.true;
            expect(hookStub.calledWithExactly('doctor')).to.be.true;
            expect(logStub.calledOnce).to.be.true;
            expect(logStub.args[0][0]).to.equal('No checks found to run.');
        });
    });

    it('doesn\'t do anything if there are no checks to run (with log + specific categories)', function () {
        const listrStub = sinon.stub().resolves();
        const logStub = sinon.stub();
        const hookStub = sinon.stub().resolves([]);
        const DoctorCommand = proxyquire(modulePath, {
            './checks': []
        });
        const instance = new DoctorCommand({listr: listrStub, log: logStub}, {hook: hookStub});

        return instance.run({categories: ['testing', 'validity']}).then(() => {
            expect(listrStub.called).to.be.false;
            expect(logStub.calledOnce).to.be.true;
            expect(hookStub.calledOnce).to.be.true;
            expect(hookStub.calledWithExactly('doctor')).to.be.true;
            expect(logStub.args[0][0]).to.equal('No checks found to run for categories "testing, validity".');
        });
    });

    it('doesn\'t do anything if there are no checks to run (without log)', function () {
        const listrStub = sinon.stub().resolves();
        const logStub = sinon.stub();
        const hookStub = sinon.stub().resolves([]);
        const DoctorCommand = proxyquire(modulePath, {
            './checks': []
        });
        const instance = new DoctorCommand({listr: listrStub, log: logStub}, {hook: hookStub});

        return instance.run({quiet: true}).then(() => {
            expect(listrStub.called).to.be.false;
            expect(hookStub.calledOnce).to.be.true;
            expect(hookStub.calledWithExactly('doctor')).to.be.true;
            expect(logStub.called).to.be.false;
        });
    });

    it('checks instance if skipInstanceCheck not passed, uses correct context', function () {
        const ui = {listr: sinon.stub().resolves()};
        const instanceStub = {checkEnvironment: sinon.stub()};
        const system = {
            getInstance: sinon.stub().returns(instanceStub),
            hook: sinon.stub().resolves([{
                title: 'Extension Task 1',
                task: 'someTask'
            }])
        };
        const findValidStub = sinon.stub();

        const DoctorCommand = proxyquire(modulePath, {
            '../../utils/find-valid-install': findValidStub,
            './checks': [{}]
        });
        const instance = new DoctorCommand(ui, system);

        return instance.run({test: true, a: 'b'}).then(() => {
            expect(findValidStub.calledOnce).to.be.true;
            expect(system.getInstance.calledOnce).to.be.true;
            expect(system.hook.calledOnce).to.be.true;
            expect(system.hook.calledWithExactly('doctor')).to.be.true;
            expect(instanceStub.checkEnvironment.calledOnce).to.be.true;
            expect(ui.listr.calledOnce).to.be.true;
            expect(ui.listr.args[0][0]).to.deep.equal([
                {},
                {
                    title: 'Extension Task 1',
                    task: 'someTask'
                }
            ]);
            const context = ui.listr.args[0][1];
            expect(context.argv).to.deep.equal({test: true, a: 'b'});
            expect(context.system).to.equal(system);
            expect(context.instance).to.equal(instanceStub);
            expect(context.ui).to.equal(ui);
            expect(context.local).to.be.false;
            expect(context.isDoctorCommand).to.be.false;
        });
    });

    it('skips instance check if skipInstanceCheck is true, uses correct context', function () {
        const ui = {listr: sinon.stub().resolves()};
        const instanceStub = {checkEnvironment: sinon.stub()};
        const system = {
            getInstance: sinon.stub().returns(instanceStub),
            hook: sinon.stub().resolves([{
                title: 'Extension Task 1',
                task: 'someTask'
            }])
        };
        const findValidStub = sinon.stub();

        const DoctorCommand = proxyquire(modulePath, {
            '../../utils/find-valid-install': findValidStub,
            './checks': [{}]
        });
        const instance = new DoctorCommand(ui, system);

        return instance.run({skipInstanceCheck: true, local: true, argv: true}).then(() => {
            expect(findValidStub.called).to.be.false;
            expect(system.hook.calledOnce).to.be.true;
            expect(system.hook.calledWithExactly('doctor')).to.be.true;
            expect(instanceStub.checkEnvironment.called).to.be.false;
            expect(ui.listr.calledOnce).to.be.true;
            expect(ui.listr.args[0][0]).to.deep.equal([
                {},
                {
                    title: 'Extension Task 1',
                    task: 'someTask'
                }
            ]);
            const context = ui.listr.args[0][1];
            expect(context.argv).to.deep.equal({skipInstanceCheck: true, local: true, argv: true});
            expect(context.system).to.equal(system);
            expect(context.ui).to.equal(ui);
            expect(context.local).to.be.true;
            expect(context.isDoctorCommand).to.be.false;
        });
    });

    it('skips instance check if only category is install, uses correct context', function () {
        const ui = {listr: sinon.stub().resolves()};
        const instanceStub = {checkEnvironment: sinon.stub()};
        const system = {
            getInstance: sinon.stub().returns(instanceStub),
            hook: sinon.stub().resolves([{
                title: 'Extension Task 1',
                task: 'someTask'
            }])
        };
        const findValidStub = sinon.stub();

        const DoctorCommand = proxyquire(modulePath, {
            '../../utils/find-valid-install': findValidStub,
            './checks': [{category: ['install']}]
        });
        const instance = new DoctorCommand(ui, system);

        return instance.run({
            skipInstanceCheck: false,
            local: true,
            argv: true,
            categories: ['install'],
            _: ['doctor']
        }).then(() => {
            expect(findValidStub.called).to.be.false;
            expect(system.hook.calledOnce).to.be.true;
            expect(system.hook.calledWithExactly('doctor')).to.be.true;
            expect(instanceStub.checkEnvironment.called).to.be.false;
            expect(ui.listr.calledOnce).to.be.true;
            expect(ui.listr.args[0][0]).to.deep.equal([{category: ['install']}]);
            const context = ui.listr.args[0][1];
            expect(context.argv).to.deep.equal({
                skipInstanceCheck: false,
                local: true,
                argv: true,
                categories: ['install'],
                _: ['doctor']
            });
            expect(context.system).to.equal(system);
            expect(context.ui).to.equal(ui);
            expect(context.local).to.be.true;
            expect(context.isDoctorCommand).to.be.true;
        });
    });

    describe('filters checks correctly', function () {
        const testChecks = [{
            title: 'Check 1',
            category: ['install']
        }, {
            title: 'Check 2',
            category: ['start']
        }, {
            title: 'Check 3',
            category: ['install', 'start']
        }];
        const listrStub = sinon.stub().resolves();
        const hookStub = sinon.stub().resolves([]);
        let instance;

        beforeEach(() => {
            const DoctorCommand = proxyquire(modulePath, {
                './checks': testChecks
            });
            instance = new DoctorCommand({listr: listrStub}, {hook: hookStub, getInstance: sinon.stub()});
        });

        afterEach(() => {
            listrStub.resetHistory();
            hookStub.resetHistory();
        });

        it('doesn\'t filter if no categories passed', function () {
            return instance.run({skipInstanceCheck: true}).then(() => {
                expect(listrStub.calledOnce).to.be.true;
                expect(hookStub.calledOnce).to.be.true;
                const tasks = listrStub.args[0][0];
                expect(tasks).to.be.an('array');
                expect(tasks.length).to.equal(3);
            });
        });

        it('filters with one category passed', function () {
            return instance.run({skipInstanceCheck: true, categories: ['install']}).then(() => {
                expect(listrStub.calledOnce).to.be.true;
                expect(hookStub.calledOnce).to.be.true;
                const tasks = listrStub.args[0][0];
                expect(tasks).to.be.an('array');
                expect(tasks.length).to.equal(2);
                expect(tasks[0].title).to.equal('Check 1');
                expect(tasks[1].title).to.equal('Check 3');
            });
        });

        it('filters with another category passed', function () {
            return instance.run({skipInstanceCheck: true, categories: ['start']}).then(() => {
                expect(listrStub.calledOnce).to.be.true;
                expect(hookStub.calledOnce).to.be.true;
                const tasks = listrStub.args[0][0];
                expect(tasks).to.be.an('array');
                expect(tasks.length).to.equal(2);
                expect(tasks[0].title).to.equal('Check 2');
                expect(tasks[1].title).to.equal('Check 3');
            });
        });

        it('filters with multiple categories passed', function () {
            return instance.run({skipInstanceCheck: true, categories: ['install', 'start']}).then(() => {
                expect(listrStub.calledOnce).to.be.true;
                expect(hookStub.calledOnce).to.be.true;
                const tasks = listrStub.args[0][0];
                expect(tasks).to.be.an('array');
                expect(tasks.length).to.equal(3);
            });
        });
    });
});


text:
user admin persistence using an RDBMS.
This bundle uses a DataSource service whose *application* String+ property contains *useradmin*


text:
package org.apache.asterix.external.feed.api;

public interface IMessageReceiver<T> {

    public void sendMessage(T message) throws InterruptedException;

    public void close(boolean processPending);

    public void start();
}


text:
package com.intellij.codeInspection.dataFlow;

import com.intellij.codeInspection.dataFlow.instructions.MethodCallInstruction;
import com.intellij.codeInspection.dataFlow.rangeSet.LongRangeSet;
import com.intellij.codeInspection.dataFlow.value.*;
import com.intellij.codeInspection.dataFlow.value.DfaRelationValue.RelationType;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiMethodCallExpression;
import com.intellij.psi.PsiMethodReferenceExpression;
import com.intellij.util.ArrayUtil;
import com.intellij.util.ObjectUtils;
import com.siyeh.ig.callMatcher.CallMapper;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import static com.intellij.psi.CommonClassNames.*;
import static com.siyeh.ig.callMatcher.CallMatcher.*;

/**
 * @author Tagir Valeev
 */
public class CustomMethodHandlers {
  interface CustomMethodHandler {
    List<DfaMemoryState> handle(DfaCallArguments callArguments, DfaMemoryState memState, DfaValueFactory factory);
  }

  private static final CallMapper<CustomMethodHandler> CUSTOM_METHOD_HANDLERS = new CallMapper<CustomMethodHandler>()
    .register(instanceCall(JAVA_LANG_STRING, "indexOf", "lastIndexOf"),
              (args, memState, factory) -> indexOf(args.myQualifier, memState, factory, SpecialField.STRING_LENGTH))
    .register(instanceCall(JAVA_UTIL_LIST, "indexOf", "lastIndexOf"),
              (args, memState, factory) -> indexOf(args.myQualifier, memState, factory, SpecialField.COLLECTION_SIZE))
    .register(instanceCall(JAVA_LANG_STRING, "equals").parameterCount(1),
              (args, memState, factory) -> stringEquals(args, memState, factory, false))
    .register(instanceCall(JAVA_LANG_STRING, "equalsIgnoreCase").parameterCount(1),
              (args, memState, factory) -> stringEquals(args, memState, factory, true))
    .register(instanceCall(JAVA_LANG_STRING, "startsWith").parameterCount(1),
              (args, memState, factory) -> stringStartsEnds(args, memState, factory, false))
    .register(instanceCall(JAVA_LANG_STRING, "endsWith").parameterCount(1),
              (args, memState, factory) -> stringStartsEnds(args, memState, factory, true))
    .register(anyOf(staticCall(JAVA_LANG_MATH, "max").parameterTypes("int", "int"),
                    staticCall(JAVA_LANG_MATH, "max").parameterTypes("long", "long"),
                    staticCall(JAVA_LANG_INTEGER, "max").parameterTypes("int", "int"),
                    staticCall(JAVA_LANG_LONG, "max").parameterTypes("long", "long")),
              (args, memState, factory) -> mathMinMax(args.myArguments, memState, factory, true))
    .register(anyOf(staticCall(JAVA_LANG_MATH, "min").parameterTypes("int", "int"),
                    staticCall(JAVA_LANG_MATH, "min").parameterTypes("long", "long"),
                    staticCall(JAVA_LANG_INTEGER, "min").parameterTypes("int", "int"),
                    staticCall(JAVA_LANG_LONG, "min").parameterTypes("long", "long")),
              (args, memState, factory) -> mathMinMax(args.myArguments, memState, factory, false))
    .register(staticCall(JAVA_LANG_MATH, "abs").parameterTypes("int"),
              (args, memState, factory) -> mathAbs(args.myArguments, memState, factory, false))
    .register(staticCall(JAVA_LANG_MATH, "abs").parameterTypes("long"),
              (args, memState, factory) -> mathAbs(args.myArguments, memState, factory, true));

  public static CustomMethodHandler find(MethodCallInstruction instruction) {
    PsiElement context = instruction.getContext();
    if(context instanceof PsiMethodCallExpression) {
      return CUSTOM_METHOD_HANDLERS.mapFirst((PsiMethodCallExpression)context);
    } else if(context instanceof PsiMethodReferenceExpression) {
      return CUSTOM_METHOD_HANDLERS.mapFirst((PsiMethodReferenceExpression)context);
    }
    return null;
  }

  private static List<DfaMemoryState> stringStartsEnds(DfaCallArguments args,
                                                       DfaMemoryState memState,
                                                       DfaValueFactory factory,
                                                       boolean ends) {
    DfaValue arg = ArrayUtil.getFirstElement(args.myArguments);
    if (arg == null) return Collections.emptyList();
    String leftConst = ObjectUtils.tryCast(getConstantValue(memState, args.myQualifier), String.class);
    String rightConst = ObjectUtils.tryCast(getConstantValue(memState, arg), String.class);
    if (leftConst != null && rightConst != null) {
      return singleResult(memState, factory.getBoolean(ends ? leftConst.endsWith(rightConst) : leftConst.startsWith(rightConst)));
    }
    DfaValue leftLength = SpecialField.STRING_LENGTH.createValue(factory, args.myQualifier);
    DfaValue rightLength = SpecialField.STRING_LENGTH.createValue(factory, arg);
    DfaValue trueRelation = factory.createCondition(leftLength, RelationType.GE, rightLength);
    DfaValue falseRelation = factory.createCondition(leftLength, RelationType.LT, rightLength);
    return applyCondition(memState, trueRelation, DfaUnknownValue.getInstance(), falseRelation, factory.getBoolean(false));
  }

  private static List<DfaMemoryState> stringEquals(DfaCallArguments args,
                                                   DfaMemoryState memState,
                                                   DfaValueFactory factory,
                                                   boolean ignoreCase) {
    DfaValue arg = ArrayUtil.getFirstElement(args.myArguments);
    if (arg == null) return Collections.emptyList();
    String leftConst = ObjectUtils.tryCast(getConstantValue(memState, args.myQualifier), String.class);
    String rightConst = ObjectUtils.tryCast(getConstantValue(memState, arg), String.class);
    if (leftConst != null && rightConst != null) {
      return singleResult(memState, factory.getBoolean(ignoreCase ? leftConst.equalsIgnoreCase(rightConst) : leftConst.equals(rightConst)));
    }
    DfaValue leftLength = SpecialField.STRING_LENGTH.createValue(factory, args.myQualifier);
    DfaValue rightLength = SpecialField.STRING_LENGTH.createValue(factory, arg);
    DfaValue trueRelation = factory.createCondition(leftLength, RelationType.EQ, rightLength);
    DfaValue falseRelation = factory.createCondition(leftLength, RelationType.NE, rightLength);
    return applyCondition(memState, trueRelation, DfaUnknownValue.getInstance(), falseRelation, factory.getBoolean(false));
  }

  private static List<DfaMemoryState> indexOf(DfaValue qualifier,
                                              DfaMemoryState memState,
                                              DfaValueFactory factory,
                                              SpecialField specialField) {
    DfaValue length = specialField.createValue(factory, qualifier);
    LongRangeSet range = memState.getValueFact(DfaFactType.RANGE, length);
    long maxLen = range == null || range.isEmpty() ? Integer.MAX_VALUE : range.max();
    return singleResult(memState, factory.getFactValue(DfaFactType.RANGE, LongRangeSet.range(-1, maxLen - 1)));
  }

  private static List<DfaMemoryState> mathMinMax(DfaValue[] args, DfaMemoryState memState, DfaValueFactory factory, boolean max) {
    if(args == null || args.length != 2) return Collections.emptyList();
    LongRangeSet first = memState.getValueFact(DfaFactType.RANGE, args[0]);
    LongRangeSet second = memState.getValueFact(DfaFactType.RANGE, args[1]);
    if (first == null || second == null || first.isEmpty() || second.isEmpty()) return Collections.emptyList();
    LongRangeSet domain = max ? LongRangeSet.range(Math.max(first.min(), second.min()), Long.MAX_VALUE)
                          : LongRangeSet.range(Long.MIN_VALUE, Math.min(first.max(), second.max()));
    LongRangeSet result = first.union(second).intersect(domain);
    return singleResult(memState, factory.getFactValue(DfaFactType.RANGE, result));
  }

  private static List<DfaMemoryState> mathAbs(DfaValue[] args, DfaMemoryState memState, DfaValueFactory factory, boolean isLong) {
    DfaValue arg = ArrayUtil.getFirstElement(args);
    if(arg == null) return Collections.emptyList();
    LongRangeSet range = memState.getValueFact(DfaFactType.RANGE, arg);
    if (range == null) return Collections.emptyList();
    return singleResult(memState, factory.getFactValue(DfaFactType.RANGE, range.abs(isLong)));
  }

  private static List<DfaMemoryState> singleResult(DfaMemoryState state, DfaValue value) {
    state.push(value);
    return Collections.singletonList(state);
  }

  @NotNull
  private static List<DfaMemoryState> applyCondition(DfaMemoryState memState,
                                                     DfaValue trueCondition,
                                                     DfaValue trueResult,
                                                     DfaValue falseCondition,
                                                     DfaValue falseResult) {
    DfaMemoryState falseState = memState.createCopy();
    List<DfaMemoryState> result = new ArrayList<>(2);
    if (memState.applyCondition(trueCondition)) {
      memState.push(trueResult);
      result.add(memState);
    }
    if (falseState.applyCondition(falseCondition)) {
      falseState.push(falseResult);
      result.add(falseState);
    }
    return result;
  }

  private static Object getConstantValue(DfaMemoryState memoryState, DfaValue value) {
    if (value instanceof DfaVariableValue) {
      value = memoryState.getConstantValue((DfaVariableValue)value);
    }
    if (value instanceof DfaConstValue) {
      return ((DfaConstValue)value).getValue();
    }
    return null;
  }
}


text:
module Context.Cache where
import Context.Reference
import Control.DateTime.Absolute
import Data.File
import Data.Map ( Map )
import Internal
import Text.Pin
import qualified Data.Map as Map

data Cache = Cache
    { refs  :: Map Reference Absolute
    , pins  :: Map Pin (Maybe File)
    -- TODO: stop caching codes (applies to Context as well)
    , codes :: Map String (Maybe (Direction, Absolute))
    } deriving Show

putRef :: Reference -> Absolute -> Cache -> Cache
putRef k a c = c{refs=Map.insert k a $ refs c}

getRef :: Reference -> Cache -> Maybe Absolute
getRef k = Map.lookup k . refs

putPin :: Pin -> Maybe File -> Cache -> Cache
putPin k a c = c{pins=Map.insert k a $ pins c}

getPin :: Pin -> Cache -> Maybe (Maybe File)
getPin k = Map.lookup k . pins

putCode :: String -> Maybe (Direction, Absolute) -> Cache -> Cache
putCode k a c = c{codes=Map.insert k a $ codes c}

getCode :: String -> Cache -> Maybe (Maybe (Direction, Absolute))
getCode k = Map.lookup k . codes

empty :: Cache
empty = Cache Map.empty Map.empty Map.empty


text:
/*!
 * @addtogroup dbtool Projects/CoX/Utilities/dbtool
 * @{
 */

#include "DBConnection.h"

#include "Components/Logging.h"
#include "Components/Settings.h"

#include <QtCore/QJsonDocument>
#include <QtCore/QJsonObject>
#include <QtCore/QJsonArray>
#include <QtSql/QtSql>

/*!
 * @brief       Check if a database is connected
 * @returns     Returns a boolean, true if database exists
 */
bool DBConnection::isConnected()
{
    QString querytext;
    if(m_config.isSqlite())
    {
        if(!fileExists(m_config.m_db_name))
            return false;

        return true;
    }
    else if(m_config.isMysql())
    {
        return m_db->isOpen();
    }
    else if(m_config.isPostgresql())
    {
        querytext = QString("SELECT table_schema || '.' || table_name FROM information_schema.tables WHERE table_type = 'BASE TABLE' AND table_schema ='%1';")
                .arg(m_config.m_db_name);
    }
    else
    {
        qWarning() << "Database configuration is set to unknown DB Driver. Connection unknown!";
        return false; // can't tell if database is connected
    }

    if(!runQuery(querytext))
        return false;

    if(m_query->size() >= 1)
        return true;

    qWarning() << "Something went wrong! Database connection failed in isConnected()";
    return false;
}

/*!
 * @brief       Run a string as query
 * @param[in]   q a QString sql query
 * @returns     Returns a boolean, true if successful
 */
bool DBConnection::runQueries(const QStringList &qlist)
{
    for(const QString &q : qlist)
    {
        if(!runQuery(q))
            return false;
    }

    return true;
}

/*!
 * @brief       Run a string as query
 * @param[in]   q a QString sql query
 * @returns     Returns a boolean, true if successful
 */
bool DBConnection::runQuery(const QString &q)
{
    if(!m_query->prepare(q))
    {
        qCritical("One of the queries failed to prepare.\n Error detail: %s\n",
                  qPrintable(m_query->lastError().text()));
        qCritical().noquote() << m_query->lastQuery();
        return false;
    }

    if(!m_query->exec())
    {
        qCritical("One of the queries failed to execute.\n Error detail: %s\n",
                  qPrintable(m_query->lastError().text()));
        qCritical().noquote() << m_query->lastQuery();
        return false;
    }

    qCDebug(logDB).noquote() << "exec:" << m_query->lastQuery();
    return true;
}

/*!
 * @brief           Delete columns (col_to_remove) in tablename using
 *                  common sql methods
 * @param[in]       tablename as QString
 * @param[in]       col_to_remove a QStringList of column names
 */
bool DBConnection::deleteColumnsCommon(const QString &tablename, const QStringList &cols_to_remove)
{
    // iterate over all columns in tablename
    for(const QString &column : cols_to_remove)
    {
        QString tmp_query = QString("ALTER TABLE %1 DROP %2;").arg(tablename, column);
        if(!runQuery(tmp_query))
        {
            qWarning() << column << "does not exist in" << tablename;
            return false;
        }
    }

    return true;
}

/*!
 * @brief           Delete columns (col_to_remove) in tablename using
 *                  sqlite specific methods
 * @param[in]       tablename as QString
 * @param[in]       col_to_remove a QStringList of column names
 */
bool DBConnection::deleteColumnsSqlite(const QString &tablename, const QStringList &cols_to_remove)
{
    // SQLite has limited ALTER TABLE support and cannot drop columns.
    // the workaround is to duplicate the table without the "dropped" columns

    // Get Original Column List and fill it
    std::vector<ColumnSchema> old_cols_arr;
    if(!getColumnsFromTable(tablename, old_cols_arr))
        return false;

    // Take all old columns and add them to new vector
    // ignoring columns from list of cols to remove
    QStringList old_cols_namelist, new_cols_namelist;
    QStringList old_cols_as_sql, new_cols_as_sql;
    for(ColumnSchema &cs : old_cols_arr)
    {
        // Create sql strings here
        old_cols_namelist.push_back(cs.m_name);
        old_cols_as_sql.push_back(QString("'%1' %2").arg(cs.m_name).arg(cs.m_data_type));

        // if column should be removed, we're done here
        if(cols_to_remove.contains(cs.m_name, Qt::CaseInsensitive))
            continue;

        new_cols_namelist.push_back(cs.m_name);
        new_cols_as_sql.push_back(QString("'%1' %2").arg(cs.m_name).arg(cs.m_data_type));
    }

    // Replace current table with one that excludes our "deleted" columns
    QStringList queries;
    queries << QString("CREATE TABLE `%1_old` (%2);")
             .arg(tablename)
             .arg(old_cols_as_sql.join(","));
    queries << QString("INSERT INTO %1_old SELECT %2 FROM %1;")
             .arg(tablename)
             .arg(old_cols_namelist.join(","));
    queries << QString("DROP TABLE %1;")
             .arg(tablename);
    queries << QString("CREATE TABLE `%1` (%2);")
             .arg(tablename)
             .arg(new_cols_as_sql.join(","));
    queries << QString("INSERT INTO %1 SELECT %2 FROM %1_old;")
             .arg(tablename)
             .arg(new_cols_namelist.join(","));
    queries << QString("DROP TABLE %1_old;")
             .arg(tablename);

    return runQueries(queries);
}

/*!
 * @brief           Delete columns (cols_to_remove) in tablename
 * @param[in]       tablename as QString
 * @param[in]       cols_to_remove a QStringList of column names
 */
bool DBConnection::deleteColumns(const QString &tablename, const QStringList &cols_to_remove)
{
    if(!m_config.isSqlite())
        return deleteColumnsCommon(tablename, cols_to_remove);

    return deleteColumnsSqlite(tablename, cols_to_remove);
}

/*!
 * @brief           Delete single column (col_to_remove) in tablename
 * @param[in]       tablename as QString
 * @param[in]       col_to_remove a QStringList of column names
 */
bool DBConnection::deleteColumn(const QString &tablename, const QString &col_to_remove)
{
    QStringList cols;
    cols.push_back(col_to_remove);
    return deleteColumns(tablename, cols);
}

/*!
 * @brief           Get Columns from tablename
 * @param[in]       tablename as QString
 * @param[out]      std::vector<ColumnSchema> a vector of columns and their datatypes
 */
bool DBConnection::getColumnsFromTable(const QString &tablename, std::vector<ColumnSchema> &old_cols)
{
    // This is only ever called on SQLite tables
    // because other DB Drivers can delete columns
    if(m_db->driverName() != "QSQLITE")
        qWarning() << "Running getColumnsFromTable on non-SQLite DB. Why?";

    QString query = QString("PRAGMA table_info(%1)").arg(tablename);
    m_query->prepare(query);
    if(!m_query->exec())
        return false;

    while(m_query->next())
    {
        ColumnSchema c;
        c.m_name = m_query->value(1).toString();
        c.m_data_type = m_query->value(2).toString();
        old_cols.push_back(c);
        qCDebug(logDB) << "Reading column:" << c.m_name << c.m_data_type;

    }

    return true; // we're done here
}

/*!
 * @brief           Some objects have become arrays of objects
 *                  like costumes for example. Convert them here.
 * @param[in,out]   obj
 */
void DBConnection::prepareCerealArray(QJsonObject &obj)
{
    QJsonArray wrapped_arr;
    wrapped_arr.append(QJsonValue(obj));
    QJsonObject wrapped_obj;
    wrapped_obj.insert("value0", QJsonValue(wrapped_arr));
    obj = wrapped_obj;
}

/*!
 * @brief           Cereal adds a wrapper around the entire object
 *                  with a key of `value0`. We add that here.
 * @param[in,out]   obj
 */
void DBConnection::prepareCerealObject(QJsonObject &obj)
{
    QJsonObject wrapped_obj;
    wrapped_obj.insert("value0", obj);
    obj = wrapped_obj;
}

/*!
 * @brief           Return a QVariantMap that we can access easily
 * @param[in]       column_name of the column that contains the json
 * @param[out]      QVariantMap of json structure
 */
QJsonObject DBConnection::loadBlob(const QString &column_name)
{
    QJsonParseError err;
    QJsonDocument jdoc = QJsonDocument::fromJson(m_query->value(column_name).toByteArray(), &err);

    if(err.error != QJsonParseError::NoError)
        qWarning() << "Json Parser Error:" << qPrintable(err.errorString()) << err.offset;

    QJsonObject obj = jdoc.object();
    if(obj.size() < 2) // if single cereal object, remove wrapper
        obj = jdoc.object()["value0"].toObject();

    qCDebug(logMigration).noquote() << "Loading Blob:" << jdoc.toJson();
    return obj;
}

/*!
 * @brief           Save jsondocument to QString to save to database.
 * @param[in]       QVariantMap map
 * @param[out]      QString of json document
 */
QString DBConnection::saveBlob(QJsonObject &obj)
{
    // annoyingly cereal wraps every object with key "value0"
    // if there is no cereal wrapper, then add it here
    if(obj.size() > 1 && !obj.keys().contains("value0", Qt::CaseInsensitive))
        prepareCerealObject(obj);

    QJsonDocument json_doc(obj);
    QString sanitized_blob = json_doc.toJson();
    sanitized_blob.replace("'","''"); // sql uses ' as an escape character, escape the escape!
    return sanitized_blob;
}

//! @}


text:
package client

import (
	"context"

	"go-common/app/interface/main/history/model"
	"go-common/library/net/rpc"
)

const (
	_progress      = "RPC.Progress"
	_position      = "RPC.Position"
	_add           = "RPC.Add"
	_delete        = "RPC.Delete"
	_history       = "RPC.History"
	_historyCursor = "RPC.HistoryCursor"
	_clear         = "RPC.Clear"
)

var (
	_noRes = &struct{}{}
)

// Service struct info.
type Service struct {
	client *rpc.Client2
}

const (
	_appid = "community.service.history"
)

// New create instance of service and return.
func New(c *rpc.ClientConfig) (s *Service) {
	s = &Service{}
	s.client = rpc.NewDiscoveryCli(_appid, c)
	return
}

// Progress return map[mid]*history.
func (s *Service) Progress(c context.Context, arg *model.ArgPro) (res map[int64]*model.History, err error) {
	res = make(map[int64]*model.History)
	err = s.client.Call(c, _progress, arg, &res)
	return
}

// Position return map[mid]*history.
func (s *Service) Position(c context.Context, arg *model.ArgPos) (res *model.History, err error) {
	res = &model.History{}
	err = s.client.Call(c, _position, arg, res)
	return
}

// Add add history .
func (s *Service) Add(c context.Context, arg *model.ArgHistory) (err error) {
	err = s.client.Call(c, _add, arg, _noRes)
	return
}

// Delete add history .
func (s *Service) Delete(c context.Context, arg *model.ArgDelete) (err error) {
	err = s.client.Call(c, _delete, arg, _noRes)
	return
}

// History return all histories .
func (s *Service) History(c context.Context, arg *model.ArgHistories) (res []*model.Resource, err error) {
	err = s.client.Call(c, _history, arg, &res)
	return
}

// HistoryCursor return all histories .
func (s *Service) HistoryCursor(c context.Context, arg *model.ArgCursor) (res []*model.Resource, err error) {
	err = s.client.Call(c, _historyCursor, arg, &res)
	return
}

// Clear clear history
func (s *Service) Clear(c context.Context, arg *model.ArgClear) (err error) {
	err = s.client.Call(c, _clear, arg, _noRes)
	return
}


text:
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-comp-3168',
  templateUrl: './comp-3168.component.html',
  styleUrls: ['./comp-3168.component.css']
})
export class Comp3168Component implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}


text:
require 'yt/annotations/note'

module Yt
  module Annotations
    # A Label annotation is just a Note annotation with text, start/end time
    # and an optional link, but shaped like a rectangle without borders.
    class Label < Note
    end
  end
end


text:
import React from 'react';
import PropTypes from 'prop-types';
import { ThemeProvider, withTheme } from '@material-ui/styles';
import Button from '@material-ui/core/Button';

function DeepChildRaw(props) {
  return <Button>{`spacing ${props.theme.spacing}`}</Button>;
}

DeepChildRaw.propTypes = {
  theme: PropTypes.object.isRequired,
};

const DeepChild = withTheme()(DeepChildRaw);

function WithTheme() {
  return (
    <ThemeProvider
      theme={{
        spacing: '8px',
      }}
    >
      <DeepChild />
    </ThemeProvider>
  );
}

export default WithTheme;


text:
import datetime

from django.conf import settings
from django.core.mail import send_mail
from django.core.management.base import BaseCommand
from django.template.loader import render_to_string

from ...models import CorporateMember

class Command(BaseCommand):

    def handle(self, *args, **options):
        thirty_days_from_now = datetime.date.today() + datetime.timedelta(days=30)
        for member in CorporateMember.objects.filter(inactive=False):
            if member.get_expiry_date() == thirty_days_from_now:
                send_mail(
                    'Expiring Django Software Foundation Membership for %s' % member.display_name,
                    render_to_string('members/corporate_member_renewal_email.txt', {
                        'contact_name': member.contact_name,
                        'member_name': member.display_name,
                        'expiry_date': member.get_expiry_date(),
                        'renewal_link': member.get_renewal_link(),
                    }),
                    settings.FUNDRAISING_DEFAULT_FROM_EMAIL,
                    [
                        settings.FUNDRAISING_DEFAULT_FROM_EMAIL,
                        member.contact_email,
                    ],
                )


text:
/* AUTO-GENERATED FILE.  DO NOT MODIFY.
 *
 * This class was automatically generated by the
 * aapt tool from the resource data it found.  It
 * should not be modified by hand.
 */

package mx.afelipe.android.alarma;

public final class R {
    public static final class attr {
    }
    public static final class color {
        public static final int BlackText=0x7f080004;
        public static final int ColorDivider=0x7f080005;
        public static final int ColorEditText=0x7f080000;
        public static final int ColorText=0x7f080001;
        public static final int GreenColor=0x7f080003;
        public static final int RedText=0x7f080002;
    }
    public static final class dimen {
        /**  Default screen margins, per the Android Design guidelines.

         Customize dimensions originally defined in res/values/dimens.xml (such as
         screen margins) for sw720dp devices (e.g. 10" tablets) in landscape here.

         */
        public static final int activity_horizontal_margin=0x7f050000;
        public static final int activity_vertical_margin=0x7f050001;
        public static final int textSize=0x7f050002;
    }
    public static final class drawable {
        public static final int actionbarbackground=0x7f020000;
        public static final int backgroundapp=0x7f020001;
        public static final int botongenerico=0x7f020002;
        public static final int botonrojo=0x7f020003;
        public static final int botonsfondo=0x7f020004;
        public static final int botonverde=0x7f020005;
        public static final int buttonsbackgound=0x7f020006;
        public static final int divider=0x7f020007;
        public static final int ic_launcher=0x7f020008;
        public static final int milogov2=0x7f020009;
        public static final int twittericon=0x7f02000a;
    }
    public static final class id {
        public static final int ActDescAlarmBtn=0x7f0a000b;
        public static final int DescSucesoTxt=0x7f0a000e;
        public static final int EstadoText=0x7f0a000a;
        public static final int SucesosListView=0x7f0a000d;
        public static final int TextView01=0x7f0a0005;
        public static final int TiempoSucesoTxt=0x7f0a000f;
        public static final int action_about=0x7f0a0010;
        public static final int detenerSonidoBtn=0x7f0a000c;
        public static final int fallaBtn=0x7f0a0006;
        public static final int imageView1=0x7f0a0000;
        public static final int imageView2=0x7f0a0001;
        public static final int irCodigoBtn=0x7f0a0008;
        public static final int irTwitterBtn=0x7f0a0002;
        public static final int textView1=0x7f0a0009;
        public static final int textView2=0x7f0a0003;
        public static final int textView3=0x7f0a0004;
        public static final int view1=0x7f0a0007;
    }
    public static final class layout {
        public static final int activity_about=0x7f030000;
        public static final int activity_main=0x7f030001;
        public static final int main_fragment_layout=0x7f030002;
        public static final int sucesoitem_layout=0x7f030003;
    }
    public static final class menu {
        public static final int about=0x7f090000;
        public static final int main=0x7f090001;
    }
    public static final class raw {
        public static final int alert_sound=0x7f040000;
    }
    public static final class string {
        public static final int about=0x7f060005;
        public static final int action_settings=0x7f060001;
        public static final int app_name=0x7f060000;
        public static final int hello_world=0x7f060002;
        public static final int home=0x7f060004;
        public static final int local_service=0x7f060006;
        public static final int title_activity_about=0x7f060003;
    }
    public static final class style {
        /**  Estilo para el dashboard
         */
        public static final int ActionBarCompat=0x7f070002;
        /**
        Base application theme, dependent on API level. This theme is replaced
        by AppBaseTheme from res/values-vXX/styles.xml on newer devices.

            Theme customizations available in newer API levels can go in
            res/values-vXX/styles.xml, while customizations related to
            backward-compatibility can go here.

        Base application theme for API 11+. This theme completely replaces
        AppBaseTheme from res/values/styles.xml on API 11+ devices.

 API 11 theme customizations can go here.

        Base application theme for API 14+. This theme completely replaces
        AppBaseTheme from BOTH res/values/styles.xml and
        res/values-v11/styles.xml on API 14+ devices.

 API 14 theme customizations can go here.
         */
        public static final int AppBaseTheme=0x7f070000;
        /**  Application theme.
         */
        public static final int AppTheme=0x7f070001;
        public static final int BotonAzulVerde=0x7f070004;
        public static final int BotonGenerico=0x7f070006;
        public static final int BotonRojo=0x7f070005;
        public static final int BotonSFondo=0x7f070007;
        public static final int DashboardButton=0x7f070003;
        public static final int FooterBar=0x7f070008;
        public static final int TextosGenericos=0x7f07000a;
        public static final int TituloLinea=0x7f070009;
        public static final int dialog_light=0x7f07000b;
    }
}


text:
@implementation IRAppDescriptor

- (id) initDescriptorWithDictionary:(NSDictionary *)aDictionary
{
    self = [super initDescriptorWithDictionary:aDictionary];
    if (self) {
        NSString *string;
        NSNumber *number;
        NSArray *array;
        NSDictionary *dictionary;

        if (self.app == nil || [self.app length] == 0) {
            NSLog(@"App Descriptor must have \"id\" property set! System will not work properly without it!");
        }

        // version
        number = aDictionary[appVersionKEY];
        if ([number longLongValue] >= 0) {
            self.version = [number longLongValue];
        } else {
            self.version = 0;
        }

        // silentUpdate
        number = aDictionary[silentUpdateKEY];
        if (number) {
            self.silentUpdate = [number boolValue];
        } else {
            self.silentUpdate = NO;
        }

        // baseUrl
        string = aDictionary[NSStringFromSelector(@selector(baseUrl))];
        if ([string length] > 0) {
            self.baseUrl = string;
        }

        // screensArray
        array = aDictionary[screensKEY];
        self.screensArray = [IRBaseDescriptor newScreenDescriptorsArrayFromDictionariesArray:array
                                                                                app:self.app
                                                                                version:self.version
                                                                                baseUrl:self.baseUrl];

        // fontsArray
        array = aDictionary[fontsKEY];
        self.fontsArray = array;

        // mainScreenId
        string = aDictionary[NSStringFromSelector(@selector(mainScreenId))];
        self.mainScreenId = string;

        // jsLibrariesArray
        array = aDictionary[jsLibrariesKEY];
        if (array) {
            self.jsLibrariesArray = [self processedJSLibrariesArray:array];
        }

        // i18n
        dictionary = aDictionary[NSStringFromSelector(@selector(i18n))];
        self.i18n = [[IRI18NDescriptor alloc] initDescriptorWithDictionary:dictionary];
    }
    return self;
}

- (id) initDescriptorForVersionWithDictionary:(NSDictionary *)aDictionary
{
    self = [super initDescriptorWithDictionary:aDictionary];
    if (self) {
        NSNumber *number;

        if (self.app == nil || [self.app length] == 0) {
            NSLog(@"App Descriptor must have \"id\" property set! System will not work properly without it!");
        }

        // version
        number = aDictionary[appVersionKEY];
        if ([number longLongValue] >= 0) {
            self.version = [number longLongValue];
        } else {
            self.version = 0;
        }

        // silentUpdate
        number = aDictionary[silentUpdateKEY];
        if (number) {
            self.silentUpdate = [number boolValue];
        } else {
            self.silentUpdate = NO;
        }
    }
    return self;
}

- (id) initDescriptorForFontsAndScreensWithDictionary:(NSDictionary *)aDictionary
{
    self = [super initDescriptorWithDictionary:aDictionary];
    if (self) {
        NSString *string;
        NSNumber *number;
        NSArray *array;

        if (self.app == nil || [self.app length] == 0) {
            NSLog(@"App Descriptor must have \"id\" property set! System may not work properly without it!");
            self.componentId = [IRUtil createKeyFromObjectAddress:self];
        }

        // version
        number = aDictionary[appVersionKEY];
        if ([number longLongValue] >= 0) {
            self.version = [number longLongValue];
        } else {
            self.version = 0;
        }

        // silentUpdate
        number = aDictionary[silentUpdateKEY];
        if (number) {
            self.silentUpdate = [number boolValue];
        } else {
            self.silentUpdate = NO;
        }

        // baseUrl
        string = aDictionary[NSStringFromSelector(@selector(baseUrl))];
        if ([string length] > 0) {
            self.baseUrl = string;
        }

        // fontsArray
        array = aDictionary[fontsKEY];
        self.fontsArray = array;

        // screensArray
        array = aDictionary[screensKEY];
        self.screensArray = array;
    }
    return self;
}

- (IRScreenDescriptor *) mainScreenDescriptor
{
    IRScreenDescriptor *mainScreenDescriptor = nil;
    for (IRScreenDescriptor *anDescriptor in self.screensArray) {
        if ([anDescriptor.componentId isEqualToString:self.mainScreenId]) {
            mainScreenDescriptor = anDescriptor;
            break;
        }
    }
    return mainScreenDescriptor;
}

- (NSString *) app {
    return self.componentId;
}

- (NSArray *) processedJSLibrariesArray:(NSArray *)jsLibrariesArray
{
    NSMutableArray *processedJSLibrariesArray = [NSMutableArray array];
    NSString *jsLibraryPath;
    if (jsLibrariesArray.count > 0) {
        for (NSString *anJSLibrary in jsLibrariesArray) {
            if ([anJSLibrary isKindOfClass:[NSDictionary class]]) {
                jsLibraryPath = ((NSDictionary *) anJSLibrary)[pathKEY][urlKEY];
            } else {
                jsLibraryPath = anJSLibrary;
            }
            if (jsLibraryPath.length > 0) {
                [processedJSLibrariesArray addObject:jsLibraryPath];
            }
        }
    }
    return processedJSLibrariesArray;
}

@end