text:
import * as React from 'react';
import * as ReactCrop from 'react-image-crop';

interface TestState {
    crop?: ReactCrop.Crop;
    percentCrop?: ReactCrop.PercentCrop;
}

const initialState = {
    crop: {
        x: 100,
        y: 200,
    },
    percentCrop: {
        x: 0,
        y: 0,
    },
};

// Basic use case
class SimpleTest extends React.Component<{}, TestState> {
    state = initialState;

    onChange = (crop: ReactCrop.Crop, percentCrop: ReactCrop.PercentCrop) => {
        this.setState({
            crop,
            percentCrop,
        });
    }

    render() {
        return <ReactCrop src="imageSrc" onChange={this.onChange} crop={this.state.crop} />;
    }
}

// Set an aspect ratio to crop
class AspectRatioTest extends React.Component<{}, TestState> {
    state = initialState;

    onChange = (crop: ReactCrop.Crop, percentCrop: ReactCrop.PercentCrop) => {
        this.setState({
            crop,
            percentCrop,
        });
    }

    onImageLoaded = (image: HTMLImageElement) => {
        this.setState({
            crop: ReactCrop.makeAspectCrop(
                {
                    x: 0,
                    y: 0,
                    aspect: 16 / 9,
                    width: 50,
                    unit: 'px',
                },
                image.width,
                image.height
            ),
        });
    }

    render() {
        return (
            <ReactCrop
                src="imageSrc"
                onChange={this.onChange}
                onImageLoaded={this.onImageLoaded}
                crop={this.state.crop}
            />
        );
    }
}

// Testing renderComponent
class RenderComponentTest extends React.Component {
    render() {
        const videoComponent = (
            <video autoPlay loop style={{ display: 'block', maxWidth: '100%' }}>
                <source src="sample.mp4" type="video/mp4" />
            </video>
        );

        return (
            <ReactCrop
                src="imageSrc"
                onChange={(crop, percentCrop) => console.log(crop, percentCrop)}
                renderComponent={videoComponent}
            />
        );
    }
}

// All available props
class CompleteTest extends React.Component<{}, TestState> {
    state = initialState;

    onChange = (crop: ReactCrop.Crop, percentCrop: ReactCrop.PercentCrop) => {
        this.setState({
            crop,
            percentCrop,
        });
    }

    onImageLoaded = (image: HTMLImageElement) => {
        this.setState({
            crop: ReactCrop.makeAspectCrop(
                {
                    x: 0,
                    y: 0,
                    aspect: 16 / 9,
                    width: 20,
                    unit: 'px',
                },
                image.width,
                image.height
            ),
        });
    }

    onImageError = (event: React.SyntheticEvent<HTMLImageElement>) => {
        console.warn('Error loading image');
    }

    render() {
        return (
            <ReactCrop
                src="imageSrc"
                onChange={this.onChange}
                onImageLoaded={this.onImageLoaded}
                crop={this.state.crop}
                minWidth={30}
                minHeight={30}
                maxWidth={90}
                maxHeight={90}
                keepSelection={true}
                disabled={false}
                style={{ border: '1px solid black', position: 'relative' }}
                onComplete={() => console.log('Crop complete')}
                onDragStart={() => console.log('Drag start')}
                onDragEnd={() => console.log('Drag end')}
                crossorigin="anonymous"
                onImageError={this.onImageError}
                className="my-cropper"
                locked={false}
                renderComponent={

}
                ruleOfThirds={false}
                circularCrop={false}
            />
        );
    }
}


text: A fast evented web server

redpajama_set_name: RedPajamaGithub


text:
import base64

from .exceptions import InvalidArgumentError

encode_method = base64.encodebytes
decode_method = base64.decodebytes

PAGINATION_MODEL = {
    "list_shards": {
        "input_token": "next_token",
        "limit_key": "limit",
        "limit_default": 10000,
        "unique_attribute": "ShardId",
        "fail_on_invalid_token": False,
    },
}

PAGINATION_MODEL = {
    "list_shards": {
        "input_token": "next_token",
        "limit_key": "limit",
        "limit_default": 10000,
        "unique_attribute": "ShardId",
        "fail_on_invalid_token": False,
    },
}

def compose_new_shard_iterator(
    stream_name, shard, shard_iterator_type, starting_sequence_number, at_timestamp
):
    if shard_iterator_type == "AT_SEQUENCE_NUMBER":
        last_sequence_id = int(starting_sequence_number) - 1
    elif shard_iterator_type == "AFTER_SEQUENCE_NUMBER":
        last_sequence_id = int(starting_sequence_number)
    elif shard_iterator_type == "TRIM_HORIZON":
        last_sequence_id = 0
    elif shard_iterator_type == "LATEST":
        last_sequence_id = shard.get_max_sequence_number()
    elif shard_iterator_type == "AT_TIMESTAMP":
        last_sequence_id = shard.get_sequence_number_at(at_timestamp)
    else:
        raise InvalidArgumentError(f"Invalid ShardIteratorType: {shard_iterator_type}")
    return compose_shard_iterator(stream_name, shard, last_sequence_id)

def compose_shard_iterator(stream_name, shard, last_sequence_id):
    return encode_method(
        f"{stream_name}:{shard.shard_id}:{last_sequence_id}".encode("utf-8")
    ).decode("utf-8")

def decompose_shard_iterator(shard_iterator):
    return decode_method(shard_iterator.encode("utf-8")).decode("utf-8").split(":")


text:
namespace file_based_test_driver {

// Represents a single mode of execution in TestCaseOutputs.
class TestCaseMode {
 public:
  class LessThan {
   public:
    bool operator()(const TestCaseMode& a, const TestCaseMode& b) const {
      return a.mode_parts_ < b.mode_parts_;
    }
  };
  class JoinFormatter {
   public:
    void operator()(std::string* out, const TestCaseMode& mode) const {
      absl::StrAppend(out, mode.ToString());
    }
  };
  using Set = std::set<TestCaseMode, LessThan>;
  using UnorderedSet = absl::node_hash_set<TestCaseMode>;
  template <class T>
  using Map = std::map<TestCaseMode, T, LessThan>;
  template <class T>
  using UnorderedMap = absl::node_hash_map<TestCaseMode, T>;

  static file_based_test_driver_base::StatusOr<TestCaseMode> Create(
      std::vector<std::string> mode_parts);
  // Create a description of a test, which is a space-separated list of
  // mode-parts.
  static file_based_test_driver_base::StatusOr<TestCaseMode> Create(absl::string_view description);

  TestCaseMode() = default;

  std::string ToString() const;
  bool empty() const { return mode_parts_.empty(); }

  bool operator==(const TestCaseMode& other) const {
    return mode_parts_ == other.mode_parts_;
  }

  template <typename H>
  friend H AbslHashValue(H h, const TestCaseMode& test_case_mode) {
    return H::combine(std::move(h), test_case_mode.mode_parts_);
  }

  static file_based_test_driver_base::StatusOr<std::vector<TestCaseMode>> ParseModes(
      absl::string_view modes_string);
  static std::string CollapseModes(const TestCaseMode::Set& modes);

 private:
  std::vector<std::string> mode_parts_;
};

inline std::ostream& operator<<(std::ostream& o, const TestCaseMode& m) {
  return o << m.ToString();
}

}  // namespace file_based_test_driver

#endif  // THIRD_PARTY_FILE_BASED_TEST_DRIVER_TEST_CASE_MODE_H_


text:
package com.hg.core.dao;

import java.io.Serializable;
import java.util.List;

/**
 *

 * The interface should exist without implement any ORM framework
 *

 *

 * 此interface应脱离于ORM框架技术而存在
 *

 */
public interface BaseDao<T, PK extends Serializable> {

    T findById(PK id);

    List<T> findByQuery(String query);

    /**
     * @param pager contain firstResult and maxResults
     */
    List<T> findByQuery(final String query, final Pager pager);

    /**
     * @param values query's values
     */
    List<T> findByQuery(String query, Object... values);

    /**
     * @param pager contain firstResult and maxResults
     * @param values query's values
     */
    List<T> findByQuery(final String query, final Pager pager, final Object... values);

    long count();

    T save(T transientInstance);

    void delete(T persistentInstance);

    T merge(T detachedInstance);

    void flush();

    /**
     *

     * Initiative loading

     * Example: xxDao.initialize(Parent.getChildren())
     *

     *

     * 主动加载

     * 例如: xxDao.initialize(Parent.getChildren())
     *

     *
     * @param obj Loading object
     */
    void initialize(Object obj);
}


text:
package chav1961.purelib.ui.swing;

import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.util.Arrays;
import java.util.Locale;

import javax.swing.InputVerifier;
import javax.swing.JCheckBox;
import javax.swing.JComponent;

import chav1961.purelib.basic.URIUtils;
import chav1961.purelib.basic.exceptions.ContentException;
import chav1961.purelib.basic.exceptions.LocalizationException;
import chav1961.purelib.basic.exceptions.SyntaxException;
import chav1961.purelib.basic.interfaces.LoggerFacade.Severity;
import chav1961.purelib.i18n.interfaces.Localizer;
import chav1961.purelib.i18n.interfaces.Localizer.LocaleChangeListener;
import chav1961.purelib.model.interfaces.ContentMetadataInterface.ContentNodeMetadata;
import chav1961.purelib.model.interfaces.NodeMetadataOwner;
import chav1961.purelib.ui.swing.BooleanPropChangeEvent.EventChangeType;
import chav1961.purelib.ui.swing.inner.BooleanPropChangeListenerRepo;
import chav1961.purelib.ui.swing.interfaces.BooleanPropChangeListener;
import chav1961.purelib.ui.swing.interfaces.BooleanPropChangeListenerSource;
import chav1961.purelib.ui.swing.interfaces.JComponentInterface;
import chav1961.purelib.ui.swing.interfaces.JComponentMonitor;
import chav1961.purelib.ui.swing.interfaces.JComponentMonitor.MonitorEvent;

public class JCheckBoxWithMeta extends JCheckBox implements NodeMetadataOwner, LocaleChangeListener, JComponentInterface, BooleanPropChangeListenerSource {
	private static final long 			serialVersionUID = -3207016216489833670L;
	private static final Class<?>[]		VALID_CLASSES = {Boolean.class,boolean.class};

	private final BooleanPropChangeListenerRepo	repo = new BooleanPropChangeListenerRepo();
	private final ContentNodeMetadata	metadata;
	private final Localizer				localizer;
	private boolean						currentValue, invalid = false;

	public JCheckBoxWithMeta(final ContentNodeMetadata metadata, final Localizer localizer, final JComponentMonitor monitor) throws LocalizationException {
		if (metadata == null) {
			throw new NullPointerException("Metadata can't be null");
		}
		else if (localizer == null) {
			throw new NullPointerException("Localizer can't be null");
		}
		else if (monitor == null) {
			throw new NullPointerException("Monitor can't be null");
		}
		else if (!InternalUtils.checkClassTypes(metadata.getType(),VALID_CLASSES)) {
			throw new IllegalArgumentException("Invalid node type ["+metadata.getType().getCanonicalName()+"] for the given control. Only "+Arrays.toString(VALID_CLASSES)+" are available");
		}
		else {
			this.metadata = metadata;
			this.localizer = localizer;

			final String	name = URIUtils.removeQueryFromURI(metadata.getUIPath()).toString();

			InternalUtils.addComponentListener(this,()->callLoad(monitor));
			addFocusListener(new FocusListener() {
				@Override
				public void focusLost(final FocusEvent e) {
					try{if (currentValue != isSelected()) {
							if (monitor.process(MonitorEvent.Saving,metadata,JCheckBoxWithMeta.this)) {
								currentValue = isSelected();
							}
						}
						monitor.process(MonitorEvent.FocusLost,metadata,JCheckBoxWithMeta.this);
					} catch (ContentException exc) {
						SwingUtils.getNearestLogger(JCheckBoxWithMeta.this).message(Severity.error, exc,exc.getLocalizedMessage());
					}
				}

				@Override
				public void focusGained(final FocusEvent e) {
					currentValue = isSelected();
					try{
						monitor.process(MonitorEvent.FocusGained,metadata,JCheckBoxWithMeta.this);
						getActionMap().get(SwingUtils.ACTION_ROLLBACK).setEnabled(false);
					} catch (ContentException exc) {
						SwingUtils.getNearestLogger(JCheckBoxWithMeta.this).message(Severity.error, exc,exc.getLocalizedMessage());
					}
				}
			});
			SwingUtils.assignActionKey(this,WHEN_FOCUSED,SwingUtils.KS_EXIT,(e)->{
				try{if (monitor.process(MonitorEvent.Rollback,metadata,JCheckBoxWithMeta.this)) {
						assignValueToComponent(currentValue);
						getActionMap().get(SwingUtils.ACTION_ROLLBACK).setEnabled(false);
					}
				} catch (ContentException exc) {
					SwingUtils.getNearestLogger(JCheckBoxWithMeta.this).message(Severity.error, exc,exc.getLocalizedMessage());
				}
			}, SwingUtils.ACTION_ROLLBACK);
			addActionListener((e)->getActionMap().get(SwingUtils.ACTION_ROLLBACK).setEnabled(true));
			setInputVerifier(new InputVerifier() {
				@Override
				public boolean verify(final JComponent input) {
					try{return monitor.process(MonitorEvent.Validation,metadata,JCheckBoxWithMeta.this);
					} catch (ContentException e) {
						return false;
					}
				}
			});

			if (metadata.getFormatAssociated() != null) {
				if (metadata.getFormatAssociated().isReadOnly(false)) {
					setEnabled(false);
				}
			}

			setName(name);
			InternalUtils.registerAdvancedTooptip(this);
			fillLocalizedStrings();
		}
	}

	@Override
	public void localeChanged(final Locale oldLocale, final Locale newLocale) throws LocalizationException {
		fillLocalizedStrings();
	}

	@Override
	public ContentNodeMetadata getNodeMetadata() {
		return metadata;
	}

	@Override
	public String getRawDataFromComponent() {
		return Boolean.valueOf(isSelected()).toString();
	}

	@Override
	public Object getValueFromComponent() {
		return currentValue;
	}

	@Override
	public Object getChangedValueFromComponent() throws SyntaxException {
		return isSelected();
	}

	@Override
	public void assignValueToComponent(final Object value) {
		if (value == null) {
			if (InternalUtils.checkNullAvailable(getNodeMetadata())) {
				setSelected(false);
			}
			else {
				throw new NullPointerException("Value to assign can't be null");
			}
		}
		else if (value instanceof Boolean) {
			setSelected((Boolean)value);
		}
		else if (value instanceof String) {
			final String	str = value.toString();

			if ("true".equals(str) || "false".equals(str)) {
				setSelected(Boolean.valueOf((String)value));
			}
			else {
				throw new IllegalArgumentException("String ["+value+"] to assign contains invald value");
			}
		}
		else {
			throw new IllegalArgumentException("Value to assign must be Boolean, not ["+value.getClass().getCanonicalName()+"]");
		}
	}

	@Override
	public Class<?> getValueType() {
		return Boolean.class;
	}

	@Override
	public String standardValidation(final Object value) {
		if (value == null) {
			if (InternalUtils.checkNullAvailable(getNodeMetadata())) {
				return null;
			}
			else {
				return InternalUtils.buildStandardValidationMessage(getNodeMetadata(), InternalUtils.VALIDATION_NULL_VALUE);
			}
		}
		else {
			return null;
		}
	}

	@Override
	public void setInvalid(boolean invalid) {
		this.invalid = invalid;
	}

	@Override
	public boolean isInvalid() {
		return invalid;
	}

	@Override
	public void addBooleanPropChangeListener(final BooleanPropChangeListener listener) {
		repo.addBooleanPropChangeListener(listener);
	}

	@Override
	public void removeBooleanPropChangeListener(final BooleanPropChangeListener listener) {
		repo.removeBooleanPropChangeListener(listener);
	}

	@Override
	public void setVisible(final boolean aFlag) {
		final boolean old = isVisible();

		super.setVisible(aFlag);
		if (repo != null && aFlag != old) {
			repo.fireBooleanPropChange(this, EventChangeType.VISIBILE, aFlag);
		}
	}

	@Override
	public boolean isEnabled() {
		if (getParent() != null) {
			return super.isEnabled() && getParent().isEnabled();
		}
		else {
			return super.isEnabled();
		}
	}

	@Override
	public void setEnabled(boolean b) {
		final boolean old = isEnabled();

		super.setEnabled(b);
		if (repo != null && b != old) {
			repo.fireBooleanPropChange(this, EventChangeType.ENABLED, b);
		}
	}

	@Override
	public void setSelected(boolean b) {
		final boolean old = isSelected();

		super.setSelected(b);
		if (repo != null && b != old) {
			repo.fireBooleanPropChange(this, EventChangeType.SELECTED, b);
		}
	}

	private void fillLocalizedStrings() throws LocalizationException {
		if (getNodeMetadata().getTooltipId() != null && !getNodeMetadata().getTooltipId().trim().isEmpty()) {
			setToolTipText(localizer.getValue(getNodeMetadata().getTooltipId()));
		}
	}

	private void callLoad(final JComponentMonitor monitor) {
		try{monitor.process(MonitorEvent.Loading,metadata,this);
			currentValue = isSelected();
		} catch (ContentException exc) {
			SwingUtils.getNearestLogger(JCheckBoxWithMeta.this).message(Severity.error, exc,exc.getLocalizedMessage());
		}
	}
}


text:
- Veda: version <=  v1.2.0
- Vednn:  https://github.com/mergian/vednn + patch

###### Veda, Llvm-Ve, Vednn installation script

```
#it may require sudo  user for installing veda and llvm-ve
bash libnd4j/build_ve_prerequisites.sh
```

---------------------

### libdn4j  Aurora Ve library with Vednn

##### Building libnd4j with vednn

Specify vednn installation folder if it was not installed in ```/opt/nec/ve```:
```
export VEDNN_ROOT="your installation folder"
```
Specify nlc root:
```
#here we are using 2.3.0
export NLC_ROOT=/opt/nec/ve/nlc/2.3.0/
```
Building libdn4j:
```

./buildnativeoperations.sh -o aurora -dt "float;double;int;int64;bool" -t -h vednn -j 120
```

####### Additional notes
If you are facing `Unable to grow stack` error while running the test, then set this environment variable
```
export OMP_STACKSIZE=1G
```
---------------------

### libdn4j Cpu library with platform  Ve  Vednn acceleration

##### Libnd4j + Veda Vednn

```
#build libnd4j and tests tuned for the current Cpu with Ve Vednn acceleration
./buildnativeoperations.sh -a native -t -h vednn -j $(nproc)
```
it outputs:
./blasbuild/cpu/libnd4jcpu_so
./blasbuild/cpu/libnd4jcpu_device.so

##### Usage
Veda Ve library should be either in the working directory or it's path should be set using *DEVICE_LIB_LOADPATH* environment variable.
```
#example:
#running conv2d tests:
export DEVICE_LIB_LOADPATH=${PWD}/blasbuild/cpu/blas
${PWD}/blasbuild/cpu/tests_cpu/layers_tests/runtests --gtest_filter=*conv2*
```

There is not any need to set the device library path manually within nd4j framework. Loading and setting the right device library path are handled inside.

##### Dl4j installation
```
export VEDNN_ROOT="your VEDNN root folder"
helper=vednn
extension=avx2
mvn clean  install  -DskipTests  -Dlibnd4j.helper=${helper} -Dlibnd4j.extension=${extension} -Djavacpp.platform.extension=-${helper}-${extension} -Dlibnd4j.classifier=linux-x86_64-${helper}-${extension} -Pcpu

#or if you followed Prerequisites section
libnd4j/build_veda.sh

```
###### Notes
   - vc/vcpp file extensions are used to diferentitate VE device files from c/cpp in cmake. Cmake will compile them using nec.


text:
package org.apache.pig.piggybank.evaluation.math;

import java.io.IOException;

import org.apache.pig.EvalFunc;
import org.apache.pig.data.Tuple;
import org.apache.pig.impl.logicalLayer.schema.Schema;
import org.apache.pig.data.DataType;

/**
 * math.SIGNUM implements a binding to the Java function
* {@link java.lang.Math#signum(double) Math.signum(double)}.
* Given a single data atom it Returns the signum function of the argument.
*
*

*
Parameters:

*
value - Double.

*
*
Return Value:

*
Double

*
*
Return Schema:

*
SIGNUM_inputSchema

*
*
Example:

*

* register math.jar;

* A = load 'mydata' using PigStorage() as ( float1 );

* B = foreach A generate float1, math.SIGNUM(float1);
*

*

*
* @see Math#signum(double)
* @see
* @author ajay garg
*
*/
public class DoubleSignum extends EvalFunc<Double>{
    /**
     * java level API
     * @param input expects a single numeric DataAtom value
     * @param output returns a single numeric DataAtom value,
     * signum function of the argument
     */
    @Override
    public Double exec(Tuple input) throws IOException {
        if (input == null || input.size() == 0)
            return null;

        try{
            Double d = (Double)input.get(0);
            return Math.signum(d);
        }catch (Exception e){
            throw new IOException("Caught exception processing input row ", e);
        }

    }

    @Override
    public Schema outputSchema(Schema input) {
        return new Schema(new Schema.FieldSchema(getSchemaName(this.getClass().getName().toLowerCase(), input), DataType.DOUBLE));
    }
}


text:
package equus.matching.cases;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

import equus.matching.NoConvertCase;

public class EqualsCase<S> implements NoConvertCase<S> {
  private final S matchValue;

  public EqualsCase(@Nonnull S matchValue) {
    this.matchValue = matchValue;
  }

  @Override
  public boolean match(@Nullable S subject) {
    return matchValue.equals(subject);
  }

}


text:
from __future__ import print_function

import unittest
from paddle.fluid.tests.unittests.test_matmul_op import *

if __name__ == '__main__':
    unittest.main()


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE122_Heap_Based_Buffer_Overflow__c_CWE805_struct_loop_63b.c
Label Definition File: CWE122_Heap_Based_Buffer_Overflow__c_CWE805.label.xml
Template File: sources-sink-63b.tmpl.c
*/
/*
 * @description
 * CWE: 122 Heap Based Buffer Overflow
 * BadSource:  Allocate using malloc() and set data pointer to a small buffer
 * GoodSource: Allocate using malloc() and set data pointer to a large buffer
 * Sinks: loop
 *    BadSink : Copy twoIntsStruct array to data using a loop
 * Flow Variant: 63 Data flow: pointer to data passed from one function to another in different source files
 *
 * */

#include "std_testcase.h"

#ifndef OMITBAD

void CWE122_Heap_Based_Buffer_Overflow__c_CWE805_struct_loop_63b_badSink(twoIntsStruct * * dataPtr)
{
    twoIntsStruct * data = *dataPtr;
    {
        twoIntsStruct source[100];
        {
            size_t i;
            /* Initialize array */
            for (i = 0; i < 100; i++)
            {
                source[i].intOne = 0;
                source[i].intTwo = 0;
            }
        }
        {
            size_t i;
            /* POTENTIAL FLAW: Possible buffer overflow if data < 100 */
            for (i = 0; i < 100; i++)
            {
                data[i] = source[i];
            }
            printStructLine(&data[0]);
            free(data);
        }
    }
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* goodG2B uses the GoodSource with the BadSink */
void CWE122_Heap_Based_Buffer_Overflow__c_CWE805_struct_loop_63b_goodG2BSink(twoIntsStruct * * dataPtr)
{
    twoIntsStruct * data = *dataPtr;
    {
        twoIntsStruct source[100];
        {
            size_t i;
            /* Initialize array */
            for (i = 0; i < 100; i++)
            {
                source[i].intOne = 0;
                source[i].intTwo = 0;
            }
        }
        {
            size_t i;
            /* POTENTIAL FLAW: Possible buffer overflow if data < 100 */
            for (i = 0; i < 100; i++)
            {
                data[i] = source[i];
            }
            printStructLine(&data[0]);
            free(data);
        }
    }
}

#endif /* OMITGOOD */


text:
package org.sakaiproject.entitybroker.entityprovider.capabilities;

import org.sakaiproject.entitybroker.entityprovider.EntityProvider;
import org.sakaiproject.entitybroker.entityprovider.annotations.EntityCustomAction;

/**
 * This entity supports custom actions (as defined by RoR and REST microformat:
 * http://microformats.org/wiki/rest/urls)

 * This means that there are custom actions which can be invoked on entities or entity spaces,
 * custom actions can augment the current entity operation or they can completely
 * change the behavior and skip the current operation entirely

 * You can create methods in your entity provider which either end with {@value #ACTION_METHOD_SUFFIX}
 * or use the {@link EntityCustomAction} suffix to define the custom actions

 * You can describe the actions using the {@link Describeable} key: <prefix>.action.<actionKey> = description

 * If you want more control then you can use {@link ActionsDefineable} and {@link ActionsExecutionControllable}

 * @see EntityCustomAction for more details about the custom action methods
 *
 * @author Aaron Zeckoski (azeckoski @ gmail.com)
 */
public interface ActionsExecutable extends EntityProvider {

   /**
    * Use this suffix or the {@link EntityCustomAction} annotation to indicate custom actions
    * for your entities
    */
   public static String ACTION_METHOD_SUFFIX = "CustomAction";

}


text:
ShotViewWindow = function(shotInfo) {
	var self = Titanium.UI.createWindow({
		backgroundColor : 'black',
		exitOnClose : false,
		orientationModes : [Ti.UI.PORTRAIT, Ti.UI.UPSIDE_PORTRAIT],
		layout : 'vertical'
	});

	var shotPicture = Ti.UI.createImageView({
		image : shotInfo.shot.shot_picture,
		height : '80%',
		width : 'auto'
	});
	self.add(shotPicture);

	var buttonWrapper = Ti.UI.createView({
		backgroundColor : 'black',
		width : '100%',
		height : '20%',
		layout : 'horizontal'
	});
	self.add(buttonWrapper);

	var disputeButton = Titanium.UI.createButton({
		title : 'Dispute Kill',
		width : '40%',
		left : '5%',
		right : '5%',
		bottom : '10%',
		borderRadius : 1,
		font : {
			fontFamily : 'Arial',
			fontWeight : 'bold',
			fontSize : 14
		}
	});
	buttonWrapper.add(disputeButton);

	var confirmButton = Titanium.UI.createButton({
		title : 'Confirm Kill',
		width : '40%',
		left : '5%',
		right : '5%',
		bottom : '10%',
		borderRadius : 1,
		font : {
			fontFamily : 'Arial',
			fontWeight : 'bold',
			fontSize : 14
		}
	});
	buttonWrapper.add(confirmButton);

	disputeButton.addEventListener('click', function() {
		DisputeWindow = require('ui/common/game/DisputeWindow');
		if (self.tab) {
			self.tab.open(new DisputeWindow(shotInfo.shot.shot_id));
		} else {
			self.containingTab.open(new DisputeWindow(shotInfo.shot.shot_id));
		}
	});

	confirmButton.addEventListener('click', function() {
		Ti.App.fireEvent('network:game:shot:decide', {
			shot_id : shotInfo.shot.shot_id,
			shot_upheld : 'True',
			claim : 'Good shot!'
		});
	});

	Ti.App.addEventListener('network:game:shot:decide:success', function() {
		Ti.App.fireEvent('ui:toast', {
			message : 'Kill confirmed.'
		});
		self.close();
	});

	Ti.App.addEventListener('network:game:shot:decide:failure', function() {
		Ti.App.fireEvent('ui:toast', {
			message : 'Confirmation failed.  Please try again.'
		});
	});

	return self;
};

module.exports = ShotViewWindow;


text:
import sys

import importlib
import os

from iridium.config.configmanager import ConfigManager

configmanager = ConfigManager()

def add_client_to_path(base_dir=None, debug=False, base_clients=None):
    """
    Can set the python sdk clients.  If git is set to True, then base_dir must
    have a valid directory pointing to the folder where the projects were cloned
    to.  By default, base_clients will import the keystone, nova and glance
    python-{}client modules.

    :param base_dir: Only needed if git=True. The folder where the git cloned
                     clients are
    :param git: If set to False, use the regular yum or pip installed module,
                if True, use git cloned modules
    :param base_clients: A sequence of python-{}clients to import

    :return: the final sys.path
    """
    client = "{}client"
    if base_clients is None:
        base_clients = ["glance", "keystone", "nova"]

    if base_dir and not os.path.isdir(base_dir):
        raise core.exceptions.ArgumentError("{} does not exists".format(base_dir))

    if debug:
        client = "python-{}client"
        if base_dir is None:
            # use the location from smog_config.yml
            base_dir = configmanager.cfg_manager('rdo_clones')

        if not os.path.isdir(base_dir):
            raise Exception("Unable to find base directory to load modules {}".format(base_dir))

        extra = [os.path.join(base_dir, client.format(x)) for x in base_clients]
        for d in extra:
            if not os.path.isdir(d):
                raise core.exceptions.ArgumentError("{} does not exist".format(d))
        sys.path = extra + sys.path
    else:
        clients = map(client.format, base_clients)
        map(importlib.import_module, clients)

    return sys.path


text:
function CarNumber(number){

	this.number = number;

	this.getNumber = function(){
		return 	this.number;
	}
}

module.exports = CarNumber;


text:
package io.datarouter.nodewatch.config;

import javax.inject.Inject;
import javax.inject.Singleton;

import io.datarouter.storage.setting.DatarouterSettingCategory;
import io.datarouter.storage.setting.SettingFinder;
import io.datarouter.storage.setting.SettingRoot;
import io.datarouter.storage.setting.cached.CachedSetting;

@Singleton
public class DatarouterTableCountPublisherSettingRoot extends SettingRoot{

	public final CachedSetting<Boolean> runLatestTableCountPublisherJob;

	@Inject
	public DatarouterTableCountPublisherSettingRoot(SettingFinder finder){
		super(finder, DatarouterSettingCategory.DATAROUTER, "datarouterTableCountPublisher.");
		runLatestTableCountPublisherJob = registerBoolean("runLatestTableCountPublisherJob", false);
	}

}


text:
package org.apache.gobblin.util;

import com.linkedin.avroutil1.compatibility.AvroCompatibilityHelper;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.apache.avro.Schema;

/**
 * Avro schema utility class to perform schema property conversion to the appropriate data types
 */
@Slf4j
public class AvroSchemaUtils {

  private AvroSchemaUtils() {

  }

  /**
   * Get schema property value as integer
   * @param schema
   * @param prop
   * @return Integer
   */
  public static Integer getValueAsInteger(final Schema schema, String prop) {
    String value = AvroCompatibilityHelper.getSchemaPropAsJsonString(schema, prop,
        false, false);
    try {
      return Integer.parseInt(value);
    } catch (NumberFormatException ex) {
      log.error("Exception while converting to integer ", ex.getCause());
      throw new IllegalArgumentException(ex);
    }
  }

  /***
   * Copy properties to an Avro Schema field
   * @param fromField Avro Schema Field to copy properties from
   * @param toField Avro Schema Field to copy properties to
   */
  public static void copyFieldProperties(final Schema.Field fromField, final Schema.Field toField) {
    List<String> allPropNames = AvroCompatibilityHelper.getAllPropNames(fromField);
    if (null != allPropNames) {
      for (String propName : allPropNames) {
        String propValue = AvroCompatibilityHelper.getFieldPropAsJsonString(fromField, propName,
            true, false);
        AvroCompatibilityHelper.setFieldPropFromJsonString(toField, propName, propValue, false);
      }
    }
  }

  /***
   * Copy properties to an Avro Schema
   * @param fromSchema Avro Schema to copy properties from
   * @param toSchema Avro Schema to copy properties to
   */
  public static void copySchemaProperties(final Schema fromSchema, final Schema toSchema) {
    List<String> allPropNames = AvroCompatibilityHelper.getAllPropNames(fromSchema);
    if (null != allPropNames) {
      for (String propName : allPropNames) {
        String propValue = AvroCompatibilityHelper.getSchemaPropAsJsonString(fromSchema, propName,
            true, false);
        AvroCompatibilityHelper.setSchemaPropFromJsonString(toSchema, propName, propValue, false);
      }
    }
  }
}


text:
title: Python Review: Built-In Functions
layout: post
author: sam.rix
permalink: /python-review:-built-in-functions/
source-id: 1GupU_Dbsgxq3XsYDISqCQXo_YeLunWL0F_XIlojem_E
published: true
---

    Title
    Continuing Python on codecademy
    Date
    20.6.17

    Starting point:
    We had to carry on with are Python work.

    Target for this lesson?
    To do 3 individual tasks.

    Did I reach my target?
(add details to "Lesson Review")
    Yes I did.

    Lesson Review

    How did I learn? What strategies were effective?

    The strategies I used to make lots of progress on python and to get up to Review: Built-In Functions were, to take my time and think about what I was writing instead of rushing in and then getting stuck on it for a long time. And if I still got it wrong the first time after thinking about it for a while I would delete it all and start again.

    What limited my learning? Which habits do I need to work on?

    The habits I need to work on are thinking more about the task I have just done. This will really help when I am doing a harder task and I can't just try and do it as fast as I can and then get it wrong.

    What will I change for next time? How will I improve ?

    Next time I will improve by, taking my time on task and not just doing it as fast as I can. I will also go back to an exercise if I forget what to do. This will help me do the exercise quicker, it will also reinforce the work I have just done.


text:
export interface FfzChannelEmotesResponse {
    // room: Room;
    sets: Sets;
}

export interface FfzGlobalEmotesResponse {
    sets: Sets;
}

// export interface Room {
//     _id:             number;
//     css:             null;
//     display_name:    string;
//     id:              string;
//     is_group:        boolean;
//     mod_urls:        null;
//     moderator_badge: null;
//     set:             number;
//     twitch_id:       number;
//     user_badges:     UserBadges;
// }

// export interface UserBadges {
// }

export interface Sets {
    [key: string]: EmoteSet;
}

export interface EmoteSet {
    // _type:       number;
    // css:         null;
    // description: null;
    emoticons:   Emoticon[];
    // icon:        null;
    // id:          number;
    // title:       string;
}

export interface Emoticon {
    // css:      null;
    // height:   number;
    // hidden:   boolean;
    id:       number;
    // margins:  null;
    // modifier: boolean;
    name:     string;
    // offset:   null;
    // owner:    Owner;
    // public:   boolean;
    urls:     { [key: string]: string };
    // width:    number;
}

export interface Owner {
    _id:          number;
    display_name: string;
    name:         string;
}


text:
#include "./elemwise_unary_op.h"
#include "./elemwise_binary_op.h"
#include "./elemwise_binary_scalar_op.h"

namespace mxnet {
namespace op {
MXNET_OPERATOR_REGISTER_BINARY_SCALAR(_maximum_scalar)
.set_attr<FCompute>("FCompute<cpu>", BinaryScalarCompute<cpu, mshadow_op::maximum>)
.set_attr<nnvm::FGradient>("FGradient", ElemwiseGradUseIn{"_backward_maximum_scalar"})
.add_alias("_MaximumScalar");

MXNET_OPERATOR_REGISTER_BINARY(_backward_maximum_scalar)
.add_argument("scalar", "float", "scalar value")
.set_attr_parser([](NodeAttrs* attrs) {attrs->parsed = std::stod(attrs->dict["scalar"]);})
.set_attr<FCompute>("FCompute<cpu>", BinaryScalarBackward<cpu, mshadow_op::ge>);

MXNET_OPERATOR_REGISTER_BINARY_SCALAR(_minimum_scalar)
.set_attr<FCompute>("FCompute<cpu>", BinaryScalarCompute<cpu, mshadow_op::minimum>)
.set_attr<nnvm::FGradient>("FGradient", ElemwiseGradUseIn{"_backward_minimum_scalar"})
.add_alias("_MinimumScalar");

MXNET_OPERATOR_REGISTER_BINARY(_backward_minimum_scalar)
.add_argument("scalar", "float", "scalar value")
.set_attr_parser([](NodeAttrs* attrs) {attrs->parsed = std::stod(attrs->dict["scalar"]);})
.set_attr<FCompute>("FCompute<cpu>", BinaryScalarBackward<cpu, mshadow_op::le>);

MXNET_OPERATOR_REGISTER_BINARY_SCALAR(_power_scalar)
.set_attr<FCompute>("FCompute<cpu>", BinaryScalarCompute<cpu, mshadow_op::power>)
.set_attr<nnvm::FGradient>("FGradient", ElemwiseGradUseIn{"_backward_power_scalar"})
.add_alias("_PowerScalar");

MXNET_OPERATOR_REGISTER_BINARY(_backward_power_scalar)
.add_argument("scalar", "float", "scalar value")
.set_attr_parser([](NodeAttrs* attrs) {attrs->parsed = std::stod(attrs->dict["scalar"]);})
.set_attr<FCompute>("FCompute<cpu>", BinaryScalarBackward<cpu, mshadow_op::power_grad>);

MXNET_OPERATOR_REGISTER_BINARY_SCALAR(_rpower_scalar)
.set_attr<FCompute>("FCompute<cpu>", BinaryScalarCompute<cpu, mshadow_op::rpower>)
.set_attr<nnvm::FGradient>("FGradient", ElemwiseGradUseOut{"_backward_rpower_scalar"})
.add_alias("_RPowerScalar");

MXNET_OPERATOR_REGISTER_BINARY(_backward_rpower_scalar)
.add_argument("scalar", "float", "scalar value")
.set_attr_parser([](NodeAttrs* attrs) {attrs->parsed = std::stod(attrs->dict["scalar"]);})
.set_attr<FCompute>("FCompute<cpu>", BinaryScalarBackward<cpu, mshadow_op::rpower_grad>);

MXNET_OPERATOR_REGISTER_BINARY_SCALAR(_hypot_scalar)
.set_attr<FCompute>("FCompute<cpu>", BinaryScalarCompute<cpu, mshadow_op::hypot>)
.set_attr<nnvm::FGradient>("FGradient", ElemwiseGradUseIn{ "_backward_hypot_scalar" })
.add_alias("_HypotScalar");

MXNET_OPERATOR_REGISTER_BINARY(_backward_hypot_scalar)
.add_argument("scalar", "float", "scalar value")
.set_attr_parser([](NodeAttrs* attrs) {attrs->parsed = std::stod(attrs->dict["scalar"]); })
.set_attr<FCompute>("FCompute<cpu>", BinaryScalarBackward<cpu, mshadow_op::hypot_grad_left>);

MXNET_OPERATOR_REGISTER_BINARY_SCALAR(smooth_l1)
.describe(R"code(Calculate Smooth L1 Loss(lhs, scalar) by summing

.. math::

    f(x) =
    \begin{cases}
    (\sigma x)^2/2,& \text{if }x < 1/\sigma^2\\
    |x|-0.5/\sigma^2,& \text{otherwise}
    \end{cases}

where :math:`x` is an element of the tensor *lhs* and :math:`\sigma` is the scalar.

Example::

  smooth_l1([1, 2, 3, 4], sigma=1) = [0.5, 1.5, 2.5, 3.5]

)code" ADD_FILELINE)
.set_attr<FCompute>("FCompute<cpu>", BinaryScalarCompute<cpu, mshadow_op::smooth_l1_loss>)
.set_attr<nnvm::FGradient>("FGradient", ElemwiseGradUseIn{ "_backward_smooth_l1" });

MXNET_OPERATOR_REGISTER_BINARY(_backward_smooth_l1)
.set_attr_parser([](NodeAttrs* attrs) {attrs->parsed = std::stod(attrs->dict["scalar"]); })
.set_attr<FCompute>("FCompute<cpu>", BinaryScalarBackward<cpu, mshadow_op::smooth_l1_gradient>);

}  // namespace op
}  // namespace mxnet


text:
/**
 * webida - project configurator
 *
 * Src:
 *   plugins/project-configurator/projectConfigurator.js
 */
define(['webida-lib/app',
        'webida-lib/util/path',
        'dojo/topic',
        'external/lodash/lodash.min',
        'webida-lib/util/notify',
], function (ide, pathutil, topic, _, notify) {
    'use strict';

    var projectConfigurator = {};
    var fsMount = ide.getFSCache(); // ide.getMount();
    var projectPropertyList = [];
    var noProjectList = [];

    projectConfigurator.DEBUG_MODE = 'debug';
    projectConfigurator.RUN_MODE = 'run';

    var projectConfigurationLoadPromise = readProjectRunConfigurations()
        .then(getConfigurationObjectByProject)
        .then(function () {
            topic.publish('projectConfig.loadCompleted');
            // FIXME this module has no relation with runAs
            if (projectPropertyList.length === 0 && noProjectList.length === 0) {
                topic.publish('toolbar.runas.disable');
            }
        });

    function readProjectRunConfigurations() {
        return new Promise(function (resolve, reject) {
            fsMount.list(ide.getPath(), function (err, projectList) {
                if (err) {
                    notify.error(err);
                    reject(err);
                } else {
                    resolve(projectList);
                }
            });
        });
    }

    function getConfigurationObjectByProject(projectList) {
        return Promise.all(projectList.map(function (project) {
            return new Promise(function (resolve) {
                if (project.isDirectory === true && project.name[0] !== '.') {
                    getConfigurationObjectFromPath(ide.getPath() + '/' + project.name + '/', function (obj) {
                        if (obj) {
                            addProjectPropertyByName(obj);
                        } else {
                            addNoProjectByName(project.name);
                        }
                        resolve();
                    });
                } else {
                    resolve();
                }
            });
        }));
    }

    //readProjectRunConfigurations();

    function deleteProjectPropertyByName(projectName) {
        if (!projectName) {
            return;
        }
        var temp;

        for (var i = 0; i < projectPropertyList.length; i++) {
            temp = projectPropertyList[i];
            if (temp.name === projectName) {
                projectPropertyList.splice(i, 1);
                if (projectPropertyList.length === 0 && noProjectList.length === 0) {
                    topic.publish('toolbar.runas.disable');
                }
                return;
            }
        }
        topic.publish('projectConfig.changed', projectName);
    }

    function replaceProjectProperty(obj) {
        var temp;

        for (var i = 0; i < projectPropertyList.length; i++) {
            temp = projectPropertyList[i];
            if (temp.name === obj.name) {
                projectPropertyList.splice(i, 1, obj);
                return;
            }
        }

        addProjectPropertyByName(obj);
    }

    function exsistProjectProperty(name) {
        var temp;

        for (var i = 0; i < projectPropertyList.length; i++) {
            temp = projectPropertyList[i];
            if (temp.name === name) {
                return true;
            }
        }

        return false;
    }

    function addProjectPropertyByName(obj) {
        if (!obj) {
            return;
        }

        projectPropertyList.push(obj);

        if (noProjectList.length === 0 && projectPropertyList.length === 1) {
            topic.publish('toolbar.runas.enable');
        }
    }

    function getProjectPropertyByName(projectName) {
        if (!projectName) {
            return null;
        }
        var temp;

        for (var i = 0; i < projectPropertyList.length; i++) {
            temp = projectPropertyList[i];
            if (temp.name === projectName) {
                return temp;
            }
        }

        return null;
    }

    function getProjectPropertyByPath(path) {
        if (!path) {
            return null;
        }
        var pathSplit = path.split('/');
        var projectName = pathSplit[2];

        return getProjectPropertyByName(projectName);
    }

    function getConfigurationObjectFromPath(projectPath, cb) {
        var obj = null;
        if (!projectPath) {
            cb(null);
        }

        fsMount.exists(projectPath + '.project', function (err, exist) {
            if (err) {
                cb(null);
            } else {
                if (exist) {
                    fsMount.readFile(projectPath + '.project/project.json', function (err, content) {
                        if (err) {
                            console.log(err);
                            cb(null);
                        } else {
                            if (content !== '') {
                                obj = JSON.parse(content);
                                var splitProjectPath = projectPath.split('/');
                                var projectName = splitProjectPath[2];
                                if (obj.name !== projectName) {
                                    obj.name = projectName;
                                    var date = new Date();
                                    obj.created = date.toGMTString();
                                    projectConfigurator.saveProjectProperty(projectPath, obj, null);
                                }
                            }
                            cb(obj);
                        }
                    });
                } else {
                    cb(null);
                }
            }
        });
    }

    function getProjectRootPath(childPath) {
        if (!childPath) {
            return null;
        }
        var splitPath = childPath.split('/');
        if (splitPath.length < 3) {
            return null;
        }
        return splitPath.slice(0, 3).join('/') + '/';
    }

    topic.subscribe('fs.cache.file.set', function (fsURL, target, type, maybeModified) {
        var splitTarget = target.split('/');
        var idePath = ide.getPath() + '/';
        if (splitTarget.length !== 5 || !maybeModified) {
            return;
        }
        var name = splitTarget[4];

        if (name === 'project.json') {
            if (idePath === '/' + splitTarget[1] + '/' && splitTarget[3] === '.project') {
                var splitTargetDir = target.split('.project');
                if (splitTargetDir[0]) {
                    getConfigurationObjectFromPath(splitTargetDir[0], function (obj) {
                        if (obj) {
                            replaceProjectProperty(obj);
                        }
                        topic.publish('projectConfig.changed', splitTargetDir[2]);
                        //console.log('replace project property : ' + obj);
                    });
                }
            }
        }
    });

    function existNoProject(name) {
        for (var i = 0; i < noProjectList.length; i++) {
            if (noProjectList[i].name === name) {
                return true;
            }
        }
        return false;
    }

    function deleteNoProjectByName(name) {
        for (var i = 0; i < noProjectList.length; i++) {
            if (noProjectList[i].name === name) {
                noProjectList.splice(i, 1);
                if (projectPropertyList.length === 0 && noProjectList.length === 0) {
                    topic.publish('toolbar.runas.disable');
                }
                return;
            }
        }
    }

    function addNoProjectByName(name) {
        if (existNoProject(name) === true) {
            return;
        }

        var noProjectObj = {
            'name': name,
            'isProject' : false
        };

        noProjectList.push(noProjectObj);

        if (noProjectList.length === 1 && projectPropertyList.length === 0) {
            topic.publish('toolbar.runas.enable');
        }
    }

    function newProjectAdded(projectPath, projectName) {
        if (!projectPath || !projectName) {
            return;
        }
        getConfigurationObjectFromPath(projectPath, function (obj) {
            if (obj) {
                if (exsistProjectProperty(projectName) === true) {
                    replaceProjectProperty(obj);
                } else {
                    addProjectPropertyByName(obj);
                }
                deleteNoProjectByName(projectName);
            } else {
                addNoProjectByName(projectName);
                console.log('newProjectAdded fail ');
            }
            topic.publish('projectConfig.changed', projectName);
        });
    }

    topic.subscribe('projectWizard.created', function (targetDir, projectName) {
        //console.log(projectName);
        newProjectAdded(targetDir + '/' + projectName + '/', projectName);
    });

    topic.subscribe('fs.cache.node.added', function (fsURL, targetDir, name, type, created) {
        //console.log('node added' +  ':' + fsURL + ':' + targetDir + ':' + name + ':' + type + ':' + created);
        if (created === false) {
            return;
        }
        var splitTargetDir = targetDir.split('/');
        var idePath = ide.getPath() + '/';				//workspace

        //project folder added
        if (targetDir === idePath && name[0] !== '.') {
            newProjectAdded(targetDir + name + '/', name);
        }

        //.project folder added
        if (name === '.project' && type === 'dir' && splitTargetDir[2][0] !== '.') {
            // check .project
            if (splitTargetDir.length === 4 && idePath === '/' + splitTargetDir[1] + '/') {
                newProjectAdded(targetDir, splitTargetDir[2]);
            }
        }

        //project.json file added
        if (name === 'project.json'  && type === 'file' && splitTargetDir[2][0] !== '.') {
            if (splitTargetDir.length === 5 && idePath === '/' + splitTargetDir[1] + '/' &&
                splitTargetDir[3] === '.project') {
                var projectNameSplit = targetDir.split('.project');
                newProjectAdded(projectNameSplit[0], splitTargetDir[2]);
            }
        }
    });

    topic.subscribe('fs.cache.node.deleted', function (fsURL, targetDir, name, type) {
        var splitTargetDir = targetDir.split('/');

        //project folder delete
        var idePath = ide.getPath() + '/';

        if (targetDir === idePath) {
            deleteProjectPropertyByName(name);
            deleteNoProjectByName(name);
        }

        //.project folder delete
        if (name === '.project' && type === 'dir') {
            // check .project
            if (splitTargetDir.length === 4 && idePath === '/' + splitTargetDir[1] + '/') {
                deleteProjectPropertyByName(splitTargetDir[2]);
                addNoProjectByName(splitTargetDir[2]);
            }
        }

        //project.json delete
        if (name === 'project.json' && type === 'file') {
            // check .project
            if (splitTargetDir.length === 5 && idePath === '/' + splitTargetDir[1] + '/' &&
                splitTargetDir[3] === '.project') {
                deleteProjectPropertyByName(splitTargetDir[2]);
                addNoProjectByName(splitTargetDir[2]);
            }
        }
    });

    function makeProjectProjectObject(name, description, created,
        type, path) {
        var obj = {
            'name': name,
            'description': description,
            'created': created,
            'type': type,
            'path': path,
            'isProject' : true
        };
        return obj;
    }

    function makeProjectRunObject(name, path, fragment, argument, openArgument,
        liveReload) {
        var obj = {
            'name': name,
            'path': path,
            'fragment': fragment,
            'argument': argument,
            'openArgument': openArgument,
            'liveReload': liveReload
        };
        return obj;
    }

    projectConfigurator.makeEmptyProjectPropertyObject = function () {
        return makeProjectProjectObject('', '', '', '', '');
    };

    projectConfigurator.makeEmptyRunObject = function () {
        return makeProjectRunObject('', '', '', '', '', '');
    };

    projectConfigurator.getOwnerProjectRootPath = function (childFilePath) {
        var workspacePath = ide.getPath();

        if (childFilePath.substring(0, workspacePath.length) === workspacePath) {
            var subpath = childFilePath.substring(workspacePath.length + 1);
            var names = subpath.split('/');
            if (names.length > 0) {
                return pathutil.combine(workspacePath, names[0]);
            }
        }

        return null;
    };

    function createProjectFolder(path, cb) {
        var splitPath = path.split('/');

        if (splitPath.length !== 4) {
            if (cb) {
                cb('error: ' + path + 'is not a project path');
            }
            return;
        }
        var filePath = path + '.project';
        fsMount.exists(filePath, function (err, result) {
            if (err) {
                notify.error('"exists" API call failed: ' + err);
                return;
            }
            if (result) {
                if (cb) {
                    cb();
                }
            } else {
                fsMount.createDirectory(filePath, function (err) {
                    if (err) {
                        cb('"createDirectory" API call failed: ' + err);
                    } else {
                        if (cb) {
                            cb();
                        }
                    }
                });
            }
        });

    }
    projectConfigurator.createProjectProperty = function (path, cb) {
        var filePath = path + '.project';

        fsMount.exists(filePath, function (err, result) {
            if (err) {
                notify.error('"exists" API call failed: ' + err);
                return;
            }
            if (result) {
                filePath += '/project.json';

                var date = new Date();
                var pathSplit = filePath.split('/');
                var name = pathSplit[2];
                var obj = makeProjectProjectObject(name, '', date.toGMTString(), '', path);

                //projectConfigurator.saveProjectProperty(path, obj, cb);
                projectConfigurator.saveProjectProperty(path, obj, function (err) {
                    if (err) {
                        notify.error('"writeFile" API call failed: ' + err);
                    } else {
                        addProjectPropertyByName(obj);
                        if (cb) {
                            cb();
                        }
                    }
                });
            } else {
                fsMount.createDirectory(filePath, function (err) {
                    if (err) {
                        cb(filePath + ' create fail');
                    } else {
                        filePath += '/project.json';

                        var date = new Date();
                        var pathSplit = filePath.split('/');
                        var name = pathSplit[2];
                        var obj = makeProjectProjectObject(name, '', date.toGMTString(), '', filePath);

                        projectConfigurator.saveProjectProperty(path, obj, function (err) {
                            if (err) {
                                notify.error('"writeFile" API call failed: ' + err);
                            } else {
                                addProjectPropertyByName(obj);
                                if (cb) {
                                    cb();
                                }
                            }
                        });
                    }
                });
            }
        });

    };

    projectConfigurator.saveProjectProperty = function (path, obj, cb) {
        var jsonText = JSON.stringify(obj);
        createProjectFolder(path, function (err) {
            if (err) {
                if (cb) {
                    cb(err);
                }
                return;
            }
            fsMount.writeFile(path + '.project/project.json', jsonText, function (err) {
                if (err) {
                    console.log(path + 'Failed to save .project/project.json');
                    if (cb) {
                        cb(err);
                    }
                } else {

                    if (cb) {
                        cb();
                    }
                }
            });
        });
    };

    projectConfigurator.getProjectFileName = function () {
        return '.project/project.json';
    };

    projectConfigurator.getConfigurationObject = function (path, c) {
        return projectConfigurator.getConfigurationObjectByPath(path, c);
    };

    projectConfigurator.getConfigurationObjectByPath = function (path, callback) {
        projectConfigurationLoadPromise.then(function () {
            var obj = getProjectPropertyByPath(path);
            if (callback) {
                callback(obj);
            }
        });
        return getProjectPropertyByPath(path);
    };

    projectConfigurator.getConfigurationObjectByProjectName = function (name, callback) {
        projectConfigurationLoadPromise.then(function () {
            var obj = getProjectPropertyByName(name);

            if (callback) {
                callback(obj);
            }
        });
        return getProjectPropertyByName(name);
    };

    projectConfigurator.getProjectRootPath = getProjectRootPath;

    projectConfigurator.getProjectPropertyList = function (callback) {
        projectConfigurationLoadPromise.then(function () {
            if (callback) {
                callback(projectPropertyList);
            }
        });
        return projectPropertyList;
    };

    projectConfigurator.getRunAsList = function () {
        var runAsList = projectPropertyList.concat(noProjectList);
        runAsList.sort(function (a, b) {
            if (a.name > b.name) {
                return 1;
            }
            else {
                return -1;
            }
        });
        return runAsList;
    };

    projectConfigurator.getProjectRootHtml = function (filePath, c) {
        var projectRootPath = projectConfigurator.getOwnerProjectRootPath(filePath);
        var projectFileName = projectConfigurator.getProjectFileName();
        if (projectRootPath === undefined || projectRootPath === null ||
           projectFileName === undefined || projectFileName === null) {
            c([]);
        } else {
            var projectConfPath = pathutil.combine(projectRootPath, projectFileName);
            projectConfigurator.getConfigurationObject(projectConfPath, function (projectObj) {
                var htmlPaths = [];
                if (projectObj && projectObj.run && projectObj.run.list && projectObj.run.list.length > 0) {
                    for (var i = 0; i < projectObj.run.list.length; i++) {
                        var runObj = projectObj.run.list[i];
                        if (pathutil.endsWith(runObj.path, '.html', true)) {
                            var htmlPath = runObj.path;
                            if (/^\//.test(htmlPath)) {
                                htmlPath = htmlPath.substr(1);
                            }
                            htmlPath = projectRootPath + '/' + htmlPath;
                            if (!/^\//.test(htmlPath)) {
                                htmlPath = '/' + htmlPath;
                            }
                            htmlPaths.push(htmlPath);
                        }
                    }
                }
                c(htmlPaths);
            });
        }
    };

    return projectConfigurator;
});


text:
/**
 * @fileoverview 确认对象是否在数组中
 * @authors liangdong2
 * @param {Array} arr 要操作的数组
 * @param {Mixed} item 要搜索的对象
 * @return {Boolean} 如果对象在数组中,返回true
 * @example
	var $contains = require('kit/util/contains');
	console.debug($contains([1,2,3,4,5],3));	//true
 */

define('lib/kit/arr/contains',function(require,exports,module){

	module.exports = function(arr, item){
		var index = arr.indexOf(item);
		return index >= 0;
	};

});


text:
require 'spec_helper'

describe NanoApi::Controller::Markerable do
  context do
    include RSpec::Rails::ControllerExampleGroup

    controller do
      include NanoApi::Controller::Markerable

      def new
        render :nothing => true
      end
    end

    let(:affiliate_attributes){{}}
    before do
      controller.stub(affiliate: affiliate_attributes)
    end

    describe '.marker' do
      [ {:marker => 'referer'}, {:ref => 'referer'} ].each do |param|
        specify do
          get :new, param
          controller.send(:marker).should == 'referer'
        end
      end
    end

    describe 'should save new marker in cookies' do
      [ {:marker => 'referer'}, {:ref => 'referer'} ].each do |param|
        specify do
          get :new, param
          controller.send(:cookies)[:marker].should == 'referer'
          response.status.should == 301
        end
      end
    end

    context 'marker is NOT given in request params' do
      describe 'should save default marker to cookies when marker in cookies is blank' do
        specify do
          get :new
          controller.send(:cookies)[:marker].should == 'direct'
        end
      end

      describe 'should NOT save default marker to cookies when marker in cookies is NOT blank' do
        specify do
          get :new, marker: 'test'
          get :new
          controller.send(:cookies)[:marker].should_not == 'direct'
        end
      end
    end

    context 'new marker is affiliate marker' do
      it 'should update cookies' do
        get :new, :marker => 'test'
        get :new, :marker => '12345'

        controller.send(:cookies)[:marker].should == '12345'
      end

      it 'should update affiliate cookies' do
        get :new, :marker => '12346'
        get :new, :marker => '12345'

        controller.send(:cookies)[:marker].should == '12345'
      end
    end

    context 'new marker is not affiliate marker' do
      it 'should update cookies' do
        get :new, :marker => 'test'
        get :new, :marker => 'test1'

        controller.send(:cookies)[:marker].should == 'test1'
      end

      it 'should not update affiliate cookies' do
        get :new, :marker => '12345'
        get :new, :marker => 'test1'

        controller.send(:cookies)[:marker].should == '12345'
      end
    end

    it 'should not update cookie expired time for same affiliate requests' do
      get :new, :marker => '12345'

      controller.send(:cookies).should_not_receive(:[]=).with(:marker, an_instance_of(Hash))
      get :new, :marker => '12345'
    end

    shared_examples_for :marker_cookie_setter do
      before(:all){Timecop.freeze}
      after(:all){Timecop.return}
      let(:marker){'test'}

      it 'should set cookie with correct cookie params' do
        controller.send(:cookies).should_receive(:[]=).with(:marker, cookie_params)
        get :new, :marker => marker
      end
    end

    context 'non affiliate marker' do
      let(:affiliate_attributes){nil}
      let(:cookie_params){{value: marker, domain: 'test.host', expires: 30.days.from_now}}

      it_should_behave_like :marker_cookie_setter
    end

    context 'affiliate marker with custom marker life time' do
      let(:affiliate_attributes){{marker_life_time_in_days: 1}}
      let(:cookie_params){{value: marker, domain: 'test.host', expires: 1.day.from_now}}

      it_should_behave_like :marker_cookie_setter
    end
  end
end


text:
CREATE TABLE hash_check_test (
  id integer PRIMARY KEY
);


text:
package org.apache.sqoop.hive;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Map;
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Properties;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.sqoop.io.CodecMap;

import com.cloudera.sqoop.SqoopOptions;
import com.cloudera.sqoop.manager.ConnManager;
import org.apache.sqoop.util.FileSystemUtil;

/**
 * Creates (Hive-specific) SQL DDL statements to create tables to hold data
 * we're importing from another source.
 *
 * After we import the database into HDFS, we can inject it into Hive using
 * the CREATE TABLE and LOAD DATA INPATH statements generated by this object.
 */
public class TableDefWriter {

  public static final Log LOG = LogFactory.getLog(
      TableDefWriter.class.getName());

  private SqoopOptions options;
  private ConnManager connManager;
  private Configuration configuration;
  private String inputTableName;
  private String outputTableName;
  private boolean commentsEnabled;

  /**
   * Creates a new TableDefWriter to generate a Hive CREATE TABLE statement.
   * @param opts program-wide options
   * @param connMgr the connection manager used to describe the table.
   * @param inputTable the name of the table to load.
   * @param outputTable the name of the Hive table to create.
   * @param config the Hadoop configuration to use to connect to the dfs
   * @param withComments if true, then tables will be created with a
   *        timestamp comment.
   */
  public TableDefWriter(final SqoopOptions opts, final ConnManager connMgr,
      final String inputTable, final String outputTable,
      final Configuration config, final boolean withComments) {
    this.options = opts;
    this.connManager = connMgr;
    this.inputTableName = inputTable;
    this.outputTableName = outputTable;
    this.configuration = config;
    this.commentsEnabled = withComments;
  }

  private Map<String, Integer> externalColTypes;

  /**
   * Set the column type map to be used.
   * (dependency injection for testing; not used in production.)
   */
  public void setColumnTypes(Map<String, Integer> colTypes) {
    this.externalColTypes = colTypes;
    LOG.debug("Using test-controlled type map");
  }

  /**
   * Get the column names to import.
   */
  private String [] getColumnNames() {
    String [] colNames = options.getColumns();
    if (null != colNames) {
      return colNames; // user-specified column names.
    } else if (null != externalColTypes) {
      // Test-injection column mapping. Extract the col names from this.
      ArrayList<String> keyList = new ArrayList<String>();
      for (String key : externalColTypes.keySet()) {
        keyList.add(key);
      }

      return keyList.toArray(new String[keyList.size()]);
    } else if (null != inputTableName) {
      return connManager.getColumnNames(inputTableName);
    } else {
      return connManager.getColumnNamesForQuery(options.getSqlQuery());
    }
  }

  /**
   * @return the CREATE TABLE statement for the table to load into hive.
   */
  public String getCreateTableStmt() throws IOException {
    Map<String, Integer> columnTypes;
    Properties userMapping = options.getMapColumnHive();
    Boolean isHiveExternalTableSet = !StringUtils.isBlank(options.getHiveExternalTableDir());
    if (externalColTypes != null) {
      // Use pre-defined column types.
      columnTypes = externalColTypes;
    } else {
      // Get these from the database.
      if (null != inputTableName) {
        columnTypes = connManager.getColumnTypes(inputTableName);
      } else {
        columnTypes = connManager.getColumnTypesForQuery(options.getSqlQuery());
      }
    }

    String [] colNames = getColumnNames();
    StringBuilder sb = new StringBuilder();
    if (options.doFailIfHiveTableExists()) {
      if (isHiveExternalTableSet) {
        sb.append("CREATE EXTERNAL TABLE `");
      } else {
        sb.append("CREATE TABLE `");
      }
    } else {
      if (isHiveExternalTableSet) {
        sb.append("CREATE EXTERNAL TABLE IF NOT EXISTS `");
      } else {
        sb.append("CREATE TABLE IF NOT EXISTS `");
      }
    }

    if(options.getHiveDatabaseName() != null) {
      sb.append(options.getHiveDatabaseName()).append("`.`");
    }
    sb.append(outputTableName).append("` ( ");

    // Check that all explicitly mapped columns are present in result set
    for(Object column : userMapping.keySet()) {
      boolean found = false;
      for(String c : colNames) {
        if (c.equals(column)) {
          found = true;
          break;
        }
      }

      if (!found) {
        throw new IllegalArgumentException("No column by the name " + column
                + "found while importing data");
      }
    }

    boolean first = true;
    String partitionKey = options.getHivePartitionKey();
    for (String col : colNames) {
      if (col.equals(partitionKey)) {
        throw new IllegalArgumentException("Partition key " + col + " cannot "
            + "be a column to import.");
      }

      if (!first) {
        sb.append(", ");
      }

      first = false;

      Integer colType = columnTypes.get(col);
      String hiveColType = userMapping.getProperty(col);
      if (hiveColType == null) {
        hiveColType = connManager.toHiveType(inputTableName, col, colType);
      }
      if (null == hiveColType) {
        throw new IOException("Hive does not support the SQL type for column "
            + col);
      }

      sb.append('`').append(col).append("` ").append(hiveColType);

      if (HiveTypes.isHiveTypeImprovised(colType)) {
        LOG.warn(
            "Column " + col + " had to be cast to a less precise type in Hive");
      }
    }

    sb.append(") ");

    if (commentsEnabled) {
      DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
      String curDateStr = dateFormat.format(new Date());
      sb.append("COMMENT 'Imported by sqoop on " + curDateStr + "' ");
    }

    if (partitionKey != null) {
      sb.append("PARTITIONED BY (")
        .append(partitionKey)
        .append(" STRING) ");
     }

    sb.append("ROW FORMAT DELIMITED FIELDS TERMINATED BY '");
    sb.append(getHiveOctalCharCode((int) options.getOutputFieldDelim()));
    sb.append("' LINES TERMINATED BY '");
    sb.append(getHiveOctalCharCode((int) options.getOutputRecordDelim()));
    String codec = options.getCompressionCodec();
    if (codec != null && (codec.equals(CodecMap.LZOP)
            || codec.equals(CodecMap.getCodecClassName(CodecMap.LZOP)))) {
      sb.append("' STORED AS INPUTFORMAT "
              + "'com.hadoop.mapred.DeprecatedLzoTextInputFormat'");
      sb.append(" OUTPUTFORMAT "
              + "'org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat'");
    } else {
      sb.append("' STORED AS TEXTFILE");
    }

    if (isHiveExternalTableSet) {
      // add location
      sb.append(" LOCATION '"+options.getHiveExternalTableDir()+"'");
    }

    LOG.debug("Create statement: " + sb.toString());
    return sb.toString();
  }

  /**
   * @return the LOAD DATA statement to import the data in HDFS into hive.
   */
  public String getLoadDataStmt() throws IOException {
    Path finalPath = getFinalPath();

    StringBuilder sb = new StringBuilder();
    sb.append("LOAD DATA INPATH '");
    sb.append(finalPath.toString() + "'");
    if (options.doOverwriteHiveTable()) {
      sb.append(" OVERWRITE");
    }
    sb.append(" INTO TABLE `");
    if(options.getHiveDatabaseName() != null) {
      sb.append(options.getHiveDatabaseName()).append("`.`");
    }
    sb.append(outputTableName);
    sb.append('`');

    if (options.getHivePartitionKey() != null) {
      sb.append(" PARTITION (")
        .append(options.getHivePartitionKey())
        .append("='").append(options.getHivePartitionValue())
        .append("')");
    }

    LOG.debug("Load statement: " + sb.toString());
    return sb.toString();
  }

  public Path getFinalPath() throws IOException {
    String warehouseDir = options.getWarehouseDir();
    if (null == warehouseDir) {
      warehouseDir = "";
    } else if (!warehouseDir.endsWith(File.separator)) {
      warehouseDir = warehouseDir + File.separator;
    }

    // Final path is determined in the following order:
    // 1. Use target dir if the user specified.
    // 2. Use input table name.
    String tablePath = null;
    String targetDir = options.getTargetDir();
    if (null != targetDir) {
      tablePath = warehouseDir + targetDir;
    } else {
      tablePath = warehouseDir + inputTableName;
    }
    return FileSystemUtil.makeQualified(new Path(tablePath), configuration);
  }

  /**
   * Return a string identifying the character to use as a delimiter
   * in Hive, in octal representation.
   * Hive can specify delimiter characters in the form '\ooo' where
   * ooo is a three-digit octal number between 000 and 177. Values
   * may not be truncated ('\12' is wrong; '\012' is ok) nor may they
   * be zero-prefixed (e.g., '\0177' is wrong).
   *
   * @param charNum the character to use as a delimiter
   * @return a string of the form "\ooo" where ooo is an octal number
   * in [000, 177].
   * @throws IllegalArgumentException if charNum > 0177.
   */
  public static String getHiveOctalCharCode(int charNum) {
    if (charNum > 0177) {
      throw new IllegalArgumentException(
          "Character " + charNum + " is an out-of-range delimiter");
    }

    return String.format("\\%03o", charNum);
  }

}


text:
<html>
	<head>
		<title>Starfield</title>
		<style>
			body { margin: 0; }
			canvas { width: 100%; height: 100% }
		</style>
	</head>
	<body>
		<script src="js/three.min.js"></script>
		<script>
			var particles = 20000;
			var velocity  = {max: 0.001, min: 0.000001};
			var depth     = 1000;

			var mouseX = 0, mouseY = 0, mouseDown = false;
			var cloud;

			var scene, camera, frustum, screenMatrix, renderer,
				directionalLight, pointLight;

			function init() {
				scene = new THREE.Scene();
				lights();
				camera();
				action();
			}

			function lights() {
				// Lighting
				var directionalLight = new THREE.DirectionalLight(0xffffff, 0.5);
				directionalLight.position.set(0, -1, 1);
				scene.add(directionalLight);

				var pointLight = new THREE.PointLight(0xffffff, 2, 300);
				pointLight.position.set(0, 0, 0);
				scene.add(pointLight);
			}

			function camera() {
				camera = new THREE.PerspectiveCamera(90, window.innerWidth / window.innerHeight, 1, depth);
				camera.position.z = depth/2;

				frustum      = new THREE.Frustum();
				screenMatrix = new THREE.Matrix4();
			}

			function action() {
				renderer = new THREE.WebGLRenderer();
				renderer.setSize(window.innerWidth, window.innerHeight);
				document.body.appendChild(renderer.domElement);
				makeCloud();
				loop();
			}

			function loop() {
				requestAnimationFrame(loop);
				updateCloud();
				renderer.render(scene, camera);
			}

			function randVector() {
				var w = window.innerWidth;
				var h = window.innerHeight;
				var rand = THREE.Math.randInt.bind(THREE.Math);
				var x = rand(-w/2, w/2),
					y = rand(-h/2, h/2),
					z = rand(1, depth);
				return new THREE.Vector3(x, y, z);
			}

			function makeCloud() {
				var geometry = new THREE.Geometry();
				var material = new THREE.PointCloudMaterial({
					color: 0xffffff
				});
				for (var i=0; i<particles; i++) {
					var v = randVector();
					v.velocity = THREE.Math.randFloat(velocity.min, velocity.max);
					geometry.vertices.push(v);
				}
				cloud = new THREE.PointCloud(geometry, material);
				scene.add(cloud);
			}

			function updateCloud() {
				var w = window.innerWidth;
				var h = window.innerHeight;
				var x = mouseX - w/2;
				var y = h/2 - mouseY;
				if (mouseDown) {
					cloud.rotation.y += x * 0.00001;
					cloud.rotation.x += y * -0.00001;
				}

				var target = new THREE.Vector3(x, y, depth);

				cloud.geometry.vertices.forEach(function(v, i) {
					v.lerp(target, v.velocity);
					if (v.z > depth/2 || v.z < 0) {
						var rand = randVector();
						v.x = rand.x;
						v.y = rand.y;
						v.z = 1;
					}
				});

				cloud.geometry.verticesNeedUpdate = true;
			}

			function randColor() {
				var num = THREE.Math.randFloat.bind(THREE.Math, 0.0, 1.0);
				return new THREE.Color(num(), num(), num());
			}

			document.body.onmousemove = function(e) {
				mouseX = e.clientX;
				mouseY = e.clientY;
			}

			document.body.onmousedown = function(e) {
				mouseDown = true;
			}

			document.body.onmouseup = function(e) {
				mouseDown = false;
			}

			init();
		</script>
	</body>
</html>


text:
from tests.utils import resource_file
from owslib.wps import WebProcessingService

def test_wps_execute():
    wps = WebProcessingService(
        'http://cida.usgs.gov/gdp/process/WebProcessingService',
        skip_caps=True)

    # Execute fake invocation of Execute operation using cached HTTP request and response
    request = open(resource_file('wps_USGSExecuteRequest1.xml'), 'rb').read()
    response = open(resource_file('wps_USGSExecuteResponse1a.xml'), 'rb').read()
    execution = wps.execute(None, [], request=request, response=response)
    assert execution.status == 'ProcessStarted'
    assert execution.isComplete() is False

    # Simulate end of process
    response = open(resource_file('wps_USGSExecuteResponse1b.xml'), 'rb').read()
    execution.checkStatus(sleepSecs=0, response=response)
    assert execution.status == 'ProcessSucceeded'
    assert execution.isComplete() is True

    # Display location of process output
    output = execution.processOutputs[0]
    assert output.reference == \
        'http://cida.usgs.gov/climate/gdp/process/RetrieveResultServlet?id=1318528582026OUTPUT.601bb3d0-547f-4eab-8642-7c7d2834459e'  # noqa


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN">

        <title>Trail: Learning the Java Language: Table of Contents (The Java™ Tutorials)</title>
        <meta name="description" content="This beginner Java tutorial describes fundamentals of programming in the Java programming language" />
        <meta name="keywords" content="java programming, learn java, java sample code, java objects, java classes, java inheritance, interfaces, variables, arrays, data types, operators, control flow, number, string" />

                            Download
                                the JDK

                            Search the
                                Tutorials

            Home Page

            « Previous

Trail: Learning the Java Language: Table of Contents

Object-Oriented Programming Concepts

What Is an Object?

What Is a Class?

What Is Inheritance?

What Is an Interface?

What Is a Package?

Questions and Exercises: Object-Oriented Programming Concepts

Language Basics

Variables

Primitive Data Types

Arrays

Summary of Variables

Questions and Exercises: Variables

Operators

Assignment, Arithmetic, and Unary Operators

Equality, Relational, and Conditional Operators

Bitwise and Bit Shift Operators

Summary of Operators

Questions and Exercises: Operators

Expressions, Statements, and Blocks

Questions and Exercises: Expressions, Statements, and Blocks

Control Flow Statements

The if-then and if-then-else Statements

The switch Statement

The while and do-while Statements

The for Statement

Branching Statements

Summary of Control Flow Statements

Questions and Exercises: Control Flow Statements

Classes and Objects

Classes

Declaring Classes

Declaring Member Variables

Defining Methods

Providing Constructors for Your Classes

Passing Information to a Method or a Constructor

Objects

Creating Objects

Using Objects

More on Classes

Returning a Value from a Method

Using the this Keyword

Controlling Access to Members of a Class

Understanding Instance and Class Members

Initializing Fields

Summary of Creating and Using Classes and Objects

Questions and Exercises: Classes

Questions and Exercises: Objects

Nested Classes

Inner Class Example

Summary of Nested Classes

Questions and Exercises: Nested Classes

Enum Types

Questions and Exercises: Enum Types

Annotations

Questions and Exercises: Annotations

Interfaces and Inheritance

Interfaces

Defining an Interface

Implementing an Interface

Using an Interface as a Type

Rewriting Interfaces

Summary of Interfaces

Questions and Exercises: Interfaces

Inheritance

Overriding and Hiding Methods

Polymorphism

Hiding Fields

Using the Keyword super

Object as a Superclass

Writing Final Classes and Methods

Abstract Methods and Classes

Summary of Inheritance

Questions and Exercises: Inheritance

Numbers and Strings

Numbers

The Numbers Classes

Formatting Numeric Print Output

Beyond Basic Arithmetic

Summary of Numbers

Questions and Exercises: Numbers

Characters

Strings

Converting Between Numbers and Strings

Manipulating Characters in a String

Comparing Strings and Portions of Strings

The StringBuilder Class

Summary of Characters and Strings

Questions and Exercises: Characters and Strings

Generics

Introduction

Generic Types

Generic Methods and Constructors

Type Inference

Bounded Type Parameters

Subtyping

Wildcards

Type Erasure

Using Non-Reifiable Parameters with Varargs Methods

Summary of Generics

Questions and Exercises: Generics

Packages

Creating and Using Packages

Creating a Package

Naming a Package

Using Package Members

Managing Source and Class Files

Summary of Creating and Using Packages

Questions and Exercises: Creating and Using Packages

        « Previous

Problems with the examples? Try Compiling and Running
        the Examples: FAQs.

    Complaints? Compliments? Suggestions? Give
    us your feedback.

Your use of this page and all the material on pages under "The Java Tutorials" banner,
and all the material on pages under "The Java Tutorials" banner is subject to the Java SE Tutorial Copyright
and License.
Additionally, any example code contained in any of these Java
Tutorials pages is licensed under the
Code
Sample License.

About Oracle | Oracle Technology Network | Terms of Service

Copyright © 1995, 2011 Oracle and/or its affiliates. All rights reserved.

        Previous page:

Next page:

A browser with JavaScript enabled is required for this page to operate properly.


text:
require 'jwt/json'
require 'jwt/verify'

# JWT::Decode module
module JWT
  extend JWT::Json

  # Decoding logic for JWT
  class Decode
    attr_reader :header, :payload, :signature

    def initialize(jwt, key, verify, options, &keyfinder)
      @jwt = jwt
      @key = key
      @verify = verify
      @options = options
      @keyfinder = keyfinder
    end

    def decode_segments
      header_segment, payload_segment, crypto_segment = raw_segments(@jwt, @verify)
      @header, @payload = decode_header_and_payload(header_segment, payload_segment)
      @signature = Decode.base64url_decode(crypto_segment.to_s) if @verify
      signing_input = [header_segment, payload_segment].join('.')
      [@header, @payload, @signature, signing_input]
    end

    def raw_segments(jwt, verify)
      segments = jwt.split('.')
      required_num_segments = verify ? [3] : [2, 3]
      raise(JWT::DecodeError, 'Not enough or too many segments') unless required_num_segments.include? segments.length
      segments
    end
    private :raw_segments

    def decode_header_and_payload(header_segment, payload_segment)
      header = JWT.decode_json(Decode.base64url_decode(header_segment))
      payload = JWT.decode_json(Decode.base64url_decode(payload_segment))
      [header, payload]
    end
    private :decode_header_and_payload

    def self.base64url_decode(str)
      str += '=' * (4 - str.length.modulo(4))
      Base64.decode64(str.tr('-_', '+/'))
    end

    def verify
      @options.each do |key, val|
        next unless key.to_s =~ /verify/

        Verify.send(key, payload, @options) if val
      end
    end
  end
end


text:
namespace co {

// 连接池
// @typename Connection: 连接类型
template <typename Connection>
class ConnectionPool
{
public:
    typedef std::shared_ptr<Connection> ConnectionPtr;
    typedef std::function<Connection*()> Factory;
    typedef std::function<void(Connection*)> Deleter;
    typedef std::function<bool(Connection*)> CheckAlive;

    // @Factory: 创建连接的工厂
    // @Deleter: 销毁连接, 传递NULL时会使用delete删除连接.
    // @maxConnection: 最大连接数, 0表示不限数量
    // @maxIdleConnection: 最大空闲连接数, 0表示不限数量
    // 注意:Factory和Deleter的调用可能会并行.
    explicit ConnectionPool(Factory f, Deleter d = NULL, size_t maxConnection = 0, size_t maxIdleConnection = 0)
        : factory_(f), deleter_(d), count_(0),
        maxConnection_(maxConnection),
        maxIdleConnection_(maxIdleConnection == 0 ? maxConnection : maxIdleConnection),
        channel_(maxIdleConnection_)
    {
        if (maxIdleConnection_ == 0)
            maxIdleConnection_ = maxConnection_;

        if (!deleter_) {
            deleter_ = [](Connection * ptr){ delete ptr; };
        }
    }

    ~ConnectionPool()
    {
        Connection* ptr = nullptr;
        while (channel_.TryPop(ptr)) {
            Delete(ptr);
        }
    }

    // 预创建一些连接
    // @nConnection: 连接数量, 大于maxIdleConnection_的部分无效
    void Reserve(size_t nConnection)
    {
        for (size_t i = Count(); i < maxIdleConnection_; ++i)
        {
            Connection* connection = CreateOne();
            if (!connection) break;
            if (!channel_.TryPush(connection)) {
                Delete(connection);
                break;
            }
        }
    }

    // 获取一个连接
    // 如果池空了并且连接数达到上限, 则会等待
    // 返回的智能指针销毁时, 会自动将连接归还给池
    ConnectionPtr Get(CheckAlive checkAliveOnGet = NULL,
            CheckAlive checkAliveOnPut = NULL)
    {
        Connection* connection = nullptr;
retry_get:
        if (channel_.TryPop(connection)) {
            if (checkAliveOnGet && !checkAliveOnGet(connection)) {
                Delete(connection);
                connection = nullptr;
                goto retry_get;
            }

            return Out(connection, checkAliveOnPut);
        }

        connection = CreateOne();
        if (connection)
            return Out(connection, checkAliveOnPut);

        channel_ >> connection;
        if (checkAliveOnGet && !checkAliveOnGet(connection)) {
            Delete(connection);
            connection = nullptr;
            goto retry_get;
        }

        return Out(connection, checkAliveOnPut);
    }

    // 获取一个连接
    // 如果池空了并且连接数达到上限, 则会等待
    // 返回的智能指针销毁时, 会自动将连接归还给池
    //
    // @timeout: 等待超时时间, 仅在协程中有效, 例: std::chrono::seconds(1)
    // @checkAliveOnGet: 申请时检查连接是否还有效
    // @checkAliveOnPut: 归还时检查连接是否还有效
    ConnectionPtr Get(FastSteadyClock::duration timeout,
            CheckAlive checkAliveOnGet = NULL,
            CheckAlive checkAliveOnPut = NULL)
    {
        FastSteadyClock::time_point deadline = FastSteadyClock::now() + timeout;
        Connection* connection = nullptr;
retry_get:
        if (channel_.TryPop(connection)) {
            if (checkAliveOnGet && !checkAliveOnGet(connection)) {
                Delete(connection);
                connection = nullptr;
                goto retry_get;
            }

            return Out(connection, checkAliveOnPut);
        }

        connection = CreateOne();
        if (connection)
            return Out(connection, checkAliveOnPut);

        if (channel_.TimedPop(connection, deadline)) {
            if (checkAliveOnGet && !checkAliveOnGet(connection)) {
                Delete(connection);
                connection = nullptr;
                goto retry_get;
            }

            return Out(connection, checkAliveOnPut);
        }

        return ConnectionPtr();
    }

    size_t Count()
    {
        return count_;
    }

private:
    Connection* CreateOne()
    {
        if (++count_ > maxConnection_) {
            --count_;
            return nullptr;
        }

        // return factory_();
        Connection *ret = factory_();
        if(!ret)
            --count_;
        return ret;
    }

    void Put(Connection* connection)
    {
        if (!channel_.TryPush(connection)) {
            Delete(connection);
        }
    }

    void Delete(Connection* connection)
    {
        --count_;
        deleter_(connection);
    }

    ConnectionPtr Out(Connection* connection, CheckAlive checkAliveOnPut)
    {
        if (!connection)
            return ConnectionPtr(NULL); // add by huangbt 2020-4-26
        return ConnectionPtr(connection, [this, checkAliveOnPut](Connection* ptr){
                    if (checkAliveOnPut && !checkAliveOnPut(ptr)) {
                        this->Delete(ptr);
                        return ;
                    }

                    this->Put(ptr);
                });
    }

private:
    Factory factory_;
    Deleter deleter_;
    std::atomic<size_t> count_;
    size_t maxConnection_;
    size_t maxIdleConnection_;
    Channel<Connection*> channel_;
};

} // namespace co


text:
package org.apache.pinot.core.data.recordtransformer;

import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.pinot.core.data.function.FunctionEvaluator;
import org.apache.pinot.core.data.function.FunctionEvaluatorFactory;
import org.apache.pinot.spi.config.table.TableConfig;
import org.apache.pinot.spi.config.table.ingestion.TransformConfig;
import org.apache.pinot.spi.data.FieldSpec;
import org.apache.pinot.spi.data.Schema;
import org.apache.pinot.spi.data.readers.GenericRow;

/**
 * The {@code ExpressionTransformer} class will evaluate the function expressions.
 * <p>NOTE: should put this before the {@link DataTypeTransformer}. After this, transformed column can be treated as
 * regular column for other record transformers.
 */
public class ExpressionTransformer implements RecordTransformer {

  private final LinkedHashMap<String, FunctionEvaluator> _expressionEvaluators = new LinkedHashMap<>();

  public ExpressionTransformer(TableConfig tableConfig, Schema schema) {
    Map<String, FunctionEvaluator> expressionEvaluators = new HashMap<>();
    if (tableConfig.getIngestionConfig() != null && tableConfig.getIngestionConfig().getTransformConfigs() != null) {
      for (TransformConfig transformConfig : tableConfig.getIngestionConfig().getTransformConfigs()) {
        expressionEvaluators.put(transformConfig.getColumnName(),
            FunctionEvaluatorFactory.getExpressionEvaluator(transformConfig.getTransformFunction()));
      }
    }
    for (FieldSpec fieldSpec : schema.getAllFieldSpecs()) {
      String fieldName = fieldSpec.getName();
      if (!fieldSpec.isVirtualColumn() && !expressionEvaluators.containsKey(fieldName)) {
        FunctionEvaluator functionEvaluator = FunctionEvaluatorFactory.getExpressionEvaluator(fieldSpec);
        if (functionEvaluator != null) {
          expressionEvaluators.put(fieldName, functionEvaluator);
        }
      }
    }

    // Sort the transform functions based on dependencies
    Set<String> visited = new HashSet<>();
    for (Map.Entry<String, FunctionEvaluator> entry : expressionEvaluators.entrySet()) {
      topologicalSort(entry.getKey(), expressionEvaluators, visited);
    }
  }

  private void topologicalSort(String column, Map<String, FunctionEvaluator> expressionEvaluators, Set<String> visited) {
    if (visited.contains(column)) {
      return;
    }
    FunctionEvaluator functionEvaluator = expressionEvaluators.get(column);
    if (functionEvaluator == null) {
      visited.add(column);
      return;
    }
    List<String> arguments = functionEvaluator.getArguments();
    for (String arg : arguments) {
      topologicalSort(arg, expressionEvaluators, visited);
    }
    visited.add(column);
    _expressionEvaluators.put(column, functionEvaluator);
  }

  @Override
  public GenericRow transform(GenericRow record) {
    for (Map.Entry<String, FunctionEvaluator> entry : _expressionEvaluators.entrySet()) {
      String column = entry.getKey();
      FunctionEvaluator transformFunctionEvaluator = entry.getValue();
      // Skip transformation if column value already exist.
      // NOTE: column value might already exist for OFFLINE data
      if (record.getValue(column) == null) {
        Object result = transformFunctionEvaluator.evaluate(record);
        record.putValue(column, result);
      }
    }
    return record;
  }
}


text:
[![Build Status](https://travis-ci.org/JohnGiorgi/Alfred.svg?branch=master)](https://travis-ci.org/JohnGiorgi/Alfred)
[![Codacy Badge](https://api.codacy.com/project/badge/Grade/602b339a97574424aad9175a6cf56b9e)](https://app.codacy.com/app/JohnGiorgi/Alfred?utm_source=github.com&utm_medium=referral&utm_content=JohnGiorgi/Alfred&utm_campaign=Badge_Grade_Dashboard)
[![Coverage Status](https://coveralls.io/repos/github/JohnGiorgi/Alfred/badge.svg?branch=master)](https://coveralls.io/github/JohnGiorgi/Alfred?branch=master)

# Alfred

Alfred is a Python application built using the web-framework [Flask](https://github.com/pallets/flask/). Inbound SMS sent to your Twilio phone number are forwarded to Alfred as a HTTP request. Alfred intelligently generates a response (SMS to the sender via a HTTP POST request to Twilio) and an action (e.g.: turning off the lights in your home).

### Table of Contents
1. [Setup](#setup)
  -  [Get Twilio Number](#get-number)
  - [Setup Virtual Environment (Optional)](#virtual-env)
  - [Install and Run](#install)
2. [Connect to services](#connect)
  - [Phillips Hue](#hue)
  - [OWM](#owm)
  - [Nest Learning Thermostat](#nest)
  - [WolframAlpha](#wolfram)
3. [What can you ask Alfred to do?](#ask-alfred)
4. [Changelog](#change-log)

## Setup

### Get a Twilio Number

First you need a Twilio phone number capable of sending and receiving SMS messages. You can get a number with your free trial [here](https://www.twilio.com/try-twilio).

### Setting up a Virtual Environment (OPTIONAL)

It is recommended that you set up a virtual environment. See [here](https://conda.io/docs/using/envs.html) for how to activate
a `conda` environment. The environment can be activated by calling `source activate <env name>`.

### Install and Run

1. Navigate to the directory you want to save smsbot to, and `git clone` there. Or download the source code as a `.zip`.
2. Activate your environment from the previous step (optional).
3. If you plan on using all features of Alfred, then run `pip install -r requirements.txt` from within the cloned directory. Otherwise take a look at `requirements.txt` and `pip install` the features that you want (`flask`, `twilio` and `nltk` are required).
3. Run the main script: `python src/run_alfred.py`. Note the port reported by Flask on the command line, ex: 'Running on http://XXX.X.X.X:5000/'
4. Install `ngrok` (download [here](https://ngrok.com/)) and add it to your `PATH`.
5. Run ngrok: `ngrok http <port>`, where port would be **5000** from the example above. Note the **forwarding address** reported by ngrok on the command line, ex: 'http://XXXXXXXX.ngrok.io'
6. Copy and past one of the **forwarding addresses** into the "A MESSAGE COMES IN" field on the Twilio dashboard (from the dashboard, click the '#' then your phone number and scroll down to "Messaging"). Make sure the drop down is set to "**Webhook**".

### Setting up each service

#### Phillips Hue

If you plan on using the script with the Philips Hue Bridge, there are a few extra steps:
1. Make sure that in `/src/config.ini` you have set `bridgeIP` to the **IP** of your Bridge. Instructions on how to find that [here](https://developers.meethue.com/documentation/getting-started).
2. Before running the script for the first time, press the button on the Hue Bridge. Then, within 30 seconds call the script and pass the `--connectBridge` flag (you only have to do this **once**).
3. That's it. Try texting your Twilio number 'Turn on all the lights please!' to make sure things are working.

*Note, you can also run* `python src/run_alfred.py --setup` *and Alfred will walk you through this process and modify the configuration file for you*.

#### Weather
Requests for weather information rely on the OpenWeatherMap.org API. An API key is already provided with Alfred, but if you would prefer to use your own sign up [here](https://openweathermap.org/), then go to **API Keys** and copy your key to the config file (at `/src/config.ini`).

#### Nest Learning Thermostat
Coming soon.

#### WolframAlpha
Coming soon.

## What can you ask Alfred to do?

- Example 1: "Turn on the lights" <turns on all lights>
- Example 2: "Turn on the bedroom lights" <turns on all lights in the Phillips hue group 'Bedroom', if this group exists>
- Example 3: "Dim the living room lights" <sets all lights in the Phillips hue group 'Living room' to 15% intensity>
- Example 4: "Set the lights to 50%" <sets all lights to 50% intensity>
- Example 5: "Warm the bedroom lights" <sets all lights in the Phillips hue group 'Bedroom' to the warmest end of the spectrum>
- Example 6: "Set the living room lights blue" <sets all lights in the Phillips hue group 'Living room' to blue>
- Example 7: "Wiki Barack Obama" <returns wiki summary with link>
- Example 8: "What is the weather like in New York City?" <returns weather summary for location>

## Changelog

**Latest commits**:
- Added the ability to set light colors. Try "Set bedroom lights green"
- Added two new command "Warm the lights" and "Cool the lights"


text:
function hline(line_width, line_opacity) {
    var line = createElement(div);
    css(line, "width:100%;height:" + line_width + "px;background-color:#000;");
    line_opacity && setOpacity(line, line_opacity);
    return line;
}