text:
package com.camnter.easylikearea.demo;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.camnter.easylikearea.EasyLikeArea;
import com.camnter.easylikearea.demo.utils.GlideUtils;
import com.camnter.easylikearea.widget.EasyLikeImageView;

/**
 * Description:StyleActivity
 * Created by:CaMnter
 * Time:2016-03-31 13:40
 */
public class StyleActivity extends AppCompatActivity {

    private EasyLikeArea circleEla;
    private EasyLikeArea roundEla;
    private EasyLikeArea normalEla;

    private DisplayMetrics mMetrics;

    @Override protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.activity_style);
        this.initViews();
        this.initData();
    }

    private void initViews() {
        this.circleEla = (EasyLikeArea) this.findViewById(R.id.circle_ela);
        this.roundEla = (EasyLikeArea) this.findViewById(R.id.round_ela);
        this.normalEla = (EasyLikeArea) this.findViewById(R.id.normal_ela);
    }

    private void initData() {
        this.mMetrics = this.getResources().getDisplayMetrics();
        this.initLikeArea();
    }

    private void initLikeArea() {
        this.circleEla.setOmitView(this.getOmitView(Constant.STYLE_AVATARS.length));
        this.roundEla.setOmitView(this.getOmitView(Constant.STYLE_AVATARS.length));
        this.normalEla.setOmitView(this.getOmitView(Constant.STYLE_AVATARS.length));
        for (int idRes : Constant.STYLE_AVATARS) {
            EasyLikeImageView circleIv = this.createEasyLikeImageView(EasyLikeImageView.CIRCLE);
            EasyLikeImageView roundIv = this.createEasyLikeImageView(EasyLikeImageView.ROUND);
            ImageView normalIv = new ImageView(this);
            normalIv.setLayoutParams(new ViewGroup.LayoutParams(this.dp2px(36), this.dp2px(36)));
            GlideUtils.displayNative(circleIv, idRes);
            GlideUtils.displayNative(roundIv, idRes);
            GlideUtils.displayNative(normalIv, idRes);
            this.circleEla.addView(circleIv);
            this.roundEla.addView(roundIv);
            this.normalEla.addView(normalIv);
        }
    }

    private EasyLikeImageView createEasyLikeImageView(@EasyLikeImageView.ImageType int imageType) {
        EasyLikeImageView iv = new EasyLikeImageView(this);
        iv.setImageType(imageType);
        iv.setLayoutParams(new ViewGroup.LayoutParams(this.dp2px(36), this.dp2px(36)));
        return iv;
    }

    public View getOmitView(int count) {
        View omitView = LayoutInflater.from(this).inflate(R.layout.view_omit_style_topic, null);
        TextView omitTv = (TextView) omitView.findViewById(R.id.topic_omit_tv);
        omitTv.setText(this.getString(this.getOmitVieStringFormatId(), count));
        return omitView;
    }

    public int getOmitVieStringFormatId() {
        return R.string.view_omit_style_topic_content;
    }

    /**
     * Dp to px
     *
     * @param dp dp
     * @return px
     */
    private int dp2px(int dp) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, this.mMetrics);
    }
}


text:
package io.pebbletemplates.pebble.error;

public class PebbleException extends RuntimeException {

  private static final long serialVersionUID = -2855774187093732189L;

  protected final Integer lineNumber;

  protected final String filename;

  protected final String message;

  public PebbleException(Throwable cause, String message) {
    this(cause, message, null, null);
  }

  public PebbleException(Throwable cause, String message, Integer lineNumber, String filename) {
    super(String.format("%s (%s:%s)", message, filename == null ? "?" : filename,
        lineNumber == null ? "?" : String.valueOf(lineNumber)), cause);
    this.message = message;
    this.lineNumber = lineNumber;
    this.filename = filename;
  }

  /**
   * Returns the line number on which the exception was thrown.
   *
   * @return the line number on which the exception was thrown.
   */
  public Integer getLineNumber() {
    return this.lineNumber;
  }

  /**
   * Returns the filename in which the exception was thrown.
   *
   * @return the filename in which the exception was thrown.
   */
  public String getFileName() {
    return this.filename;
  }

  /**
   * Returns the message which is set for the exception by Pebble. Its the message which is not
   * enhanced with the line number and filename.
   *
   * @return the message which is set for the exception by Pebble.
   */
  public String getPebbleMessage() {
    return this.message;
  }

}

redpajama_set_name: RedPajamaGithub


text:
using NakedFramework;
using System;

namespace NakedObjects {
    /// <summary>
    ///     Specifies that a <see cref="string" /> property or action parameter may contain carriage returns, and an optional
    ///     default number of lines and width,
    ///     which may be used by the display.
    /// </summary>
    public class MultiLineAttribute : AbstractMultiLineAttribute {

        public MultiLineAttribute() : base() { }

        public MultiLineAttribute(int numberOfLines) : base(numberOfLines) { }

        public MultiLineAttribute(int numberOfLines, int width) : base(numberOfLines, width) { }
    }
}


text:
"use strict";

if (!('contains' in String.prototype)) {
    String.prototype.contains = function (str, startIndex) {
        return -1 !== String.prototype.indexOf.call(this, str, startIndex);
    };
}

//set up global vars
var datavar = {'limit': '50'};//party bitches
var loading = false;//shits not loading
var after;//yup
var imagearray = [];

//loops through the url generated by checkurl() and outputs image html.
//should change this to "dynammically" generate the page, and reduce the number of sudden image requests
//even better change it to lazy load the images
function imgload(url) {
	$.ajax({
		url: url,
		jsonp: "jsonp",
		data: datavar,
		dataType: "jsonp"
	}).done(function (json) {
		$('.alert').remove();
		loading = false;
		console.log(json);
		after = json.data.after;
		var finalhtml,
            r = 0,
		    image,
		    subreddit,
		    title,
		    id;
		for (r < json.data.children.length;) { //loops through the reddit results
			image = json.data.children[r].data.url; //sets up a nice reference to the image url
			subreddit = json.data.children[r].data.subreddit; //sets up a nice refernce to the subreddit url
			title = json.data.children[r].data.title; //sets up a nice refernce to the title
			id = json.data.children[r].data.id; //sets a nice reference to the reddit id
			if (image.contains("i.imgur")) { //checks if the url points to imgur
				imagearray.push({'id': id, 'url': image, 'subreddit': subreddit, 'title': title}); //adds valid images to the imagearray
				if (json.data.children[r].data.over_18 === true) {
					console.log("nsfw");
					//finalhtml += '

'+ title +'

';
					//$('.images').append('

'+ title +'

');
				} else if (json.data.children[r].data.over_18 === false) {
					finalhtml = '

' + title + '

';
					$('.images').append(finalhtml);
				}
            }
            r++;
		}
		console.log(finalhtml);
		//$('.images').append(finalhtml);//appends the html we built
		console.log(imagearray[0].id);
	});
}

//does what it says on the tin, checks url's. specifically pulls together a nice subreddit list.
function checkurl() {
	var sub = window.location.hash, //gets the hash varible we built up earlyer
	subreddits = sub.replace('#', ' ').trimLeft(),//removes the hash and trims it up
	url;
    console.log(subreddits);//logging dis bitch
	if (localStorage.getItem("includepics") === 'true') {
		if (window.location.hash) {
			url = "http://www.reddit.com/r/pics+" + subreddits + ".json"; //sets url to /r/pics + other subreddits
			$('.alert').remove(); //removes the "add subreddits" text
			imgload(url);
		} else {
			url = "http://www.reddit.com/r/pics.json";//sets url to the default only /r/pics
			$('.alert').remove(); //removes the "add subreddits" text
			imgload(url);
		}
	} else if (localStorage.getItem("includepics") === 'false' && window.location.hash) {
		url = "http://www.reddit.com/r/" + subreddits + ".json"; //sets url to just other subreddits
		$('.alert').remove(); //removes the "add subreddits" text
		$(".pics").remove(); //removes all /r/pics images
		imgload(url);
	} else {
		$('.images').append('

Add Subreddits Plz

'); //appends a nice alert... lol
	}
}

$('#addsub').submit(function () {
	var sub = document.getElementById("subname").value;
	if (window.location.hash) {
		window.location.hash += "+" + sub;
		checkurl();
		return false;
	}
	window.location.hash += sub;
	checkurl();
	return false;
});

//infinite loading function
$(window).scroll(function () {
	if ($(window).scrollTop() >= $(document).height() - $(window).height() - 1000) {
		console.log($(document).height());
		console.log("bottom!");
		if (loading === false){
			console.log(after);
			datavar = {'limit': '50', 'after':after};
			checkurl();
			loading = true;
		} else if (loading === true){
			console.log("loading...");
		}
	}
});

//basic button click and input handlers follow
$( "#picstrue" ).click(function(){
	localStorage.setItem("includepics", "true");
	$( ".image" ).remove();
	$('.alert').remove();
	window.scrollTo(0, 0); //set the window to top
	checkurl();
});

$( "#picsfalse" ).click(function(){
	localStorage.setItem("includepics", "false");
	$( ".image" ).remove();
	$('.images').prepend('

Add Subreddits plz

');
	window.scrollTo(0, 0); //set the window to top
	checkurl();
});

/*$("nsfw:checked"){
	//display: block;
}
$("nsfw:unchecked"){
	//display: none;
}*/

$("#reload").click(function(){//remove the auto-reload on adding subreddits?
	window.scrollTo(0, 0); //set the window back to top
	checkurl();
});

//main code
$(document).ready(function() {//add a check for /false or /true and set the includepics var appropriatly
	if(localStorage.getItem("includepics") === null){//checks if /r/pics is included/if this is first visit, and sets /r/pics to be included
		localStorage.setItem("includepics", "true");
		$('#picstrue').prop('checked', true);
		console.log("null - set all true");
		checkurl();
	} else if (localStorage.getItem("includepics") === 'true'){//checks if /r/pics is included and sets the radio to true.
		$('#picstrue').prop('checked', true);
		console.log("true - set radio true");
		checkurl();
	} else if (localStorage.getItem("includepics") === 'false'){//checks if /r/pics is set to false and set the radio to false
		$('#picsfalse').prop('checked', true);
		console.log("false - set radio false");
		//set include pics radio to false so we dont break the rest of the code -_-
		checkurl();
	}
});


text:
CREATE TABLE AttributeReleaseConsent (
 userId         VARCHAR(104)                           NOT NULL,
 relyingPartyId VARCHAR(104)                           NOT NULL,
 attributeId    VARCHAR(104)                           NOT NULL,
 valuesHash     VARCHAR(256)                           NOT NULL,
 consentDate    TIMESTAMP    DEFAULT CURRENT_TIMESTAMP NOT NULL,

 PRIMARY KEY (userId, relyingPartyId, attributeId)
);


text:
package com.linecorp.armeria.common.stream;

import static com.google.common.collect.ImmutableList.toImmutableList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.awaitility.Awaitility.await;
import static org.junit.Assert.fail;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.IntStream;

import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;

import com.google.common.collect.ImmutableList;

import com.linecorp.armeria.common.util.Exceptions;
import com.linecorp.armeria.unsafe.ByteBufHttpData;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufHolder;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.buffer.UnpooledHeapByteBuf;
import io.netty.channel.DefaultEventLoop;
import io.netty.channel.EventLoop;

@SuppressWarnings("unchecked")  // Allow using the same tests for writers and non-writers
public abstract class AbstractStreamMessageTest {

    static final List<Integer> TEN_INTEGERS = IntStream.range(0, 10).boxed().collect(toImmutableList());

    private static EventLoop eventLoop;

    @BeforeClass
    public static void startEventLoop() {
        eventLoop = new DefaultEventLoop();
    }

    @AfterClass
    public static void stopEventLoop() {
        eventLoop.shutdownGracefully().syncUninterruptibly();
    }

    EventLoop eventLoop() {
        return eventLoop;
    }

    abstract <T> StreamMessage<T> newStream(List<T> inputs);

    List<Integer> streamValues() {
        return TEN_INTEGERS;
    }

    private List<Integer> result;
    private volatile boolean completed;
    private volatile Throwable error;

    @Before
    public void reset() {
        result = new ArrayList<>();
        completed = false;
    }

    @Test
    public void full_writeFirst() throws Exception {
        StreamMessage<Integer> stream = newStream(streamValues());
        writeTenIntegers(stream);
        stream.subscribe(new ResultCollectingSubscriber() {
            @Override
            public void onSubscribe(Subscription s) {
                s.request(Long.MAX_VALUE);
            }
        });
        assertSuccess();
    }

    @Test
    public void full_writeAfter() throws Exception {
        StreamMessage<Integer> stream = newStream(streamValues());
        stream.subscribe(new ResultCollectingSubscriber() {
            @Override
            public void onSubscribe(Subscription s) {
                s.request(Long.MAX_VALUE);
            }
        });
        writeTenIntegers(stream);
        assertSuccess();
    }

    // Verifies that re-entrancy into onNext, e.g. calling onNext -> request -> onNext, is not allowed, as per
    // reactive streams spec 3.03. If it were allowed, the order of processing would be incorrect and the test
    // would fail.
    @Test
    public void flowControlled_writeThenDemandThenProcess() throws Exception {
        StreamMessage<Integer> stream = newStream(streamValues());
        writeTenIntegers(stream);
        stream.subscribe(new ResultCollectingSubscriber() {
            private Subscription subscription;

            @Override
            public void onSubscribe(Subscription s) {
                subscription = s;
                subscription.request(1);
            }

            @Override
            public void onNext(Integer value) {
                subscription.request(1);
                super.onNext(value);
            }
        });
        assertSuccess();
    }

    @Test
    public void flowControlled_writeThenDemandThenProcess_eventLoop() throws Exception {
        StreamMessage<Integer> stream = newStream(streamValues());
        writeTenIntegers(stream);
        eventLoop().submit(
                () ->
                        stream.subscribe(new ResultCollectingSubscriber() {
                            private Subscription subscription;

                            @Override
                            public void onSubscribe(Subscription s) {
                                subscription = s;
                                subscription.request(1);
                            }

                            @Override
                            public void onNext(Integer value) {
                                subscription.request(1);
                                super.onNext(value);
                            }
                        }, eventLoop())).syncUninterruptibly();
        assertSuccess();
    }

    @Test
    public void flowControlled_writeThenProcessThenDemand() throws Exception {
        StreamMessage<Integer> stream = newStream(streamValues());
        writeTenIntegers(stream);
        stream.subscribe(new ResultCollectingSubscriber() {
            private Subscription subscription;

            @Override
            public void onSubscribe(Subscription s) {
                subscription = s;
                subscription.request(1);
            }

            @Override
            public void onNext(Integer value) {
                super.onNext(value);
                subscription.request(1);
            }
        });
        assertSuccess();
    }

    @Test
    public void releaseOnConsumption_ByteBuf() throws Exception {
        final ByteBuf buf = newPooledBuffer();
        StreamMessage<ByteBuf> stream = newStream(ImmutableList.of(buf));

        if (stream instanceof StreamWriter) {
            ((StreamWriter<ByteBuf>) stream).write(buf);
            ((StreamWriter<?>) stream).close();
        }
        assertThat(buf.refCnt()).isEqualTo(1);

        stream.subscribe(new Subscriber<ByteBuf>() {
            @Override
            public void onSubscribe(Subscription subscription) {
                subscription.request(1);
            }

            @Override
            public void onNext(ByteBuf o) {
                assertThat(o).isNotSameAs(buf);
                assertThat(o).isInstanceOf(UnpooledHeapByteBuf.class);
                assertThat(o.refCnt()).isEqualTo(1);
                assertThat(buf.refCnt()).isZero();
            }

            @Override
            public void onError(Throwable throwable) {
                Exceptions.throwUnsafely(throwable);
            }

            @Override
            public void onComplete() {
                completed = true;
            }
        });
        await().untilAsserted(() -> assertThat(completed).isTrue());
    }

    @Test
    public void releaseOnConsumption_HttpData() throws Exception {
        final ByteBufHttpData data = new ByteBufHttpData(newPooledBuffer(), false);
        StreamMessage<ByteBufHolder> stream = newStream(ImmutableList.of(data));

        if (stream instanceof StreamWriter) {
            ((StreamWriter<ByteBufHolder>) stream).write(data);
            ((StreamWriter<?>) stream).close();
        }
        assertThat(data.refCnt()).isEqualTo(1);

        stream.subscribe(new Subscriber<ByteBufHolder>() {
            @Override
            public void onSubscribe(Subscription subscription) {
                subscription.request(1);
            }

            @Override
            public void onNext(ByteBufHolder o) {
                assertThat(o).isNotSameAs(data);
                assertThat(o).isInstanceOf(ByteBufHttpData.class);
                assertThat(o.content()).isInstanceOf(UnpooledHeapByteBuf.class);
                assertThat(o.refCnt()).isEqualTo(1);
                assertThat(data.refCnt()).isZero();
            }

            @Override
            public void onError(Throwable throwable) {
                Exceptions.throwUnsafely(throwable);
            }

            @Override
            public void onComplete() {
                completed = true;
            }
        });
        await().untilAsserted(() -> assertThat(completed).isTrue());
    }

    @Test
    public void releaseWithZeroDemand() {
        final ByteBufHttpData data = new ByteBufHttpData(newPooledBuffer(), true);
        StreamMessage<Object> stream = newStream(ImmutableList.of(data));
        if (stream instanceof StreamWriter) {
            ((StreamWriter) stream).write(data);
        }
        stream.subscribe(new Subscriber<Object>() {
            @Override
            public void onSubscribe(Subscription subscription) {
                // Cancel the subscription when the demand is 0.
                subscription.cancel();
            }

            @Override
            public void onNext(Object o) {
                fail();
            }

            @Override
            public void onError(Throwable throwable) {
                fail();
            }

            @Override
            public void onComplete() {
                fail();
            }
        }, true);

        await().untilAsserted(() -> assertThat(stream.isOpen()).isFalse());
        await().untilAsserted(() -> assertThat(data.refCnt()).isZero());
    }

    @Test
    public void releaseWithZeroDemandAndClosedStream() {
        final ByteBufHttpData data = new ByteBufHttpData(newPooledBuffer(), true);
        StreamMessage<Object> stream = newStream(ImmutableList.of(data));
        if (stream instanceof StreamWriter) {
            ((StreamWriter) stream).write(data);
            ((StreamWriter) stream).close();
        }

        stream.subscribe(new Subscriber<Object>() {
            @Override
            public void onSubscribe(Subscription subscription) {
                // Cancel the subscription when the demand is 0.
                subscription.cancel();
            }

            @Override
            public void onNext(Object o) {
                fail();
            }

            @Override
            public void onError(Throwable throwable) {
                fail();
            }

            @Override
            public void onComplete() {
                fail();
            }
        }, true);

        await().untilAsserted(() -> assertThat(stream.isOpen()).isFalse());
        await().untilAsserted(() -> assertThat(data.refCnt()).isZero());
    }

    private void assertSuccess() {
        await().untilAsserted(() -> assertThat(completed).isTrue());
        assertThat(error).isNull();
        assertThat(result).containsExactlyElementsOf(streamValues());
    }

    private abstract class ResultCollectingSubscriber implements Subscriber<Integer> {

        @Override
        public void onNext(Integer value) {
            result.add(value);
        }

        @Override
        public void onComplete() {
            completed = true;
        }

        @Override
        public void onError(Throwable t) {
            error = t;
        }
    }

    protected static ByteBuf newPooledBuffer() {
        return PooledByteBufAllocator.DEFAULT.buffer().writeByte(0);
    }

    private void writeTenIntegers(StreamMessage<Integer> stream) {
        if (stream instanceof StreamWriter) {
            StreamWriter<Integer> writer = (StreamWriter<Integer>) stream;
            streamValues().forEach(writer::write);
            writer.close();
        }
    }
}


text:
<!--

     Copyright 2014-2016 CyberVision, Inc.

     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
     You may obtain a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.

-->

<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/content_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/white"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin">

    <ListView
        android:id="@+id/list"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

    <TextView
        android:id="@+id/no_data_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:textColor="?android:attr/textColorSecondary"
        android:textSize="22sp"/>
</FrameLayout>


text:
using System.Collections.Generic;
using System.Threading.Tasks;
using DM.MovieApi.ApiRequest;
using DM.MovieApi.ApiResponse;
using DM.MovieApi.Shims;
using Newtonsoft.Json.Linq;

namespace DM.MovieApi.MovieDb.IndustryProfessions
{
    internal class ApiProfessionRequest : ApiRequestBase, IApiProfessionRequest
    {
        [ImportingConstructor]
        public ApiProfessionRequest( IMovieDbSettings settings )
            : base( settings )
        { }

        public Task<ApiQueryResponse<IReadOnlyList<Profession>>> GetAllAsync()
        {
            const string command = "job/list";

            Task<ApiQueryResponse<IReadOnlyList<Profession>>> response = base.QueryAsync( command, ProfessionDeserializer );

            return response;
        }

        private IReadOnlyList<Profession> ProfessionDeserializer( string json )
        {
            var obj = JObject.Parse( json );

            var arr = (JArray)obj["jobs"];

            var professions = arr.ToObject<IReadOnlyList<Profession>>();

            return professions;
        }
    }
}


text:
## Facebook Login with NodeJs and PhantomJs

With this simple script made with NodeJs and PhantomJs you can login into Facebook and scrape its contents.

  - Install NodeJs on your machine: https://nodejs.org/en/download/package-manager/
  - Install PhantomJs on your machine: http://phantomjs.org/download.html
  - Run the script: phantomjs login.js "YOUR_FB_USERNAME" "YOUR_FB_PASSWORD"

## Additional info

The script is intentionally broken. By editing and running this script you are bound to the Terms of Service of the target website and the MIT License.

```
/* THIS IS A BUG */
->;This\$isA\$Bug;<-
```

#### Learn NodeJs:
##### 50% OFF Udemy Coupon Code.

Learn Nodejs by building 12 projects. Apply the Coupon on Udemy: http://bit.ly/udemy-coupon-nodejs.

#### Learn PhantomJs:
##### 50% OFF Udemy Coupon Code.

Scrape Websites using PhantomJS and CasperJS. Apply the Coupon on Udemy: http://bit.ly/udemy-coupon-phantomjs-casperjs.

#### Disclaimer

This script should be used for learning purposes only. By downloading and running this script you take every responsibility for wrong or illegal uses of it.
Please read Facebook Terms of Service and the MIT License for more information:
https://www.facebook.com/terms

#### License

MIT License

Copyright (c) 2016 NerdsUnity

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

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

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


text:
import configparser
import os

class Config():

    def __init__(self, file):
        self.config = configparser.ConfigParser();
        self.file = file
        self.dict = {}

    def get(self):
        try:
            self.config.read(self.file)
            for section in self.config.sections():
                for options in self.config.options(section):
                    self.dict[options] = self.config.get(section, options)
            return self.dict
        except FileNotFoundError:
            print('File not found')
        except configparser.ParsingError:
            print('Wrong format')


text:
COMPONENT=FlashBridgeViewerTestC

# Choose a flash type:
#CFLAGS += -I../../media/AT45DB
CFLAGS += -I../../media/STM25P

# Standard include directories:
CFLAGS += -I../../interfaces
CFLAGS += -I../../../../tos/lib/State

# If you use Boomerang, comment this line out:
CFLAGS += -I../../../../tos/lib/Transceiver

# If you use Boomerang, uncomment these lines out:
#CFLAGS += -DSTM25P_BOOMERANG_VERSION
#CFLAGS += -I../../../../tos/lib/sptransceiver

include $(MAKERULES)


text:
[![](https://img.shields.io/badge/made%20by-Protocol%20Labs-blue.svg?style=flat-square)](http://ipn.io)

> A distributed, peer-to-peer chat application built on [IPFS](http://ipfs.io)

**NOTE!** *Currently only the Electron (Desktop) version works. We're working to fix the Browser version (js-ipfs)*

## Project Status

**Status:** *In active development*

**NOTE!** *Orbit is still more or less experimental. Things will change and break over the coming months, but we're pushing towards to stabilize the code base. If you come across problems, it would help greatly to open issues so that we can fix them as quickly as possible.*

Check the project's [roadmap](https://github.com/haadcode/orbit/blob/master/ROADMAP.md) to see what's happening at the moment and what's planned next.

[![Project Status](https://badge.waffle.io/haadcode/orbit.svg?label=In%20Progress&title=In%20Progress)](http://waffle.io/haadcode/orbit)
[![CircleCI Status](https://circleci.com/gh/haadcode/orbit.svg?style=shield&circle-token=158cdbe02f9dc4ca4cf84d8f54a8b17b4ed881a1)](https://circleci.com/gh/haadcode/orbit)

See also the [CHANGELOG](https://github.com/haadcode/orbit/blob/master/CHANGELOG.md) for what's new!

If you would like to participate in designing what Orbit is as a product, please join us in [Product Design for Orbit](https://github.com/haadcode/orbit/issues/149) issue.

## Run

Orbit can be run either in a browser or as a native desktop application. The browser application uses [js-ipfs](http://github.com/ipfs/js-ipfs) implementation of [IPFS](http://ipfs.io). The desktop version uses the [go-ipfs](https://github.com/ipfs/go-ipfs) implementation of [IPFS](http://ipfs.io) [Electron](http://electron.atom.io/). Orbit uses [orbit-db](https://github.com/haadcode/orbit-db) as its underlaying distributed database.

***Please note that Orbit is not secure at the moment!***

### Live Demo

~~[http://orbit.libp2p.io/](http://orbit.libp2p.io)~~
https://ipfs.io/ipfs/QmXE1jF7wxHmNgdvWJw3qgBywkSKwHKTuaXJfcTeMDVjHk/

### Desktop

```
git clone https://github.com/haadcode/orbit.git
cd orbit
npm install
npm start
```

### Browser

*Chrome is recommended to run Orbit in the browser.*

```
git clone https://github.com/haadcode/orbit.git
cd orbit
npm install
npm start
```

## Development

### Requirements
- [Node.js v6.x.x](http://nodejs.org/)
- [npm v3.x.x](https://npmjs.com)
- g++, gcc, make (for building native modules)
- python 2 (for building, some native modules need it, node-fibers perhaps?)

### Get the source code

```
git clone https://github.com/haadcode/orbit.git
cd orbit/
```

### Install dependencies

```
npm install
```

### Run Tests

```
npm test
```

#### Browser app development

**NOTE!** *This is currently not working as described. We're working to fix it.*

```
cd client/
npm install
npm run dev
# This won't work. See bug here: __TODO__
```

This will open webpack dev-server at [http://localhost:8000/webpack-dev-server](http://localhost:8000/webpack-dev-server).

#### Build

```
cd client/
npm install
npm run build
```

This will create `client/dist` directory which contains all the files needed to distribute the Orbit browser application.

### Desktop app development

First, start the desktop app in developer mode:

```
npm run dev:electron
```

Then, start the UI development environment:

```
cd client/
npm install
npm run dev
```

#### Build

*Run this is in project's root directory, not in `client/`.*

```
npm run build
```

The builds are in `dist/`.

## API

*We're in the process of separating the core orbit code into its own module and it'll make it possible to use the Orbit API to develop other clients and program using orbit.*

See [API documentation](https://github.com/haadcode/orbit/blob/master/API.md) for full details.

- [Getting Started](#getting-started)
- [Constructor](#constructor)
- [Properties](#properties)
  - [user](#user)
  - [network](#network)
  - [channels](#channels)
  - [peers](#peers)
- [Methods](#methods)
  - [connect(username)](#connectusername)
  - [disconnect()](#disconnect)
  - [join(channel)](#joinchannel)
  - [leave(channel)](#leavechannel)
  - [send(channel, message)](#sendchannel-message)
  - [get(channel, [lessThanHash], [greaterThanHash], [amount])](#getchannel-lessthanhash-greaterthanhash-amount)
  - [getPost(hash, [withUserProfile = true])](#getposthash-withuserprofile--true)
  - [getUser(hash)](#getuserhash)
  - [addFile(channel, source)](#addfilechannel-source)
  - [getFile(hash)](#getfilehash)
  - [getDirectory(hash)](#getdirectoryhash)

## Contributing

[![](https://img.shields.io/badge/freenode-%23ipfs-blue.svg?style=flat-square)](http://webchat.freenode.net/?channels=%23ipfs)

I would be happy to accept PRs! If you want to work on something, it'd be good to talk beforehand to make sure nobody else is working on it. You can reach me on Twitter [@haadcode](https://twitter.com/haadcode) or on IRC #ipfs on Freenode, or in the comments of the [issues section](https://github.com/haadcode/orbit/issues).

A good place to start are the issues labelled ["help wanted"](https://github.com/haadcode/orbit/issues?q=is%3Aopen+is%3Aissue+label%3A%22help+wanted%22+sort%3Areactions-%2B1-desc) or the project's [status board](https://waffle.io/haadcode/orbit).

## License

[MIT](LICENSE) © 2016 haadcode


text:
package org.apache.sshd.server.keyprovider;

import java.io.File;
import java.security.KeyPair;
import java.security.spec.ECGenParameterSpec;

import org.apache.sshd.common.KeyPairProvider;
import org.apache.sshd.common.util.SecurityUtils;
import org.apache.sshd.util.BaseTest;
import org.junit.Test;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;

/**
 * TODO Add javadoc
 *
 * @author Apache MINA SSHD Project
 */
public class PEMGeneratorHostKeyProviderTest extends BaseTest {

    @Test
    public void testDSA() {
        if (!SecurityUtils.isBouncyCastleRegistered()) {
            return;
        }

        File path = new File("target/keys");
        path.mkdirs();
        path = new File(path, "simple.key");
        path.delete();

        // Generate
        PEMGeneratorHostKeyProvider provider = new PEMGeneratorHostKeyProvider();
        provider.setAlgorithm("DSA");
        provider.setKeySize(512);
        provider.setPath(path.getPath());
        assertEquals(KeyPairProvider.SSH_DSS, provider.getKeyTypes());
        KeyPair pk1 = provider.loadKey(KeyPairProvider.SSH_DSS);
        assertNotNull(pk1);

        // Read existing
        provider = new PEMGeneratorHostKeyProvider();
        provider.setAlgorithm("DSA");
        provider.setKeySize(512);
        provider.setPath(path.getPath());
        assertEquals(KeyPairProvider.SSH_DSS, provider.getKeyTypes());
        KeyPair pk2 = provider.loadKey(KeyPairProvider.SSH_DSS);
        assertNotNull(pk2);

        assertEquals(pk2.getPublic(), pk1.getPublic());
    }

    @Test
    public void testRSA() {
        if (!SecurityUtils.isBouncyCastleRegistered()) {
            return;
        }

        File path = new File("target/keys");
        path.mkdirs();
        path = new File(path, "simple.key");
        path.delete();

        // Generate
        PEMGeneratorHostKeyProvider provider = new PEMGeneratorHostKeyProvider();
        provider.setAlgorithm("RSA");
        provider.setKeySize(512);
        provider.setPath(path.getPath());
        assertEquals(KeyPairProvider.SSH_RSA, provider.getKeyTypes());
        KeyPair pk1 = provider.loadKey(KeyPairProvider.SSH_RSA);
        assertNotNull(pk1);

        // Read existing
        provider = new PEMGeneratorHostKeyProvider();
        provider.setAlgorithm("RSA");
        provider.setKeySize(512);
        provider.setPath(path.getPath());
        assertEquals(KeyPairProvider.SSH_RSA, provider.getKeyTypes());
        KeyPair pk2 = provider.loadKey(KeyPairProvider.SSH_RSA);
        assertNotNull(pk2);

        assertEquals(pk2.getPublic(), pk1.getPublic());
    }

    @Test
    public void testEC_NISTP256() {
        if (!SecurityUtils.isBouncyCastleRegistered()) {
            return;
        }

        File path = new File("target/keys");
        path.mkdirs();
        path = new File(path, "simple.key");
        path.delete();

        // Generate
        PEMGeneratorHostKeyProvider provider = new PEMGeneratorHostKeyProvider();
        provider.setAlgorithm("EC");
        provider.setKeySpec(new ECGenParameterSpec("prime256v1"));
        provider.setPath(path.getPath());
        assertEquals(KeyPairProvider.ECDSA_SHA2_NISTP256, provider.getKeyTypes());
        KeyPair pk1 = provider.loadKey(KeyPairProvider.ECDSA_SHA2_NISTP256);
        assertNotNull(pk1);

        // Read existing
        provider = new PEMGeneratorHostKeyProvider();
        provider.setAlgorithm("EC");
        provider.setKeySpec(new ECGenParameterSpec("prime256v1"));
        provider.setPath(path.getPath());
        assertEquals(KeyPairProvider.ECDSA_SHA2_NISTP256, provider.getKeyTypes());
        KeyPair pk2 = provider.loadKey(KeyPairProvider.ECDSA_SHA2_NISTP256);
        assertNotNull(pk2);

        assertEquals(pk2.getPublic(), pk1.getPublic());
    }

    @Test
    public void testEC_NISTP384() {
        if (!SecurityUtils.isBouncyCastleRegistered()) {
            return;
        }

        File path = new File("target/keys");
        path.mkdirs();
        path = new File(path, "simple.key");
        path.delete();

        // Generate
        PEMGeneratorHostKeyProvider provider = new PEMGeneratorHostKeyProvider();
        provider.setAlgorithm("EC");
        provider.setKeySpec(new ECGenParameterSpec("P-384"));
        provider.setPath(path.getPath());
        assertEquals(KeyPairProvider.ECDSA_SHA2_NISTP384, provider.getKeyTypes());
        KeyPair pk1 = provider.loadKey(KeyPairProvider.ECDSA_SHA2_NISTP384);
        assertNotNull(pk1);

        // Read existing
        provider = new PEMGeneratorHostKeyProvider();
        provider.setAlgorithm("EC");
        provider.setKeySpec(new ECGenParameterSpec("P-384"));
        provider.setPath(path.getPath());
        assertEquals(KeyPairProvider.ECDSA_SHA2_NISTP384, provider.getKeyTypes());
        KeyPair pk2 = provider.loadKey(KeyPairProvider.ECDSA_SHA2_NISTP384);
        assertNotNull(pk2);

        assertEquals(pk2.getPublic(), pk1.getPublic());
    }

    @Test
    public void testEC_NISTP521() {
        if (!SecurityUtils.isBouncyCastleRegistered()) {
            return;
        }

        File path = new File("target/keys");
        path.mkdirs();
        path = new File(path, "simple.key");
        path.delete();

        // Generate
        PEMGeneratorHostKeyProvider provider = new PEMGeneratorHostKeyProvider();
        provider.setAlgorithm("EC");
        provider.setKeySpec(new ECGenParameterSpec("P-521"));
        provider.setPath(path.getPath());
        assertEquals(KeyPairProvider.ECDSA_SHA2_NISTP521, provider.getKeyTypes());
        KeyPair pk1 = provider.loadKey(KeyPairProvider.ECDSA_SHA2_NISTP521);
        assertNotNull(pk1);

        // Read existing
        provider = new PEMGeneratorHostKeyProvider();
        provider.setAlgorithm("EC");
        provider.setKeySpec(new ECGenParameterSpec("P-521"));
        provider.setPath(path.getPath());
        assertEquals(KeyPairProvider.ECDSA_SHA2_NISTP521, provider.getKeyTypes());
        KeyPair pk2 = provider.loadKey(KeyPairProvider.ECDSA_SHA2_NISTP521);
        assertNotNull(pk2);

        assertEquals(pk2.getPublic(), pk1.getPublic());
    }
}


text:
package io.github.jokoframework.security.constantes;

/**
 * Created by afeltes on 07/07/16.
 */
public class JokoConstants {
    public static final String HEADER_USER_AGENT = "User-agent";
    public static final String FIREFOX = "Firefox";
    public static final String SEAMONKEY = "Seamonkey";
    public static final String CHROME = "Chrome";
    public static final String CHROMIUM = "Chromium";
    public static final String SAFARI = "Safari";
    public static final String OPR = "OPR";
    public static final String OPERA = "Opera";
    public static final String MSIE = "MSIE";
    public static final String INTERNET_EXPLORER = "Internet Explorer";
    public static final String NOT_AVAILABLE = "N/A";
}


text:
/**
 * Switch is UI element accessible as a jQuery UI widget
 *
 * Set Value: $element.bswitch('option', 'value', value);
 * Get Value: value = $element.bswitch('option', 'value');
 * Focus:     $element.bswitch('focus');
 *
 * Events:
 *     valuechange - when value is change by a slider or is set
 *     focus - when bswitch is focused
 *
 */
$.widget('ui.bswitch', {

	options: {
		value: null
	},

	_init: function() {
		// Wrapping the element with div
		this.element.wrapInner('
');
		this.element.get(0).tagName = 'div';

		var w = {
				_self: this,
				element: this.element,
				gapSize: 3,
				lis: null,
				ui: null,
				uiHandle: null,
				uiBackground: null,
				hasHardToSay: this.element.hasClass("b-switch_with-hard-to-say"),
				sliderValueToSwitchValue: null,
				switchValueToSliderValue: null
			};

		this.w = w;

		w.sliderValueToSwitchValue = function(value) {
			var $valueLI = w.lis.eq(value - 1);
			if ($valueLI.size())
				return $valueLI.data('v');
			else
				return -1;
		};

		w.switchValueToSliderValue = function(value) {
			if (value == -1 && w.hasHardToSay)
				return w.ui.slider('option', 'max');

			var result = null;
			w.lis.each(function(i) {
				if ($(this).data('v') === value) {
					result = i + 1;
					return false;
				}
			});
			return result;
		};

		// Saving reference to options (list items)
		w.lis = this.element.find('li');

		var nAnswers = w.lis.size() + (w.hasHardToSay? w.gapSize + 1 : 0);

		// FIXME Picking default value
		w.lis.each(function(i) {
			if ($(this).hasClass('default'))
				currentAnswer = i + 1;
		});

		w.ui = this.element.prepend('

').children().eq(1);
		if (w.hasHardToSay) {
			w.ui.prev().addClass('b-switch__ear-right_hts');
			var hardToSayCircle = $('

' + lang.str['answer.hts'] + '

');
			var hardToSayGap = $('
');

			hardToSayCircle.click(function() {
				if (w._self.options.disabled)
					return;
				w.ui.slider('value', w.ui.slider("option", "max"));
				w._self.focus();
			});
			w.ui.prev().append(hardToSayCircle).append(hardToSayGap);
		}

		w.ui.width((nAnswers-1)*15);

		w.ui.slider({
			value : currentAnswer,
			min : 1,
			max : nAnswers,
			step : 1,
			slide : function(event, ui) {
				$("#amount").val("$" + ui.value);
			}
		});
		w.uiHandle = w.ui.find('.ui-slider-handle');
		w.uiBackground = $('
').appendTo(w.ui);

		// Making "ears" clickable
		w.ui.prev().find(".b-switch__uiwrapright").click(function(){
			if (w._self.options.disabled)
				return;
			w.ui.slider('value', w.ui.slider("option", "max") - (hasHardToSay ? w.gapSize - 1 : 0));
			w._self.focus();
		});
		w.ui.next().find(".b-switch__uiwrapleft").click(function(){
			if (w._self.options.disabled)
				return;
			w.ui.slider('value', w.ui.slider("option", "min"));
			w._self.focus();
		});

		// Making values clickable
		w.lis.each(function(i){
			$(this).click(function(){
				if (w._self.options.disabled)
					return;
				w.ui.slider('value', i+1);
				w._self.focus();
			});
		});

		// Slider colouring according to value
		w.ui.bind( "slidechange", function(event, ui) {
			w._self.options.value = w.sliderValueToSwitchValue(ui.value);
			w._self.stopBlink();
			w._self._trigger("changevalue");

			w._self._updateColor();
		});

		w.ui.bind( "slide", function(event, ui) {
			if (!w.hasHardToSay)
				return;

			var value = ui.value;
			var max = w.ui.slider("option", "max");
			if (value > max - w.gapSize - 1) {
				if (value != max) {
					return false;
				};
			};
		});

		// Disabling standard keydown method and replacing it with left-right actions only
		// Default values are skipped when pressing left/right
		w.uiHandle.unbind('keydown');
		w.uiHandle.bind('keydown', function(event) {
			if (w._self.options.disabled)
				return;
			var delta = 0;
			if (event.keyCode == KEY_LEFT) {
				delta = -1;
			} else if (event.keyCode == KEY_RIGHT) {
				delta = 1;
			} else {
				return;
			}
			var newValue = w.ui.slider('value') + delta;
			if (w.lis.eq(newValue - 1).hasClass('default'))
				newValue += delta;
			if (w.hasHardToSay) {
				var max = w.ui.slider("option", "max");
				if (newValue > max - w.gapSize - 1 && newValue != max) {
					if (delta > 0)
						newValue = max;
					else
						newValue = max - w.gapSize - 1;
				}
			}
			w.ui.slider('value', newValue);
		});
	},

	_setOption: function (key, value) {
		switch (key) {
			case 'value':
				if (this.options.value == value)
					return;
				this.w.ui.slider('value', this.w.switchValueToSliderValue(value));
				this.w._self.stopBlink();
				this.w._self._trigger("changevalue");
				break;
			case 'disabled':
				this.w.ui.slider('option', 'disabled', value);
				break;
			default:
				return;
		}
		$.Widget.prototype._setOption.apply( this, arguments );
	},

	setAnswerColor: function(answer, color) {
		//var value = this.ui.value;
		var $valueLI = this.w.lis.filter(function() {
			return $(this).data('v') == answer;
		});
		$valueLI[0].className = $valueLI[0].className.replace(/\bcolor_.*?\b/g, '');
		$valueLI.addClass("color_"+color);
		this._updateColor();
		return;
	},

	focus: function() {
		this.w.uiHandle.focus();
		this._trigger('focus');
	},

	blink: function() {
		var className = 'blinking';
		var w = this.w;
		var elem = this.w.uiHandle;
		elem.removeClass(className);

		var concurrentToken = Math.random();
		w.concurrentToken = concurrentToken;
		$(document.body).everyTime(100, function() {
			if (concurrentToken != w.concurrentToken) {
				return;
			}
			elem.toggleClass(className);
		}, 4);
	},

	stopBlink: function () {
		this.w.concurrentToken = Math.random();
		this.w.uiHandle.removeClass('blinking');
	},

	_updateColor: function() {
		var value = this.w.ui.slider("option", "value");
		var $valueLI = this.w.lis.eq(value - 1);
		// Removing all classes starting with 'color_'
		this.w.element[0].className = this.w.element[0].className.replace(/\bcolor_.*?\b/g, '');
		if (this.w.hasHardToSay && value == this.w.ui.slider("option", "max"))
			this.w.element.addClass('color_yellow');
		else
			this.w.element.addClass($valueLI.attr('class'));
	}
});


text:
<?php

namespace ischenko\yii2\jsloader;

use ischenko\yii2\jsloader\base\Loader;
use ischenko\yii2\jsloader\helpers\JsExpression;
use ischenko\yii2\jsloader\requirejs\Config;
use ischenko\yii2\jsloader\requirejs\JsRenderer;
use RuntimeException;
use yii\di\Instance;
use yii\helpers\Json;
use yii\web\View;

/**
 * RequireJS implementation
 *
 * @author Roman Ishchenko <roman@ishchenko.ck.ua>
 * @since 1.0
 */
class RequireJs extends Loader
{
    /**
     * @var string URL to be used to load the RequireJS library. If value is empty the loader will publish library from the bower package
     */
    public $libraryUrl;

    /**
     * @var string path to the RequireJS library
     */
    public $libraryPath = '@bower/requirejs/require.js';

    /**
     * @see http://requirejs.org/docs/api.html#data-main
     *
     * @var string|callable|false URL of script file that will be used as value for the data-main entry. FALSE means do not use the data-main entry.
     */
    public $main;

    /**
     * @var string|array|JsRendererInterface
     */
    public $renderer = JsRenderer::class;

    /**
     * @var Config
     */
    private $config;

    public function init()
    {
        parent::init();

        $this->renderer = Instance::ensure($this->renderer, JsRendererInterface::class);
    }

    /**
     * @return Config
     */
    public function getConfig(): ConfigInterface
    {
        if (!$this->config) {
            $this->config = new Config();
        }

        return $this->config;
    }

    /**
     * Performs actual rendering of the JS loader
     *
     * @param JsExpression[] $jsExpressions a list of js expressions indexed by position
     */
    protected function doRender(array $jsExpressions)
    {
        $resultJsCode = '';

        krsort($jsExpressions);

        foreach ($jsExpressions as $position => $jsExpression) {
            if (!empty($resultJsCode)) {
                $expression = $jsExpression;

                while (($code = $expression->getExpression()) instanceof JsExpression) {
                    $expression = $code;
                }

                if ($position === View::POS_READY && !empty($code)) {
                    $code = $this->encloseJqueryReady($code);
                }

                $expression->setExpression("{$code}\n{$resultJsCode}");
            }

            $resultJsCode = $jsExpression->render($this->renderer);
        }

        $this->publishRequireJs($resultJsCode);
    }

    /**
     * @param string $code
     */
    protected function publishRequireJs($code)
    {
        $view = $this->getView();
        $assetManager = $view->getAssetManager();

        if (empty($this->libraryUrl)) {
            list(, $this->libraryUrl) = $assetManager->publish($this->libraryPath);
        }

        $requireConfig = $this->renderRequireConfig();
        $requireOptions = ['position' => View::POS_HEAD];

        if ($this->main === false) {
            $view->registerJs($code, View::POS_END);
            $view->registerJs($requireConfig, View::POS_HEAD);
        } else {
            $requireOptions['async'] = 'async';
            $requireOptions['defer'] = 'defer';

            $main = $this->resolveMainScript($this->main, "{$requireConfig};\n{$code}");

            list(, $requireOptions['data-main']) = $assetManager->publish($main);
        }

        $view->registerJsFile($this->libraryUrl, $requireOptions);
    }

    /**
     * Performs rendering of configuration block for RequireJS
     *
     * @return string
     */
    protected function renderRequireConfig()
    {
        $jsonOptions = 320;

        if (YII_DEBUG) {
            $jsonOptions |= JSON_PRETTY_PRINT;
        }

        $config = $this->getConfig()->toArray();
        $config = Json::encode((object)array_filter($config), $jsonOptions);

        return "require.config({$config});";
    }

    /**
     * @param string $code
     *
     * @return string
     */
    private function encloseJqueryReady($code)
    {
        return "jQuery(function() {\n{$code}\n});";
    }

    /**
     * @param string $filePath
     * @param string $content
     *
     * @return string full path to a file
     *
     * @throws RuntimeException
     */
    private function writeFileContent($filePath, $content)
    {
        if (!file_exists($filePath)) {
            if (@file_put_contents($filePath, $content, LOCK_EX) === false) {
                throw new RuntimeException("Failed to write data into a file \"$filePath\"");
            }
        }

        return $filePath;
    }

    /**
     * @param mixed $main
     * @param string $code
     * @return string
     */
    private function resolveMainScript($main, $code): string
    {
        if (is_callable($main)) {
            $main = call_user_func($main, $code, $this);
        }

        if (empty($main = trim($main))) {
            $main = md5($code) . '.js';
        }

        $path = $this->getRuntimePath()
            . DIRECTORY_SEPARATOR . ltrim($main, DIRECTORY_SEPARATOR);

        return $this->writeFileContent($path, $code);
    }
}


text:
package com.liferay.login.web.internal.portlet.action;

import com.liferay.login.web.internal.constants.LoginPortletKeys;
import com.liferay.portal.kernel.model.Company;
import com.liferay.portal.kernel.portlet.bridges.mvc.MVCRenderCommand;
import com.liferay.portal.kernel.theme.ThemeDisplay;
import com.liferay.portal.kernel.util.WebKeys;

import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;

import org.osgi.service.component.annotations.Component;

/**
 * @author Liferay
 */
@Component(
	property = {
		"javax.portlet.name=" + LoginPortletKeys.FAST_LOGIN,
		"javax.portlet.name=" + LoginPortletKeys.LOGIN,
		"mvc.command.name=/login/forgot_password"
	},
	service = MVCRenderCommand.class
)
public class ForgotPasswordMVCRenderCommand implements MVCRenderCommand {

	@Override
	public String render(
		RenderRequest renderRequest, RenderResponse renderResponse) {

		System.out.println("In " + getClass().getName() + " render");

		ThemeDisplay themeDisplay = (ThemeDisplay)renderRequest.getAttribute(
			WebKeys.THEME_DISPLAY);

		Company company = themeDisplay.getCompany();

		if (!company.isSendPassword() && !company.isSendPasswordResetLink()) {
			return "/login.jsp";
		}

		renderResponse.setTitle(themeDisplay.translate("forgot-password"));

		return "/forgot_password.jsp";
	}

}


text:
static ConVar mat_debugdepthmode( "mat_debugdepthmode", "0" );
static ConVar mat_debugdepthval( "mat_debugdepthval", "128.0f" );
static ConVar mat_debugdepthvalmax( "mat_debugdepthvalmax", "256.0f" );

BEGIN_SHADER_FLAGS( DebugDepth, "Help for DebugDepth", SHADER_NOT_EDITABLE )
	BEGIN_SHADER_PARAMS
	END_SHADER_PARAMS

	SHADER_INIT_PARAMS()
	{
		SET_FLAGS2( MATERIAL_VAR2_SUPPORTS_HW_SKINNING );
	}

	SHADER_INIT
	{
	}

	SHADER_FALLBACK
	{
		return 0;
	}

	SHADER_DRAW
	{
		SHADOW_STATE
		{
			// Set stream format (note that this shader supports compression)
			unsigned int flags = VERTEX_POSITION | VERTEX_FORMAT_COMPRESSED;
			int nTexCoordCount = 1;
			int userDataSize = 0;
			pShaderShadow->VertexShaderVertexFormat( flags, nTexCoordCount, NULL, userDataSize );

			DECLARE_STATIC_VERTEX_SHADER( debugdrawdepth_vs20 );
			SET_STATIC_VERTEX_SHADER( debugdrawdepth_vs20 );

			if( g_pHardwareConfig->SupportsPixelShaders_2_b() )
			{
				DECLARE_STATIC_PIXEL_SHADER( debugdrawdepth_ps20b );
				SET_STATIC_PIXEL_SHADER( debugdrawdepth_ps20b );
			}
			else
			{
				DECLARE_STATIC_PIXEL_SHADER( debugdrawdepth_ps20 );
				SET_STATIC_PIXEL_SHADER( debugdrawdepth_ps20 );
			}
		}
		DYNAMIC_STATE
		{
			DECLARE_DYNAMIC_VERTEX_SHADER( debugdrawdepth_vs20 );
			SET_DYNAMIC_VERTEX_SHADER_COMBO( SKINNING,  s_pShaderAPI->GetCurrentNumBones() > 0 );
			SET_DYNAMIC_VERTEX_SHADER_COMBO( COMPRESSED_VERTS, (int)vertexCompression );
			SET_DYNAMIC_VERTEX_SHADER( debugdrawdepth_vs20 );

			Vector4D vecZFilter( 0, 0, 0, 1 );
			int nDepthMode = mat_debugdepthmode.GetInt();
			if ( nDepthMode > 1 )
			{
				nDepthMode = 0;
			}

			vecZFilter[nDepthMode] = 1;
			s_pShaderAPI->SetPixelShaderConstant( 1, vecZFilter.Base() );

			Vector4D vecModulationColor( 0, 0, 0, 1 );
			if ( IS_FLAG_SET( MATERIAL_VAR_DECAL ) )
			{
				vecModulationColor[0] = 0;
				vecModulationColor[1] = 1;
				vecModulationColor[2] = 1;
			}
			else
			{
				vecModulationColor[0] = 1;
				vecModulationColor[1] = 1;
				vecModulationColor[2] = 1;
			}
			s_pShaderAPI->SetPixelShaderConstant( 2, vecModulationColor.Base() );

			float flDepthFactor = mat_debugdepthval.GetFloat();
			float flDepthFactorMax = mat_debugdepthvalmax.GetFloat();
			if ( flDepthFactor == 0 )
			{
				flDepthFactor = 1.0f;
			}
			Vector4D vecZFactor( (flDepthFactorMax - flDepthFactor), flDepthFactor, 1, 1 );
			pShaderAPI->SetVertexShaderConstant( VERTEX_SHADER_SHADER_SPECIFIC_CONST_0, vecZFactor.Base() );
		}
		Draw();
	}
END_SHADER


text:
using PagedList;
using PortFolio.Models;
using PortFolio.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace PortFolio.Controllers
{
    public class BlogController : Controller
    {

        public const int MAX_STR_SIZE = 500;
        ADO db = new ADO();

        // GET: Blog
        public ActionResult Index(int page = 1, int pageSize = 5)
        {
            TempData["Categories"] = db.Categorie.ToList();
            List<Article> lstArticle = db.Article.ToList();
            PagedList<Article> lstPaged = new PagedList<Article>(lstArticle, page, pageSize);
            foreach(Article ar in lstPaged)
            {
                ar.Texte = ParseText.Parse(ar.Texte);
            }
            return View(lstPaged);
        }

        [ActionName("ShowCategorie")]
        public ActionResult Index(int id, int page = 1, int pageSize = 5)
        {
            TempData["Categories"] = db.Categorie.ToList();
            List<Article> lstArticle = db.Article.Where(a => a.CategorieID == id).ToList();
            PagedList<Article> lstPaged = new PagedList<Article>(lstArticle, page, pageSize);
            foreach (Article ar in lstPaged)
            {
                ar.Texte = ParseText.Parse(ar.Texte);
            }
            return View("Index", lstPaged);
        }

        public ActionResult Details(int id)
        {
            var obj = db.Article.Find(id);
            obj.Texte = ParseText.Parse(obj.Texte);
            return View(obj);
        }
    }
}


text:
'''Unittests for burrow.'''

import atexit
import os
import signal
import sys
import time

import burrow

def start_server():
    '''Fork and start the server, saving the pid in a file.'''
    kill_server()
    pid = os.fork()
    if pid == 0:
        server = burrow.Server(add_default_log_handler=False)
        server.frontends[0].default_ttl = 0
        server.run()
        sys.exit(0)
    pid_file = open('TestHTTP.pid', 'w')
    pid_file.write(str(pid))
    pid_file.close()
    atexit.register(kill_server)
    time.sleep(1)

def kill_server():
    '''Try killing the server if the pid file exists.'''
    try:
        pid_file = open('TestHTTP.pid', 'r')
        pid = pid_file.read()
        pid_file.close()
        try:
            os.kill(int(pid), signal.SIGUSR1)
            time.sleep(1)
            os.kill(int(pid), signal.SIGTERM)
        except OSError:
            pass
        os.unlink('TestHTTP.pid')
    except IOError:
        pass

start_server()


text:
package com.alexjlockwood.example.submissionstatus;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

/**
 * Main activity for the sample app.
 */
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
  private static final String STATE_ENABLE_ROTATION = "state_debug_rotation";
  private static final String STATE_SHOW_CPS = "state_debug_cps";
  private static final String STATE_SLOW_ANIMATION = "state_debug_slow_animation;";
  private static final String STATE_ICON_TYPE = "state_icon_type";

  private SubmissionStatusDrawable mDrawable;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //noinspection ConstantConditions
    getSupportActionBar().setSubtitle(R.string.action_bar_subtitle);

    mDrawable = new SubmissionStatusDrawable(this);

    if (savedInstanceState != null) {
      //noinspection WrongConstant
      mDrawable.setIconType(savedInstanceState.getInt(STATE_ICON_TYPE));
      mDrawable.setDebugEnableRotation(savedInstanceState.getBoolean(STATE_ENABLE_ROTATION));
      mDrawable.setDebugShowControlPoints(savedInstanceState.getBoolean(STATE_SHOW_CPS));
      mDrawable.setDebugSlowDownAnimation(savedInstanceState.getBoolean(STATE_SLOW_ANIMATION));
    }

    //noinspection deprecation
    findViewById(R.id.submission_status_view).setBackgroundDrawable(mDrawable);
    findViewById(R.id.returned).setOnClickListener(this);
    findViewById(R.id.done).setOnClickListener(this);
    findViewById(R.id.late).setOnClickListener(this);
  }

  @Override
  protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putBoolean(STATE_ENABLE_ROTATION, mDrawable.getDebugEnableRotation());
    outState.putBoolean(STATE_SHOW_CPS, mDrawable.getDebugShowControlPoints());
    outState.putBoolean(STATE_SLOW_ANIMATION, mDrawable.getDebugSlowAnimation());
    outState.putInt(STATE_ICON_TYPE, mDrawable.getIconType());
  }

  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return super.onCreateOptionsMenu(menu);
  }

  @Override
  public boolean onPrepareOptionsMenu(Menu menu) {
    menu.findItem(R.id.action_enable_rotation).setChecked(mDrawable.getDebugEnableRotation());
    menu.findItem(R.id.action_show_cps).setChecked(mDrawable.getDebugShowControlPoints());
    menu.findItem(R.id.action_slow_animation).setChecked(mDrawable.getDebugSlowAnimation());
    return super.onPrepareOptionsMenu(menu);
  }

  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    if (item.isCheckable()) {
      item.setChecked(!item.isChecked());
    }
    if (item.getItemId() == R.id.action_enable_rotation) {
      mDrawable.setDebugEnableRotation(item.isChecked());
      return true;
    }
    if (item.getItemId() == R.id.action_show_cps) {
      mDrawable.setDebugShowControlPoints(item.isChecked());
      return true;
    }
    if (item.getItemId() == R.id.action_slow_animation) {
      mDrawable.setDebugSlowDownAnimation(item.isChecked());
      return true;
    }
    return super.onOptionsItemSelected(item);
  }

  @Override
  public void onClick(View v) {
    switch (v.getId()) {
      case R.id.done:
        mDrawable.setIconType(SubmissionStatusDrawable.DONE);
        break;
      case R.id.late:
        mDrawable.setIconType(SubmissionStatusDrawable.LATE);
        break;
      case R.id.returned:
        mDrawable.setIconType(SubmissionStatusDrawable.RETURNED);
        break;
    }
  }
}


text:
describe Travis::API::V3::Queries::BuildBackups do
  subject { described_class.new({ 'build_backups.repository_id' => repo.id }, 'BuildBackups') }

  describe '#all' do
    let(:repo) { FactoryBot.create(:repository) }
    let!(:build_backup) { FactoryBot.create(:build_backup, repository: repo) }

    it 'returns backups for repo' do
      backups = subject.all

      expect(backups.first.file_name).to eq(build_backup.file_name)
    end
  end
end


text:
package org.apache.carbondata.core.datastore.page;

import java.math.BigDecimal;

/**
 * This is a decorator of column page, it performs decoding lazily (when caller calls getXXX
 * method to get the value from the page)
 */
public class LazyColumnPage extends ColumnPage {

  // decorated column page
  private ColumnPage columnPage;

  // encode that will apply to page data in getXXX
  private ColumnPageValueConverter converter;

  private LazyColumnPage(ColumnPage columnPage, ColumnPageValueConverter converter) {
    super(columnPage.getDataType(), columnPage.getPageSize(), columnPage.scale,
        columnPage.precision);
    this.columnPage = columnPage;
    this.converter = converter;
  }

  public static ColumnPage newPage(ColumnPage columnPage, ColumnPageValueConverter codec) {
    return new LazyColumnPage(columnPage, codec);
  }

  @Override
  public String toString() {
    return String.format("[converter: %s, data type: %s", converter, columnPage.getDataType());
  }

  @Override
  public long getLong(int rowId) {
    switch (columnPage.getDataType()) {
      case BYTE:
        return converter.decodeLong(columnPage.getByte(rowId));
      case SHORT:
        return converter.decodeLong(columnPage.getShort(rowId));
      case SHORT_INT:
        return converter.decodeLong(columnPage.getShortInt(rowId));
      case INT:
        return converter.decodeLong(columnPage.getInt(rowId));
      case LONG:
        return columnPage.getLong(rowId);
      default:
        throw new RuntimeException("internal error: " + this.toString());
    }
  }

  @Override
  public double getDouble(int rowId) {
    switch (columnPage.getDataType()) {
      case BYTE:
        return converter.decodeDouble(columnPage.getByte(rowId));
      case SHORT:
        return converter.decodeDouble(columnPage.getShort(rowId));
      case SHORT_INT:
        return converter.decodeDouble(columnPage.getShortInt(rowId));
      case INT:
        return converter.decodeDouble(columnPage.getInt(rowId));
      case LONG:
        return converter.decodeDouble(columnPage.getLong(rowId));
      case FLOAT:
        return converter.decodeDouble(columnPage.getFloat(rowId));
      case DOUBLE:
        return columnPage.getDouble(rowId);
      default:
        throw new RuntimeException("internal error: " + this.toString());
    }
  }

  @Override
  public float getFloat(int rowId) {
    throw new UnsupportedOperationException("internal error");
  }

  @Override
  public BigDecimal getDecimal(int rowId) {
    return columnPage.getDecimal(rowId);
  }

  @Override
  public byte[] getBytes(int rowId) {
    return columnPage.getBytes(rowId);
  }

  @Override
  public byte[] getBytePage() {
    throw new UnsupportedOperationException("internal error");
  }

  @Override
  public short[] getShortPage() {
    throw new UnsupportedOperationException("internal error");
  }

  @Override
  public byte[] getShortIntPage() {
    throw new UnsupportedOperationException("internal error");
  }

  @Override
  public int[] getIntPage() {
    throw new UnsupportedOperationException("internal error");
  }

  @Override
  public long[] getLongPage() {
    throw new UnsupportedOperationException("internal error");
  }

  @Override
  public float[] getFloatPage() {
    throw new UnsupportedOperationException("internal error");
  }

  @Override
  public double[] getDoublePage() {
    throw new UnsupportedOperationException("internal error");
  }

  @Override
  public byte[][] getByteArrayPage() {
    throw new UnsupportedOperationException("internal error");
  }

  @Override
  public void putDecimal(int rowId, BigDecimal decimal) {
    throw new UnsupportedOperationException("internal error");
  }

  @Override
  public byte[] getDecimalPage() {
    throw new UnsupportedOperationException("internal error");
  }

  @Override
  public byte[] getFlattenedBytePage() {
    throw new UnsupportedOperationException("internal error");
  }

  @Override
  public void convertValue(ColumnPageValueConverter codec) {
    throw new UnsupportedOperationException("internal error");
  }

  @Override
  public void setBytePage(byte[] byteData) {
    throw new UnsupportedOperationException("internal error");
  }

  @Override
  public void setShortPage(short[] shortData) {
    throw new UnsupportedOperationException("internal error");
  }

  @Override
  public void setShortIntPage(byte[] shortIntData) {
    throw new UnsupportedOperationException("internal error");
  }

  @Override
  public void setIntPage(int[] intData) {
    throw new UnsupportedOperationException("internal error");
  }

  @Override
  public void setLongPage(long[] longData) {
    throw new UnsupportedOperationException("internal error");
  }

  @Override
  public void setFloatPage(float[] floatData) {
    throw new UnsupportedOperationException("internal error");
  }

  @Override
  public void setDoublePage(double[] doubleData) {
    throw new UnsupportedOperationException("internal error");
  }

  @Override
  public void setByteArrayPage(byte[][] byteArray) {
    throw new UnsupportedOperationException("internal error");
  }

  @Override
  public void freeMemory() {
    columnPage.freeMemory();
  }

  @Override
  public void putByte(int rowId, byte value) {
    throw new UnsupportedOperationException("internal error");
  }

  @Override
  public void putShort(int rowId, short value) {
    throw new UnsupportedOperationException("internal error");
  }

  @Override
  public void putInt(int rowId, int value) {
    throw new UnsupportedOperationException("internal error");
  }

  @Override
  public void putLong(int rowId, long value) {
    throw new UnsupportedOperationException("internal error");
  }

  @Override
  public void putDouble(int rowId, double value) {
    throw new UnsupportedOperationException("internal error");
  }

  @Override
  public void putBytes(int rowId, byte[] bytes) {
    throw new UnsupportedOperationException("internal error");
  }

  @Override
  public void putShortInt(int rowId, int value) {
    throw new UnsupportedOperationException("internal error");
  }

  @Override
  public void putBytes(int rowId, byte[] bytes, int offset, int length) {
    throw new UnsupportedOperationException("internal error");
  }

  @Override
  public byte getByte(int rowId) {
    throw new UnsupportedOperationException("internal error");
  }

  @Override
  public short getShort(int rowId) {
    throw new UnsupportedOperationException("internal error");
  }

  @Override
  public int getShortInt(int rowId) {
    throw new UnsupportedOperationException("internal error");
  }

  @Override
  public int getInt(int rowId) {
    throw new UnsupportedOperationException("internal error");
  }
}


text:
"""A policy class that chooses from a set of policies to get the actions from.

This mixture policy takes a list of policies and will randomly choose one of
them for every observation. The distribution is defined by the
`mixture_distribution`.
"""

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

from typing import Optional, Sequence, Text

import gin
import tensorflow as tf  # pylint: disable=g-explicit-tensorflow-version-import
import tensorflow_probability as tfp

from tf_agents.policies import tf_policy
from tf_agents.specs import tensor_spec
from tf_agents.trajectories import policy_step
from tf_agents.typing import types
from tf_agents.utils import nest_utils

tfd = tfp.distributions

MIXTURE_AGENT_ID = 'mixture_agent_id'
SUBPOLICY_INFO = 'subpolicy_info'

@gin.configurable
class MixturePolicy(tf_policy.TFPolicy):
  """A policy that chooses from a set of policies to decide the action."""

  def __init__(self,
               mixture_distribution: types.Distribution,
               policies: Sequence[tf_policy.TFPolicy],
               name: Optional[Text] = None):
    """Initializes an instance of `MixturePolicy`.

    Args:
      mixture_distribution: A `tfd.Categorical` distribution on the domain `[0,
        len(policies) -1]`. This distribution is used by the mixture policy to
        choose which policy to listen to.
      policies: List of TF Policies. These are the policies that the mixture
        policy chooses from in every time step.
      name: The name of this instance of `MixturePolicy`.
    """
    self._policies = policies
    if not isinstance(mixture_distribution, tfd.Categorical):
      raise TypeError(
          'mixture distribution must be an instance of `tfd.Categorical`.')
    self._mixture_distribution = mixture_distribution
    action_spec = policies[0].action_spec
    time_step_spec = policies[0].time_step_spec
    for policy in policies[1:]:
      assert action_spec == policy.action_spec, 'Inconsistent action specs.'
      assert time_step_spec == policy.time_step_spec, ('Inconsistent time step '
                                                       'specs.')
      assert policies[0].info_spec == policy.info_spec, ('Inconsistent info '
                                                         'specs.')

    info_spec = {
        MIXTURE_AGENT_ID:
            tensor_spec.BoundedTensorSpec(
                shape=(), dtype=tf.int32, minimum=0, maximum=len(policies) - 1),
        SUBPOLICY_INFO:
            policies[0].info_spec
    }

    super(MixturePolicy, self).__init__(
        time_step_spec=time_step_spec,
        action_spec=action_spec,
        info_spec=info_spec,
        name=name)

  def _variables(self):
    variables = sum([p.variables() for p in self._policies], [])
    variables.extend(self._mixture_distribution.variables)  # pytype: disable=attribute-error  # dynamic-method-lookup
    return variables

  def _distribution(self, time_step, policy_state):
    raise NotImplementedError(
        '_distribution is not implemented for this policy.')

  def _action(self, time_step, policy_state, seed=None):
    first_obs = tf.nest.flatten(time_step.observation)[0]
    batch_size = tf.compat.dimension_value(
        first_obs.shape[0]) or tf.shape(first_obs)[0]
    policy_choice = self._mixture_distribution.sample(batch_size)
    policy_steps = [
        policy.action(time_step, policy_state) for policy in self._policies
    ]
    policy_actions = nest_utils.stack_nested_tensors(
        [step.action for step in policy_steps], axis=-1)
    policy_infos = nest_utils.stack_nested_tensors(
        [step.info for step in policy_steps], axis=-1)

    expanded_choice = tf.expand_dims(policy_choice, axis=-1)
    mixture_action = tf.nest.map_structure(
        lambda t: tf.gather(t, policy_choice, batch_dims=1), policy_actions)

    expanded_mixture_info = tf.nest.map_structure(
        lambda t: tf.gather(t, expanded_choice, batch_dims=1, axis=-1),
        policy_infos)
    mixture_info = tf.nest.map_structure(lambda t: tf.squeeze(t, axis=-1),
                                         expanded_mixture_info)
    return policy_step.PolicyStep(mixture_action, policy_state, {
        MIXTURE_AGENT_ID: policy_choice,
        SUBPOLICY_INFO: mixture_info
    })


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<meta name="robots" content="noindex">
<title>Debugging macros.</title>
<link href="doxygen.css" rel="stylesheet" type="text/css">

Class Hierarchy   Compound List   Compound Members   Related Pages

 The debugging macros are defined in debug.h.

 Flash native code needs to define two macros that are used for debugging the program.

 FLASHASSERT is a standard assert function with a long name to avoid name space collisions.

 FLASHOUTPUT is a "printf" which sends output to a debugging window.

Version
1.0 of the Flash 4 Porting SDK
Middlesoft, Inc.


text:
from setuptools import setup, find_packages

import printio as pkg

name = pkg.__name__

setup(name=pkg.__name__,
      version=pkg.__version__,
      license="MIT",
      description=pkg.__doc__,
      long_description=open('README.rst', 'r').read(),
      author=pkg.__author__,
      author_email=pkg.__email__,
      url=pkg.__homepage__,
      packages=find_packages(),
      classifiers=["Development Status :: 3 - Alpha",
                   "Intended Audience :: Developers",
                   "License :: OSI Approved :: MIT License",
                   "Operating System :: OS Independent",
                   "Programming Language :: Python",
                   "Topic :: Software Development :: Libraries :: Python Modules",
                  ],
     )


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using Inbox2.Framework.Plugins.SharedControls;
using Inbox2.Platform.Channels.Entities;
using Inbox2.Platform.Channels.Text;

namespace Inbox2.Plugins.Conversations.Helpers
{
	[DataContract]
	public class NewMessageDataHelper
	{
		[DataMember]
		public long? SourceMessageId { get; set; }

		[DataMember]
		public SourceAddressCollection To { get; set; }

		[DataMember]
		public SourceAddressCollection Cc { get; set; }

		[DataMember]
		public SourceAddressCollection Bcc { get; set; }

		[DataMember]
		public string Context { get; set; }

		[DataMember]
		public string Body { get; set; }

		[DataMember]
		public long SelectedChannelId { get; set; }

		[DataMember]
		public List<AttachmentDataHelper> AttachedFiles { get; set; }

		[DataMember]
		public bool SuppressSignature { get; set; }

		public NewMessageDataHelper()
		{
			AttachedFiles = new List<AttachmentDataHelper>();
		}

		public static NewMessageDataHelper Parse(string mailtoString)
		{
			var uri = new Uri(mailtoString);

			var to = new SourceAddress(String.Format("{0}@{1}", uri.UserInfo, uri.DnsSafeHost));
			var cc = new SourceAddressCollection();
			var bcc = new SourceAddressCollection();
			var subject = String.Empty;
			var body = String.Empty;

			// See if there is a subject embedded in the url
			if (uri.Query.Length > 0)
			{
				var parts = NameValueParser.GetCollection(uri.Query, "?", "&");

				if (parts["subject"] != null)
					subject = parts["subject"];

				if (parts["body"] != null)
					body = parts["body"];

				if (parts["cc"] != null)
					cc = new SourceAddressCollection(parts["cc"]);

				if (parts["bcc"] != null)
					bcc = new SourceAddressCollection(parts["bcc"]);
			}

			return new NewMessageDataHelper { Context = subject, To = to.ToList(), Cc = cc, Bcc = bcc, Body = body };
		}

		public override bool Equals(object obj)
		{
			var other = obj as NewMessageDataHelper;

			if (other == null)
				return false;

			if (!SourceMessageId.HasValue)
				return false;

			if (!other.SourceMessageId.HasValue)
				return false;

			return SourceMessageId.Value.Equals(other.SourceMessageId.Value);
		}

		public override int GetHashCode()
		{
			return SourceMessageId.GetHashCode();
		}
	}
}


text:
<?php

class AdminAvailabilityExportController extends AdminController {

	public function postIndex(){

		header('Content-Description: File Transfer');

		$day = Input::get('day');

		if ($day == "All")
		{
			header('Content-Type: application/zip');

			$days = array(
        			"Sunday",
        			"Monday",
        			"Tuesday",
        			"Wednesday",
        			"Thursday",
        			"Friday",
        			"Saturday"
        		);

			$zipname = date("F_Y")."_".$day;
			$zip = new ZipArchive;
			$zip->open($zipname, ZipArchive::CREATE);
			foreach ($days as $day) {
				$zip->addFromString(date("F_Y")."_".$day.'.csv', $this->generateCSV($day));
			}
			$zip->close();

			header('Content-disposition: attachment; filename='.$zipname.'.zip');
			header('Content-Length: ' . filesize($zipname));
			readfile($zipname);
		}
		else
		{
			header('Content-type: text/plain');
			header('Content-Disposition: attachment; filename='.date("F_Y")."_".$day.".csv");
			echo $this->generateCSV($day);
		}
	}

	//Method to generate CSV for a certain day
	private function generateCSV($day)
	{
		$data = array();

		$tas = TA::active();

		foreach ($tas as $ta) {
			$data[$ta->id] = array();
		}

		$availabilities = Availability::day($day);

		foreach ($availabilities as $availability) {
			for ($i=$availability->start; $i < $availability->end; $i+=50) {
				$data[$availability->ta_id][$i] = $availability->prefered;
			}
		}

		$csv = ",";
		foreach ($data as $ta_id => $times) {
			$ta = TA::find($ta_id);
			$csv .= $ta->name.",";
		}
		$csv .= "\n";

		$start = Time::toNumber(Settings::get('availability_start_hour')->value);
		$end = Time::toNumber(Settings::get('availability_end_hour')->value);

		for ($i=$start; $i < $end; $i+=50) {
			$csv .= Number::toTime($i).",";
			foreach ($data as $ta_id => $times) {
				if (isset($times[$i]))
					$csv .= ($times[$i]+1).",";
				else $csv .= '0,';
			}
			$csv .= "\n";
		}

		return $csv;
	}
}


text:
<!doctype html>

  <title>AMD Riot example</title>
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <link rel="stylesheet" href="/example/css/styles.css">

    RequireJS Example
    RequireJS all-in-one-file
    SystemJS Example
    SystemJS + precompiled tags

Timer

      <timer></timer>

Panels

      <panels></panels>

Todo

      <todo></todo>


text:
<?php

error_reporting(E_ALL);
ini_set('include_path', ini_get('include_path').';../Classes/');
require 'PHPExcel/Reader/Excel2007.php';
include 'PHPExcel/Writer/Excel2007.php';

echo date('H:i:s') . " Load from Excel2007 file\n";
$objReader = new PHPExcel_Reader_Excel2007;
$objPHPExcel = $objReader->load("05featuredemo.xlsx");

echo date('H:i:s') . " Write to Excel2007 format\n";
$objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
$objWriter->save(str_replace('.php', '.xlsx', __FILE__));

echo date('H:i:s') . " Done writing file.\r\n";


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>F-Index</title>
<meta name="date" content="2017-01-25">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes

A B C D E F G I M N O P R S T V W X Z

F

Fault - Class in ee.ria.dhx.types.eu.x_road.dhx.producer

 Java class for fault complex type.

Fault() - Constructor for class ee.ria.dhx.types.eu.x_road.dhx.producer.Fault

File() - Constructor for class ee.ria.dhx.types.ee.riik.schemas.deccontainer.vers_2_1.DecContainer.File

FileDataHandler - Class in ee.ria.dhx.util

Extension of DataHandler which allows to delete the underlying file.

FileDataHandler(FileDataSource) - Constructor for class ee.ria.dhx.util.FileDataHandler

Contructor.

FileUtil - Class in ee.ria.dhx.util

Utility methods related to files.

FileUtil() - Constructor for class ee.ria.dhx.util.FileUtil

forClass(Class<? extends Object>) - Static method in enum ee.ria.dhx.util.CapsuleVersionEnum

Method finds XSdVersion for given Class.

fromValue(String) - Static method in enum ee.ria.dhx.types.ee.riik.schemas.deccontainer.vers_2_1.AccessConditionType

fromValue(String) - Static method in enum ee.ria.dhx.types.eu.x_road.xsd.identifiers.XRoadObjectType

A B C D E F G I M N O P R S T V W X Z

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes


text:
import Ember from 'ember-metal/core'; // Ember.assert, Ember.Handlebars

import ComponentTemplateDeprecation from 'ember-views/mixins/component_template_deprecation';
import TargetActionSupport from 'ember-runtime/mixins/target_action_support';
import View from 'ember-views/views/view';

import { get } from 'ember-metal/property_get';
import { set } from 'ember-metal/property_set';
import isNone from 'ember-metal/is_none';

import { computed } from 'ember-metal/computed';

import { MUTABLE_CELL } from 'ember-views/compat/attrs-proxy';

function validateAction(component, actionName) {
  if (actionName && actionName[MUTABLE_CELL]) {
    actionName = actionName.value;
  }
  Ember.assert('The default action was triggered on the component ' + component.toString() +
               ', but the action name (' + actionName + ') was not a string.',
               isNone(actionName) || typeof actionName === 'string' || typeof actionName === 'function');
  return actionName;
}

/**
@module ember
@submodule ember-views
*/

/**
  An `Ember.Component` is a view that is completely
  isolated. Properties accessed in its templates go
  to the view object and actions are targeted at
  the view object. There is no access to the
  surrounding context or outer controller; all
  contextual information must be passed in.

  The easiest way to create an `Ember.Component` is via
  a template. If you name a template
  `components/my-foo`, you will be able to use
  `{{my-foo}}` in other templates, which will make
  an instance of the isolated component.

  ```handlebars
  {{app-profile person=currentUser}}
  ```

  ```handlebars
  <!-- app-profile template -->
  <h1>{{person.title}}</h1>
  <img src={{person.avatar}}>
  <p class='signature'>{{person.signature}}</p>
  ```

  You can use `yield` inside a template to
  include the **contents** of any block attached to
  the component. The block will be executed in the
  context of the surrounding context or outer controller:

  ```handlebars
  {{#app-profile person=currentUser}}
    <p>Admin mode</p>
    {{! Executed in the controller's context. }}
  {{/app-profile}}
  ```

  ```handlebars
  <!-- app-profile template -->
  <h1>{{person.title}}</h1>
  {{! Executed in the components context. }}
  {{yield}} {{! block contents }}
  ```

  If you want to customize the component, in order to
  handle events or actions, you implement a subclass
  of `Ember.Component` named after the name of the
  component. Note that `Component` needs to be appended to the name of
  your subclass like `AppProfileComponent`.

  For example, you could implement the action
  `hello` for the `app-profile` component:

  ```javascript
  App.AppProfileComponent = Ember.Component.extend({
    actions: {
      hello: function(name) {
        console.log("Hello", name);
      }
    }
  });
  ```

  And then use it in the component's template:

  ```handlebars
  <!-- app-profile template -->

  <h1>{{person.title}}</h1>
  {{yield}} <!-- block contents -->

  <button {{action 'hello' person.name}}>
    Say Hello to {{person.name}}
  </button>
  ```

  Components must have a `-` in their name to avoid
  conflicts with built-in controls that wrap HTML
  elements. This is consistent with the same
  requirement in web components.

  @class Component
  @namespace Ember
  @extends Ember.View
  @public
*/
var Component = View.extend(TargetActionSupport, ComponentTemplateDeprecation, {
  isComponent: true,
  /*
    This is set so that the proto inspection in appendTemplatedView does not
    think that it should set the components `context` to that of the parent view.
  */
  controller: null,
  context: null,

  instrumentName: 'component',
  instrumentDisplay: computed(function() {
    if (this._debugContainerKey) {
      return '{{' + this._debugContainerKey.split(':')[1] + '}}';
    }
  }),

  init() {
    this._super.apply(this, arguments);
    set(this, 'controller', this);
    set(this, 'context', this);
  },

  /**
  A components template property is set by passing a block
  during its invocation. It is executed within the parent context.

  Example:

  ```handlebars
  {{#my-component}}
    // something that is run in the context
    // of the parent context
  {{/my-component}}
  ```

  Specifying a template directly to a component is deprecated without
  also specifying the layout property.

  @deprecated
  @property template
  @public
  */
  template: computed('_template', {
    get() {
      Ember.deprecate(`Accessing 'template' in ${this} is deprecated. To determine if a block was specified to ${this} please use '{{#if hasBlock}}' in the components layout.`,
                      false,
                      { id: 'ember-views.component-template-get', until: '3.0.0' });

      return get(this, '_template');
    },

    set(key, value) {
      return set(this, '_template', value);
    }
  }),

  _template: computed('templateName', {
    get() {
      if (get(this, '_deprecatedFlagForBlockProvided')) {
        return true;
      }
      var templateName = get(this, 'templateName');
      var template = this.templateForName(templateName, 'template');

      Ember.assert('You specified the templateName ' + templateName + ' for ' + this + ', but it did not exist.', !templateName || !!template);
      return template || get(this, 'defaultTemplate');
    },
    set(key, value) {
      return value;
    }
  }),

  /**
  Specifying a components `templateName` is deprecated without also
  providing the `layout` or `layoutName` properties.

  @deprecated
  @property templateName
  @public
  */
  templateName: null,

  /**
    If the component is currently inserted into the DOM of a parent view, this
    property will point to the controller of the parent view.

    @property targetObject
    @type Ember.Controller
    @default null
    @private
  */
  targetObject: computed('controller', function(key) {
    if (this._targetObject) { return this._targetObject; }
    if (this._controller) { return this._controller; }
    var parentView = get(this, 'parentView');
    return parentView ? get(parentView, 'controller') : null;
  }),

  /**
    Calls a action passed to a component.

    For example a component for playing or pausing music may translate click events
    into action notifications of "play" or "stop" depending on some internal state
    of the component:

    ```javascript
    // app/components/play-button.js
    export default Ember.Component.extend({
      click() {
        if (this.get('isPlaying')) {
          this.sendAction('play');
        } else {
          this.sendAction('stop');
        }
      }
    });
    ```

    The actions "play" and "stop" must be passed to this `play-button` component:

    ```handlebars
    {{! app/templates/application.hbs }}
    {{play-button play=(action "musicStarted") stop=(action "musicStopped")}}
    ```

    When the component receives a browser `click` event it translate this
    interaction into application-specific semantics ("play" or "stop") and
    calls the specified action.

    ```javascript
    // app/controller/application.js
    export default Ember.Controller.extend({
      actions: {
        musicStarted() {
          // called when the play button is clicked
          // and the music started playing
        },
        musicStopped() {
          // called when the play button is clicked
          // and the music stopped playing
        }
      }
    });
    ```

    If no action is passed to `sendAction` a default name of "action"
    is assumed.

    ```javascript
    // app/components/next-button.js
    export default Ember.Component.extend({
      click() {
        this.sendAction();
      }
    });
    ```

    ```handlebars
    {{! app/templates/application.hbs }}
    {{next-button action=(action "playNextSongInAlbum")}}
    ```

    ```javascript
    // app/controllers/application.js
    App.ApplicationController = Ember.Controller.extend({
      actions: {
        playNextSongInAlbum() {
          ...
        }
      }
    });
    ```

    @method sendAction
    @param [action] {String} the action to call
    @param [params] {*} arguments for the action
    @public
  */
  sendAction(action, ...contexts) {
    var actionName;

    // Send the default action
    if (action === undefined) {
      action = 'action';
    }
    actionName = get(this, 'attrs.' + action) || get(this, action);
    actionName = validateAction(this, actionName);

    // If no action name for that action could be found, just abort.
    if (actionName === undefined) { return; }

    if (typeof actionName === 'function') {
      actionName.apply(null, contexts);
    } else {
      this.triggerAction({
        action: actionName,
        actionContext: contexts
      });
    }
  },

  send(actionName, ...args) {
    var target;
    var hasAction = this._actions && this._actions[actionName];

    if (hasAction) {
      var shouldBubble = this._actions[actionName].apply(this, args) === true;
      if (!shouldBubble) { return; }
    }

    if (target = get(this, 'target')) {
      Ember.assert('The `target` for ' + this + ' (' + target +
                   ') does not have a `send` method', typeof target.send === 'function');
      target.send(...arguments);
    } else {
      if (!hasAction) {
        throw new Error(Ember.inspect(this) + ' had no action handler for: ' + actionName);
      }
    }
  }

  /**
    Returns true when the component was invoked with a block template.

    Example (`hasBlock` will be `false`):

    ```hbs
    {{! templates/application.hbs }}

    {{foo-bar}}

    {{! templates/components/foo-bar.js }}
    {{#if hasBlock}}
      This will not be printed, because no block was provided
    {{/if}}
    ```

    Example (`hasBlock` will be `true`):

    ```hbs
    {{! templates/application.hbs }}

    {{#foo-bar}}
      Hi!
    {{/foo-bar}}

    {{! templates/components/foo-bar.js }}
    {{#if hasBlock}}
      This will be printed because a block was provided
      {{yield}}
    {{/if}}
    ```

    @public
    @property hasBlock
    @returns Boolean
  */

  /**
    Returns true when the component was invoked with a block parameter
    supplied.

    Example (`hasBlockParams` will be `false`):

    ```hbs
    {{! templates/application.hbs }}

    {{#foo-bar}}
      No block parameter.
    {{/foo-bar}}

    {{! templates/components/foo-bar.js }}
    {{#if hasBlockParams}}
      This will not be printed, because no block was provided
      {{yield this}}
    {{/if}}
    ```

    Example (`hasBlockParams` will be `true`):

    ```hbs
    {{! templates/application.hbs }}

    {{#foo-bar as |foo|}}
      Hi!
    {{/foo-bar}}

    {{! templates/components/foo-bar.js }}
    {{#if hasBlockParams}}
      This will be printed because a block was provided
      {{yield this}}
    {{/if}}
    ```
    @public
    @property hasBlockParams
    @returns Boolean
  */
});

Component.reopenClass({
  isComponentFactory: true
});

export default Component;


text:
package org.wso2.carbon.databridge.receiver.thrift.service;

import org.apache.thrift.TProcessor;
import org.apache.thrift.protocol.TProtocolFactory;
import org.apache.thrift.server.TServlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Thrift Secure Event Transmission Servlet.
 */
public class ThriftSecureEventTransmissionServlet extends TServlet {

    public ThriftSecureEventTransmissionServlet(TProcessor processor,
                                                TProtocolFactory inProtocolFactory,
                                                TProtocolFactory outProtocolFactory) {
        super(processor, inProtocolFactory, outProtocolFactory);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws IOException, ServletException {
        doPost(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        if (request.isSecure()) {
            super.doPost(request, response);
        }

    }
}


text:
RSpec.shared_context "changeset / seeds" do
  before do
    jane_id = conn[:users].insert name: "Jane"
    joe_id = conn[:users].insert name: "Joe"

    conn[:tasks].insert user_id: joe_id, title: "Joe Task"
    task_id = conn[:tasks].insert user_id: jane_id, title: "Jane Task"

    conn[:tags].insert task_id: task_id, name: "red"

    jane_post_id = conn[:posts].insert author_id: jane_id, title: "Hello From Jane", body: "Jane Post"
    joe_post_id = conn[:posts].insert author_id: joe_id, title: "Hello From Joe", body: "Joe Post"

    red_id = conn[:labels].insert name: "red"
    green_id = conn[:labels].insert name: "green"
    blue_id = conn[:labels].insert name: "blue"

    conn[:posts_labels].insert post_id: jane_post_id, label_id: red_id
    conn[:posts_labels].insert post_id: jane_post_id, label_id: blue_id

    conn[:posts_labels].insert post_id: joe_post_id, label_id: green_id

    conn[:messages].insert author: "Jane", body: "Hello folks"
    conn[:messages].insert author: "Joe", body: "Hello Jane"

    conn[:reactions].insert message_id: 1, author: "Joe"
    conn[:reactions].insert message_id: 1, author: "Anonymous"
    conn[:reactions].insert message_id: 2, author: "Jane"
  end
end


text:
using System;
using System.Data;

namespace Triple.Api.EntityFramework
{
    public class DbContextScopeFactory : IDbContextScopeFactory
    {
        private readonly IDbContextFactory _dbContextFactory;

        public DbContextScopeFactory()
        {
            this._dbContextFactory = null;
        }

        //public DbContextScopeFactory(IDbContextFactory dbContextFactory)
        //{
        //    this._dbContextFactory = dbContextFactory;
        //}

        public IDbContextScope Create(DbContextScopeOption joiningOption = DbContextScopeOption.JoinExisting)
        {
            return new DbContextScope(joiningOption, false, null, this._dbContextFactory);
        }

        public IDbContextReadOnlyScope CreateReadOnly(
            DbContextScopeOption joiningOption = DbContextScopeOption.JoinExisting)
        {
            return new DbContextReadOnlyScope(joiningOption, null, this._dbContextFactory);
        }

        public IDbContextScope CreateWithTransaction(IsolationLevel isolationLevel)
        {
            return new DbContextScope(DbContextScopeOption.ForceCreateNew, false, isolationLevel, this._dbContextFactory);
        }

        public IDbContextReadOnlyScope CreateReadOnlyWithTransaction(IsolationLevel isolationLevel)
        {
            return new DbContextReadOnlyScope(DbContextScopeOption.ForceCreateNew, isolationLevel,
                this._dbContextFactory);
        }

        public IDisposable SuppressAmbientContext()
        {
            return new AmbientContextSuppressor();
        }
    }
}