text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>Partial record storage and retrieval</title>
    <link rel="stylesheet" href="gettingStarted.css" type="text/css" />
    <meta name="generator" content="DocBook XSL Stylesheets V1.73.2" />
    <link rel="start" href="index.html" title="Berkeley DB Programmer's Reference Guide" />
    <link rel="up" href="am_misc.html" title="Chapter 4.  Access Method Wrapup" />
    <link rel="prev" href="am_misc_bulk.html" title="Retrieving and updating records in bulk" />
    <link rel="next" href="am_misc_struct.html" title="Storing C/C++ structures/objects" />

          Partial record storage and retrieval

          Prev
          Chapter 4.
		Access Method Wrapup

           Next

Partial record storage and retrieval

It is possible to both store and retrieve parts of data items in all
Berkeley DB access methods.  This is done by setting the
DB_DBT_PARTIAL flag DBT structure passed to the
Berkeley DB method.

The DB_DBT_PARTIAL flag is based on the values of two fields
of the DBT structure: dlen and doff.  The value
of dlen is the number of bytes of the record in which the
application is interested.  The value of doff is the offset from
the beginning of the data item where those bytes start.

For example, if the data item were ABCDEFGHIJKL, a doff
value of 3 would indicate that the bytes of interest started at
D, and a dlen value of 4 would indicate that the bytes
of interest were DEFG.

When retrieving a data item from a database, the dlen bytes
starting doff bytes from the beginning of the record are
returned, as if they comprised the entire record.  If any or all of the
specified bytes do not exist in the record, the retrieval is still
successful and any existing bytes are returned.

When storing a data item into the database, the dlen bytes
starting doff bytes from the beginning of the specified key's
data record are replaced by the data specified by the data and
size fields.  If dlen is smaller than size, the
record will grow, and if dlen is larger than size, the
record will shrink. If the specified bytes do not exist, the record will
be extended using nul bytes as necessary, and the store call will still
succeed.

The following are various examples of the put case for the
DB_DBT_PARTIAL flag. In all examples, the initial data item is 20
bytes in length:

          ABCDEFGHIJ0123456789

size = 20
doff = 0
dlen = 20
data = abcdefghijabcdefghij

Result: The 20 bytes at offset 0 are replaced by the 20 bytes of
data; that is, the entire record is replaced.

ABCDEFGHIJ0123456789 -> abcdefghijabcdefghij

size = 10
doff = 20
dlen = 0
data = abcdefghij

Result: The 0 bytes at offset 20 are replaced by the 10 bytes of
data; that is, the record is extended by 10 bytes.

ABCDEFGHIJ0123456789 -> ABCDEFGHIJ0123456789abcdefghij

size = 10
doff = 10
dlen = 5
data = abcdefghij

Result: The 5 bytes at offset 10 are replaced by the 10 bytes of
data.

ABCDEFGHIJ0123456789 -> ABCDEFGHIJabcdefghij56789

size = 10
doff = 10
dlen = 0
data = abcdefghij

Result: The 0 bytes at offset 10 are replaced by the 10 bytes of
data; that is, 10 bytes are inserted into the record.

ABCDEFGHIJ0123456789 -> ABCDEFGHIJabcdefghij0123456789

size = 10
doff = 2
dlen = 15
data = abcdefghij

Result: The 15 bytes at offset 2 are replaced by the 10 bytes of
data.

ABCDEFGHIJ0123456789 -> ABabcdefghij789

size = 10
doff = 0
dlen = 0
data = abcdefghij

Result: The 0 bytes at offset 0 are replaced by the 10 bytes of
data; that is, the 10 bytes are inserted at the beginning of the
record.

ABCDEFGHIJ0123456789 -> abcdefghijABCDEFGHIJ0123456789

size = 0
doff = 0
dlen = 10
data = ""

Result: The 10 bytes at offset 0 are replaced by the 0 bytes of
data; that is, the first 10 bytes of the record are discarded.

ABCDEFGHIJ0123456789 -> 0123456789

size = 10
doff = 25
dlen = 0
data = abcdefghij

Result: The 0 bytes at offset 25 are replaced by the 10 bytes of
data; that is, 10 bytes are inserted into the record past the end
of the current data (\0 represents a nul byte).

ABCDEFGHIJ0123456789 -> ABCDEFGHIJ0123456789\0\0\0\0\0abcdefghij

          Prev

            Up

           Next

          Retrieving and updating records in bulk

            Home

           Storing C/C++ structures/objects

redpajama_set_name: RedPajamaGithub


text:
<?php
    /**
     * Container class
     *
     * @author      Gerald Plusquellec
     */
    namespace Thin;

    class Container extends Object
    {
        protected $values = [];
        protected $_metas = [];
        public $_token;

        public static function instance()
        {
            return container();
        }

        public function __construct($values = [])
        {
            if (is_object($values)) {
                $values = $values->assoc();
            }

            if (count($values)) {
                $this->values = $this->make($values);
            } else {
                $this->values = $values;
            }

            $this->_token = Utils::token();
        }

        public function make(array $array)
        {
            $return = [];

            foreach ($array as $k => $v) {
                if (Arrays::is($v)) {
                    $o = new self;
                    $return[$k] = $o->populate($v);
                } else {
                    $return[$k] = $v;
                }
            }

            return $return;
        }

        public function offsetSet($id, $value)
        {
            $this->values[$id] = $value;
        }

        public function offsetGet($id)
        {
            if (!Arrays::exists($id, $this->values)) {
                throw new Exception(sprintf('Identifier "%s" is not defined.', $id));
            }

            $isFactory = is_object($this->values[$id]) && method_exists($this->values[$id], '__invoke');

            return (true === $isFactory) ? $this->values[$id]($this) : $this->values[$id];
        }

        public function offsetExists($id)
        {
            return ake($id, $this->values);
        }

        public function offsetUnset($id)
        {
            unset($this->values[$id]);
        }

        public static function share(\Closure $callable)
        {
            return function ($c) use ($callable) {
                static $object;

                if (null === $object) {
                    $object = $callable($c);
                }

                return $object;
            };
        }

        public static function protect(\Closure $callable)
        {
            return function ($c) use ($callable) {
                return $callable;
            };
        }

        public function raw($id)
        {
            if (!Arrays::exists($id, $this->values)) {
                throw new Exception(sprintf('Identifier "%s" is not defined.', $id));
            }

            return $this->values[$id];
        }

        public function extend($id, \Closure $callable)
        {
            if (!Arrays::exists($id, $this->values)) {
                throw new Exception(sprintf('Identifier "%s" is not defined.', $id));
            }

            $factory = $this->values[$id];

            if (!($factory instanceof \Closure)) {
                throw new Exception(sprintf('Identifier "%s" does not contain an object definition.', $id));
            }

            return $this->values[$id] = function ($c) use ($callable, $factory) {
                return $callable($factory($c), $c);
            };
        }

        public function keys()
        {
            return array_keys($this->values);
        }

        public function values()
        {
            return $this->values;
        }

        public function showVars()
        {
            return get_object_vars($this);
        }

        public function route(Container $route)
        {
            $routes = container()->getMapRoutes();
            $routes = empty($routes) ? [] : $routes;
            $routes[$route->getName()] = $route;
            container()->setMapRoutes($routes);

            return $this;
        }

        public function link($routeName, $params = [])
        {
            $link = URLSITE;
            $routes = container()->getMapRoutes();

            if (Arrays::isArray($routes)) {
                if (ake($routeName, $routes)) {
                    $route = $routes[$routeName];
                    $path = $route->getPath();

                    if (count($params)) {
                        foreach ($params as $key => $param) {
                            $path = strReplaceFirst('(.*)', $param, $path);
                        }
                    }

                    $link .= $path;
                }
            }

            return $link;
        }

        public function isRoute($routeName)
        {
            $routes = container()->getMapRoutes();

            if (Arrays::isArray($routes)) {
                if (ake($routeName, $routes)) {
                    $route = $routes[$routeName];
                    $actualRoute = $this->getRoute();

                    return $actualRoute === $route;
                }
            }

            return false;
        }

        public static function create($name = null, $array = [])
        {
            $name       = (null === $name) ? sha1(time()) : $name;
            $o          = o($name);

            return $o->populate($array);
        }

        public function event($id, \Closure $closure)
        {
            $this->values[sha1($id . $this->_token)] = $closure;

            return $this;
        }

        public function daol($c, $f, $args = [])
        {
            $c = strstr($c, '-') ? strrev(repl('-', '', $c)) : $c;
            $exist = isAke($this->values, sha1($f . $this->_token), null);

            if (empty($exist)) {
                $exist = isAke($this->_closures, $f, null);

                if (empty($exist)) {
                    $exist = registry('events.' . $f);

                    if (!empty($exist)) {
                        event($c, $exist);
                    } else {
                        $callable = function () use ($f) {
                            return call_user_func_array($f, func_get_args());
                        };
                        event($c, $callable);
                    }
                } else {
                    event($c, $exist);
                }
            } else {
                event($c, $exist);
            }

            return $this;
        }

        public function run($id, $args = [])
        {
            $id = sha1($id . $this->_token);

            if (Arrays::exists($id, $this->values)) {
                return call_user_func_array($this->values[$id], $args);
            }

            return null;
        }

        public function tokenize()
        {
            return $this->_token;
        }

        public function meta()
        {
            $args = func_get_args();

            if (count($args) == 0) {
                return $this->_metas;
            } elseif (count($args) == 1) {
                return isAke($this->_metas, Arrays::first($args), null);
            } elseif (count($args) == 2) {
                $this->_metas[Arrays::first($args)] = Arrays::last($args);
            }

            return $this;
        }

        public function copyMeta(Container $obj)
        {
            $this->_metas = $obj->meta();

            return $this;
        }
    }


text:
package com.intellij.psi.codeStyle.arrangement.std;

import org.jetbrains.annotations.NotNull;

/**
 * Type of {@link StdArrangementSettingsToken}. Defines UI role used to display the token. Used to differentiate between semantically
 * different tokens when constructing matchers.
 * (see {@link com.intellij.psi.codeStyle.arrangement.match.StdArrangementEntryMatcher.StdMatcherBuilderImpl}).
 *
 * @author Roman.Shein
 */
public class StdArrangementTokenType {
  @NotNull private final StdArrangementTokenUiRole myUiRole;
  @NotNull private final String myId;

  public StdArrangementTokenType(@NotNull StdArrangementTokenUiRole uiRole, @NotNull String id) {
    myUiRole = uiRole;
    myId = id;
  }

  @NotNull public StdArrangementTokenUiRole getUiRole() {
    return myUiRole;
  }

  public boolean is(ArrangementSettingsToken token) {
    return token instanceof StdArrangementSettingsToken && this.equals(((StdArrangementSettingsToken)token).getTokenType());
  }

  @Override
  public int hashCode() {
    return myId.hashCode();
  }

  @Override
  public boolean equals(Object o) {
    if (this == o) {return true;}
    if (o == null || !(o instanceof StdArrangementTokenType)) {
      return false;
    }
    StdArrangementTokenType oType = (StdArrangementTokenType) o;
    return oType.myId.equals(myId) && myUiRole == oType.myUiRole;
  }

  public static final String GENERAL_ID = "GENERAL";
  public static final String GROUPING_ID = "GROUPING";
  public static final String MODIFIER_ID = "MODIFIER";
  public static final String REG_EXP_ID = "REG_EXP";
  public static final String ENTRY_TYPE_ID = "ENTRY_TYPE";
  public static final String ORDER_ID = "ORDER";
  public static final String ALIAS_ID = "ALIAS";

  public static final StdArrangementTokenType GENERAL = new StdArrangementTokenType(StdArrangementTokenUiRole.LABEL, GENERAL_ID);
  public static final StdArrangementTokenType GROUPING = new StdArrangementTokenType(StdArrangementTokenUiRole.CHECKBOX, GROUPING_ID);
  public static final StdArrangementTokenType MODIFIER = new StdArrangementTokenType(StdArrangementTokenUiRole.BULB, MODIFIER_ID);
  public static final StdArrangementTokenType REG_EXP = new StdArrangementTokenType(StdArrangementTokenUiRole.TEXT_FIELD, REG_EXP_ID);
  public static final StdArrangementTokenType ENTRY_TYPE = new StdArrangementTokenType(StdArrangementTokenUiRole.BULB, ENTRY_TYPE_ID);
  public static final StdArrangementTokenType ORDER = new StdArrangementTokenType(StdArrangementTokenUiRole.COMBO_BOX, ORDER_ID);
  public static final StdArrangementTokenType ALIAS = new StdArrangementTokenType(StdArrangementTokenUiRole.BULB, ALIAS_ID);
}


text:
package com.google.cloud.automl.v1beta1.samples;

// [START automl_v1beta1_generated_AutoMl_ListTableSpecs_sync]
import com.google.cloud.automl.v1beta1.AutoMlClient;
import com.google.cloud.automl.v1beta1.DatasetName;
import com.google.cloud.automl.v1beta1.ListTableSpecsRequest;
import com.google.cloud.automl.v1beta1.TableSpec;
import com.google.protobuf.FieldMask;

public class SyncListTableSpecs {

  public static void main(String[] args) throws Exception {
    syncListTableSpecs();
  }

  public static void syncListTableSpecs() throws Exception {
    // This snippet has been automatically generated and should be regarded as a code template only.
    // It will require modifications to work:
    // - It may require correct/in-range values for request initialization.
    // - It may require specifying regional endpoints when creating the service client as shown in
    // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
    try (AutoMlClient autoMlClient = AutoMlClient.create()) {
      ListTableSpecsRequest request =
          ListTableSpecsRequest.newBuilder()
              .setParent(DatasetName.of("[PROJECT]", "[LOCATION]", "[DATASET]").toString())
              .setFieldMask(FieldMask.newBuilder().build())
              .setFilter("filter-1274492040")
              .setPageSize(883849137)
              .setPageToken("pageToken873572522")
              .build();
      for (TableSpec element : autoMlClient.listTableSpecs(request).iterateAll()) {
        // doThingsWith(element);
      }
    }
  }
}
// [END automl_v1beta1_generated_AutoMl_ListTableSpecs_sync]


text:
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Recommended option

                <img src="<?=Yii::$app->params['assetsDir']?>images/eea-logo.png" alt="" />

Time to sell = 30 days

Estimation

                        Selling price

                        £21,000-£56,000

                <a href="<?=Yii::$app->params['moreAboutSQPage']?>" class="orange-btn" style="font-size:15px;">
                    Click here to find out more about Express Estate Agency's Quick Sale Option


text:
#ifndef MODULES_AUDIO_PROCESSING_AEC3_DELAY_ESTIMATE_H_
#define MODULES_AUDIO_PROCESSING_AEC3_DELAY_ESTIMATE_H_

namespace webrtc {

// Stores delay_estimates.
struct DelayEstimate {
  enum class Quality { kCoarse, kRefined };

  DelayEstimate(Quality quality, size_t delay)
      : quality(quality), delay(delay) {}

  Quality quality;
  size_t delay;
};

}  // namespace webrtc

#endif  // MODULES_AUDIO_PROCESSING_AEC3_DELAY_ESTIMATE_H_


text:
package com.mercury.daos;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateTemplate;

import com.mercury.beans.Message;
import com.mercury.daos.MessageDaoImpl2;

public class MessageDaoImpl2 implements MessageDao{
	private HibernateTemplate template;
	private Session session;

	public void setSessionFactory(SessionFactory sessionFactory) { //Spring IoC bean
		template = new HibernateTemplate(sessionFactory);
		session = sessionFactory.openSession();
		//session = sessionFactory.getCurrentSession();
	}

	@Override
	public Message postNew(Message msg) {
		try{
			if(msg.getReply() == 0) {
				System.out.println(msg.getMid());
				msg.setReply(msg.getMid());
			}
			template.saveOrUpdate(msg);
			return msg;
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println("failed to save post...");
		return null;
	}

	@Override
	public Message retrievePost(int messageId) {
		return template.get(Message.class, messageId);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Message> retrieveByPost(int messageId) {
		return template.findByNamedParam("from Message", "reply", messageId);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Message> retrieveByBoard(String boardName) {
		String hql = "from Message where board = :name";
		Query query = session.createQuery(hql);
		query.setParameter("name", boardName);
		return query.list();
	}
/*	public List<Message> retrieveByBoard(String boardName) {
		//String hql = "from Message where board = 'default'"; this one works
		String hql = "from Message where board = ?";
		return template.find(hql, boardName); //.find(hql);
	}*/

	@SuppressWarnings("unchecked")
	@Override
	public List<Message> retrieveByUsername(String username) {
		String hql = "from Message where username = ?"; //TODO change to use the same prepared statement as above
		List<Message> list = template.find(hql, username);
		return list;
	}

	/*public static void main(String[] args) {
		ApplicationContext actx = new ClassPathXmlApplicationContext("spring-servlet.xml");
		MessageDaoImpl mdi = (MessageDaoImpl) actx.getBean("messageDao");

		Message msg = new Message();
		msg.setMid(2);
		System.out.println(""+ msg.getMid() + msg.getText() + msg.getBoard() + msg.getReply() +" "+msg.getTime());
		mdi.getTemplate().save(msg);
		//Message msg2 = (Message) mdi.getPost((long)1);
		for(Message msg : mdi.getByUsername("peter")) {
			System.out.println(msg.getText());
		}
		//System.out.println("" + msg2.getTime());
	}*/
}


text:
import sys
import os
import datetime

# add parent dir to path to access webrecorder package
wr_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, wr_path)

from redis import StrictRedis
from fakeredis import FakeStrictRedis
import fakeredis

import json
import shutil

from six.moves.urllib.parse import urlsplit

from pywb.utils.loaders import BlockLoader

from webrecorder.rec.storage.storagepaths import add_local_store_prefix, strip_prefix

from webrecorder.models import User, Collection, Recording, BookmarkList
from webrecorder.models.stats import Stats
from webrecorder.models.usermanager import CLIUserManager, UserTable

from webrecorder.utils import sanitize_title

from argparse import ArgumentParser, RawTextHelpFormatter

# ============================================================================
class Migration(object):
    MIGRATE_Q = 'migrate:q'

    DEFAULT_LIST_NAME = 'Bookmarks'
    DEFAULT_LIST_DESC = 'List automatically created from visible pages on {0}'

    def __init__(self, old_redis_url, new_redis_url, dry_run=True,
                 per_recording_list=False, s3_import=False, s3_root=None):
        self.old_redis = StrictRedis.from_url(old_redis_url, decode_responses=True)
        self.dry_run = dry_run
        self.per_recording_list = per_recording_list
        self.s3_import = s3_import

        if s3_import:
            assert(s3_root)
            import boto3
            self.s3_root = s3_root
            self.s3 = boto3.client('s3')
        else:
            self.s3_root = None
            self.s3 = None

        if self.dry_run:
            import redis
            redis.StrictRedis = fakeredis.FakeStrictRedis
            self.redis = FakeStrictRedis.from_url(new_redis_url, decode_responses=True)
        else:
            self.redis = StrictRedis.from_url(new_redis_url, decode_responses=True)

        print('Redis Inited')

        self.cli = CLIUserManager(new_redis_url)

    def delete_user(self, username):
        user = self.cli.all_users.make_user(username)
        user.delete_me()

    def delete_coll(self, username, coll_name):
        print('Deleting Collection: {0}/{1}'.format(username, coll_name))
        user = self.cli.all_users.make_user(username)
        if not user:
            print('No User')
            return

        collection = user.get_collection_by_name(coll_name)
        if not collection:
            print('No Collection')
            return

        user.remove_collection(collection)

    def copy_key(self, from_key, to_key):
        data = self.old_redis.hgetall(from_key)
        if data:
            self.redis.hmset(to_key, data)

    def migrate_all(self):
        if not self.redis.exists(self.MIGRATE_Q):
            all_users = self.old_redis.hkeys('h:users')
            for user in all_users:
                self.redis.rpush(self.MIGRATE_Q, user)

            self.copy_key('h:register', 'h:register')
            self.copy_key('h:temp-usage', Stats.ALL_CAPTURE_TEMP_KEY)
            self.copy_key('h:user-usage', Stats.ALL_CAPTURE_USER_KEY)

            print('QUEUED USERS:', len(all_users))

        while True:
            user = self.redis.lpop(self.MIGRATE_Q)
            if not user:
                print('All Done!')
                return

            self.migrate_user(user)

    def migrate_user(self, username, new_username=None, coll_name=None, skip_if_exists=True):
        new_username = new_username or username
        print('Processing User: {0} -> {1}'.format(username, new_username))

        if new_username not in self.cli.all_users:
            # migrate from h:users and u:<info> to new user info
            user_data = self.old_redis.hget('h:users', username)
            user_data = json.loads(user_data)
            reg_data = user_data.pop('desc', '')
            if reg_data:
                user_data['reg_data'] = reg_data
                try:
                    reg_data_json = json.loads(reg_data)
                    if 'name' in reg_data_json:
                        user_data['full_name'] = reg_data_json['name']
                except:
                    pass

            user_data.pop('space_utilization', '')

            # update with u:id:info data
            old_u_key = User.INFO_KEY.format(user=username)
            user_data.update(self.old_redis.hgetall(old_u_key))

            # update new username with data
            new_u_key = User.INFO_KEY.format(user=new_username)
            self.redis.hmset(new_u_key, user_data)

            # add user to s:users, now a valid user!
            self.redis.sadd(UserTable.USERS_KEY, new_username)
        else:
            if skip_if_exists:
                print('User exists, skipping')
                return

            print('Use already exists, migrating collections')

        user = self.cli.all_users.make_user(new_username)

        if not coll_name:
            # get all collection list
            colls = self.old_redis.smembers(User.COLLS_KEY.format(user=new_username))
        else:
            colls = [coll_name]

        total_size = 0

        for coll in colls:
            print('  Processing Collection: ' + coll)
            total_size += self.migrate_collection(user, username, coll)

        if not coll_name:
            user.set_prop('size', total_size)

        try:
            target_dirname = user.make_user_temp_warc_path()
            os.rmdir(target_dirname)
        except Exception as e:
            pass
            #print('Error deleting user dir: ' + str(e))

    def migrate_collection(self, user, old_user, old_coll):
        # get old coll info data
        old_info_key = 'c:{user}:{coll}:info'.format(user=old_user, coll=old_coll)
        old_coll_data = self.old_redis.hgetall(old_info_key)

        if not old_coll_data or not old_coll_data.get('id'):
            print('  SKIPPING INVALID: ' + old_coll)
            return 0

        collection = user.create_collection(old_coll,
                                            allow_dupe=False,
                                            title=old_coll_data.get('title', ''),
                                            desc=old_coll_data.get('desc', ''),
                                            public=old_coll_data.get('r:@public') == '1')

        print('  New Collection Created: ' + collection.my_id)

        if old_coll_data.get('created_at'):
            collection.set_prop('created_at', old_coll_data.get('created_at'), update_ts=False)
        else:
            print('  OBJ ERR: created_at missing')

        #collection.set_prop('size', old_coll_data.get('size', '0'))

        collection.bookmarks_list = None

        recs = self.old_redis.smembers('c:{user}:{coll}:recs'.format(user=old_user, coll=old_coll))

        patch_recordings = {}

        total_size = 0

        for rec in recs:
            old_rec_base_key = 'r:{user}:{coll}:{rec}:'.format(user=old_user, coll=old_coll, rec=rec)
            print('    Processing Recording: ' + rec)
            recording, size = self.migrate_recording(collection, rec, old_rec_base_key)

            total_size += size

            # track patch recordings
            if recording and recording.get_prop('rec_type') == 'patch':
                print('    Patch: yes')
                id_ = self.old_redis.hget(old_rec_base_key + 'info', 'id')
                patch_recordings[id_] = recording

        collection.set_prop('size', total_size, update_ts=False)

        # add bookmarks to Bookmarks list
        if hasattr(collection, 'pages_for_bookmarks'):
            # sort pages oldest to newest
            pages = sorted(collection.pages_for_bookmarks, key=lambda x: x.get('timestamp') or x.get('ts', ''))

            for page in pages:
                bookmark = collection.bookmarks_list.create_bookmark(page)

        # map source to patch recordings, if any
        if not patch_recordings:
            return total_size

        all_recordings = collection.get_recordings()
        for recording in all_recordings:
            title = recording.get_prop('title')
            if not title:
                continue

            patch_title = 'patch-of-' + sanitize_title(title)
            patch_recording = patch_recordings.get(patch_title)
            if patch_recording:
                print('Patch Mapped ({0}) {1} -> {2}'.format(title, recording.my_id, patch_recording.my_id))
                recording.set_patch_recording(patch_recording, update_ts=False)

        return total_size

    def migrate_recording(self, collection, rec, old_rec_base_key):
        # old rec info
        old_rec_data = self.old_redis.hgetall(old_rec_base_key + 'info')

        if not old_rec_data or not old_rec_data.get('id'):
            print('SKIPPING INVALID: ' + rec)
            return None, 0

        # get remote archive list
        ra_list = self.old_redis.smembers(old_rec_base_key + 'ra')

        # set title
        title = old_rec_data.get('title', rec)
        rec_type = old_rec_data.get('rec_type')

        recording = collection.create_recording(title=title,
                                                desc='',
                                                rec_type=rec_type,
                                                ra_list=ra_list)

        print('    New Recording Created: ' + recording.my_id)

        pages = self.old_redis.hvals(old_rec_base_key + 'page')
        pages = [json.loads(page) for page in pages]
        collection.import_pages(pages, recording)

        # copy files
        warc_files = self.old_redis.hgetall(old_rec_base_key + 'warc')

        if self.s3_import:
            total_size = self.copy_rec_files_s3(collection.get_owner(), collection, recording, warc_files)
        else:
            total_size = self.copy_rec_files(collection.get_owner(), collection, recording, warc_files)

        recording.set_prop('size', total_size, update_ts=False)

        # and list for public pages
        visible_pages = [page for page in pages if page.get('hidden') != '1']

        if visible_pages:
            # shared 'Bookmarks' list
            if not collection.bookmarks_list:
                public_desc = self.DEFAULT_LIST_DESC.format(self.datestring())

                collection.bookmarks_list = collection.create_bookmark_list(dict(title=self.DEFAULT_LIST_NAME,
                                                                                desc=public_desc,
                                                                                public=True))

                collection.pages_for_bookmarks = []

            # per-recording list of public bookmarks
            if self.per_recording_list:
                recording_list = collection.create_bookmark_list(dict(title=title,
                                                                      public=False))
            else:
                recording_list = None

            # create bookmarks for visible pages
            for page in visible_pages:
                #page['rec'] = recording.my_id
                page['page_id'] = collection._new_page_id(page)

                print('    BOOKMARK: ' + page.get('timestamp', '') + ' ' + page.get('url', ''))

                if recording_list:
                    bookmark_1 = recording_list.create_bookmark(page)

                #bookmark_2 = collection.bookmarks_list.create_bookmark(page)
                collection.pages_for_bookmarks.append(page)

        # copy props
        if 'created_at' in old_rec_data:
            recording.set_prop('created_at', old_rec_data['created_at'], update_ts=False)
        else:
            print('    OBJ ERR: created_at missing')

        if 'updated_at' in old_rec_data:
            recording.set_prop('updated_at', old_rec_data['updated_at'], update_ts=False)
            recording.set_prop('recorded_at', old_rec_data['updated_at'], update_ts=False)
        else:
            print('    OBJ ERR: updated_at missing')

        return recording, total_size

    def copy_rec_files_s3(self, user, collection, recording, warc_files):
        coll_warc_key = recording.COLL_WARC_KEY.format(coll=collection.my_id)
        rec_warc_key = recording.REC_WARC_KEY.format(rec=recording.my_id)

        # Copy WARCs
        total_size = 0

        coll_root = self.s3_root + collection.get_dir_path() + '/'

        for n, url in warc_files.items():
            if not url.startswith('s3://'):
                print('Skipping: ' + url)
                continue

            src_parts = urlsplit(url)
            src_bucket = src_parts.netloc
            src_key = src_parts.path.lstrip('/')

            try:
                res = self.s3.head_object(Bucket=src_bucket,
                                          Key=src_key)
            except Exception as e:
                print('Skipping: ' + url)
                print(e)
                continue

            size = res['ContentLength']

            if n != recording.INDEX_FILE_KEY:
                target_file = coll_root + 'warcs/' + n

                self.redis.hset(coll_warc_key, n, target_file)
                self.redis.sadd(rec_warc_key, n)
                total_size += size
            else:
                target_file = coll_root + 'indexes/' + os.path.basename(url)
                recording.set_prop(n, target_file, update_ts=False)

            # target
            target_parts = urlsplit(target_file)
            target_bucket = target_parts.netloc
            target_key = target_parts.path.lstrip('/')

            params = dict(Bucket=target_bucket,
                          Key=target_key,
                          CopySource=dict(Bucket=src_bucket, Key=src_key))

            print('    Copying:')
            print('      From: s3://' + src_bucket + '/' + src_key)
            print('      To: s3://' + target_bucket + '/' + target_key)
            print('      Size: ' + str(size))

            try:
                if not self.dry_run:
                    res = self.s3.copy_object(**params)
            except Exception as e:
                print('    ERROR:')
                print(e)

        return total_size

    def copy_rec_files(self, user, collection, recording, warc_files):
        if self.dry_run:
            target_dirname = os.path.join('/tmp/migrate4.0', collection.my_id)
        else:
            target_dirname = user.get_user_temp_warc_path()

        os.makedirs(target_dirname, exist_ok=True)
        print('Writing to dir: ' + target_dirname)

        coll_warc_key = recording.COLL_WARC_KEY.format(coll=collection.my_id)
        rec_warc_key = recording.REC_WARC_KEY.format(rec=recording.my_id)

        # Copy WARCs
        loader = BlockLoader()
        total_size = 0

        for n, url in warc_files.items():
            if not url.startswith('s3://'):
                print('FILE ERR: Skipping local file: ' + url)
                continue

            local_filename = n if n != recording.INDEX_FILE_KEY else os.path.basename(url)
            target_file = os.path.join(target_dirname, local_filename)

            src = loader.load(url)

            try:
                with open(target_file, 'wb') as dest:
                    print('Copying {0} -> {1}'.format(url, target_file))
                    shutil.copyfileobj(src, dest)
                    size = dest.tell()

                target_file = add_local_store_prefix(target_file)
                if n != recording.INDEX_FILE_KEY:
                    self.redis.hset(coll_warc_key, n, target_file)
                    self.redis.sadd(rec_warc_key, n)
                    total_size += size
                else:
                    recording.set_prop(n, target_file, update_ts=False)

                if self.dry_run:
                    os.remove(strip_prefix(target_file))

            except:
                import traceback
                traceback.print_exc()

        # commit from temp dir to storage
        if not self.dry_run:
            recording.commit_to_storage()

        return total_size

    def datestring(self):
        return datetime.datetime.utcnow().isoformat()[:19].replace('T', ' ')

# ============================================================================
def main(args=None):
    desc = """Migrate Webrecorder 3.x -> Webrecorder 4.x data model.

Recommended usage for migrating from a Webrecorder 3.x installation:

1) Update REDIS_BASE_URL in wr.env to redis://redis/2 to use a blank new Redis DB

2) Recreate Webrecorder containers via ./recreate.sh, which will remove old containers and build new ones.

3) docker exec -it webrecorder_app_1 python ./migration_scripts/migrate4.0.py --new-redis=redis://redis/2

New data will be stored in redis db 2 and under ./data/storage/
Old data will remain in redis db 1 and under ./data/warcs

"""

    parser = ArgumentParser(description=desc,
                            formatter_class=RawTextHelpFormatter)

    parser.add_argument('--old-redis', default='redis://redis:6379/1', help='Source redis url for old data')
    parser.add_argument('--new-redis', default='redis://redis:6379/2',
                        help='Target redis url for new data, should correspond to REDIS_BASE_URL when running Webrecorder')

    parser.add_argument('--run-import', default=False, action='store_true', help='Run the import and copy data, defaults to false (dry run)')

    parser.add_argument('--user', help='Import a single user only')
    parser.add_argument('--coll', help='Import a single collection only')

    parser.add_argument('--skip-user-if-exists', help='Skip user completely if already exists')
    parser.add_argument('--overwrite', default=False, action='store_true', help='Delete existing user and collection before importing')

    parser.add_argument('--per-recording-list', default=False, action='store_true',
                        help='Generate a list of bookmarks for each recording session')

    parser.add_argument('--s3-root', default=os.environ.get('S3_ROOT'),
                        help='Target S3 url s3://bucket/prefix/ for importing data to s3, required for s3 import, defaults to S3_ROOT env variable')

    parser.add_argument('--s3-import', default=False, action='store_true', help='Use S3 based copy, useful when migrating from one s3 path to another')

    res = parser.parse_args(args=args)

    dry_run = not res.run_import
    if dry_run:
        print('Dry run, add --run-import to actually run the import')
        print('')

    m = Migration(old_redis_url=res.old_redis,
                  new_redis_url=res.new_redis,
                  dry_run=dry_run,
                  per_recording_list=res.per_recording_list,
                  s3_root=res.s3_root,
                  s3_import=res.s3_import)

    # import single user
    if res.user and not res.coll:
        if res.overwrite:
            m.delete_user(res.user)

        m.migrate_user(res.user, skip_if_exists=res.skip_user_if_exists)

    # import single user and collection
    elif res.user and res.coll:
        if res.overwrite:
            m.delete_coll(res.user, res.coll)

        m.migrate_user(res.user, coll_name=res.coll, skip_if_exists=res.skip_user_if_exists)

    elif not res.user and res.coll:
        print('Invalid Args, a --user must be specified along with a --coll argument')
        sys.exit(1)

    # import all
    else:
        m.migrate_all()

# ============================================================================
if __name__ == '__main__':
    main()


text:
using ::testing::_;

namespace blink {

IntSize scaled(IntSize p, float scale) {
  p.scale(scale, scale);
  return p;
}

class LinkSelectionTestBase : public ::testing::Test {
 protected:
  enum DragFlag { SendDownEvent = 1, SendUpEvent = 1 << 1 };
  using DragFlags = unsigned;

  void emulateMouseDrag(const IntPoint& downPoint,
                        const IntPoint& upPoint,
                        int modifiers,
                        DragFlags = SendDownEvent | SendUpEvent);

  void emulateMouseClick(const IntPoint& clickPoint,
                         WebMouseEvent::Button,
                         int modifiers,
                         int count = 1);
  void emulateMouseDown(const IntPoint& clickPoint,
                        WebMouseEvent::Button,
                        int modifiers,
                        int count = 1);

  String getSelectionText();

  FrameTestHelpers::WebViewHelper m_helper;
  WebViewImpl* m_webView = nullptr;
  Persistent<WebLocalFrameImpl> m_mainFrame = nullptr;
};

void LinkSelectionTestBase::emulateMouseDrag(const IntPoint& downPoint,
                                             const IntPoint& upPoint,
                                             int modifiers,
                                             DragFlags dragFlags) {
  if (dragFlags & SendDownEvent) {
    const auto& downEvent = FrameTestHelpers::createMouseEvent(
        WebMouseEvent::MouseDown, WebMouseEvent::Button::Left, downPoint,
        modifiers);
    m_webView->handleInputEvent(downEvent);
  }

  const int kMoveEventsNumber = 10;
  const float kMoveIncrementFraction = 1. / kMoveEventsNumber;
  const auto& upDownVector = upPoint - downPoint;
  for (int i = 0; i < kMoveEventsNumber; ++i) {
    const auto& movePoint =
        downPoint + scaled(upDownVector, i * kMoveIncrementFraction);
    const auto& moveEvent = FrameTestHelpers::createMouseEvent(
        WebMouseEvent::MouseMove, WebMouseEvent::Button::Left, movePoint,
        modifiers);
    m_webView->handleInputEvent(moveEvent);
  }

  if (dragFlags & SendUpEvent) {
    const auto& upEvent = FrameTestHelpers::createMouseEvent(
        WebMouseEvent::MouseUp, WebMouseEvent::Button::Left, upPoint,
        modifiers);
    m_webView->handleInputEvent(upEvent);
  }
}

void LinkSelectionTestBase::emulateMouseClick(const IntPoint& clickPoint,
                                              WebMouseEvent::Button button,
                                              int modifiers,
                                              int count) {
  auto event = FrameTestHelpers::createMouseEvent(
      WebMouseEvent::MouseDown, button, clickPoint, modifiers);
  event.clickCount = count;
  m_webView->handleInputEvent(event);
  event.setType(WebMouseEvent::MouseUp);
  m_webView->handleInputEvent(event);
}

void LinkSelectionTestBase::emulateMouseDown(const IntPoint& clickPoint,
                                             WebMouseEvent::Button button,
                                             int modifiers,
                                             int count) {
  auto event = FrameTestHelpers::createMouseEvent(
      WebMouseEvent::MouseDown, button, clickPoint, modifiers);
  event.clickCount = count;
  m_webView->handleInputEvent(event);
}

String LinkSelectionTestBase::getSelectionText() {
  return m_mainFrame->selectionAsText();
}

class TestFrameClient : public FrameTestHelpers::TestWebFrameClient {
 public:
  MOCK_METHOD4(loadURLExternally,
               void(const WebURLRequest&,
                    WebNavigationPolicy,
                    const WebString& downloadName,
                    bool shouldReplaceCurrentEntry));
};

class LinkSelectionTest : public LinkSelectionTestBase {
 protected:
  void SetUp() override {
    const char* const kHTMLString =
        "Text to select "
        "foobar"
        "
Lorem ipsum dolor sit amet
";

    m_webView = m_helper.initialize(false, &m_testFrameClient, nullptr, nullptr,
                                    [](WebSettings* settings) {});
    m_mainFrame = m_webView->mainFrameImpl();
    FrameTestHelpers::loadHTMLString(
        m_mainFrame, kHTMLString, URLTestHelpers::toKURL("http://foobar.com"));
    m_webView->resize(WebSize(800, 600));
    m_webView->page()->focusController().setActive(true);

    auto* document = m_mainFrame->frame()->document();
    ASSERT_NE(nullptr, document);
    auto* linkToSelect = document->getElementById("link")->firstChild();
    ASSERT_NE(nullptr, linkToSelect);
    // We get larger range that we actually want to select, because we need a
    // slightly larger rect to include the last character to the selection.
    const auto rangeToSelect =
        Range::create(*document, linkToSelect, 5, linkToSelect, 16);

    const auto& selectionRect = rangeToSelect->boundingBox();
    const auto& selectionRectCenterY = selectionRect.center().y();
    m_leftPointInLink = selectionRect.minXMinYCorner();
    m_leftPointInLink.setY(selectionRectCenterY);

    m_rightPointInLink = selectionRect.maxXMinYCorner();
    m_rightPointInLink.setY(selectionRectCenterY);
    m_rightPointInLink.move(-2, 0);
  }

  TestFrameClient m_testFrameClient;
  IntPoint m_leftPointInLink;
  IntPoint m_rightPointInLink;
};

TEST_F(LinkSelectionTest, MouseDragWithoutAltAllowNoLinkSelection) {
  emulateMouseDrag(m_leftPointInLink, m_rightPointInLink, 0);
  EXPECT_TRUE(getSelectionText().isEmpty());
}

TEST_F(LinkSelectionTest, MouseDragWithAltAllowSelection) {
  emulateMouseDrag(m_leftPointInLink, m_rightPointInLink,
                   WebInputEvent::AltKey);
  EXPECT_EQ("to select", getSelectionText());
}

TEST_F(LinkSelectionTest, HandCursorDuringLinkDrag) {
  emulateMouseDrag(m_rightPointInLink, m_leftPointInLink, 0, SendDownEvent);
  m_mainFrame->frame()->localFrameRoot()->eventHandler().scheduleCursorUpdate();
  testing::runDelayedTasks(50);
  const auto& cursor =
      m_mainFrame->frame()->chromeClient().lastSetCursorForTesting();
  EXPECT_EQ(Cursor::Hand, cursor.getType());
}

TEST_F(LinkSelectionTest, CaretCursorOverLinkDuringSelection) {
  emulateMouseDrag(m_rightPointInLink, m_leftPointInLink, WebInputEvent::AltKey,
                   SendDownEvent);
  m_mainFrame->frame()->localFrameRoot()->eventHandler().scheduleCursorUpdate();
  testing::runDelayedTasks(50);
  const auto& cursor =
      m_mainFrame->frame()->chromeClient().lastSetCursorForTesting();
  EXPECT_EQ(Cursor::IBeam, cursor.getType());
}

TEST_F(LinkSelectionTest, HandCursorOverLinkAfterContextMenu) {
  // Move mouse.
  emulateMouseDrag(m_rightPointInLink, m_leftPointInLink, 0, 0);

  // Show context menu. We don't send mouseup event here since in browser it
  // doesn't reach blink because of shown context menu.
  emulateMouseDown(m_leftPointInLink, WebMouseEvent::Button::Right, 0, 1);

  LocalFrame* frame = m_mainFrame->frame();
  // Hide context menu.
  frame->page()->contextMenuController().clearContextMenu();

  frame->localFrameRoot()->eventHandler().scheduleCursorUpdate();
  testing::runDelayedTasks(50);
  const auto& cursor =
      m_mainFrame->frame()->chromeClient().lastSetCursorForTesting();
  EXPECT_EQ(Cursor::Hand, cursor.getType());
}

TEST_F(LinkSelectionTest, SingleClickWithAltStartsDownload) {
  EXPECT_CALL(
      m_testFrameClient,
      loadURLExternally(_, WebNavigationPolicy::WebNavigationPolicyDownload,
                        WebString(), _));
  emulateMouseClick(m_leftPointInLink, WebMouseEvent::Button::Left,
                    WebInputEvent::AltKey);
}

TEST_F(LinkSelectionTest, SingleClickWithAltStartsDownloadWhenTextSelected) {
  auto* document = m_mainFrame->frame()->document();
  auto* textToSelect = document->getElementById("page_text")->firstChild();
  ASSERT_NE(nullptr, textToSelect);

  // Select some page text outside the link element.
  const Range* rangeToSelect =
      Range::create(*document, textToSelect, 1, textToSelect, 20);
  const auto& selectionRect = rangeToSelect->boundingBox();
  m_mainFrame->moveRangeSelection(selectionRect.minXMinYCorner(),
                                  selectionRect.maxXMaxYCorner());
  EXPECT_FALSE(getSelectionText().isEmpty());

  EXPECT_CALL(
      m_testFrameClient,
      loadURLExternally(_, WebNavigationPolicy::WebNavigationPolicyDownload,
                        WebString(), _));
  emulateMouseClick(m_leftPointInLink, WebMouseEvent::Button::Left,
                    WebInputEvent::AltKey);
}

class LinkSelectionClickEventsTest : public LinkSelectionTestBase {
 protected:
  class MockEventListener final : public EventListener {
   public:
    static MockEventListener* create() { return new MockEventListener(); }

    bool operator==(const EventListener& other) const final {
      return this == &other;
    }

    MOCK_METHOD2(handleEvent, void(ExecutionContext* executionContext, Event*));

   private:
    MockEventListener() : EventListener(CPPEventListenerType) {}
  };

  void SetUp() override {
    const char* const kHTMLString =
        "

"
        "Sometexttoshow";

    m_webView = m_helper.initialize(false);
    m_mainFrame = m_webView->mainFrameImpl();
    FrameTestHelpers::loadHTMLString(
        m_mainFrame, kHTMLString, URLTestHelpers::toKURL("http://foobar.com"));
    m_webView->resize(WebSize(800, 600));
    m_webView->page()->focusController().setActive(true);

    auto* document = m_mainFrame->frame()->document();
    ASSERT_NE(nullptr, document);

    auto* emptyDiv = document->getElementById("empty_div");
    auto* textDiv = document->getElementById("text_div");
    ASSERT_NE(nullptr, emptyDiv);
    ASSERT_NE(nullptr, textDiv);
  }

  void checkMouseClicks(Element& element, bool doubleClickEvent) {
    struct ScopedListenersCleaner {
      ScopedListenersCleaner(Element* element) : m_element(element) {}

      ~ScopedListenersCleaner() { m_element->removeAllEventListeners(); }

      Persistent<Element> m_element;
    } const listenersCleaner(&element);

    MockEventListener* eventHandler = MockEventListener::create();
    element.addEventListener(
        doubleClickEvent ? EventTypeNames::dblclick : EventTypeNames::click,
        eventHandler);

    ::testing::InSequence s;
    EXPECT_CALL(*eventHandler, handleEvent(_, _)).Times(1);

    const auto& elemBounds = element.boundsInViewport();
    const int clickCount = doubleClickEvent ? 2 : 1;
    emulateMouseClick(elemBounds.center(), WebMouseEvent::Button::Left, 0,
                      clickCount);

    if (doubleClickEvent) {
      EXPECT_EQ(element.innerText().isEmpty(), getSelectionText().isEmpty());
    }
  }
};

TEST_F(LinkSelectionClickEventsTest, SingleAndDoubleClickWillBeHandled) {
  auto* document = m_mainFrame->frame()->document();
  auto* element = document->getElementById("empty_div");

  {
    SCOPED_TRACE("Empty div, single click");
    checkMouseClicks(*element, false);
  }

  {
    SCOPED_TRACE("Empty div, double click");
    checkMouseClicks(*element, true);
  }

  element = document->getElementById("text_div");

  {
    SCOPED_TRACE("Text div, single click");
    checkMouseClicks(*element, false);
  }

  {
    SCOPED_TRACE("Text div, double click");
    checkMouseClicks(*element, true);
  }
}

}  // namespace blink


text:
using RabbitMQ.Client.Framing;
// ReSharper disable InconsistentNaming
using System;
using System.Text;
using System.Threading;
using EasyNetQ.Tests.Mocking;
using NUnit.Framework;
using EasyNetQ.NonGeneric;

namespace EasyNetQ.Tests.NonGeneric
{
    [TestFixture]
    public class NonGenericExtensionsTests
    {
        private MockBuilder mockBuilder;

        [SetUp]
        public void SetUp()
        {
            mockBuilder = new MockBuilder();
        }

        [Test]
        public void Should_be_able_to_subscribe_using_non_generic_extensions()
        {
            var are = new AutoResetEvent(false);
            MyMessage deliveredMessage = null;

            Action<object> onMessage = message =>
                {
                    deliveredMessage = (MyMessage)message;
                    are.Set();
                };

            mockBuilder.Bus.Subscribe(typeof (MyMessage), "subid", onMessage);

            var properties = new BasicProperties
                {
                    Type = "EasyNetQ.Tests.MyMessage:EasyNetQ.Tests"
                };

            var body = Encoding.UTF8.GetBytes("{ Text:\"Hello World\" }");

            mockBuilder.Consumers[0].HandleBasicDeliver(
                "consumer_tag",
                0,
                false,
                "exchange",
                "routing_key",
                properties,
                body);

            are.WaitOne(1000);
            deliveredMessage.ShouldNotBeNull();
            deliveredMessage.Text.ShouldEqual("Hello World");
        }
    }
}

// ReSharper restore InconsistentNaming


text:
var util = require('util');
var _ = require('lodash');
var log = require('wizzi-core').log(module);
var error = require('wizzi-core').error;
var verify = require('wizzi-core').verify;
var jsModelType = require('wizzi-legacy').jsModelType;
var md = module.exports = {};
var myname = 'model.transformation.wizzischema.html.docs.main';

md.trans = function(model, ctx, callback) {
    if (model.wzElement != 'wizzischema') {
        error.error(myname + '.trans. Model wzElement must be wizzischema. Found: ' + model.wzElement, model);
    }
    ctx.result = {
        name: model.wzName,
        preserveTags: model.preserveTags
    };
    md.wizzischema(model, ctx);
    callback(null, ctx.result);
};

md.wizzischema = function(model, ctx, parent) {
    ctx.result.requires = [];
    ctx.result.exportTos = [];
    ctx.result.elements = [];
    var i, i_len=model.exportTos.length, exportTo;
    for (i=0; i<i_len; i++) {
        exportTo = model.exportTos[i];
        md.exportTo(exportTo, ctx, ctx.result);
    }
    var i, i_len=model.elements.length, element;
    for (i=0; i<i_len; i++) {
        element = model.elements[i];
        md.element(element, ctx, ctx.result);
    }
};

md.exportTo = function(model, ctx, parent) {
    parent.exportTos.push(model.wzName);
};

md.element = function(model, ctx, parent) {
    var flags = '';
    flags += model.isAbstract ? 'is-abstract ' : '';
    flags += model.addToChildren ? 'add-to-children ' : '';
    var node = {
        name: model.wzId,
        super: model.superId,
        tags: model.tagName.split('|'),
        flags: flags,
        attributes: [],
        relations: [],
        derived: [],
        restricts: [],
        methods: [],
        comments: []
    };
    var flatAttributes = model.getFlatAttributes();
    var i, i_len=flatAttributes.length, attr;
    for (i=0; i<i_len; i++) {
        attr = flatAttributes[i];
        node.attributes.push(attr);
    }
    var flatRelations = model.getFlatRelations();
    var i, i_len=flatRelations.length, r;
    for (i=0; i<i_len; i++) {
        r = flatRelations[i];
        node.relations.push(r);
    }
    var i, i_len=model.derived.length, d;
    for (i=0; i<i_len; i++) {
        d = model.derived[i];
        node.derived.push({
            name: d.wzId,
            tags: d.tagName.split('|')
        });
    }
    var i, i_len=model.methods.length, m;
    for (i=0; i<i_len; i++) {
        m = model.methods[i];
        var methodNode = {
            name: m.wzName,
            emitKey: m.emitKey,
            isStatic: m.isStatic,
            isKnownMethod: m.isKnownMethod,
            params: [],
            statements: [],
            comments: []
        };
        var j, j_len=m.params.length, param;
        for (j=0; j<j_len; j++) {
            param = m.params[j];
            methodNode.params.push(param.wzName);
        }
        var j, j_len=m.statements.length, stm;
        for (j=0; j<j_len; j++) {
            stm = m.statements[j];
            var k, k_len=normalizeJST(stm.wzName).length, item;
            for (k=0; k<k_len; k++) {
                item = normalizeJST(stm.wzName)[k];
                methodNode.statements.push(item);
            }
        }
        var j, j_len=m.comments.length, comment;
        for (j=0; j<j_len; j++) {
            comment = m.comments[j];
            methodNode.comments.push(comment.wzName);
        }
        node.methods.push(methodNode);
    }
    var i, i_len=model.restricts.length, restrict;
    for (i=0; i<i_len; i++) {
        restrict = model.restricts[i];
        node.restricts.push(getRestrictFill(restrict));
    }
    var i, i_len=model.comments.length, comment;
    for (i=0; i<i_len; i++) {
        comment = model.comments[i];
        node.comments.push(comment.wzName);
    }
    parent.elements.push(node);
};
function getRestrictFill(model) {
    var restrictCloned = {
        facets: [],
        comments: []
    };
    var i, i_len=model.facets.length, facet;
    for (i=0; i<i_len; i++) {
        facet = model.facets[i];
        var facetCloned = {
            type: facet.wzElement,
            value: facet.wzName,
            comments: []
        };
        var j, j_len=facet.comments.length, comment;
        for (j=0; j<j_len; j++) {
            comment = facet.comments[j];
            facetCloned.comments.push(comment.wzName);
        }
        restrictCloned.facets.push(facetCloned);
    }
    var i, i_len=model.comments.length, comment;
    for (i=0; i<i_len; i++) {
        comment = model.comments[i];
        restrictCloned.comments.push(comment.wzName);
    }
    return restrictCloned;
}
function normalizeJST(stm) {
    var json = JSON.parse(stm);
    var ret = [];
    if (verify.isArray(json)) {
        var i, i_len=json.length, item;
        for (i=0; i<i_len; i++) {
            item = json[i];
            ret.push(normalizeJSTNode(item));
        }
    }
    else {
        ret.push(normalizeJSTNode(json));
    }
    return ret;
}
function normalizeJSTNode(jstnode) {
    var node = {
        tag: jstnode.n,
        name: jstnode.n,
        value: jstnode.v,
        statements: []
    };
    if (jsModelType.__tagEntityMapping[jstnode.n]) {
        node.name = jsModelType.__tagEntityMapping[jstnode.n];
    }
    if (jstnode.childs) {
        var i, i_len=jstnode.childs.length, item;
        for (i=0; i<i_len; i++) {
            item = jstnode.childs[i];
            node.statements.push(normalizeJSTNode(item));
        }
    }
    return node;
}


text:
package org.projectfloodlight.openflow.protocol.ver14;

import org.projectfloodlight.openflow.protocol.*;
import org.projectfloodlight.openflow.protocol.action.*;
import org.projectfloodlight.openflow.protocol.actionid.*;
import org.projectfloodlight.openflow.protocol.bsntlv.*;
import org.projectfloodlight.openflow.protocol.errormsg.*;
import org.projectfloodlight.openflow.protocol.meterband.*;
import org.projectfloodlight.openflow.protocol.instruction.*;
import org.projectfloodlight.openflow.protocol.instructionid.*;
import org.projectfloodlight.openflow.protocol.match.*;
import org.projectfloodlight.openflow.protocol.stat.*;
import org.projectfloodlight.openflow.protocol.oxm.*;
import org.projectfloodlight.openflow.protocol.oxs.*;
import org.projectfloodlight.openflow.protocol.queueprop.*;
import org.projectfloodlight.openflow.types.*;
import org.projectfloodlight.openflow.util.*;
import org.projectfloodlight.openflow.exceptions.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import com.google.common.collect.ImmutableList;
import java.util.Set;
import io.netty.buffer.ByteBuf;
import com.google.common.hash.PrimitiveSink;
import com.google.common.hash.Funnel;

class OFBsnGenericStatsEntryVer14 implements OFBsnGenericStatsEntry {
    private static final Logger logger = LoggerFactory.getLogger(OFBsnGenericStatsEntryVer14.class);
    // version: 1.4
    final static byte WIRE_VERSION = 5;
    final static int MINIMUM_LENGTH = 2;

        private final static List<OFBsnTlv> DEFAULT_TLVS = ImmutableList.<OFBsnTlv>of();

    // OF message fields
    private final List<OFBsnTlv> tlvs;
//
    // Immutable default instance
    final static OFBsnGenericStatsEntryVer14 DEFAULT = new OFBsnGenericStatsEntryVer14(
        DEFAULT_TLVS
    );

    // package private constructor - used by readers, builders, and factory
    OFBsnGenericStatsEntryVer14(List<OFBsnTlv> tlvs) {
        if(tlvs == null) {
            throw new NullPointerException("OFBsnGenericStatsEntryVer14: property tlvs cannot be null");
        }
        this.tlvs = tlvs;
    }

    // Accessors for OF message fields
    @Override
    public List<OFBsnTlv> getTlvs() {
        return tlvs;
    }

    @Override
    public OFVersion getVersion() {
        return OFVersion.OF_14;
    }

    public OFBsnGenericStatsEntry.Builder createBuilder() {
        return new BuilderWithParent(this);
    }

    static class BuilderWithParent implements OFBsnGenericStatsEntry.Builder {
        final OFBsnGenericStatsEntryVer14 parentMessage;

        // OF message fields
        private boolean tlvsSet;
        private List<OFBsnTlv> tlvs;

        BuilderWithParent(OFBsnGenericStatsEntryVer14 parentMessage) {
            this.parentMessage = parentMessage;
        }

    @Override
    public List<OFBsnTlv> getTlvs() {
        return tlvs;
    }

    @Override
    public OFBsnGenericStatsEntry.Builder setTlvs(List<OFBsnTlv> tlvs) {
        this.tlvs = tlvs;
        this.tlvsSet = true;
        return this;
    }
    @Override
    public OFVersion getVersion() {
        return OFVersion.OF_14;
    }

        @Override
        public OFBsnGenericStatsEntry build() {
                List<OFBsnTlv> tlvs = this.tlvsSet ? this.tlvs : parentMessage.tlvs;
                if(tlvs == null)
                    throw new NullPointerException("Property tlvs must not be null");

                //
                return new OFBsnGenericStatsEntryVer14(
                    tlvs
                );
        }

    }

    static class Builder implements OFBsnGenericStatsEntry.Builder {
        // OF message fields
        private boolean tlvsSet;
        private List<OFBsnTlv> tlvs;

    @Override
    public List<OFBsnTlv> getTlvs() {
        return tlvs;
    }

    @Override
    public OFBsnGenericStatsEntry.Builder setTlvs(List<OFBsnTlv> tlvs) {
        this.tlvs = tlvs;
        this.tlvsSet = true;
        return this;
    }
    @Override
    public OFVersion getVersion() {
        return OFVersion.OF_14;
    }

//
        @Override
        public OFBsnGenericStatsEntry build() {
            List<OFBsnTlv> tlvs = this.tlvsSet ? this.tlvs : DEFAULT_TLVS;
            if(tlvs == null)
                throw new NullPointerException("Property tlvs must not be null");

            return new OFBsnGenericStatsEntryVer14(
                    tlvs
                );
        }

    }

    final static Reader READER = new Reader();
    static class Reader implements OFMessageReader<OFBsnGenericStatsEntry> {
        @Override
        public OFBsnGenericStatsEntry readFrom(ByteBuf bb) throws OFParseError {
            int start = bb.readerIndex();
            int length = U16.f(bb.readShort());
            if(length < MINIMUM_LENGTH)
                throw new OFParseError("Wrong length: Expected to be >= " + MINIMUM_LENGTH + ", was: " + length);
            if(bb.readableBytes() + (bb.readerIndex() - start) < length) {
                // Buffer does not have all data yet
                bb.readerIndex(start);
                return null;
            }
            if(logger.isTraceEnabled())
                logger.trace("readFrom - length={}", length);
            List<OFBsnTlv> tlvs = ChannelUtils.readList(bb, length - (bb.readerIndex() - start), OFBsnTlvVer14.READER);

            OFBsnGenericStatsEntryVer14 bsnGenericStatsEntryVer14 = new OFBsnGenericStatsEntryVer14(
                    tlvs
                    );
            if(logger.isTraceEnabled())
                logger.trace("readFrom - read={}", bsnGenericStatsEntryVer14);
            return bsnGenericStatsEntryVer14;
        }
    }

    public void putTo(PrimitiveSink sink) {
        FUNNEL.funnel(this, sink);
    }

    final static OFBsnGenericStatsEntryVer14Funnel FUNNEL = new OFBsnGenericStatsEntryVer14Funnel();
    static class OFBsnGenericStatsEntryVer14Funnel implements Funnel<OFBsnGenericStatsEntryVer14> {
        private static final long serialVersionUID = 1L;
        @Override
        public void funnel(OFBsnGenericStatsEntryVer14 message, PrimitiveSink sink) {
            // FIXME: skip funnel of length
            FunnelUtils.putList(message.tlvs, sink);
        }
    }

    public void writeTo(ByteBuf bb) {
        WRITER.write(bb, this);
    }

    final static Writer WRITER = new Writer();
    static class Writer implements OFMessageWriter<OFBsnGenericStatsEntryVer14> {
        @Override
        public void write(ByteBuf bb, OFBsnGenericStatsEntryVer14 message) {
            int startIndex = bb.writerIndex();
            // length is length of variable message, will be updated at the end
            int lengthIndex = bb.writerIndex();
            bb.writeShort(U16.t(0));

            ChannelUtils.writeList(bb, message.tlvs);

            // update length field
            int length = bb.writerIndex() - startIndex;
            bb.setShort(lengthIndex, length);

        }
    }

    @Override
    public String toString() {
        StringBuilder b = new StringBuilder("OFBsnGenericStatsEntryVer14(");
        b.append("tlvs=").append(tlvs);
        b.append(")");
        return b.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        OFBsnGenericStatsEntryVer14 other = (OFBsnGenericStatsEntryVer14) obj;

        if (tlvs == null) {
            if (other.tlvs != null)
                return false;
        } else if (!tlvs.equals(other.tlvs))
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;

        result = prime * result + ((tlvs == null) ? 0 : tlvs.hashCode());
        return result;
    }

}


text:
package slogo.backend.tokenization;

import java.util.Map;

/**
 * A rule for recognizing a token
 *
 */
public interface ITokenRule {
    /**
     * Check if a string of text matches and tokenize it if so
     *
     * @param text
     *            the text to match for
     * @param isStart
     *            whether the text is at the start of the stream
     * @param isEnd
     *            whether the text is at the end of the stream
     * @return A map with "opening", "body", and "closing" keys corresponding to
     *         the tokens representing the opening, body, and closing
     */
    public Map<String, IToken> match (String text, boolean isStart, boolean isEnd);
}


text:
Want to contribute to Scorify? That would be excellent. The project maintainer (Nate Vack) is not available for massive amounts of help, but can spend some time to help you get started working, and ultimately do things like review pull requests. This is his first experience in this sort of thing, so it'll be a learning process for him as well as you.

Things we currently need help with:

* Cleaning up scripts/score_data.py so it isn't so terrible-looking
* Clear examples of data, scoresheet, and resulting output
* Better, more readable documentation (probably partly with the above) that doesn't look like it's written for programmers.


text:
package com.francetelecom.clara.cloud.commons.testconfigurations;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashSet;
import java.util.Properties;
import java.util.Set;

public class PropertiesHelper {

	public static Set<String> loadKeys(String propertiesFileName, InputStream in) throws IOException {
		Set<String> keys = new HashSet<String>();
		Properties prop = new Properties();
		if (in == null)
			throw new IOException("unable to get resource file " + propertiesFileName);
		prop.load(in);
		in.close();
		for (Object key : prop.keySet()) {
			keys.add((String) key);
		}
		return keys;
	}

}


text:
package org.uberfire.client.views.pfly.menu;

import com.google.gwtmockito.GwtMockitoTestRunner;
import org.jboss.errai.security.shared.api.identity.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.uberfire.security.authz.AuthorizationManager;

import static org.mockito.Mockito.*;

@RunWith( GwtMockitoTestRunner.class )
public class UserMenuTest {

    @Mock
    private UserMenu.UserMenuView userMenuView;

    @Mock
    private User user;

    @Mock
    private AuthorizationManager authzManager;

    @InjectMocks
    private UserMenu userMenu;

    @Test
    public void testUserNameWithId(){
        final String userName = "mock";
        when( user.getIdentifier() ).thenReturn( userName );
        userMenu.setup();
        verify( userMenuView ).setUserName( userName );
    }

    @Test
    public void testUserNameUsingFirstAndLastName(){
        final String firstName = "Mock";
        final String lastName = "Test";
        when( user.getProperty( User.StandardUserProperties.FIRST_NAME ) ).thenReturn( firstName );
        when( user.getProperty( User.StandardUserProperties.LAST_NAME ) ).thenReturn( lastName );
        userMenu.setup();
        verify( userMenuView ).setUserName( firstName + " " + lastName );
    }

    @Test
    public void testUserNameUsingFirstName(){
        final String firstName = "Mock";
        when( user.getProperty( User.StandardUserProperties.FIRST_NAME ) ).thenReturn( firstName );
        userMenu.setup();
        verify( userMenuView ).setUserName( firstName );
    }

    @Test
    public void testUserNameUsingLastName(){
        final String lastName = "Test";
        when( user.getProperty( User.StandardUserProperties.LAST_NAME ) ).thenReturn( lastName );
        userMenu.setup();
        verify( userMenuView ).setUserName( lastName );
    }
}


text:
- Provision an ubuntu server machine (can be a cloud server such as digital ocean)
- A machine with 1gb RAM and 30gb hard disk has been sufficient for early tests
- Enable connection to the box via ssh - [how to](https://www.digitalocean.com/community/tutorials/how-to-set-up-ssh-keys--2)

### Setup Twitter API for app:
*(Optional: use as many login methods as you like)*

- Create new app on www.dev.twitter.com
- Set callback url to be `https://[SERVER URL]/twitter-callback`
- Get consumer API key and secret

### Stonecutter set up:
*(Optional: use as many login methods as you like)*

- Deploy a Stonecutter instance, as found [here](https://github.com/d-cent/stonecutter)
- Login as an admin
- Navigate to Apps page
- Add an app for your Objective8 instance
- Get client ID and secret, as generated by Stonecutter

### Facebook set up:
*(Optional: use as many login methods as you like)*

- Create new website app [here](https://developers.facebook.com)
- Navigate to settings > advanced > Client OAuth Settings > Valid OAuth redirect URIs
- Enter `http://[SERVER URL]/facebook-callback`
- Save changes
- Take the app out of development mode
- Get consumer API key and secret

### Coracle set up:
*(Optional: needed if deploying alongside [Mooncake](https://github.com/d-cent/mooncake))*

- Deploy Coracle instance, as found [here](https://github.com/d-cent/coracle)
- If you are not using coracle, remove the coracle role in the *ops/digital_ocean_box_playbook.yml* file

### Amazon Web Services set up:
*(Optional: required if you want to back up the database)*

- Create an AWS account [here](https://aws.amazon.com/)
- Get your Access Key ID and Secret Access Key as described [here](http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSGettingStartedGuide/AWSCredentials.html)

### Configure with ansible
- Install Ansible
- In file *ops/digital_ocean_box.inventory* replace:
    - `ansible_ssh_host` with the IP address of your ubuntu server machine
    - `site_address` with the URL of the server
    - `external_jwk_set_url` with the URL of the server followed by /as2/jwk-set
- Use the *objective8_config_template* found in the */ops* directory and either replace the empty strings with your credentials or delete the variable. Save it for use in the next step and take note of the file path. You can find more information about the configuration variables [here](./CONFIG.md).
- Remove from */ops/roles/objective8_application_config/templates/objective8_config.j2* the variables that you deleted in the previous step.
- Create a */ops/roles/nginx/files/secure/* directory, and copy your SSL certificate and key files there, with the names *objective8.key* and *objective8.crt*.

Run Ansible playbook:

  The following command will install necessary packages and configure them (it will take a few minutes).
  It will require choosing a database password and supplying your Amazon S3 credentials for automatically backing up (encrypted) the database to an Amazon S3 bucket:
  ```
  ansible-playbook ops/digital_ocean_box_playbook.yml -i ops/digital_ocean_box.inventory --extra-vars "CONFIG_FILE_PATH={config file path from the previous step without the curly braces}"
  ```

### Deploy application to the server

  The following will copy the application to the server and start it running as a service in a docker container.
  Once complete you should be able to access the app at your IP address.

  ```
  chmod +x deploy_prod.sh
  REMOTE_USER={username on server} SERVER_IP={IP address of server} ./deploy_prod.sh
  ```


text:
This is a very basic example on how to use PHP to authenticate the user login.

It implements two types of authentication:
- HTML page login, when the user arrives by index.php;
- Basic Authentication method, when accessing by api.php.

[See the working example](http://ricnish.rf.gd/php-auth-example/).

Use the user 'admin' and password 'admin'.

To authenticate a page using an HTML login page, include the 'auth.php' file, and call the function **authHTML()**.

To authenticate an API script using the [BASIC Authentication method](https://en.wikipedia.org/wiki/Basic_access_authentication), include the 'auth.php' file, and call the function **authAPI()**, [test the API login](http://ricnish.rf.gd/php-auth-example/api.php)

**NOTE:** There is a lot more to be done for security in real life, this code was done for testing purposes.

The user validation is done by the function **isValidUser($user, $pass)** in the file auth.php, reimplement it to use a custom validation or to just change the default user and password.

The styles and sample page came from [Bootstrap](https://getbootstrap.com/), many thanks.


text:
/**
 * Local participant might not have real ID until he joins a conference,
 * so use 'local' as its default ID.
 *
 * @type {string}
 */
export const LOCAL_PARTICIPANT_DEFAULT_ID = 'local';

/**
 * Max length of the display names.
 *
 * @type {string}
 */
export const MAX_DISPLAY_NAME_LENGTH = 50;

/**
 * The set of possible XMPP MUC roles for conference participants.
 *
 * @enum {string}
 */
export const PARTICIPANT_ROLE = {
    MODERATOR: 'moderator',
    NONE: 'none',
    PARTICIPANT: 'participant'
};


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using Xamarin.Forms;

namespace Flipper.Controls
{
    public class RangeSlider : View
    {
        public static readonly BindableProperty CommandProperty =
                BindableProperty.Create<RangeSlider, ICommand>
            (p => p.Command, null);

        public static readonly BindableProperty MaxValueProperty =
                BindableProperty.Create<RangeSlider, double>
            (p => p.MaxValue, double.NaN, BindingMode.TwoWay, propertyChanged: (bindable, oldValue, newValue) =>
            {
                var control = (RangeSlider)bindable;
                control.RightValue = newValue;
                control.LeftValue = control.MinValue;
            });

        public static readonly BindableProperty MinValueProperty =
               BindableProperty.Create<RangeSlider, double>
           (p => p.MinValue, double.NaN,BindingMode.TwoWay, propertyChanged: (bindable, oldValue, newValue) =>
            {
                var control = (RangeSlider)bindable;
                control.LeftValue = newValue;
                control.RightValue = control.MaxValue;
            });

        public static readonly BindableProperty LeftValueProperty =
               BindableProperty.Create<RangeSlider,double>
           (p => p.LeftValue, double.NaN, BindingMode.TwoWay);

        public static readonly BindableProperty RightValueProperty =
               BindableProperty.Create<RangeSlider, double>
           (p => p.RightValue, double.NaN, BindingMode.TwoWay);

        public new static readonly BindableProperty BackgroundColorProperty =
              BindableProperty.Create<RangeSlider, Color>
          (p => p.BackgroundColor, Color.Gray);

        public static readonly BindableProperty RangeColorProperty =
              BindableProperty.Create<RangeSlider, Color>
          (p => p.RangeColor, Color.Blue);

        public static readonly BindableProperty IndicatorColorProperty =
              BindableProperty.Create<RangeSlider, Color>
          (p => p.IndicatorColor, Color.Blue);

        public static readonly BindableProperty StepProperty =
              BindableProperty.Create<RangeSlider, double>
          (p => p.Step, 1);

        public ICommand Command
        {
            get { return GetValue(CommandProperty) as ICommand; }
            set { SetValue(CommandProperty, value); }
        }

        public event EventHandler ValueChanged;

        public double MaxValue
        {
            get { return (double)GetValue(MaxValueProperty); }
            set { SetValue(MaxValueProperty, value); }
        }

        public double MinValue
        {
            get { return (double)GetValue(MinValueProperty); }
            set { SetValue(MinValueProperty, value); }
        }

        public double LeftValue
        {
            get { return (double)GetValue(LeftValueProperty); }
            set { SetValue(LeftValueProperty, value); }
        }

        public double RightValue
        {
            get { return (double)GetValue(RightValueProperty); }
            set { SetValue(RightValueProperty, value); }
        }

        public double Step
        {
            get { return (double)GetValue(StepProperty); }
            set { SetValue(StepProperty, value); }
        }

        public new Color BackgroundColor
        {
            get { return (Color)GetValue(BackgroundColorProperty); }
            set { SetValue(BackgroundColorProperty, value); }
        }

        public Color RangeColor
        {
            get { return (Color)GetValue(RangeColorProperty); }
            set { SetValue(RangeColorProperty, value); }
        }

        public Color IndicatorColor
        {
            get { return (Color)GetValue(IndicatorColorProperty); }
            set { SetValue(IndicatorColorProperty, value); }
        }

        public void NotifyValueChanged()
        {
            if(ValueChanged != null)
            {
                ValueChanged(this, new EventArgs());
            }
        }
    }
}


text:
#include "cbase.h"
#include "asw_weapon_freeze_grenades.h"
#include "in_buttons.h"

#ifdef CLIENT_DLL
#include "c_asw_player.h"
#include "c_asw_weapon.h"
#include "c_asw_marine.h"
#include "prediction.h"
#else
#include "asw_marine.h"
#include "asw_player.h"
#include "asw_weapon.h"
#include "npcevent.h"
#include "shot_manipulator.h"
#include "asw_grenade_freeze.h"
#include "asw_marine_speech.h"
#include "asw_gamerules.h"
#endif
#include "asw_marine_skills.h"
#include "asw_util_shared.h"

// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"

#define ASW_FLARES_FASTEST_REFIRE_TIME		0.1f

extern ConVar asw_grenade_throw_delay;

IMPLEMENT_NETWORKCLASS_ALIASED( ASW_Weapon_Freeze_Grenades, DT_ASW_Weapon_Freeze_Grenades )

BEGIN_NETWORK_TABLE( CASW_Weapon_Freeze_Grenades, DT_ASW_Weapon_Freeze_Grenades )
#ifdef CLIENT_DLL
	// recvprops
#else
	// sendprops
#endif
END_NETWORK_TABLE()

BEGIN_PREDICTION_DATA( CASW_Weapon_Freeze_Grenades )

END_PREDICTION_DATA()

LINK_ENTITY_TO_CLASS( asw_weapon_freeze_grenades, CASW_Weapon_Freeze_Grenades );
PRECACHE_WEAPON_REGISTER( asw_weapon_freeze_grenades );

#ifndef CLIENT_DLL
extern ConVar asw_debug_marine_damage;
//---------------------------------------------------------
// Save/Restore
//---------------------------------------------------------
BEGIN_DATADESC( CASW_Weapon_Freeze_Grenades )
	DEFINE_FIELD( m_flSoonestPrimaryAttack, FIELD_TIME ),
END_DATADESC()

#endif /* not client */

CASW_Weapon_Freeze_Grenades::CASW_Weapon_Freeze_Grenades()
{
	m_fMinRange1	= 0;
	m_fMaxRange1	= 2048;

	m_fMinRange2	= 256;
	m_fMaxRange2	= 1024;

	m_flSoonestPrimaryAttack = gpGlobals->curtime;
}

CASW_Weapon_Freeze_Grenades::~CASW_Weapon_Freeze_Grenades()
{

}

//-----------------------------------------------------------------------------
// Purpose:
// Output : Activity
//-----------------------------------------------------------------------------
Activity CASW_Weapon_Freeze_Grenades::GetPrimaryAttackActivity( void )
{
	return ACT_VM_PRIMARYATTACK;
}

bool CASW_Weapon_Freeze_Grenades::OffhandActivate()
{
	if (!GetMarine() || GetMarine()->GetFlags() & FL_FROZEN)	// don't allow this if the marine is frozen
		return false;
	PrimaryAttack();

	return true;
}

#define FLARE_PROJECTILE_AIR_VELOCITY	400

void CASW_Weapon_Freeze_Grenades::PrimaryAttack( void )
{
	CASW_Player *pPlayer = GetCommander();

	if (!pPlayer)
		return;

	CASW_Marine *pMarine = GetMarine();
	bool bThisActive = (pMarine && pMarine->GetActiveWeapon() == this);

	// grenade weapon is lost when all grenades are gone
	if ( UsesClipsForAmmo1() && !m_iClip1 )
	{
#ifndef CLIENT_DLL
		if (pMarine)
		{
			pMarine->Weapon_Detach(this);
			if (bThisActive)
				pMarine->SwitchToNextBestWeapon(NULL);
		}
		Kill();
#endif
		return;
	}

	if (pMarine && gpGlobals->curtime > m_flDelayedFire)		// firing from a marine
	{
#ifdef CLIENT_DLL
		if ( !prediction->InPrediction() || prediction->IsFirstTimePredicted() )
		{
			pMarine->DoAnimationEvent( PLAYERANIMEVENT_THROW_GRENADE );
		}
#else
		pMarine->DoAnimationEvent( PLAYERANIMEVENT_THROW_GRENADE );

		pMarine->OnWeaponFired( this, 1 );
#endif

		// start our delayed attack
		m_bShotDelayed = true;
		m_flNextPrimaryAttack = m_flNextSecondaryAttack = m_flDelayedFire = gpGlobals->curtime + asw_grenade_throw_delay.GetFloat();
		if (!bThisActive && pMarine->GetActiveASWWeapon())
		{
			// if we're offhand activating, make sure our primary weapon can't fire until we're done
			pMarine->GetActiveASWWeapon()->m_flNextPrimaryAttack = m_flNextPrimaryAttack  + 0.4f;
			pMarine->GetActiveASWWeapon()->m_bIsFiring = false;
		}
	}
}

#ifndef CLIENT_DLL
float CASW_Weapon_Freeze_Grenades::GetBoomRadius( CASW_Marine *pMarine )
{
	return MarineSkills()->GetSkillBasedValueByMarine(pMarine, ASW_MARINE_SKILL_GRENADES, ASW_MARINE_SUBSKILL_GRENADE_FREEZE_RADIUS);
}
#endif

void CASW_Weapon_Freeze_Grenades::DelayedAttack( void )
{
	m_bShotDelayed = false;

	CASW_Player *pPlayer = GetCommander();
	if ( !pPlayer )
		return;

	CASW_Marine *pMarine = GetMarine();
	if ( !pMarine || pMarine->GetWaterLevel() == 3 )
		return;

#ifndef CLIENT_DLL
	Vector vecSrc = pMarine->GetOffhandThrowSource();

	Vector vecDest = pPlayer->GetCrosshairTracePos();
	Vector newVel = UTIL_LaunchVector( vecSrc, vecDest, GetThrowGravity() ) * 28.0f;

	float fGrenadeRadius = GetBoomRadius( pMarine );
	if (asw_debug_marine_damage.GetBool())
	{
		Msg( "Freeze grenade radius = %f \n", fGrenadeRadius );
	}
	pMarine->GetMarineSpeech()->Chatter( CHATTER_GRENADE );

	// freeze aliens completely, plus the freeze duration
	float flFreezeAmount = 1.0f + MarineSkills()->GetSkillBasedValueByMarine(pMarine, ASW_MARINE_SKILL_GRENADES, ASW_MARINE_SUBSKILL_GRENADE_FREEZE_DURATION);

	if (ASWGameRules())
		ASWGameRules()->m_fLastFireTime = gpGlobals->curtime;

	CASW_Grenade_Freeze *pGrenade = CASW_Grenade_Freeze::Freeze_Grenade_Create(
		1.0f,
		flFreezeAmount,
		fGrenadeRadius,
		0,
		vecSrc, pMarine->EyeAngles(), newVel, AngularImpulse(0,0,0), pMarine, this );
	if ( pGrenade )
	{
		pGrenade->SetGravity( GetThrowGravity() );
		pGrenade->SetExplodeOnWorldContact( true );
	}

#endif
		// decrement ammo
	m_iClip1 -= 1;

#ifndef CLIENT_DLL
	DestroyIfEmpty( true );
#endif

	m_flSoonestPrimaryAttack = gpGlobals->curtime + ASW_FLARES_FASTEST_REFIRE_TIME;
	if (m_iClip1 > 0)		// only force the fire wait time if we have ammo for another shot
		m_flNextPrimaryAttack = gpGlobals->curtime + GetFireRate();
	else
		m_flNextPrimaryAttack = gpGlobals->curtime;
}

void CASW_Weapon_Freeze_Grenades::Precache()
{
	BaseClass::Precache();
}

// flares don't reload
bool CASW_Weapon_Freeze_Grenades::Reload()
{
	return false;
}

void CASW_Weapon_Freeze_Grenades::ItemPostFrame( void )
{
	BaseClass::ItemPostFrame();

	if ( m_bInReload )
		return;

	CBasePlayer *pOwner = GetCommander();

	if ( pOwner == NULL )
		return;

	//Allow a refire as fast as the player can click
	if ( ( ( pOwner->m_nButtons & IN_ATTACK ) == false ) && ( m_flSoonestPrimaryAttack < gpGlobals->curtime ) )
	{
		m_flNextPrimaryAttack = gpGlobals->curtime - 0.1f;
	}
}

int CASW_Weapon_Freeze_Grenades::ASW_SelectWeaponActivity(int idealActivity)
{
	// we just use the normal 'no weapon' anims for this
	return idealActivity;
}


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />

    <title>OpenGL ES android - La librería de la que me he enamorado</title>
    <meta name="description" content="" />

    <meta name="HandheldFriendly" content="True" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

    <link rel="shortcut icon" href="//acien101.github.io/themes/Casper/favicon.ico">

    <link rel="stylesheet" type="text/css" href="//acien101.github.io/themes/Casper/assets/css/screen.css?v=1.0.0" />
    <link rel="stylesheet" type="text/css" href="//fonts.googleapis.com/css?family=Merriweather:300,700,700italic,300italic|Open+Sans:700,400" />

    <link rel="canonical" href="https://acien101.github.io/2016/01/11/OpenGL-ES-android-La-libreria-de-la-que-me-he-enamorado.html" />

    <meta property="og:site_name" content="Nombre completo para el usuario: Fran Acién" />
    <meta property="og:type" content="article" />
    <meta property="og:title" content="OpenGL ES android - La librería de la que me he enamorado" />
    <meta property="og:description" content="En mi cabeza rondaban ideas de hacer algo relacionado con el 3D para android, y encontré OpenGl ES en android. Se trata de una librería nativa de android que tiene soporte para 2D y 3D. A día de hoy se..." />
    <meta property="og:url" content="https://acien101.github.io/2016/01/11/OpenGL-ES-android-La-libreria-de-la-que-me-he-enamorado.html" />
    <meta property="article:published_time" content="2016-01-10T23:00:00.000Z" />
    <meta property="article:modified_time" content="2016-01-11T22:34:29.495Z" />
    <meta property="article:tag" content="android" />
    <meta property="article:tag" content="OpenGl" />
    <meta property="article:tag" content="android studio" />
    <meta property="article:tag" content="open source" />
    <meta property="article:tag" content="ejemplos" />

    <meta name="twitter:card" content="summary" />
    <meta name="twitter:title" content="OpenGL ES android - La librería de la que me he enamorado" />
    <meta name="twitter:description" content="En mi cabeza rondaban ideas de hacer algo relacionado con el 3D para android, y encontré OpenGl ES en android. Se trata de una librería nativa de android que tiene soporte para 2D y 3D. A día de hoy se..." />
    <meta name="twitter:url" content="https://acien101.github.io/2016/01/11/OpenGL-ES-android-La-libreria-de-la-que-me-he-enamorado.html" />

    <meta name="generator" content="Ghost ?" />
    <link rel="alternate" type="application/rss+xml" title="Nombre completo para el usuario: Fran Acién" href="https://acien101.github.io/rss" />
    <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/8.4/styles/default.min.css">

        Home

OpenGL ES android - La librería de la que me he enamorado

                <time class="post-date" datetime="2016-01-11">11 January 2016</time>  on android,  OpenGl,  android studio,  open source,  ejemplos

En mi cabeza rondaban ideas de hacer algo relacionado con el 3D para android, y encontré OpenGl ES en android. Se trata de una librería nativa de android que tiene soporte para 2D y 3D. A día de hoy se encuentra en la versión 3.1 y la API
está muy completa de funciones y cosas ricas :)

Para alguien que no ha tenido ninguna toma de contacto con algo relacionado con el 3D, como yo, asusta un poco la dificultad, pero eso mismo hace que me guste más. En internet no hay mucha documentación de esta API para android, pero la más fácil y que recomiendo es la de android developers y esta otra más extensa. Además encontré esto ejemplo muy buenos de JimSeker.

Ya con toda la documentación nos podemos poner a la obra. Recomiendo para la gente que no ha probado esta libería antes que le heche un vistazo, sobretodo los videos de youtube de la capacidad que puede llegar a tener esta librería.

Para ir empezando a familiarizarme con OpenGL en android, he hecho un ejemplo con un SeekBar y un triangulo. Que con el SeekBar podamos girar el triagulo. El código se encuentra aqui. Y dejo unos pantallazos del ejemplo:

Yo ya he hecho mi primer ejemplo con OpenGL ES, a que esperas tu!!

                Fran Acién's Picture

Fran Acién

Read more posts by this author.

                    Almeria, Spain
                    https://twitter.com/amil101

Share this post

                    Twitter

                    Facebook

                    Google+

          Please enable JavaScript to view the comments powered by Disqus.
          comments powered by Disqus

Nombre completo para el usuario: Fran Acién © 2016

Proudly published with HubPress


text:
from distutils.core import setup
from catkin_pkg.python_setup import generate_distutils_setup

d = generate_distutils_setup(
    packages=['roboclaw_python'],
    package_dir={'': 'src'}
)

setup(**d)


text:
<?php namespace App\Repositories;

use App\Entities\ElementPropertyHistory;
use Prettus\Repository\Contracts\RepositoryInterface;

interface IElementPropertyHistoryRepository extends RepositoryInterface
{

}


text:
package org.lirazs.robolayout.example.view;

import org.lirazs.robolayout.core.util.UIViewLayoutUtil;
import org.lirazs.robolayout.core.view.LayoutViewController;
import org.robovm.apple.uikit.UILabel;
import org.robovm.apple.uikit.UIView;
import org.robovm.apple.uikit.UIViewContentMode;
import org.robovm.objc.annotation.Method;

/**
 * Created on 8/8/2015.
 */
public class LayoutAnimationsViewController extends LayoutViewController {

    public LayoutAnimationsViewController(String layoutName) {
        super(layoutName);
    }

    @Override
    public void viewDidLoad() {
        super.viewDidLoad();

        UILabel otherLabel = (UILabel) UIViewLayoutUtil.findViewById(getView(), "otherText");
        otherLabel.setContentMode(UIViewContentMode.ScaleToFill);
    }

    @Method(selector = "didPressButton")
    public void didPressButton() {
        UILabel textLabel = (UILabel) UIViewLayoutUtil.findViewById(getView(), "text");
        if(textLabel.getText().equals("Short text")) {
            textLabel.setText("Very long long text");
        } else {
            textLabel.setText("Short text");
        }

        UIView.animate(0.2, new Runnable() {
            @Override
            public void run() {
                getView().layoutIfNeeded();
            }
        });
    }

    @Override
    public boolean shouldAutorotate() {
        return true;
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<testsuite name="ru.stqa.pft.sandbox.SquareTests" tests="1" skipped="0" failures="0" errors="0" timestamp="2018-02-04T19:31:30" hostname="user-pc" time="0.0">
  <properties/>
  <testcase name="testArea" classname="ru.stqa.pft.sandbox.SquareTests" time="0.0"/>
  <system-out><![CDATA[]]></system-out>
  <system-err><![CDATA[]]></system-err>
</testsuite>


text:
#include "Types.h"
#include "SelfPatchCompareAll.h"

#include "itkImageFileReader.h"

int main(int argc, char *argv[])
{
  if(argc != 3)
    {
    std::cerr << "Only gave " << argc << " arguments!" << std::endl;
    std::cerr << "Required arguments: image mask" << std::endl;
    return EXIT_FAILURE;
    }
  std::string imageFilename = argv[1];
  std::string maskFilename = argv[2];
  std::cout << "Reading image: " << imageFilename << std::endl;
  std::cout << "Reading mask: " << maskFilename << std::endl;

  typedef itk::ImageFileReader<FloatVectorImageType> VectorImageReaderType;
  VectorImageReaderType::Pointer imageReader = VectorImageReaderType::New();
  imageReader->SetFileName(imageFilename.c_str());
  imageReader->Update();

  typedef itk::ImageFileReader<Mask> MaskReaderType;
  MaskReaderType::Pointer maskReader = MaskReaderType::New();
  maskReader->SetFileName(maskFilename.c_str());
  maskReader->Update();

  itk::Size<2> size;
  size.Fill(21);

  itk::Index<2> sourceCorner;
  sourceCorner[0] = 319;
  sourceCorner[1] = 292;
  itk::ImageRegion<2> sourceRegion(sourceCorner, size);

  itk::Index<2> targetCorner;
  targetCorner[0] = 193;
  targetCorner[1] = 218;
  itk::ImageRegion<2> targetRegion(targetCorner, size);

  Patch targetPatch(targetRegion);
  Patch sourcePatch(sourceRegion);

  CandidatePairs candidatePairs(targetPatch);
  candidatePairs.AddPairFromPatch(sourcePatch);

  SelfPatchCompareAll patchCompare(imageReader->GetOutput()->GetNumberOfComponentsPerPixel(), candidatePairs);
  patchCompare.SetImage(imageReader->GetOutput());
  patchCompare.SetMask(maskReader->GetOutput());

  patchCompare.ComputeAllDifferences();

  //float totalAbsoluteDifference = patchCompare.SlowTotalAbsoluteDifference(sourceRegion);
  //float totalSquaredDifference = patchCompare.SlowTotalSquaredDifference(sourceRegion);

  std::cerr << "Average Absolute Difference: " << candidatePairs[0].GetAverageAbsoluteDifference() << std::endl;
  //std::cerr << "Total Squared Difference: " << totalSquaredDifference << std::endl;

  return EXIT_SUCCESS;
}


text:
struct EXPCL_PANDABULLET BulletClosestHitSweepResult : public btCollisionWorld::ClosestConvexResultCallback {

PUBLISHED:
  INLINE static BulletClosestHitSweepResult empty();

  LPoint3 get_from_pos() const;
  LPoint3 get_to_pos() const;

  bool has_hit() const;

  PandaNode *get_node() const;
  LPoint3 get_hit_pos() const;
  LVector3 get_hit_normal() const;
  PN_stdfloat get_hit_fraction() const;

public:
  virtual bool needsCollision(btBroadphaseProxy* proxy0) const;

private:
  BulletClosestHitSweepResult(const btVector3 &from_pos, const btVector3 &to_pos, const CollideMask &mask);

  CollideMask _mask;

  friend class BulletWorld;
};

#include "bulletClosestHitSweepResult.I"

#endif // __BULLET_CLOSEST_HIT_SWEEP_RESULT_H__


text:
<?php
//header("Content-Type: text/Text; charset=utf-8 Cache-Control: no-store, no-cache, must-revalidate");
//include("conectar.php");

//if($wb_validity == ""){$wb_validity = 0;}
//Conectarse a la BD
//$link = conectarse();
//Inserta los registros en la BD waybill_mstr: Maestro de Guias
$slcLineaA=  $_POST["cveLineaArea"];
$txtGuiaAerea=  $_POST["guiaArea"];
$txtNumeroVuelo=  $_POST["noVuelo"];
$txtFechaVuelo=  $_POST["fechaVuelo"];
$txtRecepcioncye=  $_POST["recepcionCYE"];
$txtRemitente=  $_POST["nombreRemitente"];
$txtCalleR=  $_POST["calleRemitente"];
$txtTelefonoR=  $_POST["telefonoRemitente"];
$txtRfcR=  $_POST["rfcRemitente"];
$txtNombredo=  $_POST["estadoRemitente"];
$txtColR=  $_POST["coloniaRemitente"];
$txtMunR=  $_POST["municipioRemitente"];
$txtCodigoPr=  $_POST["codigoPR"];
$txtNombreDes=  $_POST["destinatario"];
$txtPiezas=  $_POST["piezas"];
$txtKg=  $_POST["kg"];
$txtVol=  $_POST["volumen"];
$txtVigencia=  $_POST["validezDias"];
$slcSucursal=  $_POST["sucursalDestino"];
$txtCalleD  =  $_POST["calleD"];
$txtCodigoPD=  $_POST["codigoPD"];
$txtColoniaD=  $_POST["ColoniaD"];
$txtMunicipioD=  $_POST["MunicipioD"];
$chkSello=  $_POST["Sello"];
$chkFirma=  $_POST["Firma"];
$chkRespaldo=  $_POST["Respaldo"];
$txtEstadoD=  $_POST["EstadoD"];
$txtTelefonoD=  $_POST["TelefonoD"];
$slcStatus=  $_POST["status"];
$txtRecibio=  $_POST["recibio"];
$slcTipoe=  $_POST["TipoEnvio"];
$slcRecoleccion=  $_POST["Recoleccion"];
$txtFechaA=  $_POST["llegadaacuse"];
$txtFechaEntrega=  $_POST["fechaEntrega"];
$txaObservaciones=  $_POST["observaciones"];
$cveGuia=  $_POST["cveGuia"];
$txtValord=$_POST["valorD"];
$vales=  $_POST["vales"];
$recibos=  $_POST["recibos"];
$facturas=$_POST["facturas"];
$cliente=$_POST["txtCodigoC"];
$cveDireccion=$_POST["cveDireccion"];
$reexpedicion=$_POST["chkReexpedicion"];
$usuario=$_POST["usuario"];
$empresa=$_POST["empresa"];
$empresa=str_replace ( "-", "'", $empresa);
$fecha = date("Y/m/d");
if((strlen($txtFechaEntrega) == 10 and $txtFechaEntrega != "0000/00/00") ){$slcStatus = "Entregada";}
if((strlen($txtFechaA) == 10 and $txtFechaA != "0000-00-00") ){$slcStatus = "Concluida";}
$sql1 = "INSERT INTO cguias (cveEmpresa ,cveSucursal ,cveGuia ,cveCliente,guiaArea ,cveLineaArea ,noVuelo ,fechaVuelo ,recepcionCYE ,nombreRemitente ,calleRemitente ,coloniaRemitente ,municipioRemitente ,estadoRemitente ,codigoPostalRemitente ,telefonoRemitente ,rfcRemitente ,sucursalDestino ,nombreDestinatario ,calleDestinatario ,coloniaDestinatario ,municipioDestinatario ,estadoDestinatario ,codigoPostaldestinatario ,piezas ,kg ,volumen ,validezDias ,status ,recibio ,llegadaacuse ,observaciones ,indicadorRespaldos ,sello ,firma ,fechaEntrega ,recoleccion ,tipoEnvio ,telefonoDestinatario,valorDeclarado,cveDireccion,reexpedicion,usuarioCreador,fechaCreacion)
VALUES (".$empresa.", '$cveGuia', '$cliente', '$txtGuiaAerea', '$slcLineaA', '$txtNumeroVuelo', '$txtFechaVuelo', '$txtRecepcioncye', '$txtRemitente', '$txtCalleR', '$txtColR', '$txtMunR', '$txtNombredo', '$txtCodigoPr', '$txtTelefonoR', '$txtRfcR', '$slcSucursal', '$txtNombreDes', '$txtCalleD', '$txtColoniaD', '$txtMunicipioD', '$txtEstadoD', '$txtCodigoPD', '$txtPiezas', '$txtKg', '$txtVol', '$txtVigencia', '$slcStatus', '$txtRecibio', '$txtFechaA', '$txaObservaciones', '$chkRespaldo', '$chkSello', '$chkFirma', '$txtFechaEntrega', '$slcRecoleccion', '$slcTipoe', '$txtTelefonoD','$txtValord','$cveDireccion','$reexpedicion','$usuario','$fecha')";
echo $sql1;
$conexion = mysql_connect("localhost","webcom","webcom") or die (mysql_error());
$db = mysql_select_db("cargayex",$conexion) or die (mysql_error());

$res1 = mysql_query($sql1,$conexion);
$my_error1 += mysql_error($conexion);

 $my_error1 = mysql_error($conexion);
 $sql="INSERT INTO cvalessoporte (cveEmpresa ,cveSucursal ,cveGuia ,valeSoporte,usuarioCreador,fechaCreacion )
 VALUES (".$empresa.", '$cveGuia', '$vales','$usuario','$fecha')";
  $res1 = mysql_query($sql,$conexion);
  $my_error1 += mysql_error($conexion);
  if ($facturas != "")
  {
  	$separar = explode('
',$facturas);
  foreach($separar as  $indice => $palabra){
  	$sql="INSERT INTO cfacturassoporte (cveEmpresa ,cveSucursal ,cveGuia ,facturaSoporte,usuarioCreador,fechaCreacion )
  VALUES (".$empresa.", '$cveGuia', '$palabra','$usuario','$fecha')";
  $res1 = mysql_query($sql,$conexion);
 $my_error1 += mysql_error($conexion);
 }

 }
  if ($recibos != "")
 {
 		$separar = explode('
',$recibos);
 foreach($separar as  $indice => $palabra){
 	$sql="INSERT INTO centregassoporte (cveEmpresa ,cveSucursal ,cveGuia ,entregasSoporte,usuarioCreador,fechaCreacion )
  VALUES (".$empresa.", '$cveGuia', '$palabra','$usuario','$fecha')";
   $res1 = mysql_query($sql,$conexion);
  $my_error1 += mysql_error($conexion);
  }
  }

// Verifica si existe error en la sintaxis en MySql
if(!empty($my_error1)){
echo "Error: Sintaxis MySql, verifique";
echo "Error: $my_error1";

}
else {
echo "La guía se ha registrado exitosamenteñññ...";
}
mysql_close($conexion);
?>