text:
<?php

class Portfolio_Admin_ItemController extends Controller {

    /**
     * Displays a list of tables for each category.
     *
     * Route: admin/portfolio/items
     */
    public static function manage()
    {
        $content = array(); // To be output

        if(!$categories = Portfolio::category()->orderBy('name')->all())
        {
            return array(
                'title' => 'No Categories',
                'content' => '
You need to ' . Html::a()->get('create some categories', 'admin/portfolio/categories/create') . ' before creating portfolio items.
'
            );
        }

        $headers[] = array(
            'Title',
            'attributes' => array(
                'colspan' => 2
            )
        );

        foreach($categories as $category)
        {
            $rows = array();
            $items = Portfolio::item()->where('category_id', '=', $category->id)->orderBy('created_at')->all();

            if($items)
            {
                foreach($items as $item)
                {
                    $rows[] = array(
                        Html::a()->get($item->title, 'admin/portfolio/items/edit/' . $item->id),
                        array(
                            Html::a()->get('Delete', 'admin/portfolio/items/delete/' . $item->id),
                            'attributes' => array(
                                'class' => 'right'
                            )
                        )
                    );
                }
            }
            else
            {
                $rows[] = array(
                    array(
                        'No items.',
                        'attributes' => array(
                            'colspan' => 2
                        )
                    )
                );
            }

            $content[] = array(
                'title' => $category->name,
                'content' => Html::table()->build($headers, $rows)
            );
        }

        return $content;
    }

    /**
     * Displays a form for creating a new portfolio item.
     *
     * Route: admin/portfolio/items/create
     */
    public static function create()
    {
        if($_POST)
        {
            if(Html::form()->validate())
            {
                if(!Portfolio::item()->where('title', 'LIKE', $_POST['title'])
                    ->andWhere('category_id', '=', $_POST['category_id'])->first())
                {
                    $itemId = Portfolio::item()->insert(array(
                        'category_id' => $_POST['category_id'],
                        'slug' => String::slugify($_POST['title']),
                        'title' => $_POST['title'],
                        'blurb' => $_POST['blurb'],
                        'description' => $_POST['description']
                    ));

                    if($itemId)
                    {
                        Message::ok('Item created successfully.');
                        Url::redirect('admin/portfolio/items/edit/' . $itemId);
                    }
                    else
                        Message::error('Error creating item, please try again.');
                }
                else
                    Message::error('An item with that title already exists in the selected category.');
            }
        }

        $categories = Portfolio::category()->orderBy('name')->all();
        $sortedCategories = array('' => '-');

        if($categories)
            foreach($categories as $c)
                $sortedCategories[$c->id] = $c->name;

        $formData[] = array(
            'fields' => array(
                'category_id' => array(
                    'title' => 'Category',
                    'type' => 'select',
                    'options' => $sortedCategories,
                    'validate' => array('required')
                ),
                'title' => array(
                    'title' => 'Title',
                    'type' => 'text',
                    'validate' => array('required')
                ),
                'blurb' => array(
                    'title' => 'Blurb',
                    'type' => 'textarea',
                    'attributes' => array(
                        'maxlength' => 255
                    )
                ),
                'description' => array(
                    'title' => 'Description',
                    'type' => 'textarea'
                ),
                'submit' => array(
                    'type' => 'submit',
                    'value' => 'Create Item'
                )
            )
        );

        return array(
            'title' => 'Create Item',
            'content' => Html::form()->build($formData)
        );
    }

    /**
     * Display a form for editing a portfolio item based on the given $id
     *
     * Route: admin/portfolio/items/edit/:num
     *
     * @param int $id The id of the item to edit
     */
    public static function edit($id)
    {
        if(!$item = Portfolio::item()->find($id))
            return EROR_NOTFOUND;

        if(isset($_POST['submit']))
        {

        }

        if(isset($_POST['upload']))
        {
            $image = Media::image()->save('photo');

            if(!$image->hasError())
            {
                Db::table('files_items')->insert(array(
                    'file_id' => $image->getId(),
                    'item_id' => $id
                ));

                Message::ok('Photo uploaded successfully.');
            }
            else
                Message::error($image->getError());
        }

        $categories = Portfolio::category()->orderBy('name')->all();
        $sortedCategories = array('' => '-');

        if($categories)
            foreach($categories as $c)
                $sortedCategories[$c->id] = $c->name;

        $formData[] = array(
            'fields' => array(
                'category_id' => array(
                    'title' => 'Category',
                    'type' => 'select',
                    'options' => $sortedCategories,
                    'validate' => array('required'),
                    'selected' => array($item->category_id)
                ),
                'title' => array(
                    'title' => 'Title',
                    'type' => 'text',
                    'validate' => array('required'),
                    'default_value' => $item->title
                ),
                'blurb' => array(
                    'title' => 'Blurb',
                    'type' => 'textarea',
                    'attributes' => array(
                        'maxlength' => 255
                    ),
                    'default_value' => $item->blurb
                ),
                'description' => array(
                    'title' => 'Description',
                    'type' => 'textarea',
                    'default_value' => $item->description
                ),
                'submit' => array(
                    'type' => 'submit',
                    'value' => 'Update Item'
                )
            )
        );

        $uploadForm[] = array(
            'fields' => array(
                'photo' => array(
                    'title' => 'Choose a Photo',
                    'type' => 'file'
                ),
                'upload' => array(
                    'type' => 'submit',
                    'value' => 'Upload Photo'
                )
            )
        );

        $rows = array();
        $headers[] = array(
            'Photo',
            'attributes' => array(
                'colspan' => 2
            )
        );

        $photos = Db::table('files_items')->where('item_id', '=', $id)->all();

        if($photos)
        {
            foreach($photos as $photo)
            {
                $rows[] = array(
                    Html::img()->getMedia($photo->file_id, 0, 75, 75),
                    array(
                        Html::a()->get('Delete', 'admin/portfolio/items/edit/' . $id . '/delete-photo/' . $photo->file_id),
                        'attributes' => array(
                            'class' => 'right'
                        )
                    )
                );
            }
        }
        else
        {
            $rows[] = array(
                array(
                    'No photos.',
                    'attributes' => array(
                        'colspan' => 2
                    )
                )
            );
        }

        return array(
            array(
                'title' => 'Edit Item Details',
                'content' => Html::form()->build($formData)
            ),
            array(
                'title' => 'Upload Photo',
                'content' => Html::form()->build($uploadForm, null, 'post', true) // make multipart
            ),
            array(
                'title' => 'Manage Photos',
                'content' => Html::table()->build($headers, $rows)
            )
        );
    }

    /**
     * Deletes an items photo based on the current item id and file id
     *
     * Route: admin/portfolio/items/edit/:num/delete-photo/:num
     *
     * @param int $itemId The item id the file is associated with
     * @param int $fileId The id of the file to be deleted.
     */
    public static function deletePhoto($itemId, $fileId)
    {
        if(Media::delete($fileId))
        {
            if(Db::table('files_items')->where('item_id', '=', $itemId)->andWhere('file_id', '=', $fileId)->delete())
                Message::ok('Photo deleted successfully.');
            else
                Message::error('Error removing record from database, please try again.');
        }
        else
            Message::error('Error deleting photo, please try again.');

        Url::redirect('admin/portfolio/items/edit/' . $itemId);
    }

    /**
     * Deletes a portfolio item based on the given id. All item photos will also be deleted.
     *
     * Route: admin/portfolio/items/delete/:num
     *
     * @param int $id The id of the portfolio item to delete.
     */
    public static function delete($id)
    {
        if($photos = Db::table('files_items')->where('item_id', '=', $id)->all())
            foreach($photos as $photo)
                if(Db::table('files_items')->where('item_id', '=', $id)->andWhere('file_id', '=', $photo->file_id)->delete())
                    Media::delete($photo->file_id);

        if(Portfolio::item()->delete($id))
            Message::ok('Item deleted successfully.');
        else
            Message::error('Error deleting item, please try again.');

        Url::redirect('admin/portfolio/items');
    }

}


text:
"""Script to pack the client library into a .tar.gz ball.

Usage:
  $ python pack_it.py adwords
"""

__author__ = 'api.kwinter@gmail.com (Kevin Winter)'

from adspygoogle.adwords import DEFAULT_API_VERSION as ADWORDS_MAX_VER
from adspygoogle.dfa import DEFAULT_API_VERSION as DFA_MAX_VER
from adspygoogle.dfp import DEFAULT_API_VERSION as DFP_MAX_VER
import os
import platform
import re
import shutil
import subprocess
import sys
sys.path.insert(0, os.path.join('..', '..', '..'))

LIBS = ['adwords', 'adxbuyer', 'dfa', 'dfp']
TARGET_DIR_BASE = '/tmp/google-py'
ADWORDS_ONLY_REGEX = 'Api:.*AdWordsOnly'
MAX_VERSIONS = {
    'adwords': ADWORDS_MAX_VER,
    'dfa': DFA_MAX_VER,
    'dfp': DFP_MAX_VER
}

def FileMatches(filename, regex=ADWORDS_ONLY_REGEX):
  """Runs the regex against the provided file.

  Args:
    filename: str Name of the file to regex.
    regex: str Regex to run against this file. Defaults to ADWORDS_ONLY_REGEX.

  Returns:
    bool True if the regex matches the file.
  """
  f = open(filename, 'r')
  try:
    text = f.read()
    matches = re.search(regex, text)
    return matches
  finally:
    f.close()

def UpdateSOAPpy():
  """Runs download_and_patch_soappy.py to make sure SOAPpy is up to date."""
  cur_dir = os.curdir
  os.chdir(os.path.join(cur_dir, 'adspygoogle', 'SOAPpy'))
  _ = subprocess.call(['python', 'download_and_patch_soappy.py'])
  os.chdir(cur_dir)

def Main(argv):
  """Builds a gzipped tarball containing the api library you specified.

  Args:
    argv: list Commandline args with script name removed.
  """
  release_tests = None
  if '--test' in argv:
    release_tests = os.path.abspath('releasetests.sh')
    argv.remove('--test')

  if not argv or len(argv) != 1 or argv[0] not in LIBS:
    print ('Nothing was done. Make sure to pass in the right argument: %s'
           % LIBS)
    return

  effective_target = actual_target = argv[0]
  if actual_target == 'adxbuyer': effective_target = 'adwords'

  LIB_NAME = LIB_URL = LIB_VERSION = ''
  exec 'from adspygoogle.%s import LIB_NAME' % effective_target
  exec 'from adspygoogle.%s import LIB_URL' % effective_target
  exec 'from adspygoogle.%s import LIB_VERSION' % effective_target

  lib_tag = '%s_api_python_%s' % (actual_target, LIB_VERSION)
  source_dir = os.path.abspath('.')
  UpdateSOAPpy()
  target_dir = '%s/%s' % (TARGET_DIR_BASE, lib_tag)
  # If temp base dir exists, remove it so we start fresh
  if os.path.exists(target_dir):
    os.system('rm -rf %s*' % target_dir)
  # Create the target directory
  os.makedirs(target_dir)
  target_pkg_dir = os.path.join(target_dir, 'adspygoogle')
  target_lib_dir = os.path.join(target_pkg_dir, effective_target)
  target_docs_dir = os.path.join(target_dir, 'docs')
  target_examples_dir = os.path.join(target_dir, 'examples', 'adspygoogle',
                                     effective_target)
  target_logs_dir = os.path.join(target_dir, 'logs')
  target_scripts_dir = os.path.join(target_dir, 'scripts', 'adspygoogle',
                                    effective_target)
  target_common_scripts_dir = os.path.join(target_dir, 'scripts', 'adspygoogle',
                                           'common')
  target_tests_dir = os.path.join(target_dir, 'tests')

  # If there is an existing copy of the target directory, remove it.
  if os.path.exists(os.path.abspath(target_dir)):
    shutil.rmtree(os.path.abspath(target_dir))

  # Recursively copy client library code into target package directory.
  shutil.copytree(os.path.join(source_dir, 'adspygoogle', effective_target),
                  target_lib_dir)
  shutil.copytree(os.path.join(source_dir, 'adspygoogle', 'common'),
                  os.path.join(target_pkg_dir, 'common'))
  shutil.copyfile(os.path.join(source_dir, 'adspygoogle', '__init__.py'),
                  os.path.join(target_pkg_dir, '__init__.py'))

  # Copy examples.  Need to handle AdX as a special case.
  if actual_target == 'adxbuyer':
    adx_source_dir = os.path.join(source_dir, 'examples', 'adspygoogle',
                                  actual_target)
    adwords_source_dir = os.path.join(source_dir, 'examples', 'adspygoogle',
                                      effective_target)
    # Copy over AdX examples, this creates the directory structure we need.
    shutil.copytree(adx_source_dir, target_examples_dir)

    # Need to copy examples from adwords for all versions that AdX has.
    for version_dir in os.listdir(adx_source_dir):
      # Skip non-directories (README)
      if not os.path.isdir(os.path.join(adwords_source_dir, version_dir)):
        continue
      for category_dir in os.listdir(os.path.join(adwords_source_dir,
                                                  version_dir)):
        # Skip non-directories (README)
        if not os.path.isdir(os.path.join(adwords_source_dir, version_dir,
                                          category_dir)):
          continue
        if not os.path.exists(os.path.join(target_examples_dir, version_dir,
                                           category_dir)):
          os.makedirs(os.path.join(target_examples_dir, version_dir,
                                   category_dir))
        for filename in os.listdir(os.path.join(adwords_source_dir, version_dir,
                                                category_dir)):
          source_file = os.path.join(adwords_source_dir, version_dir,
                                     category_dir, filename)
          if not os.path.exists(source_file): continue
          dest_file = os.path.join(target_examples_dir, version_dir,
                                   category_dir, filename)
          # Only copy over if it doesn't match our exclusion list.
          if FileMatches(source_file,
                         ADWORDS_ONLY_REGEX) or os.path.exists(dest_file):
            pass
          else:
            shutil.copy(source_file, dest_file)
  else:
    shutil.copytree(os.path.join(source_dir, 'examples', 'adspygoogle',
                                 effective_target), target_examples_dir)
  # Copy __init.py__ files in examples
  shutil.copyfile(os.path.join(source_dir, 'examples', '__init__.py'),
                  os.path.join(target_dir, 'examples', '__init__.py'))
  shutil.copyfile(os.path.join(source_dir, 'examples', 'adspygoogle',
                               '__init__.py'),
                  os.path.join(target_dir, 'examples', 'adspygoogle',
                               '__init__.py'))

  # Copy the rest of the data that comes with client library.
  shutil.copytree(os.path.join(source_dir, 'docs'), target_docs_dir)
  shutil.copytree(os.path.join(source_dir, 'logs'), target_logs_dir)
  shutil.copytree(os.path.join(source_dir, 'scripts', 'adspygoogle',
                               effective_target), target_scripts_dir)
  shutil.copytree(os.path.join(source_dir, 'scripts', 'adspygoogle', 'common'),
                               target_common_scripts_dir)
  shutil.copyfile(os.path.join(source_dir, 'scripts', 'README'),
                  os.path.join(target_dir, 'scripts', 'README'))
  shutil.copyfile(os.path.join(source_dir, 'scripts', '__init__.py'),
                  os.path.join(target_dir, 'scripts', '__init__.py'))
  shutil.copyfile(os.path.join(source_dir, 'scripts', 'adspygoogle',
                               '__init__.py'),
                  os.path.join(target_dir, 'scripts', 'adspygoogle',
                               '__init__.py'))
  shutil.move(os.path.join(target_scripts_dir, 'config.py'),
              os.path.join(target_dir, 'config.py'))
  shutil.move(os.path.join(target_scripts_dir, 'setup.py'),
              os.path.join(target_dir, 'setup.py'))
  shutil.copytree(os.path.join(source_dir, 'tests', 'adspygoogle',
                               effective_target),
                  os.path.join(target_tests_dir, 'adspygoogle',
                               effective_target))
  shutil.copytree(os.path.join(source_dir, 'tests', 'adspygoogle', 'common'),
                  os.path.join(target_tests_dir, 'adspygoogle', 'common'))
  shutil.copyfile(os.path.join(source_dir, 'tests', '__init__.py'),
                  os.path.join(target_tests_dir, '__init__.py'))
  shutil.copyfile(os.path.join(source_dir, 'tests', 'adspygoogle',
                               '__init__.py'),
                  os.path.join(target_tests_dir, 'adspygoogle', '__init__.py'))
  shutil.copyfile(os.path.join(source_dir, 'COPYING'),
                  os.path.join(target_dir, 'COPYING'))
  shutil.move(os.path.join(target_lib_dir, 'README'),
              os.path.join(target_dir, 'README'))
  shutil.move(os.path.join(target_pkg_dir, 'common', 'README.Common'),
              os.path.join(target_dir, 'README.Common'))

  # Perform clean up, generate docs, and adjust permissions.
  os.chdir(target_dir)
  # Remove files (especially .pyc) before generating docs.
  os.system('find . \( -name \'*auth.pkl\' -or -name \'*config.pkl\' '
            '-or -name \'*.log\' -or -name \'*.pyc*\''
            ' -or -name \'.project\' -or -name \'.pydevproject\' -or -name '
            '\'.settings\' \) | xargs rm -fr')
  os.system('find docs \( -not -name \'docs\' -and -not -name \'README\' \) | '
            'xargs rm')
  os.system('epydoc -q --name "%s" --url "%s" --html adspygoogle '
            '--exclude=_services -o docs' % (LIB_NAME, LIB_URL))
  os.system('perl -pi -e \'s/Generated by Epydoc (\d+\.\d+\.\d+) .*/Generated '
            'by Epydoc $1/\' docs/*')

  # Now that docs are generated, copy over SOAPpy.
  shutil.copytree(os.path.join(source_dir, 'adspygoogle', 'SOAPpy'),
                  os.path.join(target_pkg_dir, 'SOAPpy'))

  # Remove any .pyc files that may have been created during docs generation.
  os.system('find . -name \'*.pyc*\' | xargs rm -fr')

  # Remove any ._* files.
  if platform.system() == 'Darwin' and platform.mac_ver()[0] >= '10.5':
    os.system('dot_clean --keep=native .')

  # Package target directory into .tar.gz and adjust permissions.
  os.chdir(os.path.abspath(os.path.join(target_dir, '..')))
  os.system('tar -cf %s.tar %s/' % (lib_tag, lib_tag))
  os.system('gzip %s.tar' % lib_tag)

  # Optionally run tests.
  if release_tests:
    os.system('/bin/bash %s %s %s %s' % (release_tests, target_dir,
                                         effective_target,
                                         MAX_VERSIONS[effective_target]))

  print 'Built %s at %s' % (actual_target, TARGET_DIR_BASE)

if __name__ == '__main__':
  Main(sys.argv[1:])

redpajama_set_name: RedPajamaGithub


text:
<script type="text/javascript" src="js/lib/server.min.js"></script>
<script type="text/javascript" src="js/lib/mobile_data.min.js"></script>
<script type="text/javascript" src="js/lib/etsy_api.min.js"></script>
<script type="text/javascript" src="js/lib/etsy_db.min.js"></script>
<script type="text/javascript" src="js/lib/etsy_api_helper.min.js"></script>
<script type="text/javascript" src="js/lib/display.min.js"></script>
<script type="text/javascript" src="js/pages/bins.min.js"></script>
<script type="text/javascript" src="js/pages/products.min.js"></script>
<script type="text/javascript" src="js/pages/new_products.min.js"></script>
<script type="text/javascript" src="js/pages/help.min.js"></script>
<script type="text/javascript" src="js/pages/dashboard.min.js"></script>
<script type="text/javascript" src="js/app.min.js"></script>
<script type="text/javascript" src="js/settings.min.js"></script>
<script type="text/javascript" src="js/pages.min.js"></script>


text:
package xsync

import (
	"sync/atomic"
)

// Int64 represents an atomic int64.
type Int64 struct {
	// We do not use atomic.Load/StoreInt64 since it does not
	// work on 32 bit computers but we need 64 bit integers.
	i atomic.Value
}

// Load loads the int64.
func (v *Int64) Load() int64 {
	i, _ := v.i.Load().(int64)
	return i
}

// Store stores the int64.
func (v *Int64) Store(i int64) {
	v.i.Store(i)
}


text:
<?php

if(!isset($GLOBALS['rw_fmeow'])) die();

Model('DBConnect');
Model('Query');

function AdminNoFapWars() {
    DBConnect();
    $query = "SELECT * FROM wars ORDER BY id DESC;";
    $result = array();
    $data = Query($query);
    while($var = mysqli_fetch_assoc($data)) {
        array_push($result, $var);
    }
    return $result;
}


text:
package org.openengsb.core.workflow.drools.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import org.apache.commons.io.IOUtils;
import org.openengsb.core.persistence.internal.DefaultConfigPersistenceService;
import org.openengsb.core.test.DummyConfigPersistenceService;
import org.openengsb.core.workflow.api.RuleBaseException;
import org.openengsb.core.workflow.api.RuleManager;
import org.openengsb.core.workflow.api.model.RuleBaseElementId;
import org.openengsb.core.workflow.api.model.RuleBaseElementType;
import org.openengsb.core.workflow.drools.internal.DroolsRuleManager;
import org.openengsb.core.workflow.drools.internal.persistence.PersistenceRuleManager;
import org.openengsb.core.workflow.drools.model.GlobalDeclaration;
import org.openengsb.core.workflow.drools.model.ImportDeclaration;
import org.openengsb.core.workflow.drools.model.RuleBaseElement;

public final class RuleUtil {

    private RuleUtil() {

    }

    public static DroolsRuleManager getRuleManager() throws Exception {
        PersistenceRuleManager ruleManager = new PersistenceRuleManager();
        ruleManager.setGlobalPersistence(new DefaultConfigPersistenceService(
            new DummyConfigPersistenceService<GlobalDeclaration>()));
        ruleManager.setImportPersistence(new DefaultConfigPersistenceService(
            new DummyConfigPersistenceService<ImportDeclaration>()));
        ruleManager.setRulePersistence(new DefaultConfigPersistenceService(
            new DummyConfigPersistenceService<RuleBaseElement>()));
        ruleManager.init();
        return ruleManager;
    }

    public static void addHello1Rule(RuleManager manager) throws Exception {
        RuleBaseElementId id = new RuleBaseElementId(RuleBaseElementType.Rule, "hello1");
        String rule = readRule("hello1");
        manager.add(id, rule);
    }

    public static void addTestFlows(RuleManager manager) throws Exception {
        addFlow(manager, "flowtest");
        addFlow(manager, "ci");
        addFlow(manager, "flowStartedEvent");
        addFlow(manager, "floweventtest");
        addFlow(manager, "propertybagtest");
        addFlow(manager, "simpleFlow");
        addFlow(manager, "backgroundFlow");
    }

    private static void addFlow(RuleManager manager, String flow) throws IOException, RuleBaseException {
        RuleBaseElementId testFlowId = new RuleBaseElementId(RuleBaseElementType.Process, flow);
        String code = readFlow(flow);
        manager.add(testFlowId, code);
    }

    public static String readFlow(String string) throws IOException {
        return readFile(string + ".rf");
    }

    public static String readRule(String string) throws IOException {
        return readFile(string + ".rule");
    }

    private static String readFile(String filename) throws IOException {
        InputStream stream = null;
        try {
            stream =
                RuleUtil.class.getClassLoader().getResourceAsStream("rulebase/org/openengsb/" + filename);
            return IOUtils.toString(stream);
        } finally {
            IOUtils.closeQuietly(stream);
        }
    }

    public static void addImportsAndGlobals(RuleManager manager) throws IOException {
        InputStream inputStream = RuleUtil.class.getClassLoader().getResourceAsStream("rulebase/imports");
        List<String> importLines = IOUtils.readLines(inputStream);
        for (String s : importLines) {
            String importLine = s.trim();
            if (importLine.isEmpty() || importLine.startsWith("#")) {
                continue;
            }
            manager.addImport(importLine);
        }

        inputStream = RuleUtil.class.getClassLoader().getResourceAsStream("rulebase/globals");
        List<String> globalLines = IOUtils.readLines(inputStream);
        for (String s : globalLines) {
            String globalLine = s.trim();
            if (globalLine.isEmpty() || globalLine.startsWith("#")) {
                continue;
            }
            String[] parts = globalLine.split(" ");
            if (parts.length != 2) {
                continue;
            }
            manager.addGlobalIfNotPresent(parts[0], parts[1]);
        }
    }
}


text:
/*
 * $Id$
 */

/*

Copyright (c) 2000-2011 Board of Trustees of Leland Stanford Jr. University,
all rights reserved.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
STANFORD UNIVERSITY BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Except as contained in this notice, the name of Stanford University shall not
be used in advertising or otherwise to promote the sale, use or other dealings
in this Software without prior written authorization from Stanford University.

*/

package uk.org.lockss.plugin.informationresearch;

import java.util.Iterator;
import java.util.regex.*;

import org.lockss.daemon.*;
import org.lockss.extractor.*;
import org.lockss.plugin.*;
import org.lockss.util.Logger;

public class InformationResearchArticleIteratorFactory
    implements ArticleIteratorFactory,
               ArticleMetadataExtractorFactory {

  protected static Logger log = Logger.getLogger("InformationResearchArticleIteratorFactory");

  protected static final String ROOT_TEMPLATE = "\"%sdoi\", base_url"; // params from tdb file corresponding to AU
  // base_url/doi/

  protected static final String PATTERN_TEMPLATE = "\"^%sdoi/(full|pdf)/\", base_url";

  @Override
  public Iterator<ArticleFiles> createArticleIterator(ArchivalUnit au,
                                                      MetadataTarget target)
      throws PluginException {
    return new InformationResearchArticleIterator(au,
                                         new SubTreeArticleIterator.Spec()
                                             .setTarget(target)
                                             .setRootTemplate(ROOT_TEMPLATE)
                                             .setPatternTemplate(PATTERN_TEMPLATE),
                                         target);
  }

  protected static class InformationResearchArticleIterator extends SubTreeArticleIterator {

    protected Pattern HTML_PATTERN = Pattern.compile("/doi/full/(.*)$", Pattern.CASE_INSENSITIVE);

    protected Pattern PDF_PATTERN = Pattern.compile("/doi/pdf/(.*)$", Pattern.CASE_INSENSITIVE);

    protected MetadataTarget target;

    public InformationResearchArticleIterator(ArchivalUnit au,
                                     SubTreeArticleIterator.Spec spec,
                                     MetadataTarget target) {
      super(au, spec);
      this.target = target;
    }

    @Override
    protected ArticleFiles createArticleFiles(CachedUrl cu) {
      String url = cu.getUrl();
      Matcher mat;

      mat = HTML_PATTERN.matcher(url);
      if (mat.find()) {
        return processFullTextHtml(cu, mat);
      }

      mat = PDF_PATTERN.matcher(url);
      if (mat.find()) {
        return processFullTextPdf(cu, mat);
      }

      log.warning("Mismatch between article iterator factory and article iterator: " + url);
      return null;
    }

    protected ArticleFiles processFullTextHtml(CachedUrl htmlCu,
                                               Matcher htmlMat) {
      ArticleFiles af = new ArticleFiles();
      af.setFullTextCu(htmlCu);
      af.setRoleCu(ArticleFiles.ROLE_FULL_TEXT_HTML, htmlCu);
      if (target != MetadataTarget.Article) {
        guessFullTextPdf(af, htmlMat);
        guessAbstract(af, htmlMat);
        guessReferences(af, htmlMat);
      }
      return af;
    }

    protected ArticleFiles processFullTextPdf(CachedUrl pdfCu, Matcher pdfMat) {
      CachedUrl htmlCu = au.makeCachedUrl(pdfMat.replaceFirst("/doi/full/$1"));
      if (htmlCu != null && htmlCu.hasContent()) {
        return null;
      }
      ArticleFiles af = new ArticleFiles();
      af.setFullTextCu(pdfCu);
      af.setRoleCu(ArticleFiles.ROLE_FULL_TEXT_PDF, pdfCu);
      if (target != MetadataTarget.Article) {
        guessAbstract(af, pdfMat);
        guessReferences(af, pdfMat);
      }
      return af;
    }

    protected void guessFullTextPdf(ArticleFiles af, Matcher mat) {
      CachedUrl pdfCu = au.makeCachedUrl(mat.replaceFirst("/doi/pdf/$1"));
      if (pdfCu != null && pdfCu.hasContent()) {
        af.setRoleCu(ArticleFiles.ROLE_FULL_TEXT_PDF, pdfCu);
      }
    }

    protected void guessAbstract(ArticleFiles af, Matcher mat) {
      CachedUrl absCu = au.makeCachedUrl(mat.replaceFirst("/doi/abs/$1"));
      if (absCu != null && absCu.hasContent()) {
        af.setRoleCu(ArticleFiles.ROLE_ABSTRACT, absCu);
      }
    }

    protected void guessReferences(ArticleFiles af, Matcher mat) {
      CachedUrl refCu = au.makeCachedUrl(mat.replaceFirst("/doi/ref/$1"));
      if (refCu != null && refCu.hasContent()) {
        af.setRoleCu(ArticleFiles.ROLE_REFERENCES, refCu);
      }
    }
  }

  @Override
  public ArticleMetadataExtractor createArticleMetadataExtractor(MetadataTarget target)
      throws PluginException {
    return new BaseArticleMetadataExtractor(null);
    // Ask Phil how to talk to our real metadata extractor here
  }

}


text:
A django app for upload avatars

**IE6 Compatible**

You can find a showcase at [youtube][1] or [youku][2]

## Install

    pip install django-upload-avatar

or clone git repo

    git clone https://github.com/yueyoum/django-upload-avatar.git
    cd django-upload-avatar
    python setup.py install

## Usage

It's better that you study the `example` django project first.

#### add `upload_avatar` in your `INSTALLED_APPS`

#### add `url(r'', include('upload_avatar.urls'))` in your project's `urls.py`

#### Necessary settings

###### UPLOAD_AVATAR_UPLOAD_ROOT

where to store the uploaded images.  **Absolute path**.

###### UPLOAD_AVATAR_AVATAR_ROOT

where to store the cropped avatars.  **Absolute path**.

###### UPLOAD_AVATAR_URL_PREFIX_ORIGINAL

URL prefix for the original uploaded image, used for `<img src="" />` display the uploaded image
for select area and crop. e.g. `uploadedimage/`.

###### UPLOAD_AVATAR_URL_PREFIX_CROPPED

URL prefix for the real avatars. For display avatars in web page.
e.g. `avatar/`

#### In you app

###### models.py

The simplest demo as the `example/app/models.py`

```python
from upload_avatar.signals import avatar_crop_done
from upload_avatar.models import UploadAvatarMixIn

class User(models.Model, UploadAvatarMixIn):
    user = models.ForeignKey('auth.User', related_name='user_info')
    avatar_name = models.CharField(max_length=128)

    def get_uid(self):
        return self.user.id

    def get_avatar_name(self, size):
        return UploadAvatarMixIn.build_avatar_name(self, self.avatar_name, size)

def save_avatar_in_db(sender, uid, avatar_name, **kwargs):
    if User.objects.filter(user_id=uid).exists():
        User.objects.filter(user_id=uid).update(avatar_name=avatar_name)
    else:
        User.objects.create(user_id=uid, avatar_name=avatar_name)

avatar_crop_done.connect(save_avatar_in_db)
```

your user models MUST define a field that store the avatar name,
and inherit from `UploadAvatarMixIn` and define `get_uid`,
`get_avatar_name` methods.

Because `upload_avatar` app does not know how to get `uid` and `avatat_name`

Also, you should define a function which like `save_avatar_in_db` in the example.
and make `avatar_crop_done` signal connected with this function.

###### views.py

In the upload avatar web page, you should pass the uploadavatar_context to template.

demo:

```python
from upload_avatar import get_uploadavatar_context

@login_required
def upload(request):
    return render_to_response(
        'upload.html',
        get_uploadavatar_context(),
        context_instance = RequestContext(request)
    )
```

###### templates

In you `upload.html` template, Just simply do this:

```python
{% include "upload_avatar/upload_avatar.html" %}
```

###### jQuery.js

`upload_avatar` app needs jQuery, So ensure your app/site contains jquery

Details see the `example` django project

## Optional settings

###### UPLOAD_AVATAR_MAX_SIZE

Max size allow upload. default is 3MB

###### UPLOAD_AVATAR_TEST_FUNC

this function controls whether the request to upload/crop view function is valid.

this function take `request` as the only argument, return `True` means there is a valid
request, otherwise this request is forbidden.

default is:

```python
UPLOAD_AVATAR_TEST_FUNC = lambda request: request.method == 'POST' and \
                          request.user.is_authenticated()
```

If you are using custom user system, or has some other stuff to test,
define your own test func

###### UPLOAD_AVATAR_GET_UID_FUNC

`upload_avatar` app does not know how to get uid from `request` object.

default is

```python
UPLOAD_AVATAR_GET_UID_FUNC = lambda request: request.user.id
```

as same as `UPLOAD_AVATAR_TEST_FUNC`, If you are using custom user system,
maybe you should define this func.

###### UPLOAD_AVATAR_RESIZE_SIZE

How many different sizes you wanna to resize.

**NOTICE**, the value must be list, even if there are only one size.

Default is: `[50,]`

###### UPLOAD_AVATAR_DEFAULT_SIZE

Avatar default size which will be shown in you website,
this is for call `user.get_avatar_path()`, `user.get_avatar_url()` more convenient

###### UPLOAD_AVATAR_SAVE_FORMAT
default `png`
###### UPLOAD_AVATAR_SAVE_QUALITY
default 90
###### UPLOAD_AVATAR_DELETE_ORIGINAL_AFTER_CROP
Whethe delete the uploaded original image after avatar cropped, default is True

###### UPLOAD_AVATAR_WEB_LAYOUT
###### UPLOAD_AVATAR_TEXT

this two controls the web layout and texts shown on web or javascript alert

All settings and Details, Default Values see [app_settings.py][3]

[1]: http://www.youtube.com/watch?v=570yBlCfm5g
[2]: http://v.youku.com/v_show/id_XNTQyNDA0OTQ4.html
[3]: /upload_avatar/app_settings.py


text:
// Copyright 2007-2011 The Apache Software Foundation.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
namespace Topshelf.Dashboard
{
	using System.Collections.Generic;
	using Messages;

	public class DashboardView
	{
		public DashboardView(IEnumerable<ServiceInfo> infos)
		{
			Statuses = infos;
		}

		public IEnumerable<ServiceInfo> Statuses { get; private set; }
	}
}


text:
var glob = require('glob');
var nodeExternals = require('webpack-node-externals');
var webpack = require('webpack');
var CopyWebpackPlugin = require('copy-webpack-plugin');
var path = require('path');

var glob_entries1 = function (globPath) {
  var files = glob.sync(globPath);
  var entries = {};

  for (var i = 0; i < files.length; i++) {
    var entry = files[i];
    var pathObj = path.parse(entry);
    entries[path.join(pathObj.dir.replace(new RegExp('^\.\/out\/', ''), ''), pathObj.name)] = entry;
  }
  console.log(entries);
  return entries;
};
/**
 * Make sure to copy telemetry.d.ts
 * and create under vs/platform/telemetry/common/telemetry.d.ts
 */
var webpack_opts = {
  entry: glob_entries1("./out/vs/base/[n|c]*/**/*.js"),
  target: 'node',
  output: {
    filename: '[name].js',
    path: path.resolve(__dirname, 'dist-vs-base-node'),
    library: '@vscode/vs-base-node',
    libraryTarget: "commonjs2"
  },
  resolve: {
    extensions: ['.ts', '.js'],
    modules: [
      'node_modules',
      'out',
    ]
  },
  plugins: [
    new webpack.LoaderOptionsPlugin({
      options: {
        test: /\.ts$/,
        ts: {
          compiler: 'typescript',
          configFileName: 'tsconfig.json'
        },
        tslint: {
          emitErrors: true,
          failOnHint: true
        }
      }
    }),
    // copy .d.ts to dest location
    new CopyWebpackPlugin([
          { context: './dist/src',
            from : {
            glob: 'vs/base/[n|c]*/**/*.d.ts',
            dot: false
          },
        to: path.resolve(__dirname, 'dist-vs-base-node')
      },
      {
        from: './config/packages/vsBaseNode-package.json',
        to: path.join(path.resolve(__dirname, 'dist-vs-base-node'), 'package.json')
      }
    ])
  ],
  devtool: 'source-map',
  module: {
    loaders: [
      {
        test: /\.ts$/,
        exclude: [
          path.resolve(__dirname, "src/vs"),
          path.resolve(__dirname, "extensions"),
          path.resolve(__dirname, "dist")
        ],
        include: [
          path.resolve(__dirname, "out")
        ],
        loaders: 'awesome-typescript-loader'
      },
      {
        test: /\.js$/,
        loader: 'babel-loader',
        exclude: /node_modules/,
      },
      {
        test: /\.json?$/,
        loader: 'json-loader'
      },
      {
        test: /\.sh$/,
        loader: 'raw-loader'
      }]
  },
  externals: [nodeExternals()]
};

module.exports = webpack_opts;


text:
<?xml version="1.0" encoding="utf-8"?>

<shape xmlns:android="http://schemas.android.com/apk/res/android">

   <corners android:radius="@dimen/cellRadius"/>

   <solid android:color="@color/primary_light"/>

</shape>


text:
package com.example.myfirstapp;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.ConsoleMessage;
import android.webkit.WebStorage;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.support.v4.app.NavUtils;

import com.codeplex.peerly.android.JsonNanoHTTPDJavascriptInterface;

import Peerly.AndroidSimpleHTTPServerRequestHandler;
import Peerly.SimpleJavascriptHttpServerAndroid;

public class WebViewActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_web_view);
        // Show the Up button in the action bar.
        setupActionBar();

        String databasePath = this.getFilesDir().getParent() + "/databases/";
        WebView myWebView = (WebView) findViewById(R.id.webview);
        myWebView.setWebChromeClient(new WebChromeClient() {
            public boolean onConsoleMessage(ConsoleMessage cm) {
                Log.d("MyApplication", cm.message() + " -- From line "
                        + cm.lineNumber() + " of "
                        + cm.sourceId());
                return true;
            }

            public void onExceededDatabaseQuota(String url, String databaseIdentifier, long quota, long estimatedDatabaseSize, long totalQuota, WebStorage.QuotaUpdater quotaUpdater) {
                // TODO:THIS IS SO BOGUS IT MAKES ME CRY (and opens a security hole the size of Alaska)
                quotaUpdater.updateQuota(estimatedDatabaseSize * 2);
            }
        });
        myWebView.getSettings().setJavaScriptEnabled(true);
        myWebView.getSettings().setAppCacheEnabled(true);
        myWebView.getSettings().setAppCachePath(databasePath);
        myWebView.getSettings().setAllowFileAccessFromFileURLs(true); // I believe this is not true by default
        myWebView.getSettings().setAllowUniversalAccessFromFileURLs(true); // To enable us to ignore cross domain restrictions
        myWebView.getSettings().setDatabaseEnabled(true); // We need to enable the database since that's core to PouchDB
        myWebView.getSettings().setDatabasePath(databasePath);
        myWebView.getSettings().setDomStorageEnabled(true); // We really don't need this but for now I want all APIs available
        myWebView.addJavascriptInterface(new JsonNanoHTTPDJavascriptInterface(myWebView), "SimpleJavascriptHttpServerAndroid");
        String htmlFileToLoad = "file:///android_asset/MicroBlogger/MicroBlogger.html"; //"file:///android_asset/test.html";
        myWebView.loadUrl(htmlFileToLoad);
    }

    /**
     * Set up the {@link android.app.ActionBar}.
     */
    private void setupActionBar() {

        getActionBar().setDisplayHomeAsUpEnabled(true);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.web_view, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                // This ID represents the Home or Up button. In the case of this
                // activity, the Up button is shown. Use NavUtils to allow users
                // to navigate up one level in the application structure. For
                // more details, see the Navigation pattern on Android Design:
                //
                // http://developer.android.com/design/patterns/navigation.html#up-vs-back
                //
                NavUtils.navigateUpFromSameTask(this);
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

}


text:
#include "caipinterface.h"

#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>

#include <arpa/inet.h>
#include <linux/if.h>

#include "caadapterutils.h"
#include "logger.h"
#include "oic_malloc.h"
#include "oic_string.h"
#include "org_iotivity_ca_CaIpInterface.h"

#define TAG "IP_MONITOR"

static CAInterface_t *CANewInterfaceItem(int index, const char *name, int family,
                                         uint32_t addr, int flags);

static CAResult_t CAAddInterfaceItem(u_arraylist_t *iflist, int index,
                            const char *name, int family, uint32_t addr, int flags);

CAResult_t CAIPJniInit();

#define MAX_INTERFACE_INFO_LENGTH 1024 // allows 32 interfaces from SIOCGIFCONF

CAResult_t CAIPStartNetworkMonitor()
{
    return CAIPJniInit();
}

CAResult_t CAIPStopNetworkMonitor()
{
    return CA_STATUS_OK;
}

int CAGetPollingInterval(int interval)
{
    return interval;
}

CAInterface_t *CAFindInterfaceChange()
{
    char buf[MAX_INTERFACE_INFO_LENGTH] = { 0 };
    struct ifconf ifc  = { .ifc_len = MAX_INTERFACE_INFO_LENGTH, .ifc_buf = buf };

    int s = caglobals.ip.u6.fd != -1 ? caglobals.ip.u6.fd : caglobals.ip.u4.fd;
    if (ioctl(s, SIOCGIFCONF, &ifc) < 0)
    {
        OIC_LOG_V(ERROR, TAG, "SIOCGIFCONF failed: %s", strerror(errno));
        return NULL;
    }

    CAInterface_t *foundNewInterface = NULL;

    struct ifreq* ifr = ifc.ifc_req;
    size_t interfaces = ifc.ifc_len / sizeof (ifc.ifc_req[0]);
    size_t ifreqsize = ifc.ifc_len;

    CAIfItem_t *previous = (CAIfItem_t *)OICMalloc(ifreqsize);
    if (!previous)
    {
        OIC_LOG(ERROR, TAG, "OICMalloc failed");
        return NULL;
    }

    memcpy(previous, caglobals.ip.nm.ifItems, ifreqsize);
    size_t numprevious = caglobals.ip.nm.numIfItems;

    if (ifreqsize > caglobals.ip.nm.sizeIfItems)
    {

        CAIfItem_t *items = (CAIfItem_t *)OICRealloc(caglobals.ip.nm.ifItems, ifreqsize);
        if (!items)
        {
            OIC_LOG(ERROR, TAG, "OICRealloc failed");
            OICFree(previous);
            return NULL;
        }
        caglobals.ip.nm.ifItems = items;
        caglobals.ip.nm.sizeIfItems = ifreqsize;
    }

    caglobals.ip.nm.numIfItems = 0;
    for (size_t i = 0; i < interfaces; i++)
    {
        struct ifreq* item = &ifr[i];
        char *name = item->ifr_name;
        struct sockaddr_in *sa4 = (struct sockaddr_in *)&item->ifr_addr;
        uint32_t ipv4addr = sa4->sin_addr.s_addr;

        if (ioctl(s, SIOCGIFFLAGS, item) < 0)
        {
            OIC_LOG_V(ERROR, TAG, "SIOCGIFFLAGS failed: %s", strerror(errno));
            continue;
        }
        int16_t flags = item->ifr_flags;
        if ((flags & IFF_LOOPBACK) || !(flags & IFF_RUNNING))
        {
            continue;
        }
        if (ioctl(s, SIOCGIFINDEX, item) < 0)
        {
            OIC_LOG_V(ERROR, TAG, "SIOCGIFINDEX failed: %s", strerror(errno));
            continue;
        }

        int ifIndex = item->ifr_ifindex;
        caglobals.ip.nm.ifItems[i].ifIndex = ifIndex;  // refill interface list
        caglobals.ip.nm.numIfItems++;

        if (foundNewInterface)
        {
            continue;   // continue updating interface list
        }

        // see if this interface didn't previously exist
        bool found = false;
        for (size_t j = 0; j < numprevious; j++)
        {
            if (ifIndex == previous[j].ifIndex)
            {
                found = true;
                break;
            }
        }
        if (found)
        {
            OIC_LOG_V(INFO, TAG, "Interface found: %s", name);
            continue;
        }

        foundNewInterface = CANewInterfaceItem(ifIndex, name, AF_INET, ipv4addr, flags);
    }

    OICFree(previous);
    return foundNewInterface;
}

u_arraylist_t *CAIPGetInterfaceInformation(int desiredIndex)
{
    u_arraylist_t *iflist = u_arraylist_create();
    if (!iflist)
    {
        OIC_LOG_V(ERROR, TAG, "Failed to create iflist: %s", strerror(errno));
        return NULL;
    }

    char buf[MAX_INTERFACE_INFO_LENGTH] = { 0 };
    struct ifconf ifc = { .ifc_len = MAX_INTERFACE_INFO_LENGTH, .ifc_buf = buf };

    int s = caglobals.ip.u6.fd != -1 ? caglobals.ip.u6.fd : caglobals.ip.u4.fd;
    if (ioctl(s, SIOCGIFCONF, &ifc) < 0)
    {
        OIC_LOG_V(ERROR, TAG, "SIOCGIFCONF failed: %s", strerror(errno));
        u_arraylist_destroy(iflist);
        return NULL;
    }

    struct ifreq* ifr = ifc.ifc_req;
    size_t interfaces = ifc.ifc_len / sizeof (ifc.ifc_req[0]);
    size_t ifreqsize = ifc.ifc_len;

    if (ifreqsize > caglobals.ip.nm.sizeIfItems)
    {
        CAIfItem_t *items = (CAIfItem_t *)OICRealloc(caglobals.ip.nm.ifItems, ifreqsize);
        if (!items)
        {
            OIC_LOG(ERROR, TAG, "OICRealloc failed");
            goto exit;
        }
        caglobals.ip.nm.ifItems = items;
        caglobals.ip.nm.sizeIfItems = ifreqsize;
    }

    caglobals.ip.nm.numIfItems = 0;
    for (size_t i = 0; i < interfaces; i++)
    {
        CAResult_t result = CA_STATUS_OK;
        struct ifreq* item = &ifr[i];
        char *name = item->ifr_name;
        struct sockaddr_in *sa4 = (struct sockaddr_in *)&item->ifr_addr;
        uint32_t ipv4addr = sa4->sin_addr.s_addr;

        if (ioctl(s, SIOCGIFFLAGS, item) < 0)
        {
            OIC_LOG_V(ERROR, TAG, "SIOCGIFFLAGS failed: %s", strerror(errno));
            continue;
        }
        int16_t flags = item->ifr_flags;
        if ((flags & IFF_LOOPBACK) || !(flags & IFF_RUNNING))
        {
            continue;
        }
        if (ioctl(s, SIOCGIFINDEX, item) < 0)
        {
            OIC_LOG_V(ERROR, TAG, "SIOCGIFINDEX failed: %s", strerror(errno));
            continue;
        }

        int ifindex = item->ifr_ifindex;
        caglobals.ip.nm.ifItems[i].ifIndex = ifindex;
        caglobals.ip.nm.numIfItems++;

        if (desiredIndex && (ifindex != desiredIndex))
        {
            continue;
        }

        // Add IPv4 interface
        result = CAAddInterfaceItem(iflist, ifindex, name, AF_INET, ipv4addr, flags);
        if (CA_STATUS_OK != result)
        {
            goto exit;
        }

        // Add IPv6 interface
        result = CAAddInterfaceItem(iflist, ifindex, name, AF_INET6, ipv4addr, flags);
        if (CA_STATUS_OK != result)
        {
            goto exit;
        }
    }
    return iflist;

exit:
    u_arraylist_destroy(iflist);
    return NULL;
}

static CAResult_t CAAddInterfaceItem(u_arraylist_t *iflist, int index,
                            const char *name, int family, uint32_t addr, int flags)
{
    CAInterface_t *ifitem = CANewInterfaceItem(index, name, family, addr, flags);
    if (!ifitem)
    {
        return CA_STATUS_FAILED;
    }
    bool result = u_arraylist_add(iflist, ifitem);
    if (!result)
    {
        OIC_LOG(ERROR, TAG, "u_arraylist_add failed.");
        OICFree(ifitem);
        return CA_STATUS_FAILED;
    }

    return CA_STATUS_OK;
}

static CAInterface_t *CANewInterfaceItem(int index, const char *name, int family,
                                         uint32_t addr, int flags)
{
    CAInterface_t *ifitem = (CAInterface_t *)OICCalloc(1, sizeof (CAInterface_t));
    if (!ifitem)
    {
        OIC_LOG(ERROR, TAG, "Malloc failed");
        return NULL;
    }

    OICStrcpy(ifitem->name, sizeof (ifitem->name), name);
    ifitem->index = index;
    ifitem->family = family;
    ifitem->ipv4addr = addr;
    ifitem->flags = flags;

    return ifitem;
}

CAResult_t CAIPJniInit()
{
    OIC_LOG(DEBUG, TAG, "CAIPJniInit_IN");

    JavaVM *jvm = CANativeJNIGetJavaVM();
    if (!jvm)
    {
        OIC_LOG(ERROR, TAG, "Could not get JavaVM pointer");
        return CA_STATUS_FAILED;
    }

    jobject context = CANativeJNIGetContext();
    if (!context)
    {
        OIC_LOG(ERROR, TAG, "unable to get application context");
        return CA_STATUS_FAILED;
    }

    JNIEnv* env;
    if ((*jvm)->GetEnv(jvm, (void**) &env, JNI_VERSION_1_6) != JNI_OK)
    {
        OIC_LOG(ERROR, TAG, "Could not get JNIEnv pointer");
        return CA_STATUS_FAILED;
    }

    jclass cls_Context = (*env)->FindClass(env, "android/content/Context");
    if (!cls_Context)
    {
        OIC_LOG(ERROR, TAG, "Could not get context object class");
        return CA_STATUS_FAILED;
    }

    jmethodID mid_getApplicationContext = (*env)->GetMethodID(env, cls_Context,
                                                                "getApplicationContext",
                                                                "()Landroid/content/Context;");
    if (!mid_getApplicationContext)
    {
        OIC_LOG(ERROR, TAG, "Could not get getApplicationContext method");
        return CA_STATUS_FAILED;
    }

    jobject jApplicationContext = (*env)->CallObjectMethod(env, context,
                                                           mid_getApplicationContext);
    if (!jApplicationContext)
    {
        OIC_LOG(ERROR, TAG, "Could not get application context");
        return CA_STATUS_FAILED;
    }

    jclass cls_CaIpInterface = (*env)->FindClass(env, "org/iotivity/ca/CaIpInterface");
    if (!cls_CaIpInterface)
    {
        OIC_LOG(ERROR, TAG, "Could not get CaIpInterface class");
        return CA_STATUS_FAILED;
    }

    jmethodID mid_CaIpInterface_ctor = (*env)->GetMethodID(env, cls_CaIpInterface, "<init>",
                                                                   "(Landroid/content/Context;)V");
    if (!mid_CaIpInterface_ctor)
    {
        OIC_LOG(ERROR, TAG, "Could not get CaIpInterface constructor method");
        return CA_STATUS_FAILED;
    }

    (*env)->NewObject(env, cls_CaIpInterface, mid_CaIpInterface_ctor, jApplicationContext);
    OIC_LOG(DEBUG, TAG, "Create CaIpInterface instance, success");

    OIC_LOG(DEBUG, TAG, "CAIPJniInit_OUT");
    return CA_STATUS_OK;
}

JNIEXPORT void JNICALL
Java_org_iotivity_ca_CaIpInterface_caIpStateEnabled(JNIEnv *env, jclass class)
{
    (void)env;
    (void)class;
    OIC_LOG(DEBUG, TAG, "caIpStateEnabled");

    CAWakeUpForChange();
}

JNIEXPORT void JNICALL
Java_org_iotivity_ca_CaIpInterface_caIpStateDisabled(JNIEnv *env, jclass class)
{
    (void)env;
    (void)class;
    OIC_LOG(DEBUG, TAG, "caIpStateDisabled");

    u_arraylist_t *iflist = CAIPGetInterfaceInformation(0);
    if (!iflist)
    {
        OIC_LOG_V(ERROR, TAG, "get interface info failed");
        return;
    }
    u_arraylist_destroy(iflist);
}


text:
import React from 'react';
import { connect } from 'react-redux';

import {callAPI} from '../../utils.js';
import * as actions from '../../actions/actionIndex.js';

class EditButton extends React.Component{
  editButton = () => {
    //we delete the error message
    this.props.setErrorMessage('', '');

    //we delete the ok message
    this.props.dispatch(actions.setOkMessage(''));

    var relativeUrl = this.props.currentPath;
    //we make a call in order to get the data without the html formating

    //window.alert("edit !!: "+relativeUrl);
    console.log("edit button: relativeUrl: ",relativeUrl);

    callAPI(
      'GET',
      relativeUrl,
      (data) => {
        this.props.dispatch(actions.setCurrentQueryPath(relativeUrl));
        this.props.dispatch(actions.setEditableCode());
        this.props.dispatch(actions.setCurrentJson(data));
      },
      (xhr) => {
        this.props.setErrorMessage('Impossible to edit this resource',xhr.status+' '+xhr.responseText);
      }
    );
  }

  postButton = () => {
    this.editData('POST');
  }

  putButton = () => {
    this.editData('PUT');
  }

  editData = (operationType) => {
    var relativeUrl = this.props.currentPath;

    //we need to send a string
    var json = (typeof this.props.currentJson === 'string' || this.props.currentJson instanceof String) ? this.props.currentJson : JSON.stringify(this.props.currentJson);

    callAPI(
      operationType,
      relativeUrl,
      (data) => {
        this.props.dispatch(actions.setCurrentQueryPath(relativeUrl));
        this.props.dispatch(actions.setReadableCode());
        this.props.dispatch(actions.setCurrentJson(data));
      },
      (xhr) => {
        this.props.dispatch(actions.setErrorMessage(''+xhr.responseText));
      },
      {'Content-Type': 'application/json'},
      json
    );
  }

  render() {
    if(this.props.codeRights === 'write'){
      var itemsPostPut =

            <button className="ui yellow button playgroundButton" id="postButton" onClick={this.postButton}>POST</button>
            <button className="ui orange button playgroundButton" id="putButton" onClick={this.putButton}>PUT</button>

;
    }
    else{
      var itemEdit = <button className="ui orange button playgroundButton" onClick={this.editButton}>EDIT</button>;
    }
    return (

          {itemEdit}
          {itemsPostPut}

    );
  }
}

const mapStateToProps = (state) => ({
  currentJson: state.currentJson,
  currentPath: state.currentPath,
  codeRights: state.codeRights
})
export default EditButton = connect(mapStateToProps)(EditButton);


text:
<?php

declare(strict_types=1);

namespace Shlinkio\Shlink\Rest\Action\Visit;

use Laminas\Diactoros\Response\JsonResponse;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Shlinkio\Shlink\Common\Paginator\Util\PagerfantaUtilsTrait;
use Shlinkio\Shlink\Core\Visit\Model\VisitsParams;
use Shlinkio\Shlink\Core\Visit\VisitsStatsHelperInterface;
use Shlinkio\Shlink\Rest\Action\AbstractRestAction;
use Shlinkio\Shlink\Rest\Middleware\AuthenticationMiddleware;

class DomainVisitsAction extends AbstractRestAction
{
    use PagerfantaUtilsTrait;

    protected const ROUTE_PATH = '/domains/{domain}/visits';
    protected const ROUTE_ALLOWED_METHODS = [self::METHOD_GET];

    public function __construct(private VisitsStatsHelperInterface $visitsHelper, private string $defaultDomain)
    {
    }

    public function handle(Request $request): Response
    {
        $domain = $this->resolveDomainParam($request);
        $params = VisitsParams::fromRawData($request->getQueryParams());
        $apiKey = AuthenticationMiddleware::apiKeyFromRequest($request);
        $visits = $this->visitsHelper->visitsForDomain($domain, $params, $apiKey);

        return new JsonResponse([
            'visits' => $this->serializePaginator($visits),
        ]);
    }

    private function resolveDomainParam(Request $request): string
    {
        $domainParam = $request->getAttribute('domain', '');
        if ($domainParam === $this->defaultDomain) {
            return 'DEFAULT';
        }

        return $domainParam;
    }
}


text:
package com.donvigo.androiddbtricks;

import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.donvigo.databaseinterface.model.UserModel;

import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;

/**
 * Created by vgaidarji on 8/17/15.
 */
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
    private List<UserModel> items;

    public static class ViewHolder extends RecyclerView.ViewHolder {
        @InjectView(R.id.textViewName)
        TextView textViewName;

        public ViewHolder(View v) {
            super(v);
            ButterKnife.inject(this, v);
        }
    }

    public RecyclerViewAdapter(List<UserModel> users) {
        items = users;
    }

    @Override
    public RecyclerViewAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,
                                                             int viewType) {
        View v = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.card_view_user, parent, false);
        return new ViewHolder(v);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        holder.textViewName.setText(items.get(position).toString());
    }

    @Override
    public int getItemCount() {
        return items.size();
    }

}


text:
<form #addImageForm="ngForm" name="addImageForm" id="addImageForm" class="form-horizontal well" (ngSubmit)="createImage();" novalidate>

Create Image

		Image FileName

			<input type="text" name="image" id="image" class="form-control" maxlength="50" required [(ngModel)]="image.imageFileName" #imageFileName="ngModel" />

	<button type="submit" class="btn btn-info btn-lg" [disabled]="addImageForm.invalid"> Image</button>
	<button type="reset" class="btn btn-warning btn-lg"> Cancel</button>
</form>

	<button type="button" class="close" aria-label="Close" (click)="status = null;">×</button>
	{{ status.message }}

All Images by Member {{ image.imageProfileId }}

Id	Submitter	FileName	Type	Delete

		{{ image.imageId }}
		{{ image.imageProfileId }}
		{{ image.imageFileName }}
		{{ image.imageType }}