text:
/* -------------------------------------------------------------------------- */
/* Copyright 2002-2022, OpenNebula Project, OpenNebula Systems                */
/*                                                                            */
/* Licensed under the Apache License, Version 2.0 (the "License"); you may    */
/* not use this file except in compliance with the License. You may obtain    */
/* a copy of the License at                                                   */
/*                                                                            */
/* http://www.apache.org/licenses/LICENSE-2.0                                 */
/*                                                                            */
/* Unless required by applicable law or agreed to in writing, software        */
/* distributed under the License is distributed on an "AS IS" BASIS,          */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   */
/* See the License for the specific language governing permissions and        */
/* limitations under the License.                                             */
/* -------------------------------------------------------------------------- */

#ifndef SCHED_ACTION_ATTRIBUTE_H_
#define SCHED_ACTION_ATTRIBUTE_H_

#include <set>

#include "VirtualMachineAttribute.h"

/**
 * The VirtualMachine SCHED_ACTION attribute
 */
class SchedAction: public VirtualMachineAttribute
{
public:
    enum Repeat
    {
        NONE    = -1,
        WEEKLY  = 0,
        MONTHLY = 1,
        YEARLY  = 2,
        HOURLY  = 3
    };

    enum EndOn
    {
        END_NONE = -1,
        NEVER    = 0,
        TIMES    = 1,
        DATE     = 2
    };

    SchedAction(VectorAttribute *va, int id):VirtualMachineAttribute(va, id){};

    virtual ~SchedAction(){};

    int action_id()
    {
        return get_id();
    }

    /**
     *  Returns the REPEAT value of the SCHED_ACTION
     *    @param r repeat WEEKLY, MONTHLY, YEARLY or HOURLY
     *    @return -1 if REPEAT not found or in wrong format 0 on success
     */
    int repeat(Repeat& r);

    /**
     *  Returns the END_TYPE value of the SCHED_ACTION
     *    @param eo ends on TIMES   WEEKLY, MONTHLY, YEARLY or HOURLY
     *    @return -1 if REPEAT not found or in wrong format 0 on success
     */
    int endon(EndOn& eo);

    /**
     *  Parse the DAYS attribute of the sched action
     *    @param d set of days (unique)
     *    @return -1 if not found (d will be empty) 0 otherwise
     */
    int days(std::set<int>& _d);

    /**
     *  This function checks that the DAYS attributes are in range
     *  according to the Repeat value:
     *    @param r repeat type (hourly, weekly...)
     *    @param error in case of error
     *
     *    @return true if days are in range false (error) if not
     */
    bool days_in_range(Repeat r, std::string& error);

    /**
     *  This function checks that END_VALUE is properly defined for the
     *  associated END_TYPE
     *    @param eo end type (date, times)
     *    @param error in case of error
     *
     *    @return 0 if days are in range -1 (error) if not or -2 (not defined)
     */
    int ends_in_range(EndOn eo, std::string& error);

    /**
     *  This function parse and checks the sched action attributes: REPEAT, DAYS
     *  , END_TYPE, END_DATE. It also removed DONE and MESSAGE.
     *    @param error
     *    @param clean indicates if the user wants to remove DONE and MESSAGE
     *    @return 0 if success -1 otherwise
     */
    int parse(std::string& error, bool clean);

    /**
     *  @param stime time when the VM was started for relative time specs
     *  @return action execution time. Returns -1 on error
     */
    time_t get_time(time_t stime);

    /**
     *  @param stime time when the VM was started for relative time specs
     *  @return true if the action needs to be executed.
     */
    bool is_due(time_t stime);

    /**
     *  Compute the next action, updating the TIME attribute for this action
     *    @return time for next action, if ended or error -1
     */
    time_t next_action();
};

/**
 *  Set of VirtualMachine SCHED_ACTION attributes
 */
class SchedActions : public VirtualMachineAttributeSet
{
public:
    /* ---------------------------------------------------------------------- */
    /* Constructor and Initialization functions                               */
    /* ---------------------------------------------------------------------- */
    /**
     *  Creates the SchedAction set from a Template with SCHED_ACTION=[...]
     *  attributes, id's are auto-assigned for internal use
     *    @param tmpl template with DISK
     */
    SchedActions(Template * tmpl): VirtualMachineAttributeSet(false)
    {
        std::vector<VectorAttribute *> vas;

        tmpl->get("SCHED_ACTION", vas);

        init_attribute_map("ID", vas);
    };

    virtual ~SchedActions(){};

    /**
     *  Parse the ScheduleActions of a template
     *    @param error
     *    @param clean indicates if the user wants to remove DONE and MESSAGE
     *    @return -1 in case of error 0 otherwise
     */
    int parse(std::string& error, bool clean)
    {
        for ( schedaction_iterator action = begin(); action != end(); ++action)
        {
            if ( (*action)->parse(error, clean) == -1 )
            {
                return -1;
            }
        }

        return 0;
    }

    bool empty()
    {
        return a_set.empty();
    }

    /* ---------------------------------------------------------------------- */
    /* ---------------------------------------------------------------------- */

    /* ---------------------------------------------------------------------- */
    /* Raw VectorAttribute helpers                                            */
    /* ---------------------------------------------------------------------- */
    /**
     * Parse a set of scheduled actions and optionally assign them a valid id
     *   @param vas the vector of SCHED_ACTION
     *   @param err string in case of error
     *   @param clean remove DONE and MESSAGE attributes
     *   @param set_id to set ID for each action
     *
     *   @return 0 on success -1 if error
     */
    static int parse(std::vector<VectorAttribute *>& vas, std::string& err,
            bool clean, bool set_id);

    /**
     *  Adds a new SchedAction based on the provided VectorAttribute. The new
     *  attribute is check and parsed
     *    @param va VectorAttribute with the action
     *    @param err with description
     *
     *    @return pointer to new attribute nullptr on error
     */
    static VectorAttribute * new_action(
            const std::vector<const VectorAttribute *>& vas,
            VectorAttribute * va, std::string &err);

    static VectorAttribute * get_action(
            const std::vector<VectorAttribute *>& sched_actions, int id);

    /* ---------------------------------------------------------------------- */
    /* Iterators                                                              */
    /* ---------------------------------------------------------------------- */
    /**
     *  Generic iterator for the SchedActions set.
     */
    class SchedActionIterator : public AttributeIterator
    {
    public:
        SchedActionIterator():AttributeIterator(){};
        SchedActionIterator(const AttributeIterator& i):AttributeIterator(i){};
        virtual ~SchedActionIterator(){};

        SchedAction * operator*() const
        {
            return static_cast<SchedAction *>(map_it->second);
        }
    };

    SchedActionIterator begin()
    {
        SchedActionIterator it(ExtendedAttributeSet::begin());
        return it;
    }

    SchedActionIterator end()
    {
        SchedActionIterator it(ExtendedAttributeSet::end());
        return it;
    }

    typedef class SchedActionIterator schedaction_iterator;

protected:
    VirtualMachineAttribute * attribute_factory(VectorAttribute * va,
        int id) const
    {
        return new SchedAction(va, id);
    };
};

#endif  /*SCHED_ACTION_ATTRIBUTE_H_*/


text:
import os, re, sys
import treebankanalytics.graphs.Graph as G

__all__ = ['add_root_node', 'is_comment', 'create_node', 'create_edge', 'add_id_to_features', 'normalize_features', 'handle_extra_columns']

def add_root_node(graph):
    top_node = G.Node(0, {'token':'_top_', 'lemma':'_top_', 'cpos':'_', 'pos':'_', 'features':'_'})
    graph.add_node(top_node)

def normalize_features(features):
    if isinstance(features, str):
        if features == '_' or features == '':
            return {}
        else:
            d = [item.split('=') for item in features.split('|') if item != "_"]
            return dict(d)
    else:
        return '|'.join(["{0}={1}".format(k, features[k]) for k in features])

def handle_extra_columns(node, columns):
    node['ta_extra_columns'] = columns

def is_comment(line):
    return line.startswith('#')

def create_node(id, token, lemma, cpos, pos, features):
    args = {
        'token': token,
        'lemma': lemma,
        'cpos': cpos,
        'pos': pos,
        'features': normalize_features(features)
    }
    node = G.Node(int(id), args)
    return node

def create_edge(head, label, dep):
    if head == "-1" or head == "":
        return None
    return G.Edge(int(head), int(dep), {'label': label})

def add_id_to_features(id, node):
    if id is None:
        return

    if node.index() == 1:
        node['features']['sentid'] = id

redpajama_set_name: RedPajamaGithub


text:
@interface AppDelegate (XHLaunchAd)

-(void)setupXHLaunchAd;

@end


text:
import {MediaPipeFaceMeshMediaPipeEstimationConfig, MediaPipeFaceMeshMediaPipeModelConfig} from './types';

export const DEFAULT_FACE_MESH_MODEL_CONFIG:
    MediaPipeFaceMeshMediaPipeModelConfig = {
      runtime: 'mediapipe',
      maxFaces: 1,
      refineLandmarks: false
    };

export const DEFAULT_FACE_MESH_ESTIMATION_CONFIG:
    MediaPipeFaceMeshMediaPipeEstimationConfig = {
      flipHorizontal: false,
      staticImageMode: false,
    };


text:
package org.apache.accumulo.core.data;

import static org.junit.Assert.assertEquals;

import java.nio.ByteBuffer;

import org.junit.Before;
import org.junit.Test;

public class ArrayByteSequenceTest {

  ArrayByteSequence abs;
  byte[] data;

  @Before
  public void setUp() {
    data = new byte[] {'s', 'm', 'i', 'l', 'e', 's'};
    abs = new ArrayByteSequence(data);
  }

  @Test(expected = IllegalArgumentException.class)
  public void testInvalidByteBufferBounds0() {
    abs = new ArrayByteSequence(data, -1, 0);
  }

  @Test(expected = IllegalArgumentException.class)
  public void testInvalidByteBufferBounds1() {
    abs = new ArrayByteSequence(data, data.length + 1, 0);
  }

  @Test(expected = IllegalArgumentException.class)
  public void testInvalidByteBufferBounds2() {
    abs = new ArrayByteSequence(data, 0, -1);
  }

  @Test(expected = IllegalArgumentException.class)
  public void testInvalidByteBufferBounds3() {
    abs = new ArrayByteSequence(data, 6, 2);
  }

  @Test(expected = IllegalArgumentException.class)
  public void testInvalidByteAt0() {
    abs.byteAt(-1);
  }

  @Test(expected = IllegalArgumentException.class)
  public void testInvalidByteAt1() {
    abs.byteAt(data.length);
  }

  @Test
  public void testSubSequence() {
    assertEquals(0, abs.subSequence(0, 0).length());
    assertEquals("mile", abs.subSequence(1, 5).toString());
  }

  @Test(expected = IllegalArgumentException.class)
  public void testInvalidSubsequence0() {
    abs.subSequence(5, 1);
  }

  @Test(expected = IllegalArgumentException.class)
  public void testInvalidSubsequence1() {
    abs.subSequence(-1, 1);
  }

  @Test(expected = IllegalArgumentException.class)
  public void testInvalidSubsequence3() {
    abs.subSequence(0, 10);
  }

  @Test
  public void testFromByteBuffer() {
    ByteBuffer bb = ByteBuffer.wrap(data, 1, 4);
    abs = new ArrayByteSequence(bb);

    assertEquals("mile", abs.toString());

    bb = bb.asReadOnlyBuffer();
    abs = new ArrayByteSequence(bb);

    assertEquals("mile", abs.toString());
  }

  @Test
  public void testToString() {
    assertEquals("String conversion should round trip correctly", "",
        new ArrayByteSequence("").toString());
  }

}


text:
<?php defined('BX_DOL') or die('hack attempt');

$aPathInfo = pathinfo(__FILE__);
$aPathInfo['dirname'] = str_replace("\\", "/", $aPathInfo['dirname']); // fix Windows path
define ('BX_UPGRADE_DIR_UPGRADES', $aPathInfo['dirname'] . '/files/');

require_once($aPathInfo['dirname'] . '/classes/BxDolUpgradeController.php');
require_once($aPathInfo['dirname'] . '/classes/BxDolUpgradeUtil.php');
require_once($aPathInfo['dirname'] . '/classes/BxDolUpgradeDb.php');

bx_import('BxDolCron');
bx_import('BxDolLanguages');
bx_import('BxDolEmailTemplates');

class BxDolUpgradeCron extends BxDolCron
{
    public function processing()
    {
        $oController = new BxDolUpgradeController();
        if ($oController->setMaintenanceMode(true)) {

            // if upgrade was successful
            if (($sFolder = $oController->getAvailableUpgrade()) && $oController->runUpgrade($sFolder)) {

                setParam('sys_revision', getParam('sys_revision') + 1);

                // write upgrade log
                $oController->writeLog();

                // send email notification
                bx_import('BxDolLanguages');
                sendMailTemplateSystem('t_UpgradeSuccess', array (
                    'new_version' => bx_get_ver(true),
                    'conclusion' => $oController->getConclusion() ? _t('_sys_upgrade_conclusion', $oController->getConclusion()) : '',
                ));

                // if next upgrade is available (in case of bulk upgrade) then schedule to run it upon next cron run
                $sUpgradeDir = pathinfo(__FILE__, PATHINFO_DIRNAME);
                if ($oController->getAvailableUpgrade()) {

                    $oUpgrader = bx_instance('BxDolUpgrader');
                    $oUpgrader->setTransientUpgradeCronJob($sUpgradeDir);

                } elseif (0 === strpos($sUpgradeDir, BX_DIRECTORY_PATH_TMP)) {

                    @bx_rrmdir($sUpgradeDir);

                }
            }

            $oController->setMaintenanceMode(false);
        }

        // if something went grong during upgrade
        if ($sErrorMsg = $oController->getErrorMsg()) {

            // write upgrade log
            $oController->writeLog();

            // send email notification
            sendMailTemplateSystem('t_UpgradeFailed', array (
                'error_msg' => $sErrorMsg,
            ));

            // disable auto-upgrade if it is failed
            setParam('sys_autoupdate', '');
        }
        else { // run modules update after successful system upgrade

            bx_import('BxDolCronQuery');
            BxDolCronQuery::getInstance()->addTransientJobClass('sys_perform_upgrade_modules', 'BxDolCronUpgradeModulesCheck', 'inc/classes/BxDolCronUpgradeModulesCheck.php');
        }
    }
}

/** @} */


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Brit. basidiomyc. (Cambridge) 273 (1922)

#### Original name
Cantharellus aurantiacus Krombh.

### Remarks
null


text:
package org.apache.jmeter.gui.action;

import java.awt.Component;
import java.awt.event.ActionEvent;
import java.util.HashSet;
import java.util.Set;

import org.apache.jmeter.gui.GuiPackage;
import org.apache.jmeter.gui.tree.JMeterTreeNode;
import org.apache.jmeter.testelement.TestElement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Implements the Add Parent menu command
 */
public class AddParent extends AbstractAction {
    private static final Logger log = LoggerFactory.getLogger(AddParent.class);

    private static final Set<String> commands = new HashSet<>();

    static {
        commands.add(ActionNames.ADD_PARENT);
    }

    public AddParent() {
    }

    @Override
    public void doAction(ActionEvent e) {
        String name = ((Component) e.getSource()).getName();
        GuiPackage guiPackage = GuiPackage.getInstance();
        try {
            guiPackage.updateCurrentNode();
            TestElement controller = guiPackage.createTestElement(name);
            addParentToTree(controller);
        } catch (Exception err) {
            log.error("Exception while adding a TestElement.", err);
        }

    }

    @Override
    public Set<String> getActionNames() {
        return commands;
    }

    protected void addParentToTree(TestElement newParent) {
        GuiPackage guiPackage = GuiPackage.getInstance();
        JMeterTreeNode newNode = new JMeterTreeNode(newParent, guiPackage.getTreeModel());
        JMeterTreeNode currentNode = guiPackage.getTreeListener().getCurrentNode();
        JMeterTreeNode parentNode = (JMeterTreeNode) currentNode.getParent();
        int index = parentNode.getIndex(currentNode);
        guiPackage.getTreeModel().insertNodeInto(newNode, parentNode, index);
        JMeterTreeNode[] nodes = guiPackage.getTreeListener().getSelectedNodes();
        for (JMeterTreeNode node : nodes) {
            moveNode(guiPackage, node, newNode);
        }
    }

    private void moveNode(GuiPackage guiPackage, JMeterTreeNode node, JMeterTreeNode newParentNode) {
        guiPackage.getTreeModel().removeNodeFromParent(node);
        guiPackage.getTreeModel().insertNodeInto(node, newParentNode, newParentNode.getChildCount());
    }
}


text:
import { Util } from './Util';
import { getComponentValidator } from './Validators';

var GET = 'get',
  SET = 'set';

export const Factory = {
  addGetterSetter(constructor, attr, def?, validator?, after?) {
    Factory.addGetter(constructor, attr, def);
    Factory.addSetter(constructor, attr, validator, after);
    Factory.addOverloadedGetterSetter(constructor, attr);
  },
  addGetter(constructor, attr, def?) {
    var method = GET + Util._capitalize(attr);

    constructor.prototype[method] =
      constructor.prototype[method] ||
      function () {
        var val = this.attrs[attr];
        return val === undefined ? def : val;
      };
  },

  addSetter(constructor, attr, validator?, after?) {
    var method = SET + Util._capitalize(attr);

    if (!constructor.prototype[method]) {
      Factory.overWriteSetter(constructor, attr, validator, after);
    }
  },
  overWriteSetter(constructor, attr, validator?, after?) {
    var method = SET + Util._capitalize(attr);
    constructor.prototype[method] = function (val) {
      if (validator && val !== undefined && val !== null) {
        val = validator.call(this, val, attr);
      }

      this._setAttr(attr, val);

      if (after) {
        after.call(this);
      }

      return this;
    };
  },
  addComponentsGetterSetter(constructor, attr, components, validator?, after?) {
    var len = components.length,
      capitalize = Util._capitalize,
      getter = GET + capitalize(attr),
      setter = SET + capitalize(attr),
      n,
      component;

    // getter
    constructor.prototype[getter] = function () {
      var ret = {};

      for (n = 0; n < len; n++) {
        component = components[n];
        ret[component] = this.getAttr(attr + capitalize(component));
      }

      return ret;
    };

    var basicValidator = getComponentValidator(components);

    // setter
    constructor.prototype[setter] = function (val) {
      var oldVal = this.attrs[attr],
        key;

      if (validator) {
        val = validator.call(this, val);
      }

      if (basicValidator) {
        basicValidator.call(this, val, attr);
      }

      for (key in val) {
        if (!val.hasOwnProperty(key)) {
          continue;
        }
        this._setAttr(attr + capitalize(key), val[key]);
      }

      this._fireChangeEvent(attr, oldVal, val);

      if (after) {
        after.call(this);
      }

      return this;
    };

    Factory.addOverloadedGetterSetter(constructor, attr);
  },
  addOverloadedGetterSetter(constructor, attr) {
    var capitalizedAttr = Util._capitalize(attr),
      setter = SET + capitalizedAttr,
      getter = GET + capitalizedAttr;

    constructor.prototype[attr] = function () {
      // setting
      if (arguments.length) {
        this[setter](arguments[0]);
        return this;
      }
      // getting
      return this[getter]();
    };
  },
  addDeprecatedGetterSetter(constructor, attr, def, validator) {
    Util.error('Adding deprecated ' + attr);

    var method = GET + Util._capitalize(attr);

    var message =
      attr +
      ' property is deprecated and will be removed soon. Look at Konva change log for more information.';
    constructor.prototype[method] = function () {
      Util.error(message);
      var val = this.attrs[attr];
      return val === undefined ? def : val;
    };
    Factory.addSetter(constructor, attr, validator, function () {
      Util.error(message);
    });
    Factory.addOverloadedGetterSetter(constructor, attr);
  },
  backCompat(constructor, methods) {
    Util.each(methods, function (oldMethodName, newMethodName) {
      var method = constructor.prototype[newMethodName];
      var oldGetter = GET + Util._capitalize(oldMethodName);
      var oldSetter = SET + Util._capitalize(oldMethodName);

      function deprecated() {
        method.apply(this, arguments);
        Util.error(
          '"' +
            oldMethodName +
            '" method is deprecated and will be removed soon. Use ""' +
            newMethodName +
            '" instead.'
        );
      }

      constructor.prototype[oldMethodName] = deprecated;
      constructor.prototype[oldGetter] = deprecated;
      constructor.prototype[oldSetter] = deprecated;
    });
  },
  afterSetFilter() {
    this._filterUpToDate = false;
  },
};


text:
import logging
import logging.handlers
import os
from config import config_properties

dirname = os.path.dirname(__file__)

LOG_FILENAME = filename = os.path.join(dirname, '../log/wso2carbon.log')
logger = logging.getLogger()
LOG_LEVEL = config_properties['log_level']

if LOG_LEVEL == "INFO":
    log_level = logging.INFO
elif LOG_LEVEL == "DEBUG":
    log_level = logging.DEBUG

def set_logger():
    logger.setLevel(log_level)
    formatter = logging.Formatter('%(asctime)s %(levelname)s: %(message)s')

    console_handler = logging.StreamHandler()
    console_handler.setFormatter(formatter)
    logger.addHandler(console_handler)

    file_handler = logging.handlers.TimedRotatingFileHandler(LOG_FILENAME, when='midnight', backupCount=30)
    #Uncomment the below file_handler for a size based Rotating File handler.
    #file_handler = logging.handlers.RotatingFileHandler(LOG_FILENAME,maxBytes=10485760,backupCount=10,encoding="utf-8")

    file_handler.setFormatter(formatter)
    logger.addHandler(file_handler)

set_logger()


text:
import { NgModule } from '@angular/core';

import { SharedModule } from '../shared/shared.module';
import { ProductsComponent } from './products.component';
import { ProductComponent } from './product/product.component';
import { ProductsRoutingModule } from './products-routing.module';

@NgModule({
  imports: [
    SharedModule,
    ProductsRoutingModule
  ],
  declarations: [
    ProductsComponent,
    ProductComponent
  ]
})
export class ProductsModule {

}


text:
<nz-card
  [nzBordered]="false"
  [nzTitle]="'Uploaded Jars'"
  [nzLoading]="isLoading"
  [nzExtra]="extraTemplate"
>
  <ng-container *ngIf="!isYarn">
    <nz-table
      [nzSize]="'small'"
      [nzData]="listOfJar"
      [nzFrontPagination]="false"
      [nzShowPagination]="false"
      [nzBordered]="false"
    >

          Name
          Upload Time
          Entry Class

        <ng-container *ngFor="let jar of listOfJar; trackBy: trackJarBy">

            {{ jar.name }}
            {{ jar.uploaded | date: 'yyyy-MM-dd, HH:mm:ss' }}

                {{ entries.name }}

                -

                Delete

              <form nz-form [nzLayout]="'inline'" [formGroup]="validateForm">
                <nz-form-item>
                  <nz-form-control>
                    <nz-input-group [nzPrefix]="apiTemplate">
                      <input formControlName="entryClass" nz-input placeholder="Entry Class" />
                    </nz-input-group>
                    <ng-template #apiTemplate>

                    </ng-template>
                  </nz-form-control>
                </nz-form-item>
                <nz-form-item>
                  <nz-form-control>
                    <nz-input-group [nzPrefix]="loginTemplate">
                      <input formControlName="parallelism" nz-input placeholder="Parallelism" />
                    </nz-input-group>
                    <ng-template #loginTemplate></ng-template>
                  </nz-form-control>
                </nz-form-item>
                <nz-form-item>
                  <nz-form-control>
                    <nz-input-group [nzPrefix]="settingTemplate">
                      <input
                        formControlName="programArgs"
                        nz-input
                        placeholder="Program Arguments"
                      />
                    </nz-input-group>
                    <ng-template #settingTemplate></ng-template>
                  </nz-form-control>
                </nz-form-item>
                <nz-form-item>
                  <nz-form-control>
                    <nz-input-group [nzPrefix]="folderTemplate">
                      <input
                        formControlName="savepointPath"
                        nz-input
                        placeholder="Savepoint Path"
                      />
                    </nz-input-group>
                    <ng-template #folderTemplate></ng-template>
                  </nz-form-control>
                </nz-form-item>
                <nz-form-item>
                  <nz-form-control>

                      Allow Non Restored State

                  </nz-form-control>
                </nz-form-item>
                <nz-form-item>
                  <nz-form-control>
                    <button nz-button (click)="showPlan(jar)">Show Plan</button>
                    <button nz-button nzType="primary" (click)="submitJob(jar)">Submit</button>
                  </nz-form-control>
                </nz-form-item>
              </form>

        </ng-container>

    </nz-table>
  </ng-container>
  <ng-container *ngIf="!noAccess && isYarn">

      Yarn's AM proxy doesn't allow file uploads. Please wait while we fetch an alternate url for
      you to use

      Yarn's AM proxy doesn't allow file uploads. You can visit
      here
       to access this functionality.

  </ng-container>
</nz-card>
<ng-template #extraTemplate>

    <ng-container *ngIf="!isUploading">
      <input
        flinkFileRead
        type="file"
        class="input-file"
        id="upload-file"
        (fileRead)="uploadJar($event)"
      />

          Add New

    </ng-container>
    <nz-progress
      *ngIf="isUploading"
      [nzPercent]="progress"
      nzSize="small"
      [nzShowInfo]="false"
    ></nz-progress>

</ng-template>
<nz-drawer
  [nzHeight]="'100%'"
  [nzVisible]="planVisible"
  [nzPlacement]="'bottom'"
  [nzTitle]="'Plan Visualization'"
  (nzOnClose)="hidePlan()"
>
  <ng-container *nzDrawerContent>
    <flink-dagre></flink-dagre>
  </ng-container>
</nz-drawer>


text:
> Record, mock, and proxy HTTP traffic as middleware for the connect middleware framework.

## Getting Started

This middleware can be installed a la npm with the following command.

```shell
npm install connect-prism --save-dev
```

## Overview

Prism is similar to the Ruby project [VCR](https://github.com/elcuervo/vcr.js).

The purpose of this middleware is to provide an easy way for front end developers to record HTTP responses returned by their API (or some other remote source) and then be able replay the responses in the future.  It's basically an HTTP cache, but for developers working on a Single Page Application (SPA).

It's useful for mocking complex & high latency API calls during development.  It's also useful when writing e2e tests for your SPA only, removing the server from the equation.  This results in much faster execution of your e2e test suite.

Prism works by adding a custom connect middleware to a the [connect](https://www.npmjs.org/package/connect) middleware server.

### Modes

There are currently 4 supported modes of operation.

#### Record

The record mode will allow you to both record and proxy all HTTP traffic for a certain endpoint on your connect development server.  For example, if in production your API sits at an endpoint `/api` then you may be currently proxying requests to a server you're hosting locally on another port or to an integration machine somewhere else.  You may have also attempted to mock out services that make HTTP calls in your client side code itself.  While in record mode you can navigate your application and trigger all the types of API calls you would like to have recorded.  Prism will then listen for responses and serialize them to disk.  When you want to read these responses instead of proxying traffic to the real server you shutdown and switch to the 'mock' mode.

To make mocks more readable, responses with a content-type of `json` or `javascript` will have their data stringified as an object.  If the content-type is anything other than json or if stringification fails then it falls back to a string.

If the server returns a compressed response (gzip or deflate are supported), then prism will decompress the payload when recording the response.

Example mock generated:

```javascript
  {
    "requestUrl": "/api/ponies",
    "contentType": "application/json",
    "statusCode": 200,
    "data": {
      "text": "my little ponies"
    }
  }
```

#### Mock

The mock (read) mode will listen for requests to a certain endpoint.  When a request matches an endpoint it will attempt to find a previously recorded response in the directory you defined mocks to be saved in (./mocks by default).

If a matching response is not found then prism will return a 404.  Prism will also create a mock during a 404.  This is useful when you want to mock API endpoints that may not exist yet.  To avoid having the subsequent request from returning the generated empty mock, the file has a .404 extension.  To use the mock, populate it with the appropriate values and remove the .404 extension.  This feature was contributed by [Miloš Mošovský](https://github.com/MilosMosovsky).

#### Mock & Record

As its name implies this operation will mock and record.  This mode will first attempt to load a mock if one exists.  If a mock does not exist it will then proxy the request and record the response instead of returning a 404.

#### Proxy

And finally, prism supports simple proxying in much the same way as the [grunt-connect-proxy](https://github.com/drewzboto/grunt-connect-proxy) plugin works.  In fact, this plugin is heavily inspired by that project.  While in proxy mode, listening events for recording and mocking are disabled.

### Adding the middleware to connect

Simple add the middleware to your connect instance as in the example.  You can configure prism before or after the middleware is added.

```js
  var connect = require('connect');
  var prism = require('connect-prism');

  prism.create({
    name: 'api',
    context: '/api'
    host: 'localhost'
  });

  var app = connect()
    .use(prism.middleware)
    .use(connect.static('public'))
    .use(function(req, res){
      res.end('hello world\n');
    })

  http.createServer(app).listen(3000);
```

### Using connect-prism with Grunt.js

If you're using grunt then head on over to the [grunt-connect-prism](http://github.com/seglo/grunt-connect-prism) page for more details.

### Using connect-prism with gulp

If you're using gulp then you would just use the core library along with gulp.  For a sample configuration see the [gulpfile.js](https://github.com/seglo/prism-sample-project/blob/master/gulpfile.js) in the [prism-sample-project](https://github.com/seglo/prism-sample-project).

## Configuration

### Setting up prism

To initialize a prism instance call prism.create.  You can call prism.create more than once to run multiple configurations.

```js
  var prism = require('connect-prism');

  prism.create({
    name: 'api',
    mode: 'record',
    context: '/api'
    host: 'localhost',
    port: 8090,
    changeOrigin: true
  });
```

### Options

#### mode

Type: `String`

Default: `'proxy'`

Values: `'record'` | `'mock'` | `'proxy'` | `'mockrecord'`

By setting a mode you create an explicit declaration that the context you're proxying will always be in the configured mode.  You can optionally override the mode of all the proxies for a target by passing in a 3rd parameter to the prism grunt task prism:[target]:[mode]

i.e. `grunt prism:server:mock`

#### mocksPath

Type: `String`

Default: `'./mocks'`

Path to the root directory you want to record and mock responses.  If the directory does not exist then prism will attempt to create it.  If prism is executed with a target then recorded and mocked responses will be read from `'./mocks/targetName'`.  If no target is defined then only the default prism options will be used.

#### context

Type: `String`

Default: n/a

The starting context of your API that you are proxying.  This should be from the root of your webserver.  All requests that start with this context string will be used.

#### host

Type: `String`

Default: n/a

The server name or IP of the API that you are proxying.

#### port

Type: `Integer`

Default: n/a

The port number of the API that you are proxying.

#### https

Type: `Boolean`

Default: false

The http scheme of the API you are proxying.  `true` === `https`, `false` === `http`

#### changeOrigin

Type: `Boolean`

Default: false

Whether to change the origin on the request to the proxy, or keep the original origin.

#### delay

Type: `String` or `Integer`

Default: 0

Values: A number in milliseconds | `'auto'` | `'fast'` | `'slow'`

Delay will work with all modes.

This option allows you to simulate a delay when returning a mock response to the user.  Sometimes it's handy to simulate a delay because this will give you a better impression of how the user experience of your app will be when fully integrated with a backend server.

You can configure an exact delay in milliseconds or one of the precreated options which returns a random delay in a certain range.

* auto: 500 to 1750 ms
* fast: 150 to 1000 ms
* slow: 1500 to 3000 ms

Thanks again to [Miloš Mošovský](https://github.com/MilosMosovsky) for this feature.

#### rewrite

Type: `Object`

Default: `{}`

Add rewrite rules that prism will apply to all requests.  This functionality was copied from [grunt-connect-proxy and works the exact same way](https://github.com/drewzboto/grunt-connect-proxy#optionsrewrite).  You can configure a list of rewrite rules with an object.

```js
  {
    '^/removingcontext': '',
    '^/changingcontext': '/anothercontext'
  }
```

## TODO Wishlist
* mockrecord mode which will mock responses and attempt to record responses that don't exist yet.

## Release History
* 0.1.0 Initial release.
* 0.1.1 Stop recording all response headers.  Only capture content-type.
* 0.2.0 Support 'cassettes' by putting mocks into directories named after target.  Use http-proxy 0.10.4 to workaround around socket hangup issues in 1.1.4.
* 0.2.1 Fixed record mode and tests so we don't release broken again!
* 0.2.2 Support change origin.
* 0.3.0 Forked from grunt-connect-prism to core library.  Added delay and mock/404 feature from [Miloš Mošovský](https://github.com/MilosMosovsky).
* 0.4.0 Added rewrite functionality.  'mockrecord' mode.  More non-verbose logging for mock and recording operations.
* 0.4.1 Fix for delay auto > 0 bug and support delay in proxy mode by [generalov](https://github.com/generalov).  Fix for invalid SSL cert bug by [Josh Miller](https://github.com/velveteer).  Thanks much <3.  Made non-verbose logging more consistent.  Fixed broken verbose logging.
* 0.4.2 Fix for recording response from a rewrite rule outside of the context of a prism configuration from [Mike Kibbel](https://github.com/skibblenybbles).
* 0.5.0 Decompress responses when recording responses.


text:
<?php
/** @var Simples\Template\View $this */

$this->extend('_layout/basic/html.php', 'body');
?>

    <img src="<?php $this->image('logo.png'); ?>" class="logo" alt="building">

      simples

      Documentation
      phpZM
      GitHub


text:
module ActiveNullObject
  module Association
    extend ActiveSupport::Concern

    included do
      class << self
        alias_method_chain :belongs_to, :null_object
      end
    end

    module ClassMethods
      def belongs_to_with_null_object(relation_name, scope = nil, options = {})
        options = scope if scope.is_a?(Hash)
        null_object_name = options.delete(:null_object)
        belongs_to_without_null_object(relation_name, scope, options)
        if null_object_name
          define_null_object_getter(relation_name, null_object_name)
        end
      end

      def define_null_object_getter(relation_name, custom_name)
        create_null_object = CreateNullObject.new(relation_name, custom_name)
        define_method(relation_name) do
          super() || create_null_object.call
        end
      end
    end
  end
end


text:
package alluxio.conf;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Nullable;

/**
 * This class contains old {@link PropertyKey}s which have been removed from use
 *
 * This class is used to track keys which were deprecated in previous versions and subsequently
 * removed in a future version. We still keep them here so that it is possible to provide users with
 * useful information if they are found to be using an outdated property key.
 *
 * Being removed and still used by an application denotes an error.
 *
 * @see InstancedConfiguration#validate()
 * @see PropertyKey#fromString(String)
 */
public final class RemovedKey {

  private static final String V2_0_0 = "v2.0.0";
  private static final String V2_1_0 = "v2.1.0";
  private static final String V2_4_0 = "v2.4.0";

  /**
   * @param version the version since which a property has been removed
   *
   * @return a warning message indicating a property has been removed since a given version
   */
  private static String removedSince(String version) {
    return String.format("this property has been removed since %s.", version);
  }

  /**
   * @param version the version since which a property has been removed
   * @param newProperty the new property to use instead
   * @return a warning message indicating a property has been removed since a given version
   */
  private static String replacedSince(String version, String newProperty) {
    return String.format("this property has been removed since %s, use %s instead.", version,
        newProperty);
  }

  private static final Map<String, String> REMOVED_KEYS = new HashMap<String, String>(20) {
    {
      put("alluxio.keyvalue.enabled", removedSince(V2_0_0));
      put("alluxio.keyvalue.partition.size.bytes.max", removedSince(V2_0_0));
      put("alluxio.master.client.socket.cleanup.interval", removedSince(V2_0_0));
      put("alluxio.master.connection.timeout", removedSince(V2_0_0));
      put("alluxio.master.file.async.persist.handler", removedSince(V2_0_0));
      put("alluxio.master.heartbeat.interval",
          replacedSince(V2_0_0, PropertyKey.MASTER_LOST_WORKER_FILE_DETECTION_INTERVAL.getName()));
      put("alluxio.master.journal.formatter.class",
          "v2.0 removed the ability to specify the master journal formatter");
      put("alluxio.master.lineage.checkpoint.class", removedSince(V2_0_0));
      put("alluxio.master.lineage.checkpoint.interval", removedSince(V2_0_0));
      put("alluxio.master.lineage.recompute.interval", removedSince(V2_0_0));
      put("alluxio.master.lineage.recompute.log.path", removedSince(V2_0_0));
      put("alluxio.master.master.heartbeat.interval", replacedSince(V2_0_0,
          PropertyKey.MASTER_STANDBY_HEARTBEAT_INTERVAL.getName()));
      put("alluxio.master.startup.consistency.check.enabled", removedSince(V2_0_0));
      put("alluxio.master.thrift.shutdown.timeout", removedSince(V2_0_0));
      put("alluxio.master.retry", removedSince(V2_0_0));
      put("alluxio.master.worker.threads.max", removedSince(V2_0_0));
      put("alluxio.master.worker.threads.min", removedSince(V2_0_0));
      put("alluxio.network.netty.heartbeat.timeout", removedSince(V2_0_0));
      put("alluxio.network.thrift.frame.size.bytes.max", removedSince(V2_0_0));
      put("alluxio.underfs.object.store.read.retry.base.sleep", removedSince(V2_0_0));
      put("alluxio.underfs.object.store.read.retry.max.num", removedSince(V2_0_0));
      put("alluxio.underfs.object.store.read.retry.max.sleep", removedSince(V2_0_0));
      put("alluxio.underfs.s3a.consistency.timeout", removedSince(V2_0_0));
      put("alluxio.security.authentication.socket.timeout", removedSince(V2_0_0));
      put("alluxio.security.authentication.socket.timeout.ms", removedSince(V2_0_0));
      put("alluxio.user.block.remote.reader.class", removedSince(V2_0_0));
      put("alluxio.user.block.remote.writer.class", removedSince(V2_0_0));
      put("alluxio.user.block.worker.client.pool.size.max", removedSince(V2_0_0));
      put("alluxio.user.block.worker.client.threads", removedSince(V2_0_0));
      put("alluxio.user.failed.space.request.limits", removedSince(V2_0_0));
      put("alluxio.user.file.cache.partially.read.block", removedSince(V2_0_0));
      put("alluxio.user.file.copyfromlocal.write.location.policy.class", replacedSince(V2_0_0,
          PropertyKey.USER_FILE_COPYFROMLOCAL_BLOCK_LOCATION_POLICY.getName()));
      put("alluxio.user.file.seek.buffer.size.bytes", removedSince(V2_0_0));
      put("alluxio.user.file.write.avoid.eviction.policy.reserved.size.bytes",
          replacedSince(V2_0_0,
              PropertyKey.USER_BLOCK_AVOID_EVICTION_POLICY_RESERVED_BYTES.getName()));
      put("alluxio.user.file.write.location.policy.class",
          replacedSince(V2_0_0, PropertyKey.USER_BLOCK_WRITE_LOCATION_POLICY.getName()));
      put("alluxio.user.heartbeat.interval", removedSince(V2_0_0));
      put("alluxio.user.hostname",
          replacedSince(V2_0_0, PropertyKey.LOCALITY_TIER_NODE.getName()));
      put("alluxio.user.lineage.enabled", removedSince(V2_0_0));
      put("alluxio.user.lineage.master.client.threads", removedSince(V2_0_0));
      put("alluxio.user.local.reader.packet.size.bytes", removedSince(V2_0_0));
      put("alluxio.user.local.writer.packet.size.bytes", removedSince(V2_0_0));
      put("alluxio.user.network.netty.channel.pool.disabled", removedSince(V2_0_0));
      put("alluxio.user.network.netty.channel.pool.gc.threshold", removedSince(V2_0_0));
      put("alluxio.user.network.netty.channel.pool.size.max", removedSince(V2_0_0));
      put("alluxio.user.network.netty.channel.pool.size.min", removedSince(V2_0_0));
      put("alluxio.user.network.netty.reader.buffer.size.packets", removedSince(V2_0_0));
      put("alluxio.user.network.netty.reader.packet.size.bytes", removedSince(V2_0_0));
      put("alluxio.user.network.netty.writer.buffer.size.packets", removedSince(V2_0_0));
      put("alluxio.user.network.netty.writer.close.timeout", removedSince(V2_0_0));
      put("alluxio.user.network.netty.writer.packet.size.bytes", removedSince(V2_0_0));
      put("alluxio.user.network.socket.timeout", removedSince(V2_0_0));
      put("alluxio.user.rpc.retry.max.num.retry", removedSince(V2_0_0));
      put("alluxio.user.ufs.delegation.read.buffer.size.bytes", removedSince(V2_0_0));
      put("alluxio.user.ufs.delegation.write.buffer.size.bytes", removedSince(V2_0_0));
      put("alluxio.user.ufs.file.reader.class", removedSince(V2_0_0));
      put("alluxio.user.ufs.file.writer.class", removedSince(V2_0_0));
      put("alluxio.web.temp.path", removedSince(V2_0_0));
      put("alluxio.worker.block.threads.max", removedSince(V2_0_0));
      put("alluxio.worker.block.threads.min", removedSince(V2_0_0));
      put("alluxio.worker.data.bind.host", removedSince(V2_0_0));
      put("alluxio.worker.data.hostname", removedSince(V2_0_0));
      put("alluxio.worker.data.port", replacedSince(V2_0_0, PropertyKey.WORKER_RPC_PORT.getName()));
      put("alluxio.worker.filesystem.heartbeat.interval", removedSince(V2_1_0));
      put("alluxio.worker.file.persist.pool.size", removedSince(V2_1_0));
      put("alluxio.worker.file.persist.rate.limit", removedSince(V2_1_0));
      put("alluxio.worker.file.persist.rate.limit.enabled", removedSince(V2_1_0));
      put("alluxio.worker.memory.size", replacedSince(V2_4_0,
          PropertyKey.Name.WORKER_RAMDISK_SIZE));
      put("alluxio.worker.network.netty.async.cache.manager.threads.max", removedSince(V2_0_0));
      put("alluxio.worker.network.netty.backlog", removedSince(V2_0_0));
      put("alluxio.worker.network.netty.block.reader.threads.max", removedSince(V2_0_0));
      put("alluxio.worker.network.netty.block.writer.threads.max", removedSince(V2_0_0));
      put("alluxio.worker.network.netty.buffer.receive", removedSince(V2_0_0));
      put("alluxio.worker.network.netty.buffer.send", removedSince(V2_0_0));
      put("alluxio.worker.network.netty.file.transfer", removedSince(V2_0_0));
      put("alluxio.worker.network.netty.file.writer.threads.max", removedSince(V2_0_0));
      put("alluxio.worker.network.netty.reader.buffer.size.packets", removedSince(V2_0_0));
      put("alluxio.worker.network.netty.rpc.threads.max", removedSince(V2_0_0));
      put("alluxio.worker.network.netty.shutdown.timeout", removedSince(V2_0_0));
      put("alluxio.worker.network.netty.writer.buffer.size.packets", removedSince(V2_0_0));
      put("alluxio.worker.tieredstore.reserver.enabled", removedSince(V2_0_0));
      put("alluxio.worker.tieredstore.retry", removedSince(V2_0_0));
      put("fs.swift.apikey", replacedSince(V2_0_0, PropertyKey.Name.SWIFT_PASSWORD_KEY));
      put("fs.swift.use.public.url", removedSince(V2_0_0));
      put(Template.WORKER_TIERED_STORE_LEVEL_RESERVED_RATIO.format(0),
          replacedSince(V2_0_0, "alluxio.worker.tieredstore.level0.watermark.{high/low}.ratio"));
      put(Template.WORKER_TIERED_STORE_LEVEL_RESERVED_RATIO.format(1),
          replacedSince(V2_0_0, "alluxio.worker.tieredstore.level1.watermark.{high/low}.ratio"));
      put(Template.WORKER_TIERED_STORE_LEVEL_RESERVED_RATIO.format(2),
          replacedSince(V2_0_0, "alluxio.worker.tieredstore.level2.watermark.{high/low}.ratio"));

      put(Name.TEST_REMOVED_KEY, "This key is used only for testing. It is always removed");
    }
  };

  static final class Name {
    public static final String TEST_REMOVED_KEY = "alluxio.test.removed.key";
  }

  static final class Template {

    private static final List<Template> TEMPLATES = new ArrayList<>();

    public static final Template WORKER_TIERED_STORE_LEVEL_RESERVED_RATIO = new Template(
        "alluxio.worker.tieredstore.level%d.reserved.ratio",
        "alluxio\\.worker\\.tieredstore\\.level(\\d+)\\.reserved\\.ratio",
        "The keys associated with this template have been removed");

    private final String mFormat;
    private final Pattern mPattern;
    private final String mMessage;

    private Template(String format, String re, String removalMessage) {
      mFormat = format;
      mPattern = Pattern.compile(re);
      mMessage = removalMessage;
      TEMPLATES.add(this);
    }

    private String format(Object... o) {
      return String.format(mFormat, o);
    }

    private boolean matches(String input) {
      Matcher matcher = mPattern.matcher(input);
      return matcher.matches();
    }
  }

  /**
   * returns whether or not the given property key exists in the removed key list.
   *
   * @param key the property key to check
   * @return whether or not the key has been removed
   */
  static boolean isRemoved(String key) {
    return getMessage(key) != null;
  }

  /**
   * gets the message pertaining to a removed key or template.
   *
   * @param key the property key to check
   * @return whether or not the key has been removed
   */
  @Nullable
  public static String getMessage(String key) {
    String msg;
    if ((msg = REMOVED_KEYS.getOrDefault(key, null)) != null) {
      return msg;
    }

    for (Template t : Template.TEMPLATES) {
      if (t.matches(key)) {
        return t.mMessage;
      }
    }
    return null;
  }

  private RemovedKey() {} // prevent instantiation of this class
}


text:
'use strict';

console.log('LOGGING HELLO!');


text:
FROM ruby:2.3-alpine

MAINTAINER Adrian Moreno <adrian.moreno@emc.com>

COPY . /usr/src/app

WORKDIR /usr/src/app

RUN apk --update add git
RUN apk --update add --virtual build_deps \
 build-base ruby-dev libc-dev linux-headers openssl-dev &&\
 bundle &&\
 gem install uploader &&\
 apk del build_deps

ENTRYPOINT [ "uploader" ]


text:
namespace chatterino {

class TwitchIrcServer;
class Channel;

class IrcMessageHandler
{
    IrcMessageHandler() = default;

public:
    static IrcMessageHandler &instance();

    // parseMessage parses a single IRC message into 0+ Chatterino messages
    std::vector<MessagePtr> parseMessage(Channel *channel,
                                         Communi::IrcMessage *message);

    // parsePrivMessage arses a single IRC PRIVMSG into 0-1 Chatterino messages
    std::vector<MessagePtr> parsePrivMessage(
        Channel *channel, Communi::IrcPrivateMessage *message);
    void handlePrivMessage(Communi::IrcPrivateMessage *message,
                           TwitchIrcServer &server);

    void handleRoomStateMessage(Communi::IrcMessage *message);
    void handleClearChatMessage(Communi::IrcMessage *message);
    void handleClearMessageMessage(Communi::IrcMessage *message);
    void handleUserStateMessage(Communi::IrcMessage *message);
    void handleWhisperMessage(Communi::IrcMessage *message);

    // parseUserNoticeMessage parses a single IRC USERNOTICE message into 0+
    // chatterino messages
    std::vector<MessagePtr> parseUserNoticeMessage(
        Channel *channel, Communi::IrcMessage *message);
    void handleUserNoticeMessage(Communi::IrcMessage *message,
                                 TwitchIrcServer &server);

    void handleModeMessage(Communi::IrcMessage *message);

    // parseNoticeMessage parses a single IRC NOTICE message into 0+ chatterino
    // messages
    std::vector<MessagePtr> parseNoticeMessage(
        Communi::IrcNoticeMessage *message);
    void handleNoticeMessage(Communi::IrcNoticeMessage *message);

    void handleJoinMessage(Communi::IrcMessage *message);
    void handlePartMessage(Communi::IrcMessage *message);

    static float similarity(MessagePtr msg,
                            const LimitedQueueSnapshot<MessagePtr> &messages);
    static void setSimilarityFlags(MessagePtr message, ChannelPtr channel);

private:
    void addMessage(Communi::IrcMessage *message, const QString &target,
                    const QString &content, TwitchIrcServer &server,
                    bool isResub, bool isAction);
};

}  // namespace chatterino


text:
//
//  ContentLoader.cpp
//  ARMagicMirrorARTP
//
//  Author: Markus Konrad, Philipp Jährling
//  Copyright (c) 2013 INKA Research Group. All rights reserved.
//

#include <sstream>

#include "ContentLoader.h"
#include "ImgData.h"
#include "VidData.h"
#include "ObjData.h"
#include "Tools.h"

#pragma mark singleton stuff
//--------------------------------------------------------------
ContentLoader* ContentLoader::instance = NULL;

ContentLoader* ContentLoader::getInstance() {
    if (!instance) instance = new ContentLoader();
    return instance;
}

void ContentLoader::destroy() {
    if (instance) {
        instance->dealloc();
        delete instance;
        instance = NULL;
    }
}

#pragma mark public methods
//--------------------------------------------------------------
ContentElement* ContentLoader::getContentById(const int id) {
    ContentMap::iterator it = contents.find(id);
    if ( it == contents.end() ) {
        return NULL;
    } else {
        return it->second;
    }
}

//--------------------------------------------------------------
ContentMap ContentLoader::getAllContents() {
    return contents;
}

//--------------------------------------------------------------
void ContentLoader::loadContents(string path) throw (runtime_error) {
    // add a "/" at the end if necessary
    if (path.at(path.length() - 1) != '/') {
        path.append("/");
    }

    ofXml confXml;
    if ( confXml.load(path + "config.xml") ) {
        confXml.setTo("contents"); // root element

        int elementCount = confXml.getNumChildren();
        cout << "INFO: Try to load " << elementCount << " content elements from " << path << endl;

        // go through all child elements
        for (int i = 0; i < elementCount; i++) {
            confXml.setToChild(i); // set to child node

            // get and check the mandatory fields
            int markerId        = confXml.getIntValue("markerId");
            ContentType type    = getType( confXml.getValue("type") );

            if ( (markerId > 0) && (type != _UNKNOWN) && (confXml.exists("files")) ) {
                // create new element
                ContentElement *contentElem = new ContentElement(markerId, confXml.getValue("name"), type);
                // fill type data
                fillTypeDate(&confXml, contentElem, path);
                // configure element
                configureContentElem(&confXml, contentElem, path);
                // insert the new element
                contents.insert(pair<int, ContentElement *>(markerId, contentElem));
            }

            // set back to root node
            confXml.setToParent();
        }

        confXml.clear();

    } else {
        string err("Error accessing path: ");
        err.append(path);
        throw runtime_error(err);
    }

}

#pragma mark private methods
//--------------------------------------------------------------
void ContentLoader::dealloc() {
    contents.empty();
}

//--------------------------------------------------------------
ContentType ContentLoader::getType(string s) {
    if (s.compare("img") == 0) {
        return IMG;
    } else if (s.compare("vid") == 0) {
        return VID;
    } else if (s.compare("obj") == 0) {
        return OBJ;
    }
    return _UNKNOWN;
}

//--------------------------------------------------------------
void ContentLoader::fillTypeDate(ofXml* confXml, ContentElement* elem, string path) {

    confXml->setTo("files");
    int numFiles = confXml->getNumChildren();

    for (int i = 0; i < numFiles; i++) {
        // set file and path names
        std::ostringstream xmlFilePath;
        xmlFilePath << "file[" << i << "]";

        string file = confXml->getValue(xmlFilePath.str());
        string fullPath = path + file;

        // Handle different content types
        if (elem->type == IMG) {            // ********* IMAGE *********

            ofPixels pxls;
            bool imgLoaded = ofLoadImage(pxls, fullPath);

            if (imgLoaded) {
                bool alpha = ( pxls.getNumChannels() == 4 ) ? true : false;
                elem->typeData = new ImgData( pxls, pxls.getWidth(), pxls.getHeight(), alpha );
                cout << "INFO: loaded image " << fullPath << endl;
            }
            break;  // no more files needed

        } else if (elem->type == VID) {     // ********* VIDEO *********

            ofVideoPlayer* vidPlayer = new ofVideoPlayer;
            if ( !vidPlayer->loadMovie(fullPath) ) {
                cerr << "ERROR: could not load video data from file: " << fullPath << endl;
                delete vidPlayer;
                continue; // try the next element or break if there is none left
            }

            confXml->setToParent();
            bool alpha = confXml->getBoolValue("alpha");
            float vol = 1.0f;
            if (confXml->exists("vol")) {
                vol  = confXml->getFloatValue("vol");
            }
            confXml->setTo("files");
            // create and assign the video objekt
            elem->typeData = new VidData(vidPlayer, alpha, vol);

            cout << "INFO: loaded video " << fullPath << " (is alpha: " << alpha << ")" << endl;
            break;  // no more files needed

        } else if (elem->type == OBJ) {     // ********* 3D Object *********

            string fileExt = file.substr(file.find_last_of('.') + 1);

            // create a new empty data object if this is the first file
            if (!elem->typeData) {
                elem->typeData = new ObjData();
            }

            ObjData* obj = (ObjData*)elem->typeData;

            // fill OBJData with obj-model and png-texture
            if ( fileExt.compare("obj") == 0 && !obj->modelId ) {   // found the obj model file
                obj->modelId = Tools::createModelFromObj(fullPath);
                cout << "loaded obj " << fullPath << endl;

            } else if ( (fileExt.compare("png") == 0 || fileExt.compare("jpg") == 0) && !obj->texId) {   // found the texture
                obj->texId = Tools::createTexture(fullPath);
                cout << "loaded obj texture " << fullPath << endl;
            }

        }
    }
    confXml->setToParent();
}

//--------------------------------------------------------------
void ContentLoader::configureContentElem(ofXml* confXml, ContentElement* elem, string path) {

    // add explanation
    if (confXml->exists("explanation") && confXml->exists("explanation/file")) {
        ofPixels pxls;
        string file     = confXml->getValue("explanation/file");
        string fullPath = path + file;
        bool imgLoaded  = ofLoadImage(pxls, fullPath);

        if (imgLoaded) {
            bool alpha = ( pxls.getNumChannels() == 4 ) ? true : false;

            float scale = 1;
            if (confXml->exists("explanation/scaling")) {
                scale = confXml->getFloatValue("explanation/scaling");
            }

            elem->setExplanation(
                new ImgData( pxls, pxls.getWidth(), pxls.getHeight(), alpha),
                scale,
                confXml->getFloatValue("explanation/posTranslation/x"),
                confXml->getFloatValue("explanation/posTranslation/y"),
                confXml->getFloatValue("explanation/posTranslation/z")
            );
        }
    }

    // set content init scaling
    float scale = confXml->getFloatValue("scaling");
    if (scale > 0) {
        elem->setElemScaling(scale);
    }

    // set content init rotation
    if (confXml->exists("rotation")) {
        int rotX = confXml->getIntValue("rotation/x");
        int rotY = confXml->getIntValue("rotation/y");
        int rotZ = confXml->getIntValue("rotation/z");
        elem->setElemRotation(rotX, rotY, rotZ);
    }

    // set content init position translation
    /* IMPORTANT ... this has to be set last.
     * To center the content according to height and width,
     * typeData needs to be filled and the scaling has to be set
     */
    if (confXml->exists("posTranslation")) {
        float transX = confXml->getFloatValue("posTranslation/x");
        float transY = confXml->getFloatValue("posTranslation/y");
        float transZ = confXml->getFloatValue("posTranslation/z");
        elem->setElemTranslation(transX, transY, transZ);
    } else {
        elem->setElemTranslation();
    }
}


text:
/**
 * Problems in docker setup.
 * Removed from dev-deps, install locally
 *
 * npm install -g npm-license-crawler
 */
const crawler = require('npm-license-crawler');
const fs = require('fs');

/**
 * Describes the options for dumping the licenses.
 */
const options = {
    start: ['.'],
    json: 'licenses.json',
    onlyDirectDependencies: true
};

const production = {
    ...options,
    production: true
};

const development = {
    ...options,
    development: true
};

let data = '';

/**
 * To the `README.md` the content with used packages and
 * their licenses will appended to the end of the default content.
 */
fs.readFile(
    'README.md',
    {
        encoding: 'utf8',
        flag: 'r'
    },
    async (_, copy) => {
        let heading = '### Used software';
        const index = copy.search(heading);

        if (index > 0) {
            data = copy.slice(0, index) + heading + '\n';
        } else {
            data = copy + '\n' + heading + '\n';
        }

        data += '\nOpenSlides uses the following software or parts of them:\n\n';
    }
);

/**
 * Dump the licenses
 */
crawler.dumpLicenses(production, async (_, res) => {
    writeToFile(res);

    await crawler.dumpLicenses(development, async (_, res) => {
        writeToFile(res);
        await fs.writeFile('README.md', data, 'utf8', async () => {
            // Here the previously created file will be deleted.
            await fs.unlink('licenses.json', () => {});
        });
    });
});

/**
 * Function to write down a list of all found packages in the `package.json`.
 *
 * @param {json} licenses are all found packages in the project.
 */
function writeToFile(licenses) {
    let resources = [];
    for (let key in licenses) {
        resources.push({
            name: key,
            repository: licenses[key]['repository'],
            license: licenses[key]['licenses']
        });
    }

    for (let entry of resources) {
        data += '- [' + entry.name + ']' + '(' + entry.repository + ')' + ', License: ' + entry.license + '\n';
    }
}


text:
require 'spec_helper'
require 'library_specs'

module Rails
  class Engine
    def self.isolate_namespace(mod)
    end
  end
end

require 'rails_config'

describe SettingsSpec do

  let(:settings) do
    ->(name) do
      fn = File.dirname(__FILE__) + "/../fixtures/#{name}.yml"
      RailsConfig.load_and_set_settings fn
      Settings.development
    end
  end

  describe "#RailsConfig" do
    include_examples 'configuration library'
  end

end


text:
#ifndef SPDYLAY_SESSION_TEST_H
#define SPDYLAY_SESSION_TEST_H

void test_spdylay_session_recv(void);
void test_spdylay_session_recv_invalid_stream_id(void);
void test_spdylay_session_add_frame(void);
void test_spdylay_session_on_syn_stream_received(void);
void test_spdylay_session_on_syn_stream_received_with_push(void);
void test_spdylay_session_on_syn_reply_received(void);
void test_spdylay_session_on_window_update_received(void);
void test_spdylay_session_send_syn_stream(void);
void test_spdylay_session_send_syn_reply(void);
void test_spdylay_submit_response(void);
void test_spdylay_submit_response_with_null_data_read_callback(void);
void test_spdylay_submit_request_with_data(void);
void test_spdylay_submit_request_with_null_data_read_callback(void);
void test_spdylay_submit_syn_stream(void);
void test_spdylay_submit_syn_reply(void);
void test_spdylay_submit_headers(void);
void test_spdylay_session_reply_fail(void);
void test_spdylay_session_on_headers_received(void);
void test_spdylay_session_on_ping_received(void);
void test_spdylay_session_on_goaway_received(void);
void test_spdylay_session_on_data_received(void);
void test_spdylay_session_on_rst_received(void);
void test_spdylay_session_is_my_stream_id(void);
void test_spdylay_session_send_rst_stream(void);
void test_spdylay_session_get_next_ob_item(void);
void test_spdylay_session_pop_next_ob_item(void);
void test_spdylay_session_on_request_recv_callback(void);
void test_spdylay_session_on_stream_close(void);
void test_spdylay_session_max_concurrent_streams(void);
void test_spdylay_session_data_backoff_by_high_pri_frame(void);
void test_spdylay_session_stop_data_with_rst_stream(void);
void test_spdylay_session_stream_close_on_syn_stream(void);
void test_spdylay_session_recv_invalid_frame(void);
void test_spdylay_session_defer_data(void);
void test_spdylay_session_flow_control(void);
void test_spdylay_session_on_ctrl_not_send(void);
void test_spdylay_session_on_settings_received(void);
void test_spdylay_submit_settings(void);
void test_spdylay_session_get_outbound_queue_size(void);

#endif /* SPDYLAY_SESSION_TEST_H */


text:
import { TestBed, ComponentFixture } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { Checkbox } from './checkbox';
import { NoopAnimationsModule } from '@angular/platform-browser/animations';

describe('Checkbox', () => {

  let checkbox: Checkbox;
  let fixture: ComponentFixture<Checkbox>;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [
        NoopAnimationsModule
      ],
      declarations: [
        Checkbox
      ]
    });

    fixture = TestBed.createComponent(Checkbox);
    checkbox = fixture.componentInstance;
  });
});


text:
'''
Read in coded contexts from Excel spreadsheet review.xlsx;
create timeseries plots of cumulative counts of each of the key violent words,
which so far are:
    * hit
    * attack
    * knockout
    * punch
    * knock
    * blood
    * struck
    * strike
'''
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import pandas as pd

from datetime import datetime, date

from util import extract_datetime

plt.style.use('ggplot')

# cut and pasted from
# http://www.randalolson.com/2014/06/28/how-to-make-beautiful-data-visualizations-in-python-with-matplotlib/
CUSTOM_COLORS = [
    (31, 119, 180), (174, 199, 232), (255, 127, 14), (255, 187, 120),
    (44, 160, 44), (152, 223, 138), (214, 39, 40), (255, 152, 150),
    (148, 103, 189), (197, 176, 213), (140, 86, 75), (196, 156, 148),
    (227, 119, 194), (247, 182, 210), (127, 127, 127), (199, 199, 199),
    (188, 189, 34), (219, 219, 141), (23, 190, 207), (158, 218, 229)
]

for i in range(len(CUSTOM_COLORS)):
    r, g, b = CUSTOM_COLORS[i]
    CUSTOM_COLORS[i] = (r / 255., g / 255., b / 255.)

#: plot cumulative count figures for total and individual stations
def plot_cumulative(station, fig_counts):

    cumulative_figurative_counts = fig_counts.cumsum()
    ax = cumulative_figurative_counts.plot(
        lw=2, marker='o', color=CUSTOM_COLORS
    )

    ax.set_title(station.upper())
    ax.set_xlabel('Date')
    ax.set_ylabel('Cumulative counts')

    ax.axvline(date(2012, 10, 3), color='k', lw=1)
    ax.axvline(date(2012, 10, 11), color='k', lw=1)
    ax.axvline(date(2012, 10, 16), color='k', lw=1)
    ax.axvline(date(2012, 10, 22), color='k', lw=1)
    ax.axvline(date(2012, 10, 29), color='k', ls='--', lw=1)

    plt.subplots_adjust(bottom=0.25)

def plot_allfig_ts_bar(station, fig_counts):

    ax = fig_counts.plot(kind='bar', x=fig_counts.index,
                         color=CUSTOM_COLORS, stacked=True)

    # customize tick labels
    ticklabels = ['']*len(fig_counts.index)
    ticklabels[0] = 'October 1, 2012'
    ticklabels[5::5] = [d.strftime('%d') for d in fig_counts.index[5::5]]

    ax.xaxis.set_major_formatter(ticker.FixedFormatter(ticklabels))
    plt.gcf().autofmt_xdate()

    ax.set_title(station.upper())
    ax.set_ylabel('Daily counts')
    ax.set_xlabel('Date')

    ax.axvline(2, color='k', lw=1)
    ax.axvline(10, color='k', lw=1)
    ax.axvline(15, color='k', lw=1)
    ax.axvline(21, color='k', lw=1)
    ax.axvline(27, color='k', ls='--', lw=1)

    plt.subplots_adjust(bottom=0.25)

words = [
    w.upper() for w in
    ['hit', 'attack', 'knockout', 'punch', 'knock', 'blood',
     'struck', 'strike', ]
]

rng = pd.date_range(datetime(2012, 10, 1), datetime(2012, 10, 31), freq='D')

daily_figurative_counts = pd.DataFrame(0, index=rng, columns=words)

xl = pd.ExcelFile('review.xlsx')

figurative_counts = {
    station: pd.DataFrame(0, index=rng, columns=words)
    for station in ('cnn', 'fox', 'msnbc')
}

for word in words:

    df = pd.read_excel(xl, word, index_col=None, parse_cols='B,H')

    # extract all figurative and interesting uses
    df_fi = df[df.code == 'fi']

    # need to create indices first in case there are no matches
    # all_instance_dates = extract_datetime(df_fi.filename)
    cnn_row_idxs = ['CNN' in el for el in df_fi.filename]
    fox_row_idxs = ['FOX' in el for el in df_fi.filename]
    msnbc_row_idxs = ['MSNBC' in el for el in df_fi.filename]

    if any(cnn_row_idxs):
        cnn_instance_dates = extract_datetime(df_fi[cnn_row_idxs].filename)
    else:
        cnn_instance_dates = None

    if any(fox_row_idxs):
        fox_instance_dates = extract_datetime(df_fi[fox_row_idxs].filename)
    else:
        fox_instance_dates = None

    if any(msnbc_row_idxs):
        msnbc_instance_dates = extract_datetime(df_fi[msnbc_row_idxs].filename)
    else:
        msnbc_instance_dates = None

    instance_dates = {
        'cnn': cnn_instance_dates,
        'fox': fox_instance_dates,
        'msnbc': msnbc_instance_dates
    }

    for station, dates in instance_dates.items():
        if dates is not None:
            for d in dates:
                figurative_counts[station][word][d.date()] += 1

all_figurative_counts = figurative_counts['cnn'] + \
    figurative_counts['fox'] + \
    figurative_counts['msnbc']

figurative_counts.update(
    {'Total of CNN, MSNBC, and FOX': all_figurative_counts}
)

for station, fig_counts in figurative_counts.items():

    plot_cumulative(station, fig_counts)

    plot_allfig_ts_bar(station, fig_counts)


text:
import _overRest from 'lodash/_overRest';
import identity from 'lodash/identity';

// Lodash rest function without function.toString()
// remappings
export default function rest(func, start) {
    return _overRest(func, start, identity);
}


text:
SelfSizingCellExample
=====================

Self sizing tableview cells with Swift


text:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Shirt_model extends MY_Model {
    function __construct() {
        parent::__construct();
    }

    public function getAllShirtMale($page) {
        $shirts_male = [];
        $query = $this->db->get('shirts_male');
        // $this->output->enable_profiler(TRUE);
        foreach ($query->result() as $row) {
            $shirts_male[] = $row;
        }
        return $shirts_male;
    }

    public function getAllShirtFemale($page) {
        $shirts_female = [];
        $query = $this->db->get('shirts_female');
        // $this->output->enable_profiler(TRUE);
        foreach ($query->result() as $row) {
            $shirts_female[] = $row;
        }
        return $shirts_female;
    }

    public function checkShirtMale($did) {
        $this->db->where('Id', $did);
        $query = $this->db->get('shirts_male');
        return $query;
    }

    public function checkShirtFemale($did) {
        $this->db->where('Id', $did);
        $query = $this->db->get('shirts_female');
        return $query;
    }

    public function addShirtMale($addData) {

        $this->db->insert('shirts_male',$addData);
        $user_id = $this->db->insert_id();
        return $user_id;
    }

    public function addShirtFemale($addData) {

        $this->db->insert('shirts_female',$addData);
        $user_id = $this->db->insert_id();
        return $user_id;
    }

    public function updateShirtMale($data) {
    $this->db->select('champion_products_images, trends_images, vintage_images');
    $this->db->from('shirts_male');
    $this->db->where('Id', $data['Id']);
    $images_name = $this->db->get()->result();

    $prev_image = array();
    if(!empty($images_name[0]->champion_products_images)){
        $prev_image = explode(",", $images_name[0]->champion_products_images);
    }
    $image_select=array();
    if(!empty($data['champion_products_images']))
    {
        $image_select[] = $data['champion_products_images'];
        $new_image =  array_merge($image_select,$prev_image);
        $imagesNew = implode(",",$new_image);
        $data['champion_products_images'] = $imagesNew;
    }
    else
    {
        $data['champion_products_images'] = $images_name[0]->champion_products_images;
    }

    $prev_trendimage = array();
    if(!empty($images_name[0]->trends_images)){
        $prev_trendimage = explode(",", $images_name[0]->trends_images);
    }
    $image_trendselect=array();
    if(!empty($data['trends_images']))
    {
        $image_trendselect[] = $data['trends_images'];
        $new_trendimage =  array_merge($image_trendselect,$prev_trendimage);
        $imagesTrendNew = implode(",",$new_trendimage);
        $data['trends_images'] = $imagesTrendNew;
    }
    else
    {
        $data['trends_images'] = $images_name[0]->trends_images;
    }

    $prev_vintageimage = array();
    if(!empty($images_name[0]->vintage_images)){
        $prev_vintageimage = explode(",", $images_name[0]->vintage_images);
    }

    $image_vintageselect=array();
    if(!empty($data['vintage_images']))
    {
        $image_vintageselect[] = $data['vintage_images'];
        $new_vintageimage =  array_merge($image_vintageselect,$prev_vintageimage);
        $imagesVintageNew = implode(",",$new_vintageimage);
        $data['vintage_images'] = $imagesVintageNew;
    }
    else
    {
        $data['vintage_images'] = $images_name[0]->vintage_images;
    }

    $prev_vintagevideo = array();
    if(!empty($images_name[0]->vintage_video)){
        $prev_vintagevideo = explode(",", $images_name[0]->vintage_video);
    }

    $image_vintagevideo=array();
    if (!empty($data['vintage_video'])) {
        $image_vintagevideo[] = $data['vintage_video'];
        $new_vintagevideo =  array_merge($image_vintagevideo,$prev_vintagevideo);
        $imagesVintageVideoNew = implode(",",$new_vintagevideo);
        $data['vintage_video'] = $imagesVintageVideoNew;
    }
    else{
        $data['vintage_video'] = $images_name[0]->vintage_video;
    }

        $this->db->where('Id',$data['Id']);
        $this->db->update('shirts_male',$data);
    }

    public function updateShirtFemale($data) {
    $this->db->select('champion_products_images, trends_images, vintage_images, vintage_video');
    $this->db->from('shirts_female');
    $this->db->where('Id', $data['Id']);
    $images_name = $this->db->get()->result();

    $prev_image = explode(",", $images_name[0]->champion_products_images);

    $image_select=array();
    if(!empty($data['champion_products_images']))
    {
        $image_select[] = $data['champion_products_images'];
        $new_image =  array_merge($image_select,$prev_image);
        $imagesNew = implode(",",$new_image);
        $data['champion_products_images'] = $imagesNew;
    }
    else
    {
        $data['champion_products_images'] = $images_name[0]->champion_products_images;
    }

    $prev_trendimage = explode(",", $images_name[0]->trends_images);

    $image_trendselect=array();
    if(!empty($data['trends_images']))
    {
        $image_trendselect[] = $data['trends_images'];
        $new_trendimage =  array_merge($image_trendselect,$prev_trendimage);
        $imagesTrendNew = implode(",",$new_trendimage);
        $data['trends_images'] = $imagesTrendNew;
    }
    else
    {
        $data['trends_images'] = $images_name[0]->trends_images;
    }

    $prev_vintageimage = explode(",", $images_name[0]->vintage_images);

    $image_vintageselect=array();
    if(!empty($data['vintage_images']))
    {
        $image_vintageselect[] = $data['vintage_images'];
        $new_vintageimage =  array_merge($image_vintageselect,$prev_vintageimage);
        $imagesVintageNew = implode(",",$new_vintageimage);
        $data['vintage_images'] = $imagesVintageNew;
    }
    else
    {
        $data['vintage_images'] = $images_name[0]->vintage_images;
    }

    $prev_vintagevideo = array();
    if(!empty($images_name[0]->vintage_video)){
        $prev_vintagevideo = explode(",", $images_name[0]->vintage_video);
    }

    $image_vintagevideo=array();
    if (!empty($data['vintage_video'])) {
        $image_vintagevideo[] = $data['vintage_video'];
        $new_vintagevideo =  array_merge($image_vintagevideo,$prev_vintagevideo);
        $imagesVintageVideoNew = implode(",",$new_vintagevideo);
        $data['vintage_video'] = $imagesVintageVideoNew;
    }
    else{
        $data['vintage_video'] = $images_name[0]->vintage_video;
    }

        $this->db->where('Id',$data['Id']);
        $this->db->update('shirts_female',$data);
    }

    public function removeMaleImage($data){
    $this->db->select('champion_products_images,trends_images,vintage_images, vintage_video');
    $this->db->from('shirts_male');
    $this->db->where('Id', $data['id']);
    $image_delete = $data['image'];
        // $this->output->enable_profiler(TRUE);
        $images_name = $this->db->get()->result();
        if($data['action']=='champion-image')
        {
            $test = $images_name[0]->champion_products_images;
            $test1 = explode(",", $test);
            // print_r($test1);
            // echo $image_delete;
            // exit();
            $imagesNew = "";
            if(count($test1)>1){
            $temp_arr = array();
            for($nn=0;$nn<count($test1);$nn++)
            {
                if($test1[$nn] != $image_delete)
                {
                    $temp_arr[] = $test1[$nn];
                }
            }
             $imagesNew = implode(",",$temp_arr);
            }

            $this->db->where('Id',$data['id']);
            $this->db->set('champion_products_images',$imagesNew);
            $this->db->update('shirts_male');
        }

        if($data['action']=='trends_img')
        {
            $test = $images_name[0]->trends_images;
            $test1 = explode(",", $test);
            // print_r($test1);
            // echo $image_delete;
            // exit();
            $imagesNew = "";
            if(count($test1)>1){
            $temp_arr = array();
            for($nn=0;$nn<count($test1);$nn++)
            {
                if($test1[$nn] != $image_delete)
                {
                    $temp_arr[] = $test1[$nn];
                }
            }
             $imagesNew = implode(",",$temp_arr);
            }
            $this->db->where('Id',$data['id']);
            $this->db->set('trends_images',$imagesNew);
            $this->db->update('shirts_male');
        }

        if($data['action']=='vintage_img' || $data['action']=='vintage_video')
        {
            $test = $images_name[0]->vintage_images;
            $vid = $images_name[0]->vintage_video;

            $test1 = explode(",", $test);
            $vid_explode = explode(",", $vid);
            // print_r($test1);
            // echo $image_delete;
            // exit();
            $imagesNew = "";
            $videoNew = "";
            if(count($test1)>0 || count($vid_explode)>0){
            $temp_arr = array();
            $video_arr = array();
            if($data['action']=='vintage_img')
            {
                for($nn=0;$nn<count($test1);$nn++)
                {
                if($test1[$nn] != $image_delete)
                    {
                    $temp_arr[] = $test1[$nn];
                    $video_arr[] = $vid_explode[$nn];
                    }
                else
                {
                    $path = 'myntra/section_products/pro_shirts/process_video_and_tumbnails/'.$vid_explode[$nn];
                    unlink($path);
                }
                }

            }
            elseif($data['action']=='vintage_video')
            {
                for($nn=0;$nn<count($vid_explode);$nn++)
                {
                if($vid_explode[$nn] != $image_delete)
                    {
                    $temp_arr[] = $test1[$nn];
                    $video_arr[] = $vid_explode[$nn];
                    }
                else
                {
                    $path = 'myntra/section_products/pro_shirts/process_video_and_tumbnails/'.$test1[$nn];
                    unlink($path);
                }
                }

            }

             $imagesNew = implode(",",$temp_arr);
             $videoNew = implode(",",$video_arr);
            }
            $this->db->where('Id',$data['id']);
            $this->db->set('vintage_images',$imagesNew);
            $this->db->set('vintage_video',$videoNew);
            $this->db->update('shirts_male');
        }

    }

    public function removeFemaleImage($data){
    $this->db->select('champion_products_images,trends_images,vintage_images');
    $this->db->from('shirts_female');
    $this->db->where('Id', $data['id']);
    $image_delete = $data['image'];
        // $this->output->enable_profiler(TRUE);
        $images_name = $this->db->get()->result();
        if($data['action']=='champion-image')
        {
            $test = $images_name[0]->champion_products_images;
            $test1 = explode(",", $test);
            // print_r($test1);
            // echo $image_delete;
            // exit();
            $imagesNew = "";
            if(count($test1)>1){
            $temp_arr = array();
            for($nn=0;$nn<count($test1);$nn++)
            {
                if($test1[$nn] != $image_delete)
                {
                    $temp_arr[] = $test1[$nn];
                }
            }
             $imagesNew = implode(",",$temp_arr);
            }

            $this->db->where('Id',$data['id']);
            $this->db->set('champion_products_images',$imagesNew);
            $this->db->update('shirts_female');
        }

        if($data['action']=='trends_img')
        {
            $test = $images_name[0]->trends_images;
            $test1 = explode(",", $test);
            // print_r($test1);
            // echo $image_delete;
            // exit();
            $imagesNew = "";
            if(count($test1)>1){
            $temp_arr = array();
            for($nn=0;$nn<count($test1);$nn++)
            {
                if($test1[$nn] != $image_delete)
                {
                    $temp_arr[] = $test1[$nn];
                }
            }
             $imagesNew = implode(",",$temp_arr);
            }
            $this->db->where('Id',$data['id']);
            $this->db->set('trends_images',$imagesNew);
            $this->db->update('shirts_female');
        }

        if($data['action']=='vintage_img')
        {
            $test = $images_name[0]->vintage_images;
            $test1 = explode(",", $test);
            // print_r($test1);
            // echo $image_delete;
            // exit();
            $imagesNew = "";
            if(count($test1)>1){
            $temp_arr = array();
            for($nn=0;$nn<count($test1);$nn++)
            {
                if($test1[$nn] != $image_delete)
                {
                    $temp_arr[] = $test1[$nn];
                }
            }
             $imagesNew = implode(",",$temp_arr);
            }
            $this->db->where('Id',$data['id']);
            $this->db->set('vintage_images',$imagesNew);
            $this->db->update('shirts_female');
        }

       if($data['action']=='vintage_video')
        {
            $this->db->where('Id',$data['id']);
            $this->db->set('vintage_video',"");
            $this->db->update('shirts_female');
        }

    }

    public function update_order($data)
    {
        $this->db->where('Id',$data['Id']);
        $this->db->set('champion_products_images',$data['champion_products_images']);
        $this->db->update('shirts_male');

    }

   public function update_order_trends($data)
    {
        $this->db->where('Id',$data['Id']);
        $this->db->set('trends_images',$data['trends_images']);
        $this->db->update('shirts_male');

    }

}


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace Aoite.Serialization
{
    /// <summary>
    /// 表示一个提供序列化对象的功能。
    /// </summary>
    public class ObjectWriter : ObjectFormatterBase
    {
        /// <summary>
        /// 初始化一个类 <see cref="ObjectWriter"/> 的新实例。
        /// </summary>
        /// <param name="stream">序列化的流。</param>
        /// <param name="encoding">序列化的编码。</param>
        public ObjectWriter(Stream stream, Encoding encoding)
            : base(stream, encoding)
        {
            if(!stream.CanWrite) throw new NotSupportedException("无法写入数据。");
        }

        /// <summary>
        /// 序列化指定的对象。
        /// </summary>
        /// <param name="value">序列化的对象。</param>
        /// <param name="member">序列化的对象成员。</param>
        public void Serialize(object value, System.Reflection.MemberInfo member = null)
        {
            #region Null & DbNull & SuccessfullyResult

            if(value == null)
            {
                this.WriteNull();
                return;
            }
            if(value is DBNull)
            {
                this.WriteDBNull();
                return;
            }
            if(value is SuccessfullyResult)
            {
                this.WriteSuccessfullyResult();
                return;
            }

            #endregion

            #region ValueType

            if(value is ValueType)
            {
                if(value is Enum) value = Convert.ChangeType(value, Enum.GetUnderlyingType(value.GetType()), null);

                if(value is Guid) this.WriteGuid((Guid)value);
                else if(value is DateTime) this.WriteDateTime((DateTime)value);
                else if(value is TimeSpan) this.WriteTimeSpan((TimeSpan)value);
                else if(value is Boolean) this.WriteBoolean((Boolean)value);
                else if(value is Byte) this.WriteByte((Byte)value);
                else if(value is SByte) this.WriteSByte((SByte)value);
                else if(value is Char) this.WriteChar((Char)value);
                else if(value is Single) this.WriteSingle((Single)value);
                else if(value is Double) this.WriteDouble((Double)value);
                else if(value is Decimal) this.WriteDecimal((Decimal)value);
                else if(value is Int16) this.WriteInt16((Int16)value);
                else if(value is Int32) this.WriteInt32((Int32)value);
                else if(value is Int64) this.WriteInt64((Int64)value);
                else if(value is UInt16) this.WriteUInt16((UInt16)value);
                else if(value is UInt32) this.WriteUInt32((UInt32)value);
                else if(value is UInt64) this.WriteUInt64((UInt64)value);
                else this.WriteValueTypeObject(value);
                return;
            }

            #endregion

            if(this.TryWriteReference(value)) return;

            #region Simple

            if(value is String)
            {
                this.WriteString((String)value);
                return;
            }

            if(value is StringBuilder)
            {
                this.WriteStringBuilder((StringBuilder)value);
                return;
            }
            if(value is Type)
            {
                this.WriteType((Type)value);
                return;
            }

            #endregion

            #region Array

            if(value is Array)
            {
                if(value is String[]) this.WriteStringArray((String[])value);
                else if(value is Guid[]) this.WriteGuidArray((Guid[])value);
                else if(value is DateTime[]) this.WriteDateTimeArray((DateTime[])value);
                else if(value is TimeSpan[]) this.WriteTimeSpanArray((TimeSpan[])value);
                else if(value is Boolean[]) this.WriteBooleanArray((Boolean[])value);
                else if(value is Byte[]) this.WriteByteArray((Byte[])value);
                else if(value is SByte[]) this.WriteSByteArray((SByte[])value);
                else if(value is Char[]) this.WriteCharArray((Char[])value);
                else if(value is Single[]) this.WriteSingleArray((Single[])value);
                else if(value is Double[]) this.WriteDoubleArray((Double[])value);
                else if(value is Decimal[]) this.WriteDecimalArray((Decimal[])value);
                else if(value is Int16[]) this.WriteInt16Array((Int16[])value);
                else if(value is Int32[]) this.WriteInt32Array((Int32[])value);
                else if(value is Int64[]) this.WriteInt64Array((Int64[])value);
                else if(value is UInt16[]) this.WriteUInt16Array((UInt16[])value);
                else if(value is UInt32[]) this.WriteUInt32Array((UInt32[])value);
                else if(value is UInt64[]) this.WriteUInt64Array((UInt64[])value);
                else if(value is StringBuilder[]) this.WriteStringBuilderArray((StringBuilder[])value);
                else if(value is Type[]) this.WriteTypeArray((Type[])value);
                else if(value.GetType() == DefineTypes.ObjectArray) this.WriteObjectArray((Object[])value);
                else
                {
                    this.WriteArray(value as Array);
                }
                return;
            }

            #endregion

            var type = value.GetType();

            var customAttr = type.GetAttribute<SerializableUsageAttribute>()
                ?? (member == null ? null : member.GetAttribute<SerializableUsageAttribute>())
                ?? QuicklySerializer.CustomAttributes.TryGetValue(type);
            if(customAttr != null)
            {
                this.WriteCustom(value, customAttr.FormatterType);
                return;
            }

            #region Result & Generic

            if(type == DefineTypes.Result)
            {
                this.WriteResult((Result)value);
                return;
            }
            if(type == DefineTypes.HybridDictionary)
            {
                this.WriteHybridDictionary((System.Collections.Specialized.HybridDictionary)value);
                return;
            }
            if(type.IsGenericType)
            {
                var defineType = type.GetGenericTypeDefinition();
                if(DefineTypes.GResult == defineType)
                {
                    this.WriteGResult((Result)value, type);
                    return;
                }
                if(DefineTypes.GList == defineType)
                {
                    this.WriteGList((IList)value, type);
                    return;
                }
                if(DefineTypes.GConcurrentDictionary == defineType)
                {
                    this.WriteGConcurrentDictionary((IDictionary)value, type);
                    return;
                }
                if(DefineTypes.GDictionary == defineType)
                {
                    this.WriteGDictionary((IDictionary)value, type);
                    return;
                }
            }

            #endregion

            this.WriteObject(value, type);
        }
    }
}