text:
$(document).ready(function() {

    var videoContainer = document.getElementById('Video'),
        videoBanner = document.getElementById('Video__banner'),
        videoSticky = document.getElementById('Video__sticky'),
        videoHeight = $(videoBanner).height();

    $(videoContainer).css('height', videoHeight+'px');

    $(window).resize(function() {
        videoHeight = $(videoBanner).height();
        // console.log(videoHeight);
        $(videoContainer).css('height', videoHeight+'px');
    });

    var waypoint = new Waypoint({
        element: videoContainer,
        handler: function(direction) {
            $(videoSticky).addClass('js-Video__sticky').toggleClass('Video__sticky--show');
            $(videoBanner).addClass('js-Video__banner').toggleClass('Video__banner--sticky');
        },
        offset: function() {
            return -this.element.clientHeight
        }
    });

});

$(function(){

    var videoPlayer = document.querySelector('#Video__banner iframe'),
    videoProvider = videoPlayer.dataset.provider;

    // set iframe ID
    videoPlayer.id = videoProvider;

    // add js class for once
    // understand DOM well
    var js = true;

    // getIDs
    var $playButton = $("#Video__control"),
    $videoPoster = $("#Video__poster"),
    $videoDetails = $("#Video__details"),
    $videoPoster = $("#Video__poster"),
    $nextVideo = $("#Video__watch-next");

    function setupPlayer() {
        if(js) {
            $playButton.addClass('js-Video__control');
            $videoDetails.addClass('js-Video__details');
            // hide video poster for once
            $videoPoster.addClass('js-Video__poster Video__poster--hidden');
            js = false;
        }
        $playButton.addClass('Video__control--hidden');
        $videoDetails.addClass('Video__details--hidden');
    }

    function vidPlay() {
        $playButton.removeClass('Video__control--show').addClass('Video__control--hidden');
        $videoDetails.removeClass('Video__details--show').addClass('Video__details--hidden');
        $nextVideo.hide();
    }

    function vidPause() {
        $playButton.removeClass('Video__control--hidden').addClass('Video__control--show');
        $videoDetails.removeClass('Video__details--hidden').addClass('Video__details--show');
        $playButton.addClass('Video__control-gradient--show');
        $nextVideo.show();
        // console.log('pause event');

        // video__control on hover state
        $playButton.hover(
               function(){
                   $videoDetails.addClass('Video__details--visible');
                   $(this).addClass('Video__control-gradient--visible');
               },
               function(){
                   $videoDetails.removeClass('Video__details--visible');
                   $(this).removeClass('Video__control-gradient--visible');
               }
        );
        $videoDetails.hover(
               function(){
                   $(this).addClass('Video__details--visible');
                   $playButton.addClass('Video__control-gradient--visible');
               },
               function(){
                   $(this).removeClass('Video__details--visible');
                   $playButton.removeClass('Video__control-gradient--visible');
               }
        );
    }

    // Vemoi API
    // and some awesome events
    // don't change anything
    // real paniczone
    if(videoProvider === 'vimeo') {

        // vemio API ready
        $f(videoPlayer).addEvent('ready', ready);

        // finally the vemio function
        // trigger - play or pause
        function ready(player_id) {

            froogaloop = $f(player_id);

            $videoPoster.on("click", function() {
                froogaloop.api('play');
                setupPlayer();
            });

            // Custom Button Play Listner
            $playButton.on("click",function() {
                froogaloop.api('play');
                setupPlayer();
            });

            // video details magic part
            // when click the non-text area...
            // video will play
            $videoDetails.on("click", function(e) {
                if (e.target.nodeName == 'SPAN')
                    return false;

                // console.log('working');
                froogaloop.api('play');
                setupPlayer();
            });

            $videoDetails.mouseover(function(e) {
                if (e.target.nodeName == 'SPAN') {
                    $('#Video__control-play').removeClass('Video__control-play--scale');
                } else {
                    $('#Video__control-play').addClass('Video__control-play--scale');
                }
            });
            $videoDetails.mouseleave(function() {
                $('#Video__control-play').removeClass('Video__control-play--scale');
            });

            function setupEventListeners() {

                function onPlay() {
                    froogaloop.addEvent('play',
                    function(data) {
                        vidPlay();
                        // console.log('play event');
                    });
                }

                function onPause() {

                    froogaloop.addEvent('pause',
                    function(data) {
                        vidPause();
                    });
                }

                function onFinish() {
                    froogaloop.addEvent('finish',
                    function(data) {
                        console.log('finish');
                    });
                }
                onPlay();
                onPause();
                onFinish();
            }
            setupEventListeners();
        }

    }

    // Youtube API
    // supper cool stuff
    // don't change anything
    // real paniczone

    if(videoProvider === 'youtube') {

        // 3. This function creates an <iframe> (and YouTube player)
        //    after the API code downloads.
        var player;
        window.onYouTubeIframeAPIReady = function () {
            player = new YT.Player('youtube', {
                events: {
                    'onReady': onPlayerReady,
                    'onStateChange': onPlayerStateChange
                }
            });
        }

        // 4. The API will call this function when the video player is ready.
        function onPlayerReady(event) {

            $videoPoster.on("click", function() {
                player.playVideo();
                setupPlayer();
            });

            // Custom Button Play Listner
            $playButton.on("click",function() {
                player.playVideo();
                setupPlayer();
            });

            // video details magic part
            // when click the non-text area...
            // video will play
            $videoDetails.on("click", function(e) {
                if (e.target.nodeName == 'SPAN')
                    return false;

                // console.log('working');
                player.playVideo();
                setupPlayer();
            });

            $videoDetails.mouseover(function(e) {
                if (e.target.nodeName == 'SPAN') {
                    $('#Video__control-play').removeClass('Video__control-play--scale');
                } else {
                    console.log("HOve");
                    $('#Video__control-play').addClass('Video__control-play--scale');
                }
            });
            $videoDetails.mouseleave(function() {
                $('#Video__control-play').removeClass('Video__control-play--scale');
            });

        }

        // 5. The API calls this function when the player's state changes.
        //    The function indicates that when playing a video (state=1),
        //    the player should play for six seconds and then stop.

        function onPlayerStateChange(event) {

            if (event.data == YT.PlayerState.PLAYING) {
                vidPlay();
                // console.log('Playing');
            }

            if(event.data == YT.PlayerState.PAUSED) {
                vidPause();
            }

            if(event.data == YT.PlayerState.BUFFERING) {
                // console.log('Buffering');
            }

        }

        function stopVideo() {
            player.stopVideo();
        }

    }

})


text:
package org.apache.nifi.groups;

public interface RemoteProcessGroupPortDescriptor {

    /**
     * The comments as configured in the target port.
     *
     * @return
     */
    String getComments();

    /**
     * The number tasks that may transmit flow files to the target port
     * concurrently.
     *
     * @return
     */
    Integer getConcurrentlySchedulableTaskCount();

    /**
     * The id of the target port.
     *
     * @return
     */
    String getId();

    /**
     * The id of the remote process group that this port resides in.
     *
     * @return
     */
    String getGroupId();

    /**
     * The name of the target port.
     *
     * @return
     */
    String getName();

    /**
     * Whether or not this remote group port is configured for transmission.
     *
     * @return
     */
    Boolean isTransmitting();

    /**
     * Whether or not flow file are compressed when sent to this target port.
     *
     * @return
     */
    Boolean getUseCompression();

    /**
     * Whether ot not the target port exists.
     *
     * @return
     */
    Boolean getExists();

    /**
     * Whether or not the target port is running.
     *
     * @return
     */
    Boolean isTargetRunning();

    /**
     * Whether or not this port has either an incoming or outgoing connection.
     *
     * @return
     */
    Boolean isConnected();

}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="ISO-8859-1"?>

<web-app xmlns="http://java.sun.com/xml/ns/javaee"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
   version="2.5">

  <display-name>Servlets</display-name>
  <description> Servlets </description>-

<!--
 Define servlets that are included in the example application
-->
- <servlet>
<servlet-name>HelloWorldServlet</servlet-name>
<servlet-class>HelloWorldServlet</servlet-class>
</servlet>

- <servlet>
<servlet-name>HelloToServlet</servlet-name>
<servlet-class>HelloToServlet</servlet-class>
</servlet>

- <servlet-mapping>
<servlet-name>HelloWorldServlet</servlet-name>
<url-pattern>/servlet/HelloWorldServlet</url-pattern>
</servlet-mapping>

- <servlet-mapping>
<servlet-name>HelloToServlet</servlet-name>
<url-pattern>/servlet/HelloToServlet</url-pattern>
</servlet-mapping>

</web-app>


text:
FROM php:7.0-cli

RUN echo "America/Mexico_City" > /etc/timezone && dpkg-reconfigure --frontend noninteractive tzdata

COPY ./config/php.ini /usr/local/etc/php/

# Install modules
RUN apt-get update && apt-get install -y \
    && docker-php-ext-install pdo_mysql \
    && docker-php-ext-install mbstring \
    && docker-php-ext-install bcmath

COPY ./config/attendance-cron /etc/cron.d/attendance-cron
RUN chmod 0644 /etc/cron.d/attendance-cron

# Install PhantomJS
RUN apt-get install -y libfreetype6 libfontconfig bzip2
RUN apt-get install -y nodejs-legacy
RUN apt-get install -y npm
RUN npm install -g phantomjs-prebuilt

EXPOSE 4444

WORKDIR /usr/src/myapp/applications/console

# Add the console `bin` folder to the PATH environment variable
ENV PATH /usr/src/myapp/applications/console/bin:$PATH

RUN apt-get install -y cron

# Run the command on container startup
CMD cron -f


text:
<!DOCTYPE html>

      <meta charset="utf-8">
    <title>Interactive Thermostat</title>
    <link rel="stylesheet" type="text/css" href="public/style.css"/>
    <link rel="stylesheet" type="text/css" href="js/jquery-ui/jquery-ui.min.css"/>

    <canvas id="myCanvas" resize></canvas>

      drag me

        Current temperature:

        Wind direction:

        Wind speed:

        Location:

        <button id="temp-up">+</button>
        <button id="temp-down">-</button>
        <button id="reset-temp">reset</button>
        power saving mode
        <input type="checkbox" class="onoffswitch-checkbox" id="power-save-switch" checked>


text:
namespace Atata
{
    ///
    /// Represents the <c>
</c> heading tag.
    /// Default search finds the first occurring <c>
</c> element.
    ///
    /// <typeparam name="TOwner">The type of the owner page object.</typeparam>
    [ControlDefinition("h1", ComponentTypeName = "
 heading", IgnoreNameEndings = "Header,Heading")]
    public class H1<TOwner> : Content<string, TOwner>
        where TOwner : PageObject<TOwner>
    {
    }
}


text:
author: XORcat
comments: true
date: 2016-12-20 22:55:04+10:00
layout: single
slug: telstra-tpb-block
title: Telstra Has "Blocked" ThePirateBay.org
excerpt: How this looks, and what you can do about it.
categories:
- Tech
tags:
- telstra
- blocked
- piracy
- thepiratebay
- torrentz
- torrents
- torrenthound
- isohunt
- solarmovie
- bypass
- dns poison
- bypass block
header:
  teaser: "/assets/images/posts/0008-telstra-tpb-block/message.png"
---

Hey there!

I've just noticed that today, Telstra (the biggest ISP in Australia) has started to block ThePirateBay, and a number of other torrent file sharing sites, due to a ruling made in the Federal Court in Sydney last week.

The message Telstra serves you when visiting these sites is terribly written, but gets the point across.

![Block Message](/assets/images/posts/0008-telstra-tpb-block/message.png)

The full list of blocked domains can be found [here](https://s115a.com/sites/blocked), and more information about the case [here](https://s115a.com/news/update/28/the-blocks-begin-the-pirate-bay-torrentz-torrenthound-isohunt-and-solarmovie-gone).

This has been expected for a little while now, as [a modification to the copyright act](http://parlinfo.aph.gov.au/parlInfo/download/legislation/billsdgs/3830145/upload_binary/3830145.pdf;fileType=application/pdf) was passed in 2015 to:

> ... enable copyright owners to apply to the Federal Court of Australia for an order requiring a carriage service provider to block access to an online location operated outside Australia that has the primary purpose of infringing copyright or facilitating the infringement of copyright.

[Will Ockenden](https://willockenden.com/) has [a great summary](https://s115a.com/about) of the history of this legislation on his website dedicated to the issue, [s.115a](https://s115a.com/).

---

Let's be real, you're most likely here to try and find a way around this block. Luckily for you, it's only a minor inconvenience to you, and it also [not illegal to bypass the block](http://www.lifehacker.com.au/2016/12/is-it-legal-to-access-isp-blocked-websites/), although that doesn't mean the torrenting of copyrighted material you participate in is not illegal.

Regardless, if you need, or want to access ThePirateBay, Torrentz.eu, or other sites blocked by Telstra, here is the deal.

Telstra has implemented these blocks using a method known as ["DNS Spoofing/Poisoning"](https://en.wikipedia.org/wiki/DNS_spoofing). This means that when your computer asks Telstra's DNS server for the address of thepiratebay.org, it responds with the address of one of Telstra's servers, which serves up a message telling you that the page is blocked.

A really easy way to get around this, is to tell your computer not to use Telstra's DNS servers (there's nothing forcing you to!), and instead to use another server, such as Google's 8.8.8.8/8.8.4.4, or OpenDNS' servers.

Google has a [comprehensive guide](https://developers.google.com/speed/public-dns/docs/using?csw=1) on how to set your computer to use their DNS servers instead of Telstra's.

Essentially, Telstra hasn't blocked access to these sites at all, they have simply stopped telling you how to reach them. If you ask around, plenty of other DNS servers will tell you how to get there, and Telstra will happily route your packets to their destination.

---

On a side note, it looks like Telstra had prepared for this long ago. Their servers that host the "Content Denied" message first appeared back in November, as shown here by Shodan:

![Shodan First Seen](/assets/images/posts/0008-telstra-tpb-block/shodan-first-seen.png)

---

I hope this has helped you get access to whatever perfectly legal torrents you need to get access to.

If you'd like to get in contact, I'm always around on Twitter [@XORcat](https://twitter.com/xorcat), or on email at [xorcat@riseup.net](mailto:xorcat@riseup.net).

Thanks!

XORcat


text:
package com.google.gerrit.server.change;

import com.google.gerrit.extensions.client.ListChangesOption;
import com.google.gerrit.extensions.common.ChangeInfo;
import com.google.gerrit.extensions.restapi.Response;
import com.google.gerrit.extensions.restapi.RestReadView;
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;

import org.kohsuke.args4j.Option;

import java.util.EnumSet;

public class GetChange implements RestReadView<ChangeResource> {
  private final ChangeJson.Factory json;
  private final EnumSet<ListChangesOption> options =
      EnumSet.noneOf(ListChangesOption.class);

  @Option(name = "-o", usage = "Output options")
  void addOption(ListChangesOption o) {
    options.add(o);
  }

  @Option(name = "-O", usage = "Output option flags, in hex")
  void setOptionFlagsHex(String hex) {
    options.addAll(ListChangesOption.fromBits(Integer.parseInt(hex, 16)));
  }

  @Inject
  GetChange(ChangeJson.Factory json) {
    this.json = json;
  }

  @Override
  public Response<ChangeInfo> apply(ChangeResource rsrc) throws OrmException {
    return Response.withMustRevalidate(json.create(options).format(rsrc));
  }

  Response<ChangeInfo> apply(RevisionResource rsrc) throws OrmException {
    return Response.withMustRevalidate(json.create(options).format(rsrc));
  }
}


text:
class PostsController < ApplicationController
  before_action :authenticate_user!, except: [:index, :show]

  def index
    @posts = Post.all.order('created_at DESC')
  end

  def new
    @post = Post.new
  end

  def create
    @post = Post.new(post_params)
    if @post.save
      redirect_to @post
    else
      #render posts/new- render does not lose content like in a redirect (doesn't refresh)
      render 'new'
    end
  end

  def edit
    @post = Post.find(params[:id])
  end

  def update
    @post = Post.find(params[:id])
    if @post.update(params[:post].permit(:title, :body))
      redirect_to @post
    else
      render 'edit'
    end
  end

  def show
    @post = Post.find(params[:id])
  end

  def destroy
    @post = Post.find(params[:id])
    @post.destroy
    redirect_to root_path
  end

  private
  def post_params
    params.require(:post).permit(:title, :body)
  end

end


text:
package com.example.alexeyglushkov.wordteacher.listmodule;

import android.os.Bundle;
import android.os.Parcel;

/**
 * Created by alexeyglushkov on 26.08.16.
 */
public class SimpleCompareStrategy<T> implements CompareStrategy<T> {
    private boolean isInversed;

    public SimpleCompareStrategy() {
    }

    protected SimpleCompareStrategy(Parcel in) {
        this.isInversed = in.readByte() != 0;
    }

    @Override
    public boolean isInversed() {
        return isInversed;
    }

    @Override
    public void inverse() {
        isInversed = !isInversed;
    }

    @Override
    public int compare(T lhs, T rhs) {
        return 0;
    }

    //// Parcelable

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeByte(this.isInversed ? (byte) 1 : (byte) 0);
    }

    public static final Creator<SimpleCompareStrategy> CREATOR = new Creator<SimpleCompareStrategy>() {
        @Override
        public SimpleCompareStrategy createFromParcel(Parcel source) {
            return new SimpleCompareStrategy(source);
        }

        @Override
        public SimpleCompareStrategy[] newArray(int size) {
            return new SimpleCompareStrategy[size];
        }
    };
}


text:
//
//  CTSPaymentToken.h
//  RestFulltester
//
//  Created by Raji Nair on 24/06/14.
//  Copyright (c) 2014 Citrus. All rights reserved.
//

#import <JSONModel/JSONModel.h>

@class CTSPaymentMode;

/**
 Internal dta structure for the payment request
 */
@interface CTSPaymentToken : JSONModel
@property(strong) CTSPaymentMode<Optional>* paymentMode;
@property(strong) NSString<Optional>* type;
@property(strong) NSString<Optional>* id;
@property(strong) NSString<Optional>* cvv;

@end


text:
export default /* glsl */`
#ifdef USE_MORPHTARGETS

	transformed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];
	transformed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];
	transformed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];
	transformed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];

	#ifndef USE_MORPHNORMALS

	transformed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];
	transformed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];
	transformed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];
	transformed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];

	#endif

#endif
`;


text:
=head1 LICENSE

See the NOTICE file distributed with this work for additional information
regarding copyright ownership.

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.

=cut

=pod

=head1 NAME

Bio::EnsEMBL::Compara::RunnableDB::InsertMemberProjections

=cut

=head1 SYNOPSIS

        # Translates and insert the projections for human and mouse
    standaloneJob.pl Bio::EnsEMBL::Compara::RunnableDB::InsertMemberProjections -source_species_names "['homo_sapiens', 'mus_musculus']" -compara_db mysql://...

=cut

=head1 DESCRIPTION

This RunnableDB converts the stable IDs found in the
seq_member_projection_stable_id table to member_ids that can be inserted in
the seq_member_projection table.

Since the stable IDs are transcript stable IDs and we only store the
translation stable IDs of the protein-coding genes, this RunnableDB needs
to access the core database to get a mapping of transcripts to
translations.

The only parameter is "source_species_names" which tells which species are
used for projections. This is used to limit the memory usage by only
loading the data for the relevant species.

=cut

package Bio::EnsEMBL::Compara::RunnableDB::InsertMemberProjections;

use strict;
use warnings;

use Bio::EnsEMBL::Compara::Utils::CopyData qw(bulk_insert_iterator);

use base ('Bio::EnsEMBL::Compara::RunnableDB::BaseRunnable');

sub fetch_input {
    my $self = shift @_;

    my $source_species_names = $self->param_required('source_species_names');

    # TranscriptAdaptor has fetch_all() and TranslationAdaptor has
    # fetch_all_by_Transcript_list() but the latter insists on fetching all
    # the exons for each each translation, fetching them 1 translation at a
    # time. As you imagine, this is a killer ...
    # Direct SQL is so much faster !
    my $sql = 'SELECT transcript.stable_id, translation.stable_id FROM transcript JOIN translation ON transcript.canonical_translation_id = translation.translation_id';

    # Mapping of stable_ids (transcripts and translations) to seq_member_ids
    my %stable_id_2_seq_member_id;
    foreach my $species_name (@$source_species_names) {
        # The GenomeDB
        my $genome_db = $self->compara_dba->get_GenomeDBAdaptor->fetch_by_name_assembly($species_name)
            or die "Can't fetch the genome_db object (name=$species_name) from Compara";

        # The SeqMembers we have for this GenomeDB
        my $seq_members = $self->compara_dba->get_SeqMemberAdaptor->fetch_all_by_GenomeDB($genome_db);
        $stable_id_2_seq_member_id{ $_->stable_id } = $_->dbID for @$seq_members;
        $self->say_with_header(scalar(@$seq_members) . ' members for ' . $species_name);

        # The mapping transcript.stable_id -> translation.stable_id from the core database
        my $transcript_2_translation = $genome_db->db_adaptor->dbc->sql_helper->execute_into_hash( -SQL => $sql );
        while (my ($transcript_stable_id, $translation_stable_id) = each %{$transcript_2_translation}) {
            if ($stable_id_2_seq_member_id{$translation_stable_id}) {
                # If we have the translation, add the transcript
                $stable_id_2_seq_member_id{$transcript_stable_id} = $stable_id_2_seq_member_id{$translation_stable_id};
            }
        }
        $self->say_with_header(scalar(keys %$transcript_2_translation) . ' translations for ' . $species_name);
    }
    $self->say_with_header(scalar(keys %stable_id_2_seq_member_id) . ' stable_ids in the mapping');
    $self->param('stable_id_2_seq_member_id', \%stable_id_2_seq_member_id);
}

sub write_output {
    my $self = shift @_;
    my $stable_id_2_seq_member_id = $self->param('stable_id_2_seq_member_id');
    my $sql_select = 'SELECT target_seq_member_id, source_stable_id FROM seq_member_projection_stable_id';
    my $fetch_iterator = $self->compara_dba->dbc->sql_helper->execute( -SQL => $sql_select, -ITERATOR => 1 );
    my $data_iterator = $fetch_iterator->grep( sub { $stable_id_2_seq_member_id->{$_->[1]} } )->map( sub { [$_->[0], $stable_id_2_seq_member_id->{$_->[1]}] } );
    bulk_insert_iterator($self->compara_dba->dbc, 'seq_member_projection', $data_iterator, ['target_seq_member_id', 'source_seq_member_id'], 'REPLACE');
}

1;


text:
This project includes some gulp tasks, which I need for my work at home.
I organized the files in a manner, which helps me to create new gulp-tasks simple and fast.

Feel free to fork this project and to add some useful gulp-tasks.

# Requirements
* npm installed

All packages and tools will be installed by the npm.

## Install npm packages
Before your work starts, please install all node-packages with the following command:
```
 console@host> npm install
 ```

# Useful links
Gulp: https://gulpjs.com/
Node: https://nodejs.org/en/

# License

Copyright (c) 2017 Davide De Giorgio

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:
package org.lockss.plugin.ingenta;

import org.lockss.daemon.PluginException;
import org.lockss.extractor.ArticleMetadataExtractor;
import org.lockss.extractor.ArticleMetadataExtractorFactory;
import org.lockss.extractor.BaseArticleMetadataExtractor;
import org.lockss.extractor.MetadataTarget;
import org.lockss.plugin.ArchivalUnit;
import org.lockss.plugin.ArticleFiles;
import org.lockss.plugin.ArticleIteratorFactory;
import org.lockss.plugin.SubTreeArticleIteratorBuilder;
import org.lockss.util.Logger;

import java.util.Iterator;
import java.util.regex.Pattern;

public class IngentaRisArticleIteratorFactory2020 implements ArticleIteratorFactory, ArticleMetadataExtractorFactory {

  protected static Logger log = Logger.getLogger(IngentaRisArticleIteratorFactory2020.class);

  /*
   http://www.ingentaconnect.com/content/iuatld/ijtld/2015/00000019/00000001/art00002?format=ris
   http://www.ingentaconnect.com/content/iuatld/ijtld/2017/00000021/00000001/art00003?format=ris
   */

  protected static final String ROOT_TEMPLATE = "\"%scontent/%s/%s\", base_url, publisher_id, journal_id";
  private static final String PATTERN_TEMPLATE = "\"%scontent/%s/%s/([0-9]{4}/[^/]+/[^/]+/art[0-9]{5})((\\?format=ris)|(\\?crawler=true))\", " +
          "base_url, publisher_id, journal_id";

  public static final Pattern HTML_PATTERN = Pattern.compile("(.*)content/([^/]+)/([^/]+)/([0-9]{4}/[^/]+/[^/]+/art[0-9]{5})\\?crawler=true&mimetype=text/html", Pattern.CASE_INSENSITIVE);
  public static final Pattern HTML_PATTERN_ALTERNATIVE = Pattern.compile("(.*)content/([^/]+)/([^/]+)/([0-9]{4}/[^/]+/[^/]+/art[0-9]{5})\\?crawler=true", Pattern.CASE_INSENSITIVE);
  public static final Pattern PDF_PATTERN = Pattern.compile("(.*)content/([^/]+)/([^/]+)/([0-9]{4}/[^/]+/[^/]+/art[0-9]{5})\\?crawler=true&mimetype=application/pdf", Pattern.CASE_INSENSITIVE);
  public static final Pattern RIS_PATTERN = Pattern.compile("(.*)content/([^/]+)/([^/]+)/([0-9]{4}/[^/]+/[^/]+/art[0-9]{5})\\??format=ris", Pattern.CASE_INSENSITIVE);
  public static final String HTML_REPLACEMENT = "$1content/$2/$3/$4?crawler=true&mimetype=text/html";
  public static final String HTML_REPLACEMENT_ALTERNATIVE = "$1content/$2/$3/$4?crawler=true";
  private static final String PDF_REPLACEMENT = "http://api.ingentaconnect.com/content/$2/$3/$4?crawler=true&mimetype=application/pdf";
  public static final String RIS_REPLACEMENT = "$1content/$2/$3/$4?format=ris";

  @Override
  public Iterator<ArticleFiles> createArticleIterator(ArchivalUnit au,
                                                      MetadataTarget target)
          throws PluginException {
    SubTreeArticleIteratorBuilder builder = new SubTreeArticleIteratorBuilder(au);

    builder.setSpec(target,
            ROOT_TEMPLATE,
            PATTERN_TEMPLATE,
            Pattern.CASE_INSENSITIVE);

    builder.addAspect(RIS_PATTERN,
            RIS_REPLACEMENT,
            ArticleFiles.ROLE_ARTICLE_METADATA);

    builder.addAspect(HTML_PATTERN,
            HTML_REPLACEMENT,
            ArticleFiles.ROLE_FULL_TEXT_HTML);

    builder.addAspect(HTML_PATTERN_ALTERNATIVE,
            HTML_REPLACEMENT_ALTERNATIVE,
            ArticleFiles.ROLE_FULL_TEXT_PDF);

    builder.addAspect(PDF_PATTERN,
            PDF_REPLACEMENT,
            ArticleFiles.ROLE_FULL_TEXT_PDF);

    return builder.getSubTreeArticleIterator();
  }

  @Override
  public ArticleMetadataExtractor createArticleMetadataExtractor(MetadataTarget target)
          throws PluginException {
    return new BaseArticleMetadataExtractor(ArticleFiles.ROLE_ARTICLE_METADATA);
  }
}


text:
require "spec_helper"

RSpec.describe Telegraph::Api do
  it "has a version number" do
    expect(Telegraph::Api::VERSION).not_to be nil
  end
end


text:
Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
  # KairosDB/Cassandra Replication Factor = 5
  config.vm.provision "shell", inline: "sed -i \"s/kairosdb.datastore.cassandra.replication_factor=1/kairosdb.datastore.cassandra.replication_factor=5/g\" /opt/kairosdb/conf/kairosdb.properties"
end


text:
<?php
//UserTools.class.php

require_once ('User.class.php');
require_once ('DB.class.php');
require_once('FirePHPCore/fb.php');
class UserTools {

	//auth returns the user if succesfull, false otherwise.
	public function auth($username,$password) {
		$db = new DB();
		$result = $db->select('User', "username = '$username' AND password = '$password'");
		if ($result) {
			return $result[0];
		}
		else return false;
	}

	//Log the user in. First checks to see if the
	//username and password match a row in the database.
	//If it is successful, set the session variables
	//and store the user object within. Return $user
	public function login($username, $password) {
		//~ $password = md5($password);//formerly hashedPassword - J
		//~ $result = mysql_query("SELECT * FROM users WHERE username = '$username' AND password = '$password'");
		$user = $this->auth($username,$password);
		if((bool)$user){
			$t = new User($user);
			$s = serialize($t);
			$_SESSION['user'] = $s;
			$_SESSION['login_time'] = time();
			$_SESSION['logged_in'] = 1;
		}
		return $t ? $t : false;
	}

	//Log the user out. Destroy the session variables.
	public function logout() {
		unset($_SESSION['user']);
		unset($_SESSION['login_time']);//TODO: use something like this to autologout user.
		unset($_SESSION['logged_in']);
		session_destroy();
	}

	//Check to see if a username exists.
	//This is called during registration to make sure all user names are unique.
	public function checkUsernameExists($username) {
		$result = mysql_query("select * from User where username='$username'");
		$numRows = mysql_num_rows($result);
    	return ($numRows == 0 ? false : true);
	}

	//get a user
	//returns a (possibly empty) User object. Takes the users id as an input
	public function getUser($user_id) {
		$db = new DB();
		$result = $db->select('User', "user_id = '$user_id'");
		if ($result){//grab the 1st returned result
			$result = $result[0];
		}
		$options['user_id']=$user_id;
		$options['username']=(isset($result['username'])) ? $result['username'] : "";
		$options['password']=(isset($result['password'])) ? $result['password'] : "";
		$options['firstname']=(isset($result['firstname'])) ? $result['firstname'] : "";
		$options['lastname']=(isset($result['lastname'])) ? $result['lastname'] : "";
		$options['role']=(isset($result['role'])) ? $result['role'] : "";
		$options['email']=(isset($result['email'])) ? $result['email'] : "";
		return new User($options);
	}

}

?>


text:
<?php
// Generated by ZF2's ./bin/classmap_generator.php
return array(
    'BiBoUser\Module'                        => __DIR__ . '/Module.php',
    'BiBoUser\Controller\SkeletonController' => __DIR__ . '/src/BiBoUser/Controller/BiBoUserController.php',
    'ZendSkeletonModuleTest\Framework\TestCase'        => __DIR__ . '/tests/BiBoUser/Framework/TestCase.php',
    'ZendSkeletonModuleTest\SampleTest'                => __DIR__ . '/tests/BiBoUser/SampleTest.php',
);


text:
<?php
namespace backend\business;

use backend\models\Source;

class BusinessTask
{
}


text:
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>vue-webpack-blog</title>
    <link href="http://cdn.bootcss.com/highlight.js/8.0/styles/monokai_sublime.min.css" rel="stylesheet">
  </head>
  <body>
    <app id="app"></app>
    <!-- built files will be auto injected -->
  </body>
</html>


text:
package blockstore

import (
	"bytes"
	"crypto/sha256"
	"github.com/golang/protobuf/proto"
	"github.com/jacobsa/crypto/siv"
	"io"
	pb "mawfs"
	"os"
)

const BlockSize = 65536

const (
    MODE_DIR = 1
    MODE_EXE = 2
)

type Chunk struct {
	contents []byte
	digest   []byte
}

func NewChunk(contents, digest []byte) *Chunk {
	return &Chunk{contents: contents, digest: digest}
}

type Cipher interface {
	Encrypt(plaintext []byte) ([]byte, error)
	Decrypt(ciphertext []byte) ([]byte, error)
}

type SivCipher struct {
	// The encryption/decryption key, must be 32 bytes.
	key []byte
}

func (cipher *SivCipher) Encrypt(plaintext []byte) ([]byte, error) {
	return siv.Encrypt(nil, cipher.key, plaintext, nil)
}

func (cipher *SivCipher) Decrypt(ciphertext []byte) ([]byte, error) {
	return siv.Decrypt(cipher.key, ciphertext, nil)
}

type FSInfo struct {
	cipher Cipher
}

// Cretaes a new FSInfo object from the given password.  The password can be
// ordinary UIT8 text and of any length, the actual key will be generated from
// its SHA256 sum.
func NewFSInfo(password string) *FSInfo {
	key := sha256.Sum256([]byte(password))
	return &FSInfo{&SivCipher{key[:]}}
}

// Returns plaintext encrypted with the filesystem's cipher.
func (f *FSInfo) Encrypt(plaintext []byte) ([]byte, error) {
	return f.cipher.Encrypt(plaintext)
}

// Returns ciphertext decrypted with the filesystem's cipher.
func (f *FSInfo) Decrypt(ciphertext []byte) ([]byte, error) {
	return f.cipher.Decrypt(ciphertext)
}

func (f *FSInfo) ReadChunk(src io.Reader) (*Chunk, error) {
	// Read in the entire ciphertext.
	ciphertextBuf := bytes.NewBuffer([]byte{})
	ciphertextBuf.ReadFrom(src)

	// Get the digest.
	digest := sha256.Sum256(ciphertextBuf.Bytes())

	// Decrypt.
	plaintext, err := f.Decrypt(ciphertextBuf.Bytes())
	if err != nil {
		return nil, err
	}

	return &Chunk{contents: plaintext, digest: digest[:]}, nil
}

// Writes the chunk to the writer, returns the digest of the encrypted data.
func (f *FSInfo) WriteChunk(dst io.Writer, data []byte) ([]byte, error) {
	encrypted, err := f.Encrypt(data)
	if err != nil {
		return nil, err
	}
	_, err = dst.Write(encrypted)
	if err != nil {
		return nil, err
	}
	digest := sha256.Sum256(encrypted)
	return digest[:], nil
}

type ChangeEntry struct {
	digest []byte
	change pb.Change
}

type JournalIter interface {
	Elem() (*ChangeEntry, error)
	Next() error
	IsValid() bool
}

type UnknownName struct {
	s string
}

func (err UnknownName) Error() string {
	return err.s
}

type NodeStore interface {
	// Store a Node, return its digest.
	StoreNode(node *pb.Node) ([]byte, error)

	// Compute and return the digest for the node.  This is just like
	// storeNode() only it doesn't store the node, it just creates its digest.
	MakeDigest(data []byte) ([]byte, error)

	// Get the node at the given digest, nil if it's not currently stored.
	LoadNode(digest []byte) (*pb.Node, error)

	// Stores a Commit, returns its digest.
	StoreCommit(commit *pb.Commit) ([]byte, error)

	// Retrieves a commit object from its digest, an error if it's not
	// currently stored.
	LoadCommit(digest []byte) (*pb.Commit, error)

	//    # Get the root node (null if there is no root).
	//    @abstract Node getRoot();
	//
	// Get the root digest (null if there is no root).
	LoadRootDigest() ([]byte, error)

	// Store the digest of the root node.
	StoreRootDigest(digest []byte) error

	// Returns the digest of the head commit of a given branch.   Returns
	// null and a UnknownName error if the branch is not defined.
	GetHead(branch string) ([]byte, error)

	// Sets the digest of the head commit for the branch.
	SetHead(branch string, digest []byte) error

	// Write a change to the journal for the branch.  Returns the digest of
	// the change.
	WriteToJournal(branch string, change *pb.Change) ([]byte, error)

	// Delete the journal for a branch.
	DeleteJournal(branch string) error

	// Return an iterator over the journal
	MakeJournalIter(branch string) (JournalIter, error)

	//    ## Returns the size of the journal, or rather, the size of all of the
	//    ## changes in it.
	//    @abstract uint getJournalSize(String branch);
}

// Wraps a file in an interface.
type File interface {
	io.Closer
	io.Reader
	io.Writer
}

// Wraps a filesystem in an interface to improve testability.
type FileSys interface {
	Create(name string) (File, error)
	Open(name string) (File, error)
	Append(name string) (File, error)
	Exists(name string) bool
	Mkdir(name string) error
	Remove(name string) error
}

// Implements File.
type BackingDir struct {
	root string
}

func checkBackingDirIfaces() {
	var _ FileSys = &BackingDir{}
}

func (bd BackingDir) Create(name string) (File, error) {
	return os.Create(bd.root + name)
}

func (bd BackingDir) Open(name string) (File, error) {
	return os.Open(bd.root + name)
}

func (bd BackingDir) Append(name string) (File, error) {
	return os.OpenFile(name,
		os.O_WRONLY|os.O_APPEND|os.O_SYNC|os.O_CREATE,
		0)
}

func (bd BackingDir) Exists(name string) bool {
	if _, err := os.Stat(bd.root + name); os.IsNotExist(err) {
		return false
	} else if err == nil {
		return true
	} else {
		panic(err.Error())
	}
}

func (bd BackingDir) Mkdir(name string) error {
	return os.Mkdir(name, 0700)
}

func (bd BackingDir) Remove(name string) error {
	return os.Remove(name)
}

// NodeStore implementation that writes to a backing filesystem directory.
type ChunkStore struct {
	fsInfo  *FSInfo
	backing FileSys
}

func NewChunkStore(fsInfo *FSInfo, backing FileSys) *ChunkStore {
	return &ChunkStore{fsInfo, backing}
}

// Stores chunk data among the objects (filenames are the alt-encoded
// digests), returns the digest.
func (cs *ChunkStore) store(obj proto.Message) ([]byte, error) {
	rep, err := proto.Marshal(obj)
	if err != nil {
		return nil, err
	}

	buf := bytes.Buffer{}
	digest, err := cs.fsInfo.WriteChunk(&buf, rep)
	if err != nil {
		return nil, err
	}

	dst, err := cs.backing.Create(altEncode(digest))
	if err != nil {
		return nil, err
	}

	dst.Write(buf.Bytes())
	return digest, nil
}

func (cs *ChunkStore) load(digest []byte) (*Chunk, error) {
	src, err := cs.backing.Open(altEncode(digest))
	if err != nil {
		return nil, err
	}
	defer src.Close()

	return cs.fsInfo.ReadChunk(src)
}

func (cs *ChunkStore) StoreNode(node *pb.Node) ([]byte, error) {
	return cs.store(node)
}

func (cs *ChunkStore) LoadNode(digest []byte) (*pb.Node, error) {
	chunk, err := cs.load(digest)
	if err != nil {
		return nil, err
	}

	node := &pb.Node{}
	err = proto.Unmarshal(chunk.contents, node)
	if err != nil {
		return nil, err
	}

	return node, nil
}

func (cs *ChunkStore) MakeDigest(data []byte) ([]byte, error) {
	buf := bytes.Buffer{}
	digest, err := cs.fsInfo.WriteChunk(&buf, data)
	return digest, err
}

func (cs *ChunkStore) StoreCommit(commit *pb.Commit) ([]byte, error) {
	return cs.store(commit)
}

func (cs *ChunkStore) LoadCommit(digest []byte) (*pb.Commit, error) {
	chunk, err := cs.load(digest)
	if err != nil {
		return nil, err
	}

	commit := &pb.Commit{}
	err = proto.Unmarshal(chunk.contents, commit)
	if err != nil {
		return nil, err
	}

	return commit, nil
}

func (cs *ChunkStore) LoadRootDigest() ([]byte, error) {
	src, err := cs.backing.Open("refs/root")
	if err != nil {
		return nil, err
	}

	buf := bytes.Buffer{}
	buf.ReadFrom(src)
	return altDecode(buf.String())
}

func (cs *ChunkStore) StoreRootDigest(digest []byte) error {
	encoded := altEncode(digest)
	dst, err := cs.backing.Create("refs/root")
	if err != nil {
		return err
	}

	dst.Write([]byte(encoded))
	return nil
}

func (cs *ChunkStore) GetHead(branch string) ([]byte, error) {
	if !cs.backing.Exists("refs/" + branch) {
		return nil, UnknownName{"Unknown name: " + branch}
	}
	src, err := cs.backing.Open("refs/" + branch)
	if err != nil {
		return nil, err
	}
	buf := bytes.Buffer{}
	buf.ReadFrom(src)
	return altDecode(buf.String())
}

func (cs *ChunkStore) SetHead(branch string, digest []byte) error {
	dst, err := cs.backing.Create("refs/" + branch)
	if err != nil {
		return err
	}

	_, err = dst.Write([]byte(altEncode(digest)))
	dst.Close()
	return err
}

func (cs *ChunkStore) WriteToJournal(branch string, change *pb.Change) (
	[]byte, error) {

	// Create the journals directory first.
	if !cs.backing.Exists("journals") {
		err := cs.backing.Mkdir("journals")
		if err != nil {
			return nil, err
		}
	}

	rep, err := proto.Marshal(change)
	if err != nil {
		return nil, err
	}

	buf := bytes.Buffer{}
	digest, err := cs.fsInfo.WriteChunk(&buf, rep)
	if err != nil {
		return nil, err
	}

	envelope := proto.Buffer{}
	err = envelope.EncodeRawBytes(buf.Bytes())
	if err != nil {
		return nil, err
	}

	dst, err := cs.backing.Append("journals/" + branch)
	if err != nil {
		return nil, err
	}

	_, err = dst.Write(envelope.Bytes())
	return digest, err
}

func (cs *ChunkStore) DeleteJournal(branch string) error {
	return cs.backing.Remove(branch)
}

// Implements JournalIter.
type csJournalIter struct {
	src    File
	cs     *ChunkStore
	change *ChangeEntry
}

func (i *csJournalIter) readChange() (*ChangeEntry, error) {
	// Read the first 8 bytes which will be long enough for the chunk size.  It
	// will also necessarily be shorter than the size + chunk, because every
	// encrypted Change record has a 16 byte SIV header.
	buf := bytes.NewBuffer(make([]byte, 8))
	_, err := i.src.Read(buf.Bytes())
	if err != nil {
		return nil, err
	}

	// Try to decode a varint.
	size, n := proto.DecodeVarint(buf.Bytes())
	if n == 0 {
		return nil,
			&DecodingError{"Journal change is too large to be realistic."}
	}

	// Skip the bytes for the varint we just processed.
	buf.Next(n)

	// Read in the rest of the protobuf.
	remaining := size - (8 - uint64(n))
	remainingBuf := make([]byte, remaining)
	n, err = i.src.Read(remainingBuf)
	if uint64(n) != remaining {
		return nil, &DecodingError{"Incomplete change record."}
	} else if err != nil {
		return nil, err
	}
	buf.Write(remainingBuf)

	// Read a chunk out of it.
	chunk, err := i.cs.fsInfo.ReadChunk(buf)
	if err != nil {
		return nil, err
	}

	// Unmarshal the chunk.
	var entry ChangeEntry
	err = proto.Unmarshal(chunk.contents, &entry.change)
	if err != nil {
		return nil, err
	}
	entry.digest = chunk.digest
	return &entry, nil
}

func (cs *csJournalIter) IsValid() bool {
	return cs.change != nil
}

func newCsJournalIter(src File, cs *ChunkStore) (*csJournalIter, error) {
	result := csJournalIter{src: src, cs: cs}
	var err error
	result.change, err = result.readChange()
	if err != nil && err != io.EOF {
		return nil, err
	}

	return &result, nil
}

// There was an error decoding an object from storage.
//
// Implements error.
type DecodingError struct {
	msg string
}

func (err *DecodingError) Error() string {
	return err.msg
}

func (i *csJournalIter) Elem() (*ChangeEntry, error) {
	return i.change, nil
}

func (cs *csJournalIter) Next() error {
	var err error
	cs.change, err = cs.readChange()
	return err
}

func (cs *ChunkStore) MakeJournalIter(branch string) (JournalIter, error) {
	src, err := cs.backing.Open("journals/" + branch)
	if err != nil {
		return nil, err
	}

	return newCsJournalIter(src, cs)
}


text:
package com.sencha.gxt.examples.resources.client.model;

public interface CountryProxy {

  public void setAbbr(String abbr);

  public String getAbbr();

  public void setName(String name);

  public String getName();

  public void setValue(int value);

  public int getValue();

}


text:
import {
  DEFAULT_PIPETTE,
  makeContext,
  getRobotStateWithTipStandard,
  getErrorResult,
  getSuccessResult,
} from '../__fixtures__'
import { moveToSlot } from '../commandCreators/atomic/moveToSlot'
import { expectTimelineError } from '../__utils__/testMatchers'

describe('moveToSlot', () => {
  let invariantContext
  let robotStateWithTip
  let params

  beforeEach(() => {
    invariantContext = makeContext()
    robotStateWithTip = getRobotStateWithTipStandard(invariantContext)

    params = {
      pipette: DEFAULT_PIPETTE,
      slot: '1',
    }
  })
  it('should return a moveToSlot command without optional params', () => {
    const result = moveToSlot(params, invariantContext, robotStateWithTip)
    const res = getSuccessResult(result)
    expect(res.commands).toEqual([
      {
        command: 'moveToSlot',
        params,
      },
    ])
  })
  it('should return a moveToSlot command with optional params', () => {
    const optionalParams = {
      offset: {
        x: 1,
        y: 2,
        z: 3,
      },
      minimumZHeight: 1,
      forceDirect: true,
    }
    const combinedParams = {
      ...params,
      ...optionalParams,
    }
    const result = moveToSlot(
      combinedParams,
      invariantContext,
      robotStateWithTip
    )
    const res = getSuccessResult(result)
    expect(res.commands).toEqual([
      {
        command: 'moveToSlot',
        params: combinedParams,
      },
    ])
  })
  it('should return an invalid slot error when attempting to move to an invalid slot', () => {
    const result = moveToSlot(
      {
        ...params,
        slot: 'whack slot',
      },
      invariantContext,
      robotStateWithTip
    )
    expectTimelineError(getErrorResult(result).errors, 'INVALID_SLOT')
  })
  it('should return an invalid pipette error when using an invalid pipette', () => {
    const result = moveToSlot(
      {
        ...params,
        pipette: 'badPipette',
      },
      invariantContext,
      robotStateWithTip
    )

    expectTimelineError(getErrorResult(result).errors, 'PIPETTE_DOES_NOT_EXIST')
  })
})


text:
	<form action="#" method="post" class="form-check">

				<?php echo validation_errors('
', '
');?>

					Nama Penyakit :
					<input class="form-control requiered nm_penyakit" name="nm_penyakit" placeholder="Nama Penyakit" type="text"  autocomplete="off" value="<?php echo @$data->nm_penyakit;?>" />

					Nama Latin :
					<input class="form-control requiered nm_latin" name="nm_latin" placeholder="Nama Latin" type="text"  autocomplete="off" value="<?php echo @$data->nm_latin;?>" />

					Definisi :
					<textarea class="form-control requiered" name="definisi" placeholder="Definisi" style="resize:none;" ><?php echo @$data->definisi;?></textarea>

					Solusi :
					<textarea class="form-control requiered" name="solusi" placeholder="Solusi" style="resize:none;"><?php echo @$data->solusi;?></textarea>

						<?php
						if (($url == 'edit') || ($url == 'tambah')) {?>
							<button type="submit" name="submit" class="btn btn-primary form-control" value="submit">Simpan</button>
						<?php } else { ?>
							<a href="<?php echo base_url();?>pakar/penyakit" class="btn btn-primary">Kembali
						<?php }

						?>

	</form>


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Cytisus ponomarjovii R.M.Seredin

### Remarks
null


text:
layout: slide
title: Export to PDF
---

Presentations can be [exported to PDF](https://github.com/hakimel/reveal.js#pdf-export){: .external}, below is an example that's been uploaded to SlideShare.

<iframe id="slideshare" src="http://www.slideshare.net/slideshow/embed_code/13872948" style="height:356px;width:455px;margin:0;overflow:hidden;border:1px solid #CCC;border-width:1px 1px 0;margin-bottom:5px" allowfullscreen></iframe>
<script>
  document.getElementById('slideshare').attributeName = 'allowfullscreen';
</script>


text:
package no.found.elasticsearch.transport.netty.ssl.internal;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

public final class NonReentrantLock extends AbstractQueuedSynchronizer
        implements Lock {

    private Thread owner;

    public void lock() {
        acquire(1);
    }

    public void lockInterruptibly() throws InterruptedException {
        acquireInterruptibly(1);
    }

    public boolean tryLock() {
        return tryAcquire(1);
    }

    public boolean tryLock(long time, TimeUnit unit)
            throws InterruptedException {
        return tryAcquireNanos(1, unit.toNanos(time));
    }

    public void unlock() {
        release(1);
    }

    public boolean isHeldByCurrentThread() {
        return isHeldExclusively();
    }

    public Condition newCondition() {
        return new ConditionObject();
    }

    @Override
    protected boolean tryAcquire(int acquires) {
        if (compareAndSetState(0, 1)) {
            owner = Thread.currentThread();
            return true;
        }
        return false;
    }

    @Override
    protected boolean tryRelease(int releases) {
        if (Thread.currentThread() != owner) {
            throw new IllegalMonitorStateException();
        }
        owner = null;
        setState(0);
        return true;
    }

    @Override
    protected boolean isHeldExclusively() {
        return getState() != 0 && owner == Thread.currentThread();
    }
}


text:
package com.speedment.common.singletonstream;

import static com.speedment.common.singletonstream.internal.SingletonUtil.MESSAGE_STREAM_CONSUMED;
import static com.speedment.common.singletonstream.internal.SingletonUtil.STRICT;
import static java.util.Objects.requireNonNull;

import com.speedment.common.singletonstream.internal.SingletonIterator;
import com.speedment.common.singletonstream.internal.SingletonSpliterator;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import java.util.Spliterator;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.BinaryOperator;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.IntFunction;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.function.ToDoubleFunction;
import java.util.function.ToIntFunction;
import java.util.function.ToLongFunction;
import java.util.stream.Collector;
import java.util.stream.DoubleStream;
import java.util.stream.IntStream;
import java.util.stream.LongStream;
import java.util.stream.Stream;

/**
 * An implementation of a Stream that takes exactly one element as its source.
 *
 * This implementation supports optimized implementations of most terminal
 * operations and a some number of intermediate operations.
 *

 * With STRICT mode true, un-optimized intermediate operations just
 * returns a wrapped standard Stream implementation. With STRICT mode
 * false, most intermediate operation will be executed eagerly and
 * will return another optimized SingletonStream.
 *
 * For performance reasons, the Stream does not throw an IllegalStateOperation
 * if methods are called after a terminal operation has been called on the
 * Stream. This could be implemented using a boolean value set by each
 * terminating op. All other ops could then assert this flag.
 *
 * @author Per Minborg
 * @param <T> the type of the stream elements
 */
public final class SingletonStream<T> implements Stream<T> {

    private final T element;

    private boolean parallel;

    private boolean consumed;

    private List<Runnable> closeHandlers;

    private SingletonStream(T element) {
        this.element = element;
    }

    /**
     * Creates and returns an optimized sequential {@link Stream} implementation
     * with only a single element.
     *
     * @param element the single element
     * @param <T> the type of the stream elements
     * @return a singleton sequential stream
     */
    public static <T> SingletonStream<T> of(T element) {
        return new SingletonStream<>(element);
    }

    /**
     * Creates and returns an optimized sequential {@link Stream} implementation
     * with only a single element if the element is non-null. if the element is
     * null, an empty Stream is returned.
     *
     * @param element the single element or null
     * @param <T> the type of the stream elements
     * @return a singleton sequential stream
     */
    public static <T> Stream<T> ofNullable(T element) {
        return element == null ? empty() : of(element);
    }

    @Override
    public Stream<T> filter(Predicate<? super T> predicate) {
        requireNonNull(predicate);
        if (STRICT) {
            return toStream().filter(predicate);
        }
        return predicate.test(element) ? this : empty();
    }

    @Override
    public <R> Stream<R> map(Function<? super T, ? extends R> mapper) {
        requireNonNull(mapper);
        if (STRICT) {
            return toStream().map(mapper);
        }
        return of(mapper.apply(element));
    }

    @Override
    public IntStream mapToInt(ToIntFunction<? super T> mapper) {
        requireNonNull(mapper);
        if (STRICT) {
            return toStream().mapToInt(mapper);
        }
        return SingletonIntStream.of(mapper.applyAsInt(element));
    }

    @Override
    public LongStream mapToLong(ToLongFunction<? super T> mapper) {
        requireNonNull(mapper);
        if (STRICT) {
            return toStream().mapToLong(mapper);
        }
        return SingletonLongStream.of(mapper.applyAsLong(element));
    }

    @Override
    public DoubleStream mapToDouble(ToDoubleFunction<? super T> mapper) {
        requireNonNull(mapper);
        if (STRICT) {
            return toStream().mapToDouble(mapper);
        }
        return DoubleStream.of(mapper.applyAsDouble(element));
    }

    @Override
    public <R> Stream<R> flatMap(Function<? super T, ? extends Stream<? extends R>> mapper) {
        requireNonNull(mapper);
        if (STRICT) {
            return toStream().flatMap(mapper);
        }
        @SuppressWarnings("unchecked")
        final Stream<R> result = (Stream<R>) mapper.apply(element);
        return result;
    }

    @Override
    public IntStream flatMapToInt(Function<? super T, ? extends IntStream> mapper) {
        requireNonNull(mapper);
        if (STRICT) {
            return toStream().flatMapToInt(mapper);
        }
        return mapper.apply(element);
    }

    @Override
    public LongStream flatMapToLong(Function<? super T, ? extends LongStream> mapper) {
        requireNonNull(mapper);
        if (STRICT) {
            return toStream().flatMapToLong(mapper);
        }
        return mapper.apply(element);
    }

    @Override
    public DoubleStream flatMapToDouble(Function<? super T, ? extends DoubleStream> mapper) {
        requireNonNull(mapper);
        if (STRICT) {
            return toStream().flatMapToDouble(mapper);
        }
        return mapper.apply(element);
    }

    @Override
    public SingletonStream<T> distinct() {
        return this;
    }

    @Override
    public SingletonStream<T> sorted() {
        return this;
    }

    @Override
    public SingletonStream<T> sorted(Comparator<? super T> comparator) {
        return this;
    }

    @Override
    public Stream<T> peek(Consumer<? super T> action) {
        return toStream().peek(action);
    }

    @Override
    public Stream<T> limit(long maxSize) {
        if (maxSize == 0) {
            return empty(); // Optimization
        }
        if (maxSize > 0) {
            return this;
        }
        throw new IllegalArgumentException(Long.toString(maxSize));
    }

    @Override
    public Stream<T> skip(long n) {
        if (n == 0) {
            return this; // Optimization
        }
        if (n > 0) {
            return empty();
        }
        throw new IllegalArgumentException(Long.toString(n));
    }

    @Override
    public void forEach(Consumer<? super T> action) {
        checkConsumed();
        requireNonNull(action);
        action.accept(element);
    }

    @Override
    public void forEachOrdered(Consumer<? super T> action) {
        checkConsumed();
        requireNonNull(action);
        action.accept(element);
    }

    @Override
    public Object[] toArray() {
        return toArray(Object[]::new);
    }

    @SuppressWarnings("unchecked")
    @Override
    public  A[] toArray(IntFunction generator) {
        checkConsumed();
        requireNonNull(generator);
        final A[] result = generator.apply(1);
        result[0] = (A) element;
        return result;
    }

    @Override
    public T reduce(T identity, BinaryOperator<T> accumulator) {
        checkConsumed();
        requireNonNull(accumulator);
        return accumulator.apply(identity, element);
    }

    @Override
    public Optional<T> reduce(BinaryOperator<T> accumulator) {
        checkConsumed();
        // Just one element so the accumulator is never called.
        return toOptional();
    }

    @Override
    public  U reduce(U identity, BiFunction accumulator, BinaryOperator combiner) {
        checkConsumed();
        requireNonNull(accumulator);
        // the combiner is never used in a non-parallell stream
        return accumulator.apply(identity, element);
    }

    @Override
    public <R> R collect(Supplier<R> supplier, BiConsumer<R, ? super T> accumulator, BiConsumer<R, R> combiner) {
        checkConsumed();
        requireNonNull(supplier);
        requireNonNull(accumulator);
        final R value = supplier.get();
        accumulator.accept(value, element);
        // the combiner is never used in a non-parallell stream
        return value;
    }

    @Override
    public <R, A> R collect(Collector<? super T, A, R> collector) {
        checkConsumed();
        requireNonNull(collector);
        final A value = collector.supplier().get();
        collector.accumulator().accept(value, element);
        // the combiner is never used in a non-parallell stream
        return collector.finisher().apply(value);
    }

    @Override
    public Optional<T> min(Comparator<? super T> comparator) {
        checkConsumed();
        return toOptional();
    }

    @Override
    public Optional<T> max(Comparator<? super T> comparator) {
        checkConsumed();
        return toOptional();
    }

    @Override
    public long count() {
        checkConsumed();
        return 1;
    }

    @Override
    public boolean anyMatch(Predicate<? super T> predicate) {
        checkConsumed();
        requireNonNull(predicate);
        return predicate.test(element);
    }

    @Override
    public boolean allMatch(Predicate<? super T> predicate) {
        checkConsumed();
        requireNonNull(predicate);
        return predicate.test(element);
    }

    @Override
    public boolean noneMatch(Predicate<? super T> predicate) {
        checkConsumed();
        requireNonNull(predicate);
        return !predicate.test(element);
    }

    @Override
    public Optional<T> findFirst() {
        checkConsumed();
        return toOptional();
    }

    @Override
    public Optional<T> findAny() {
        checkConsumed();
        return toOptional();
    }

    @Override
    public Iterator<T> iterator() {
        checkConsumed();
        return new SingletonIterator<>(element);
    }

    @Override
    public Spliterator<T> spliterator() {
        checkConsumed();
        return new SingletonSpliterator<>(element);
    }

    @Override
    public boolean isParallel() {
        return parallel;
    }

    @Override
    public SingletonStream<T> sequential() {
        this.parallel = false;
        return this;
    }

    @Override
    public Stream<T> parallel() {
        this.parallel = true;
        return this;
    }

    @Override
    public Stream<T> unordered() {
        return this;
    }

    @Override
    public Stream<T> onClose(Runnable closeHandler) {
        checkConsumed(false);

        if (closeHandler == null) {
            return this;
        }

        if (closeHandlers == null) {
            this.closeHandlers = new ArrayList<>();
        }

        closeHandlers.add(closeHandler);
        return this;
    }

    @Override
    public void close() {
        consumed = true;

        if (closeHandlers == null || closeHandlers.isEmpty()) {
            return;
        }

        closeHandlers.forEach(Runnable::run);
        closeHandlers = null;
    }

    /**
     * Make the problem someone else's...
     *
     * @return A "real" Stream with the single element
     */
    private Stream<T> toStream() {
        final Stream<T> stream = Stream.of(element);
        return parallel ? stream.parallel() : stream;
    }

    private Optional<T> toOptional() {
        // if element is null, Optional will throw an NPE
        // just as the standard Stream implementation does.
        return Optional.of(element);
    }

    private static <T> Stream<T> empty() {
        return Stream.empty();
    }

    private void checkConsumed() {
        checkConsumed(true);
    }

    private void checkConsumed(boolean setConsumed) {
        if (consumed) {
            throw new IllegalStateException(MESSAGE_STREAM_CONSUMED);
        }

        if (setConsumed) {
            consumed = true;
        }
    }

    // Java 9 Stream features
    /**
     * Returns, if this stream is ordered, a stream consisting of the longest
     * prefix of elements taken from this stream that match the given predicate.
     *
     * @param predicate - a non-interfering, stateless predicate to apply to
     * elements to determine the longest prefix of elements.
     * @return the new stream
     */
    public Stream<T> takeWhile(Predicate<? super T> predicate) {
        requireNonNull(predicate);
        if (predicate.test(element)) {
            return this;
        } else {
            return empty();
        }
    }

    /**
     * Returns, if this stream is ordered, a stream consisting of the remaining
     * elements of this stream after dropping the longest prefix of elements
     * that match the given predicate. Otherwise returns, if this stream is
     * unordered, a stream consisting of the remaining elements of this stream
     * after dropping a subset of elements that match the given predicate.
     *
     * @param predicate - a non-interfering, stateless predicate to apply to
     * elements to determine the longest prefix of elements.
     *
     * @return new new stream
     */
    public Stream<T> dropWhile(Predicate<? super T> predicate) {
        requireNonNull(predicate);
        if (predicate.test(element)) {
            return empty();
        } else {
            return this;
        }
    }
}


text:
<?php

namespace Random\Name;

class Generator
{
}

class SubGenerator
{
}


text:
<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace Project\LineOfWorkBundle\DataFixtures\ORM;
use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;
use Project\LineOfWorkBundle\Entity\Job;
/**
 * Description of JobFixtures
 *
 * @author SakyHank
 */
class JobFixtures extends AbstractFixture implements OrderedFixtureInterface{
    public function load(ObjectManager $object)
    {

         $job1 = new Job();
         $job1->setCategory($object->merge($this->getReference('category-programming')));
         $job1->setUser($object->merge($this->getReference('user1')));
         $job1->setType('full-time');
         $job1->setCompany('Sensio Labs');
         //$job1->setLogo('sensio-labs.gif');
         $job1->setUrl('http://www.sensiolabs.com/');
         $job1->setPosition('Apple Developer');
         $job1->setLocation('Paris, France');
         $job1->setDescription('You\'ve already developed websites with symfony and you want to work with Open-Source technologies. You have a minimum of 3 years experience in web development with PHP or Java and you wish to participate to development of Web 2.0 sites using the best frameworks available.');
         $job1->setHowToApply('Send your resume to fabien.potencier [at] sensio.com');
         $job1->setIsPublic(true);
         $job1->setIsActivated(true);
         $job1->setToken('job_1');
         $job1->setEmail('job@example.com');
         $job1->setExpiresAt(new \DateTime('+30 days'));

         $job2 = new Job();
         $job2->setCategory($object->merge($this->getReference('category-design')));
         $job2->setUser($object->merge($this->getReference('user2')));
         $job2->setType('part-time');
         $job2->setCompany('Extreme Sensio');
         $job2->setLogo('extreme-sensio.gif');
         $job2->setUrl('http://www.extreme-sensio.com/');
         $job2->setPosition('Desktop Designer');
         $job2->setLocation('Paris, France');
         $job2->setDescription('Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in.');
         $job2->setHowToApply('Send your resume to fabien.potencier [at] sensio.com');
         $job2->setIsPublic(true);
         $job2->setIsActivated(true);
         $job2->setToken('job_2');
         $job2->setEmail('job@example.com');
         $job2->setExpiresAt(new \DateTime('+30 days'));

         $job3 = new Job();
         $job3->setCategory($object->merge($this->getReference('category-design')));
         $job3->setUser($object->merge($this->getReference('user2')));
         $job3->setType('part-time');
         $job3->setCompany('Extreme Sensio');
         $job3->setLogo('extreme-sensio.gif');
         $job3->setUrl('http://www.extreme-sensio.com/');
         $job3->setPosition('Android Designer');
         $job3->setLocation('Paris, France');
         $job3->setDescription('Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in.');
         $job3->setHowToApply('Send your resume to fabien.potencier [at] sensio.com');
         $job3->setIsPublic(true);
         $job3->setIsActivated(true);
         $job3->setToken('job_3');
         $job3->setEmail('job@example.com');
         $job3->setExpiresAt(new \DateTime('+30 days'));

         $job4 = new Job();
         $job4->setCategory($object->merge($this->getReference('category-programming')));
         $job4->setUser($object->merge($this->getReference('user1')));
         $job4->setType('full-time');
         $job4->setCompany('Sensio Labs');
         //$job1->setLogo('sensio-labs.gif');
         $job4->setUrl('http://www.sensiolabs.com/');
         $job4->setPosition('PHP Developer');
         $job4->setLocation('Cracow, Poland');
         $job4->setDescription('You\'ve already developed websites with symfony and you want to work with Open-Source technologies. You have a minimum of 3 years experience in web development with PHP or Java and you wish to participate to development of Web 2.0 sites using the best frameworks available.');
         $job4->setHowToApply('Send your resume to fabien.potencier [at] sensio.com');
         $job4->setIsPublic(true);
         $job4->setIsActivated(true);
         $job4->setToken('job_4');
         $job4->setEmail('job@example.com');
         $job4->setExpiresAt(new \DateTime('+30 days'));

         $job5 = new Job();
         $job5->setCategory($object->merge($this->getReference('category-programming')));
         $job5->setUser($object->merge($this->getReference('user1')));
         $job5->setType('full-time');
         $job5->setCompany('Sensio Labs');
         //$job1->setLogo('sensio-labs.gif');
         $job5->setUrl('http://www.sensiolabs.com/');
         $job5->setPosition('Ruby Developer');
         $job5->setLocation('New York, USA');
         $job5->setDescription('You\'ve already developed websites with symfony and you want to work with Open-Source technologies. You have a minimum of 3 years experience in web development with PHP or Java and you wish to participate to development of Web 2.0 sites using the best frameworks available.');
         $job5->setHowToApply('Send your resume to fabien.potencier [at] sensio.com');
         $job5->setIsPublic(true);
         $job5->setIsActivated(true);
         $job5->setToken('job_5');
         $job5->setEmail('job@example.com');
         $job5->setExpiresAt(new \DateTime('+30 days'));

         for($i=3 ;$i<30; $i++){
             $job = new Job();
             $job->setCategory($object->merge($this->getReference('category-design')));
             $job->setUser($object->merge($this->getReference('user2')));
             $job->setType('part-time');
             $job->setCompany('Extreme Sensio');
             $job->setLogo('extreme-sensio.gif');
             $job->setUrl('http://www.extreme-sensio.com/');
             $job->setPosition('Web Designer');
             $job->setLocation('Paris, France');
             $job->setDescription('Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in.');
             $job->setHowToApply('Send your resume to fabien.potencier [at] sensio.com');
             $job->setIsPublic(true);
             $job->setIsActivated(true);
             $job->setToken('job_'.$i);
             $job->setEmail('job'.$i.'@example.com');
             $job->setExpiresAt(new \DateTime('+30 days'));
             $object->persist($job);
         }

   /*     for($i = 100; $i <= 130; $i++)
    {
        $job = new Job();
        $job->setCategory($em->merge($this->getReference('category-programming')));
        $job->setType('full-time');
        $job->setCompany('Company '.$i);
        $job->setPosition('Web Developer');
        $job->setLocation('Paris, France');
        $job->setDescription('Lorem ipsum dolor sit amet, consectetur adipisicing elit.');
        $job->setHowToApply('Send your resume to lorem.ipsum [at] dolor.sit');
        $job->setIsPublic(true);
        $job->setIsActivated(true);
        $job->setToken('job_'.$i);
        $job->setEmail('job@example.com');

        $em->persist($job);
    }*/

         $object->persist($job1);
         $object->persist($job2);
         $object->persist($job3);
         $object->persist($job4);
         $object->persist($job5);
         $object->flush();
    }

    public function getOrder()
    {
        return 3; // the order in which fixtures will be loaded
    }
}


text:
///Generate and encapsulate all the data related to a temperature sensor.
 ///<param name="SensorAddress">The GUID for the sensor on the system</param>
 ///<param name="TempBand">The target range the temperature can be</param>
 ///<param name="TempTarget">The target temperature for the sensor</param>
TemperatureSensor::TemperatureSensor(byte* SensorAddress, float TempBand, float TempTarget, ID* InId)
{
    m_SensorAddress = SensorAddress;
    m_TemperatureBand = TempBand;
    m_TemperatureTarget = TempTarget;
    m_ID = InId;
}

///Update the target temperature for this sensor
///<param name="TempTarget">The new temperature value to shoot for</param>
void TemperatureSensor::SetTargetTemperature(float TempTarget)
{
    m_TemperatureTarget = TempTarget;
}

///Set the target temperature band
///<param name="TempBand">How wide the temperature is allowed to swing and still be in range</param>
void TemperatureSensor::SetTemperatureBand(float TempBand)
{
    m_TemperatureBand = TempBand;
}

///Determine whether our temperature is in our range of control.
///<return>The enumeration value representing what state we're in</return>
 TempInRange TemperatureSensor::ShouldBeginTemperatureAdjustment()
 {
    TempInRange retVal;
   if(m_Temperature > m_TemperatureTarget + m_TemperatureBand )
    {
       //We need to adjust our temperature, it's too high
        retVal = TOO_HOT;
    }
   else if(m_Temperature < m_TemperatureTarget - m_TemperatureBand)
   {
	   //We need to adjust our temperature, it's too low
       retVal = TOO_COLD;
   }
   else
   {
       retVal = JUST_RIGHT;
   }

   return retVal;
 }

 ///This tells us whether we've hit the target temperature within the allowable
 ///range.  If it's set to 65 with 1 degree of range, then we'll return true once we hit
 ///between 64 and 66.  This is usually a much smaller range than the temperature band
 ///we'll begin cooling at.
 ///<param name="Cooling"> True if the temperature is falling, false otherwise</param>
 ///<return>True if we've hit the temperature, false otherwise</return>
 bool TemperatureSensor::HaveHitTemperatureTarget(bool Cooling)
 {
     bool retVal = false;
     if(true == Cooling)
     {
         //Temperature is falling.  See if we've gone past it
         if(m_Temperature <= m_TemperatureTarget)
         {
             retVal = true;
         }
     }
     else
     {
         //Temperature is rising.  See if we've gone past it
         if(m_Temperature >= m_TemperatureTarget)
         {
             retVal = true;
         }
     }

     return retVal;
 }

 /// Retrieve the temperature from the OneWire sensor
 ///<param name="Sensors">Location of the bus for the OneWire sensors</param>
 ///<return>True if successful, false otherwise</return>
 bool TemperatureSensor::RetrieveTemperatureFromSensor(OneWire Sensors)
 {
     float retVal = INVALID_DATA;
     byte data[2];
   //Found the sensor we were looking for, read the data from it
     if(0 == Sensors.reset())
     {
       Logger::Log(F("Unable to reset the bus"), ERR);
       goto cleanup;
     }

     Sensors.select(m_SensorAddress);

     //Send the 0x44 command, which is the convert command
     Sensors.write(0x44);

	 //TODO: Can only do this when not in parasitic power mode
	 while(Sensors.read() == 0)
	 {
		 //Chill for 5 ms to see if it's all done
		 delay(5);
	 }

	 //TODO: This might not be needed for non-parasite powered sensors
     if(0 == Sensors.reset())
     {
       Logger::Log(F("Unable to reset the bus after converting temperature"), ERR);
       goto cleanup;
     }
     Sensors.select(m_SensorAddress);

     //Send the 0xBE command, which is read the scratchpad
     Sensors.write(0xBE);

     //The data is of the format LSB, MSB
     data[0] = Sensors.read();
     data[1] = Sensors.read();
     retVal = ((data[1] << 8) | data[0]); //using two's compliment
     retVal = retVal / 16.0;
     retVal = Utility::ToFahrenheit(retVal);

     //Reset the communication
     Sensors.reset();

     //Assign our temperature data
     m_Temperature = retVal;
cleanup:
     return retVal;
 }

 ///Print out the temperature sensor in the following format:
 ///SensorName:Temperature
 void TemperatureSensor::Print()
 {
	 char buffer[15];
   char* buf = Utility::ftoa(buffer, m_Temperature, 2);
	 Logger::LogCommunicationStatement(m_ID->GetName(), buf);
 }

///Go through the collection of sensors and validate that we have the
///requested sensor on the system.
///<param name="Sensors"> The OneWire bus that contains the temperature sensors</param>
///<return> True if found, false otherwise</return>
 bool TemperatureSensor::DoesSensorExist(OneWire Sensors)
 {
   bool retVal = false;
   byte foundSensorAddress[8];

   Logger::PrependLogStatement(DEB);
   Logger::LogStatement(F("Searching for "), DEB);
   Logger::LogStatement(m_SensorAddress, DEB);
   Logger::EndLogStatement(DEB);

   while(true == Sensors.search(foundSensorAddress))
   {
     bool found = true;

     //Print out the data
	 Logger::PrependLogStatement(DEB);
     Logger::LogStatement(F("Found sensor "), DEB);
	 Logger::LogStatement(foundSensorAddress, DEB);
	 Logger::EndLogStatement(DEB);

     //See if this is a valid address
     if ( OneWire::crc8( foundSensorAddress, 7) != foundSensorAddress[7]) {
          Logger::Log(F("CRC is not valid!"), WAR);
          Sensors.reset();
          Sensors.reset_search();
          break;
      }
      if ( foundSensorAddress[0] != 0x10 && foundSensorAddress[0] != 0x28) {
        Logger::Log(F("Device is not recognized"), WAR);
        continue;
      }

     //We found a valid device on the wire.  See if it's a match
     for(int i = 0; i < 8; i++)
     {
       if(m_SensorAddress[i] != foundSensorAddress[i])
       {
         found = false;
         break;
       }
     }
     //See if we found a match
     if(true == found)
     {
       //This is the sensor we're looking for
       Logger::Log(F("Found sensor"), DEB);
       retVal = true;
       break;
     }
   }

   Logger::Log(F("Done searching for sensors"), DEB);

cleanup:
  //Reset the temperature sensor search for subsequent invocations
  Sensors.reset_search();
  return retVal;
 }

  ///Print out the sensor data in a readable format.
  ///<param name="SensorAddress">The address of the sensor to print out</param>
  void TemperatureSensor::DebugPrintSensor(byte* SensorAddress)
 {

	Logger::PrependLogStatement(DEB);
	Logger::LogStatement(F("Device "), DEB);
    for(int i = 0; i < 8; i++){
		Logger::LogStatement(SensorAddress[i], DEB);
        Logger::LogStatement(F("-"), DEB);
    }
	Logger::EndLogStatement(DEB);
 }


text:
package com.intellij.execution.util;

import com.intellij.execution.CantRunException;
import com.intellij.execution.ExecutionBundle;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.fileEditor.impl.LoadTextUtil;
import com.intellij.openapi.util.NlsSafe;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;

public final class ScriptFileUtil {

  private static final Logger LOG = Logger.getInstance(ScriptFileUtil.class);

  private static final String SCHEME = "mem://";
  private static final Map<String, VirtualFile> ourFilesMap = ContainerUtil.createConcurrentWeakValueMap();
  private static final AtomicLong ourFileCounter = new AtomicLong();

  private ScriptFileUtil() {}

  public static boolean isMemoryScriptPath(@Nullable String url) {
    return url != null && url.startsWith(SCHEME);
  }

  public static String getScriptFilePath(@NotNull VirtualFile file) {
    if (file.isInLocalFileSystem()) return file.getPath();

    long id = ourFileCounter.incrementAndGet();
    String url = SCHEME + id + "/" + file.getName();
    ourFilesMap.put(url, file);
    return url;
  }

  @Nullable
  public static VirtualFile findScriptFileByPath(@Nullable String path) {
    if (StringUtil.isEmpty(path)) return null;
    if (!path.startsWith(SCHEME)) {
      return LocalFileSystem.getInstance().findFileByPath(path);
    }
    return ourFilesMap.get(path);
  }

  @NotNull
  public static String getLocalFilePath(@NotNull String scriptPath) throws CantRunException {
    if (isMemoryScriptPath(scriptPath)) {
      File tmpFile = copyToTempFile(scriptPath);
      return tmpFile.getAbsolutePath();
    }
    return scriptPath;
  }

  @NotNull
  public static File copyToTempFile(@NotNull @NlsSafe String path) throws CantRunException {
    VirtualFile virtualFile = findScriptFileByPath(path);
    if (virtualFile == null) {
      throw new CantRunException(ExecutionBundle.message("script.exception.file.not.found", path));
    }
    File ioFile;
    try {
      ioFile = FileUtil.createTempFile(virtualFile.getName(), "", true);
    }
    catch (IOException e) {
      throw new CantRunException(ExecutionBundle.message("script.exception.can.not.create.temp.file", virtualFile.getName()), e);
    }
    try {
      copyFile(virtualFile, ioFile);
      return ioFile;
    }
    catch (IOException e) {
      throw new CantRunException(
        ExecutionBundle.message("script.exception.can.not.write.temp.file", virtualFile.getPath(), ioFile.getAbsolutePath()), e);
    }
  }

  private static void copyFile(@NotNull VirtualFile srcFile, @NotNull File destFile) throws IOException {
    LOG.info("Copying to " + destFile.getPath());
    CharSequence content = getContent(srcFile);
    CharBuffer cb = CharBuffer.wrap(content);
    ByteBuffer bb = StandardCharsets.UTF_8.encode(cb);
    byte[] result = new byte[bb.remaining()];
    bb.get(result);
    FileUtil.writeToFile(destFile, result, false);
  }

  @NotNull
  private static CharSequence getContent(@NotNull VirtualFile file) {
    Document document = FileDocumentManager.getInstance().getCachedDocument(file);
    if (document != null) {
      return document.getText();
    }
    return LoadTextUtil.loadText(file);
  }

}


text:
package memlockfree

import (
	"sync"
	"time"

	"github.com/VolantMQ/vlapi/mqttp"
	"github.com/VolantMQ/vlapi/vlpersistence"
	"github.com/VolantMQ/vlapi/vltypes"
	"github.com/pkg/errors"
	"go.uber.org/zap"

	"github.com/VolantMQ/volantmq/configuration"
	"github.com/VolantMQ/volantmq/metrics"
	topicstypes "github.com/VolantMQ/volantmq/topics/types"
)

const (
	chanSize = 1024 * 512
)

type provider struct {
	root               *node
	metricsPackets     metrics.Packets
	metricsSubs        metrics.Subscriptions
	persist            vlpersistence.Retained
	log                *zap.SugaredLogger
	wgPublisher        sync.WaitGroup
	wgPublisherStarted sync.WaitGroup
	inbound            chan *mqttp.Publish
	inRetained         chan vltypes.RetainObject
	subIn              chan topicstypes.SubscribeReq
	unSubIn            chan topicstypes.UnSubscribeReq
	onCleanUnsubscribe func([]string)
	nodeSubscribers    func(sn *node, publishID uintptr, p *publishes)
}

var _ topicstypes.Provider = (*provider)(nil)

// NewMemProvider returns an new instance of the provider, which is implements the
// TopicsProvider interface. provider is a hidden struct that stores the topic
// subscriptions and retained messages in memory. The content is not persistent so
// when the server goes, everything will be gone. Use with care.
func NewMemProvider(config *topicstypes.MemConfig) (topicstypes.Provider, error) {
	p := &provider{
		metricsPackets:     config.MetricsPackets,
		metricsSubs:        config.MetricsSubs,
		persist:            config.Persist,
		onCleanUnsubscribe: config.OnCleanUnsubscribe,
		inbound:            make(chan *mqttp.Publish, chanSize),
		inRetained:         make(chan vltypes.RetainObject, chanSize),
		subIn:              make(chan topicstypes.SubscribeReq, chanSize),
		unSubIn:            make(chan topicstypes.UnSubscribeReq, chanSize),
	}

	if config.OverlappingSubscriptions {
		p.nodeSubscribers = overlappingSubscribers
	} else {
		p.nodeSubscribers = nonOverlappingSubscribers
	}

	p.root = newNode(nil)

	p.log = configuration.GetLogger().Named("topics").Named(config.Name)

	if p.persist != nil {
		entries, err := p.persist.Load()
		if err != nil && !errors.Is(err, vlpersistence.ErrNotFound) {
			return nil, err
		}

		for _, d := range entries {
			var pkt mqttp.IFace
			pkt, _, err = mqttp.Decode(mqttp.ProtocolV50, d.Data)
			if err != nil {
				p.log.Error("Couldn't decode retained message", zap.Error(err))
			} else {
				if m, ok := pkt.(*mqttp.Publish); ok {
					if len(d.ExpireAt) > 0 {
						var tm time.Time
						if tm, err = time.Parse(time.RFC3339, d.ExpireAt); err == nil {
							m.SetExpireAt(tm)
						} else {
							p.log.Error("Decode publish expire at", zap.Error(err))
						}
					}
					_ = p.Retain(m)
				} else {
					p.log.Warn("Unsupported retained message type", zap.String("type", m.Type().Name()))
				}
			}
		}
	}

	publisherCount := 2
	subsCount := 2
	unSunCount := 2

	p.wgPublisher.Add(publisherCount + subsCount + unSunCount + 1)
	p.wgPublisherStarted.Add(publisherCount + subsCount + unSunCount + 1)

	for i := 0; i < publisherCount; i++ {
		go p.publisher()
	}

	go p.retainer()

	for i := 0; i < subsCount; i++ {
		go p.subscriber()
	}

	for i := 0; i < unSunCount; i++ {
		go p.unSubscriber()
	}

	p.wgPublisherStarted.Wait()

	return p, nil
}

func (mT *provider) Subscribe(req topicstypes.SubscribeReq) topicstypes.SubscribeResp {
	cAllocated := false

	if req.Chan == nil {
		cAllocated = true
		req.Chan = make(chan topicstypes.SubscribeResp)
	}

	mT.subIn <- req

	resp := <-req.Chan

	if cAllocated {
		close(req.Chan)
	}

	return resp
}

func (mT *provider) UnSubscribe(req topicstypes.UnSubscribeReq) topicstypes.UnSubscribeResp {
	cAllocated := false

	if req.Chan == nil {
		cAllocated = true
		req.Chan = make(chan topicstypes.UnSubscribeResp)
	}

	mT.unSubIn <- req

	resp := <-req.Chan

	if cAllocated {
		close(req.Chan)
	}

	return resp
}

func (mT *provider) Publish(m interface{}) error {
	msg, ok := m.(*mqttp.Publish)
	if !ok {
		return topicstypes.ErrUnexpectedObjectType
	}
	mT.inbound <- msg

	return nil
}

func (mT *provider) Retain(obj vltypes.RetainObject) error {
	mT.inRetained <- obj

	return nil
}

func (mT *provider) Retained(filter string) ([]*mqttp.Publish, error) {
	var r []*mqttp.Publish

	// [MQTT-3.3.1-5]
	mT.retainSearch(filter, &r)

	return r, nil
}

func (mT *provider) Shutdown() error {
	close(mT.inbound)
	close(mT.inRetained)
	close(mT.subIn)
	close(mT.unSubIn)

	mT.wgPublisher.Wait()

	if mT.persist != nil {
		var res []*mqttp.Publish
		// [MQTT-3.3.1-5]
		mT.retainSearch("#", &res)
		mT.retainSearch("/#", &res)

		var encoded []*vlpersistence.PersistedPacket

		for _, pkt := range res {
			// Discard retained expired and QoS0 messages
			if expireAt, _, expired := pkt.Expired(); !expired && pkt.QoS() != mqttp.QoS0 {
				if buf, err := mqttp.Encode(pkt); err != nil {
					mT.log.Error("Couldn't encode retained message", zap.Error(err))
				} else {
					entry := &vlpersistence.PersistedPacket{
						Data: buf,
					}
					if !expireAt.IsZero() {
						entry.ExpireAt = expireAt.Format(time.RFC3339)
					}
					encoded = append(encoded, entry)
				}
			}
		}
		if len(encoded) > 0 {
			mT.log.Debug("Storing retained messages", zap.Int("amount", len(encoded)))
			if err := mT.persist.Store(encoded); err != nil {
				mT.log.Error("Couldn't persist retained messages", zap.Error(err))
			}
		}
	}

	mT.root = nil
	return nil
}

func (mT *provider) retain(obj vltypes.RetainObject) {
	insert := true

	// nolint: gocritic
	switch t := obj.(type) {
	case *mqttp.Publish:
		// [MQTT-3.3.1-10]
		// [MQTT-3.3.1-7]
		if len(t.Payload()) == 0 || t.QoS() == mqttp.QoS0 {
			_ = mT.retainRemove(obj.Topic())
			if len(t.Payload()) == 0 {
				insert = false
			}
		}
	}

	if insert {
		mT.retainInsert(obj.Topic(), obj)
		mT.metricsPackets.OnAddRetain()
	} else {
		mT.metricsPackets.OnSubRetain()
	}
}

func (mT *provider) subscribe(req topicstypes.SubscribeReq) topicstypes.SubscribeResp {
	resp := topicstypes.SubscribeResp{}

	if req.S == nil {
		resp.Err = topicstypes.ErrInvalidArgs
	} else {
		if req.Params.Ops.QoS() > mqttp.QoS2 {
			resp.Err = mqttp.ErrInvalidQoS
		} else {
			req.Params.Granted = req.Params.Ops.QoS()
			resp.Params = req.Params

			exists := mT.subscriptionInsert(req.Filter, req.S, req.Params)

			var r []*mqttp.Publish

			// [MQTT-3.3.1-5]
			rh := req.Params.Ops.RetainHandling()
			if (rh == mqttp.RetainHandlingRetain) || ((rh == mqttp.RetainHandlingIfNotExists) && !exists) {
				mT.retainSearch(req.Filter, &r)
			}

			for _, rt := range r {
				msg, err := rt.Clone(mqttp.ProtocolV50)
				if err != nil {
					mT.log.Errorf("clone error %s", err.Error())
				} else {
					resp.Retained = append(resp.Retained, msg)
				}
			}

			if !exists {
				mT.metricsSubs.OnSubscribe()
			}
		}
	}

	return resp
}

func (mT *provider) subscriber() {
	defer mT.wgPublisher.Done()
	mT.wgPublisherStarted.Done()

	for req := range mT.subIn {
		req.Chan <- mT.subscribe(req)
	}
}

func (mT *provider) unSubscriber() {
	defer mT.wgPublisher.Done()
	mT.wgPublisherStarted.Done()

	for req := range mT.unSubIn {
		err := mT.subscriptionRemove(req.Filter, req.S)
		req.Chan <- topicstypes.UnSubscribeResp{Err: err}
		if err == nil {
			mT.metricsSubs.OnUnsubscribe()
		}
	}
}

func (mT *provider) retainer() {
	defer mT.wgPublisher.Done()
	mT.wgPublisherStarted.Done()

	for obj := range mT.inRetained {
		mT.retain(obj)
	}
}

func (mT *provider) publisher() {
	defer mT.wgPublisher.Done()
	mT.wgPublisherStarted.Done()

	for msg := range mT.inbound {
		pubEntries := publishes{}

		mT.subscriptionSearch(msg.Topic(), msg.PublishID(), &pubEntries)

		for _, pub := range pubEntries {
			for _, e := range pub {
				cl, err := msg.Clone(mqttp.ProtocolV50)
				if err != nil {
					mT.log.Errorf("clone error %s", err.Error())
				} else if err = e.s.Publish(cl, e.qos, e.ops, e.ids); err != nil {
					mT.log.Error("publish error", zap.Error(err))
				}
			}
		}
	}
}


text:
var Wallet = require('@tradle/simple-wallet')
var bitcoin = require('@tradle/bitcoinjs-lib')
var typeforce = require('typeforce')
var utils = require('@tradle/utils')
var crypto = require('crypto')

module.exports = function (options) {
  typeforce({
    unspents: 'Array'
  }, options)

  var walletUnspents = options.unspents
  var total = walletUnspents.reduce(function (sum, n) {
    return sum + n
  }, 0)

  var priv = options.priv
  if (typeof priv === 'string') {
    priv = bitcoin.ECKey.fromWIF(priv)
  } else if (!priv) {
    priv = bitcoin.ECKey.makeRandom(true)
  }

  if (!priv) throw new Error('invalid "priv"')

  var networkName = options.networkName || 'testnet'
  var unspents = []
  var blocks = []
  var blockchain = options.blockchain
  if (!blockchain) {
    var ADDR_CACHE = {}
    blockchain = {
      blocks: {
        get: function (heights, cb) {
          process.nextTick(function () {
            var matched = blocks.filter(function (b) {
              return heights.indexOf(b.blockHeight) !== -1
            })

            if (matched.length) return cb(null, matched)
            else return cb(new Error('no blocks found'))
          })
        },
        latest: function (cb) {
          process.nextTick(function () {
            cb(null, blocks[blocks.length - 1])
          })
        }
      },
      addresses: {
        transactions: function (addrs, height, cb) {
          process.nextTick(function () {
            if (typeof height === 'function') {
              cb = height
              height = 0
            }

            height = height || 0
            var txs = blocks.filter(function (b) {
              return b.blockHeight >= height
            })
            .reduce(function (txs, b) {
              return txs.concat(b.transactions.filter(function (tx) {
                tx.block = b // ugly side effect

                var txId = tx.getId()
                var cached = ADDR_CACHE[txId]
                if (!cached) {
                  cached = ADDR_CACHE[txId] = tx.outs.map(function (out) {
                    return utils.getAddressFromOutput(out, networkName)
                  }).concat(tx.ins.map(function (input) {
                    return utils.getAddressFromInput(input, networkName)
                  })).filter(function (a) {
                    return a // filter out nulls
                  })
                }

                return cached.some(function (addr) {
                  return addrs.indexOf(addr) !== -1
                })
              }))
            }, [])

            if (!txs.length) return cb(null, [])

            cb(null, txs.map(function (tx) {
              return {
                txId: tx.getId(),
                txHex: tx.toHex(),
                blockId: tx.block.getId(),
                blockHeight: tx.block.blockHeight
              }
            }))
          })
        },
        unspents: function (addr, cb) {
          process.nextTick(function () {
            cb(null, unspents)
          })
        },
        summary: function (addrs, cb) {
          process.nextTick(function () {
            cb(null, addrs.map(function (a) {
              return {
                balance: total
              }
            }))
          })
        }
      },
      transactions: {
        get: function (txIds, cb) {
          process.nextTick(function () {
            var txs = blocks.reduce(function (soFar, b) {
              return soFar.concat(b.transactions)
            }, [])
            .filter(function (tx) {
              return txIds.indexOf(tx.getId()) !== -1
            })
            .map(function (tx) {
              return {
                txId: tx.getId(),
                txHex: tx.toHex(),
                blockId: tx.block.getId(),
                blockHeight: tx.block.blockHeight
              }
            })

            cb(null, txs)
          })
        },
        propagate: function (tx, cb) {
          var b = addFakeBlock(blocks)
          b.transactions.push(bitcoin.Transaction.fromHex(tx))
          sendTx(tx, cb)
        }
      },
      _advanceToNextBlock: function () {
        addFakeBlock(blocks)
      }
    }
  }

  var w = new Wallet({
    networkName: networkName,
    blockchain: blockchain,
    priv: priv
  })

  var tx = fund(w.address, walletUnspents)
  tx.outs.forEach(function (o, i) {
    unspents.push({
      txId: tx.getId(),
      confirmations: 6,
      address: w.addressString,
      value: o.value,
      vout: i
    })
  })

  return w
}

function fund (address, walletUnspents) {
  var prevTx = new bitcoin.Transaction()
  prevTx.addInput(new bitcoin.Transaction(), 0)
  walletUnspents.forEach(function (amount) {
    prevTx.addOutput(address.toString(), amount)
  })

  return prevTx
}

function sendTx (tx, cb) {
  process.nextTick(cb)
}

function addFakeBlock (blocks) {
  var b = new bitcoin.Block()
  if (blocks.length) {
    b.prevHash = blocks[blocks.length - 1].getHash()
  } else {
    b.prevHash = crypto.randomBytes(32)
  }

  b.merkleRoot = crypto.randomBytes(32)
  b.timestamp = Date.now() / 1000
  b.bits = Math.random() * 100000000 | 0
  b.nonce = Math.random() * 100000000 | 0
  b.height = b.blockHeight = blocks.length
  b.transactions = []
  blocks.push(b)
  return b
}