text:
package savvytodo.model.task;

import java.time.LocalDateTime;

//@@author A0124863A
/**
 * Represents a time stamp of when the task is added
 */
public class TimeStamp {
    private LocalDateTime dateTimeAdded;
    public static final LocalDateTime DEFAULT_DATE_TIME = LocalDateTime.of(2017, 04, 15, 11, 30);

    public TimeStamp() {
        dateTimeAdded = LocalDateTime.now();
    }

    public TimeStamp(TimeStamp timeStamp) {
        dateTimeAdded = timeStamp.getDateTimeAdded();
    }

    public TimeStamp(LocalDateTime dateTime) {
        dateTimeAdded = dateTime;
    }

    public LocalDateTime getDateTimeAdded() {
        return dateTimeAdded;
    }

    @Override
    public String toString() {
        return dateTimeAdded.toString();
    }

    @Override
    public boolean equals(Object other) {
        if (other == null) {
            return false;
        }

        if (this == other) {
            return true;
        }

        if (!(other instanceof TimeStamp)) {
            return false;
        }

        TimeStamp otherTimeStamp = (TimeStamp) other;
        if (!dateTimeAdded.equals(otherTimeStamp.getDateTimeAdded())) {
            return false;
        }

        return true;

    }
}


text:
package org.basex.query.func.archive;

import static org.basex.query.QueryError.*;
import static org.basex.query.func.archive.ArchiveText.*;
import static org.basex.util.Token.*;

import java.io.*;
import java.util.zip.*;

import org.basex.query.*;
import org.basex.query.func.*;
import org.basex.query.value.*;
import org.basex.query.value.item.*;
import org.basex.query.value.node.*;

/**
 * Function implementation.
 *
 * @author BaseX Team 2005-22, BSD License
 * @author Christian Gruen
 */
public final class ArchiveEntries extends StandardFunc {
  @Override
  public Value value(final QueryContext qc) throws QueryException {
    final B64 archive = toB64(exprs[0], qc, false);

    final ValueBuilder vb = new ValueBuilder(qc);
    try(ArchiveIn in = ArchiveIn.get(archive.input(info), info)) {
      while(in.more()) {
        final ZipEntry ze = in.entry();
        if(ze.isDirectory()) continue;
        final FElem elem = new FElem(Q_ENTRY).declareNS();
        long size = ze.getSize();
        if(size != -1) elem.add(SIZE, token(size));
        size = ze.getTime();
        if(size != -1) elem.add(LAST_MODIFIED, Dtm.get(size).string(info));
        size = ze.getCompressedSize();
        if(size != -1) elem.add(COMPRESSED_SIZE, token(size));
        elem.add(ze.getName());
        vb.add(elem);
      }
      return vb.value(this);
    } catch(final IOException ex) {
      throw ARCHIVE_ERROR_X.get(info, ex);
    }
  }
}

redpajama_set_name: RedPajamaGithub


text:
namespace cc {

class InputHandler;
class LayerTreeHost;
class ResourceUpdateQueue;
class Scheduler;
class ScopedThreadProxy;
class Thread;
class ThreadProxyContextRecreationTimer;

class ThreadProxy : public Proxy, LayerTreeHostImplClient, SchedulerClient, ResourceUpdateControllerClient {
public:
    static scoped_ptr<Proxy> create(LayerTreeHost*);

    virtual ~ThreadProxy();

    // Proxy implementation
    virtual bool compositeAndReadback(void *pixels, const IntRect&) OVERRIDE;
    virtual void startPageScaleAnimation(const IntSize& targetPosition, bool useAnchor, float scale, base::TimeDelta duration) OVERRIDE;
    virtual void finishAllRendering() OVERRIDE;
    virtual bool isStarted() const OVERRIDE;
    virtual bool initializeContext() OVERRIDE;
    virtual void setSurfaceReady() OVERRIDE;
    virtual void setVisible(bool) OVERRIDE;
    virtual bool initializeRenderer() OVERRIDE;
    virtual bool recreateContext() OVERRIDE;
    virtual void renderingStats(RenderingStats*) OVERRIDE;
    virtual const RendererCapabilities& rendererCapabilities() const OVERRIDE;
    virtual void loseContext() OVERRIDE;
    virtual void setNeedsAnimate() OVERRIDE;
    virtual void setNeedsCommit() OVERRIDE;
    virtual void setNeedsRedraw() OVERRIDE;
    virtual void setDeferCommits(bool) OVERRIDE;
    virtual bool commitRequested() const OVERRIDE;
    virtual void didAddAnimation() OVERRIDE { }
    virtual void start() OVERRIDE;
    virtual void stop() OVERRIDE;
    virtual size_t maxPartialTextureUpdates() const OVERRIDE;
    virtual void acquireLayerTextures() OVERRIDE;
    virtual void forceSerializeOnSwapBuffers() OVERRIDE;

    // LayerTreeHostImplClient implementation
    virtual void didLoseContextOnImplThread() OVERRIDE;
    virtual void onSwapBuffersCompleteOnImplThread() OVERRIDE;
    virtual void onVSyncParametersChanged(base::TimeTicks timebase, base::TimeDelta interval) OVERRIDE;
    virtual void onCanDrawStateChanged(bool canDraw) OVERRIDE;
    virtual void setNeedsRedrawOnImplThread() OVERRIDE;
    virtual void setNeedsCommitOnImplThread() OVERRIDE;
    virtual void postAnimationEventsToMainThreadOnImplThread(scoped_ptr<AnimationEventsVector>, base::Time wallClockTime) OVERRIDE;
    virtual bool reduceContentsTextureMemoryOnImplThread(size_t limitBytes, int priorityCutoff) OVERRIDE;
    virtual void sendManagedMemoryStats() OVERRIDE;

    // SchedulerClient implementation
    virtual void scheduledActionBeginFrame() OVERRIDE;
    virtual ScheduledActionDrawAndSwapResult scheduledActionDrawAndSwapIfPossible() OVERRIDE;
    virtual ScheduledActionDrawAndSwapResult scheduledActionDrawAndSwapForced() OVERRIDE;
    virtual void scheduledActionCommit() OVERRIDE;
    virtual void scheduledActionBeginContextRecreation() OVERRIDE;
    virtual void scheduledActionAcquireLayerTexturesForMainThread() OVERRIDE;
    virtual void didAnticipatedDrawTimeChange(base::TimeTicks) OVERRIDE;

    // ResourceUpdateControllerClient implementation
    virtual void readyToFinalizeTextureUpdates() OVERRIDE;

private:
    explicit ThreadProxy(LayerTreeHost*);
    friend class ThreadProxyContextRecreationTimer;

    // Set on impl thread, read on main thread.
    struct BeginFrameAndCommitState {
        BeginFrameAndCommitState();
        ~BeginFrameAndCommitState();

        base::TimeTicks monotonicFrameBeginTime;
        scoped_ptr<ScrollAndScaleSet> scrollInfo;
        WebKit::WebTransformationMatrix implTransform;
        PrioritizedTextureManager::BackingList evictedContentsTexturesBackings;
        size_t memoryAllocationLimitBytes;
    };
    scoped_ptr<BeginFrameAndCommitState> m_pendingBeginFrameRequest;

    // Called on main thread
    void beginFrame();
    void didCommitAndDrawFrame();
    void didCompleteSwapBuffers();
    void setAnimationEvents(AnimationEventsVector*, base::Time wallClockTime);
    void beginContextRecreation();
    void tryToRecreateContext();

    // Called on impl thread
    struct ReadbackRequest {
        CompletionEvent completion;
        bool success;
        void* pixels;
        IntRect rect;
    };
    void forceBeginFrameOnImplThread(CompletionEvent*);
    void beginFrameCompleteOnImplThread(CompletionEvent*, ResourceUpdateQueue*);
    void beginFrameAbortedOnImplThread();
    void requestReadbackOnImplThread(ReadbackRequest*);
    void requestStartPageScaleAnimationOnImplThread(IntSize targetPosition, bool useAnchor, float scale, base::TimeDelta duration);
    void finishAllRenderingOnImplThread(CompletionEvent*);
    void initializeImplOnImplThread(CompletionEvent*, InputHandler*);
    void setSurfaceReadyOnImplThread();
    void setVisibleOnImplThread(CompletionEvent*, bool);
    void initializeContextOnImplThread(GraphicsContext*);
    void initializeRendererOnImplThread(CompletionEvent*, bool* initializeSucceeded, RendererCapabilities*);
    void layerTreeHostClosedOnImplThread(CompletionEvent*);
    void setFullRootLayerDamageOnImplThread();
    void acquireLayerTexturesForMainThreadOnImplThread(CompletionEvent*);
    void recreateContextOnImplThread(CompletionEvent*, GraphicsContext*, bool* recreateSucceeded, RendererCapabilities*);
    void renderingStatsOnImplThread(CompletionEvent*, RenderingStats*);
    ScheduledActionDrawAndSwapResult scheduledActionDrawAndSwapInternal(bool forcedDraw);
    void forceSerializeOnSwapBuffersOnImplThread(CompletionEvent*);
    void setNeedsForcedCommitOnImplThread();

    // Accessed on main thread only.
    bool m_animateRequested; // Set only when setNeedsAnimate is called.
    bool m_commitRequested; // Set only when setNeedsCommit is called.
    bool m_commitRequestSentToImplThread; // Set by setNeedsCommit and setNeedsAnimate.
    bool m_forcedCommitRequested;
    scoped_ptr<ThreadProxyContextRecreationTimer> m_contextRecreationTimer;
    LayerTreeHost* m_layerTreeHost;
    bool m_rendererInitialized;
    RendererCapabilities m_RendererCapabilitiesMainThreadCopy;
    bool m_started;
    bool m_texturesAcquired;
    bool m_inCompositeAndReadback;

    scoped_ptr<LayerTreeHostImpl> m_layerTreeHostImpl;

    scoped_ptr<InputHandler> m_inputHandlerOnImplThread;

    scoped_ptr<Scheduler> m_schedulerOnImplThread;

    scoped_refptr<ScopedThreadProxy> m_mainThreadProxy;

    // Holds on to the context we might use for compositing in between initializeContext()
    // and initializeRenderer() calls.
    scoped_ptr<GraphicsContext> m_contextBeforeInitializationOnImplThread;

    // Set when the main thread is waiting on a scheduledActionBeginFrame to be issued.
    CompletionEvent* m_beginFrameCompletionEventOnImplThread;

    // Set when the main thread is waiting on a readback.
    ReadbackRequest* m_readbackRequestOnImplThread;

    // Set when the main thread is waiting on a commit to complete.
    CompletionEvent* m_commitCompletionEventOnImplThread;

    // Set when the main thread is waiting on layers to be drawn.
    CompletionEvent* m_textureAcquisitionCompletionEventOnImplThread;

    scoped_ptr<ResourceUpdateController> m_currentResourceUpdateControllerOnImplThread;

    // Set when the next draw should post didCommitAndDrawFrame to the main thread.
    bool m_nextFrameIsNewlyCommittedFrameOnImplThread;

    bool m_renderVSyncEnabled;

    base::TimeDelta m_totalCommitTime;
    size_t m_totalCommitCount;

    bool m_deferCommits;
    bool m_deferredCommitPending;
};

}  // namespace cc

#endif


text:
    © {{ site.time | date: '%Y' }}
        Milegao
    {% include ga.html %}


text:
@class IvarInfomation;
@interface NSObject (Base)
//判断是否为
+(BOOL)isBaseTarget;
-(BOOL)isBaseTarget;
//判断是否可以转换保存
-(BOOL)isEnCode;
+(BOOL)isEnCode;

//遍历本类 和 父类
-(void)enumerateObjectsUsingBlock:(void(^)(IvarInfomation *info))Block;

-(void)enumeratePropertyValue:(void(^)(NSString *proName,id value))Block;

+(void)enumerateIvar:(void(^)(NSString *proName))Block;

+(void)enumerateIvar2:(void (^)(NSString *name,NSString *type))Block;

//辅助函数

-(void)db_enumerateClazz:(Class)clazz propertys:(void(^)(objc_property_t t,NSString *name,id value))block;

-(void)db_enumerateClazz:(Class)clazz ivars:(void(^)(Ivar t,NSString *name,id value))block;

+(void)db_enumeratePropertys:(void(^)(objc_property_t t,NSString *name))block;

+(void)db_enumerateIvars:(void(^)(Ivar t,NSString *name))block;
//是否实现摸个协议
+(BOOL)isimplementationProtocol:(NSString *)name;
@end


text:
class DebugTextRenderer;
class DebugVectorRenderer;

class DebugCulling
{
private:
	DebugTextRenderer* textRenderer;
	DebugVectorRenderer* vectorRenderer;

	bool cullingCameraIsLocked;

	Vec2f guideTextPosition;

public:
	DebugCulling(DebugTextRenderer* textRenderer, DebugVectorRenderer* vectorRenderer);
	~DebugCulling();

	void UpdateAndDraw(Scene* scene);

	void SetLockCullingCamera(bool lockCullingCamera);
	void SetGuideTextPosition(const Vec2f& pos) { guideTextPosition = pos; }
};


text:
<!DOCTYPE html>

	<title>WebSocket Client</title>

	<form id="form">
		<input type="text" id="message">
		<button type="submit">Send</button>
	</form>


text:
HM.contentsections = {
  home:[] // Slide 3
, Staying_healthy_during_pregnancy:['Staying_healthy_during_pregnancy'] // Slide 4
, Eating_well_during_pregnancy:['Staying_healthy_during_pregnancy'] // Slide 5-7
, Things_to_avoid_during_pregnancy:['Staying_healthy_during_pregnancy'] // Slide 8
, People_with_rashes:['Staying_healthy_during_pregnancy'] // Slide 9
, Smoking_and_alcohol:['Staying_healthy_during_pregnancy'] // Slide 10
, Chemicals_and_fumes:['Staying_healthy_during_pregnancy'] // Slide 11
, Malaria_during_pregnancy:['Staying_healthy_during_pregnancy'] // Slide 12
, Anemia_during_pregnancy:['Staying_healthy_during_pregnancy'] // Slide 13-14
, Signs_of_malaria:['Staying_healthy_during_pregnancy'] // Slide 15-16
, Common_complaints_during_pregnancy:['Staying_healthy_during_pregnancy'] // Slide 17
, Tiredness_during_pregnancy:['Staying_healthy_during_pregnancy'] // Slide 18
, Increased_vaginal_discharge:['Staying_healthy_during_pregnancy'] // Slide 19
, Nausea_during_pregnancy:['Staying_healthy_during_pregnancy'] // Slide 20-21
, Cravings_during_pregnancy:['Staying_healthy_during_pregnancy'] // Slide 22
, Things_to_check_during_pregnancy:['Staying_healthy_during_pregnancy'] // Slide 23
, Her_temperature:['Staying_healthy_during_pregnancy'] // Slide 24-26
, Her_blood_pressure:['Staying_healthy_during_pregnancy'] // Slide 27-28
, The_position_of_the_baby:['Staying_healthy_during_pregnancy'] // Slide 29-30
, Baby_is_lying_sideways:['Danger_Signs_During_Birth', 'Staying_healthy_during_pregnancy'] // Slide 31
, Signs_of_kidney_or_bladder_infection:['Staying_healthy_during_pregnancy'] // Slide 32-33
, If_she_has_a_bladder_infection:['Staying_healthy_during_pregnancy', 'How_Tos'] // Slide 34-35
, Medicines_for_a_kidney_infection:['Staying_healthy_during_pregnancy'] // Slide 36
, Danger_Signs_During_Pregnancy:['Danger_Signs_During_Pregnancy'] // Slide 37
, Bleeding_during_pregnancy:['Danger_Signs_During_Pregnancy'] // Slide 38
, Bleeding_first_half_pregnancy:['Danger_Signs_During_Pregnancy'] // Slide 39
, Bleeding_second_half_pregnancy:['Danger_Signs_During_Pregnancy'] //  Slide 40
, Severe_abdominal_pain_during_pregnancy:['Danger_Signs_During_Pregnancy'] // Slide 41
, Preeclampsia_during_pregnancy:['Danger_Signs_During_Pregnancy', 'Danger_Signs_During_Birth'] // Slide 42-43
, Severe_preeclampsia:['Danger_Signs_During_Pregnancy', 'Danger_Signs_During_Birth'] // Slide 44
, Seizures_during_pregnancy:['Danger_Signs_During_Pregnancy', 'Danger_Signs_During_Birth'] // Slide 45-46
, Danger_Signs_During_Birth:['Danger_Signs_During_Birth'] // Slide 47
, Too_long_labor:['Danger_Signs_During_Birth'] // Slide 48-49
, What_to_do_strong_labor:['Danger_Signs_During_Birth', 'How_Tos'] // Slide 50
, What_to_do_not_strong_labor:['Danger_Signs_During_Birth'] // Slide 51
, Fever_during_labor:['Danger_Signs_During_Birth'] // Slide 52
, Water_breaks_no_labor:['Danger_Signs_During_Birth'] // Slide 53-54
, Green_or_brown_waters:['Danger_Signs_During_Birth'] // Slide 55-56
, How_to_lower_fever:['How_Tos', '*'] // Slide 57
, Bleeding_during_labor:['Danger_Signs_During_Birth'] // Slide 59
, Danger_Signs_After_Birth:['Danger_Signs_After_Birth'] // Slide 60
, Bleeding_After_Birth:['Danger_Signs_After_Birth'] // Slide 61-62
, Bleeding_Before_Placenta:['Danger_Signs_After_Birth'] // Slide 63-64
, Bleeding_After_Placenta:['Danger_Signs_After_Birth'] // Slide 65-66
, Fever_After_Birth:['Danger_Signs_After_Birth'] // Slide 67-68
, How_Tos:['How_Tos'] // Slide 69-70
, How_to_treat_malaria:['How_Tos', '*'] // Slide 71-72
, How_to_prevent_malaria:['How_Tos', '*'] // Slide 73
, How_to_take_blood_pressure1:['How_Tos', '*'] // Slide 74
, How_to_take_blood_pressure2:['How_Tos', '*'] // Slide 75
, How_to_take_blood_pressure3:['How_Tos', '*'] // Slide 76
, How_to_take_blood_pressure4:['How_Tos', '*'] // Slide 77
, How_to_take_blood_pressure5:['How_Tos', '*'] // Slide 78
, How_to_check_baby_position1:['How_Tos', '*'] // Slide 79-80
, How_to_check_baby_position2:['How_Tos', '*'] // Slide 81
, How_to_check_baby_position3:['How_Tos', '*'] // Slide 82
, How_to_check_baby_position4:['How_Tos', '*'] // Slide 83
, How_to_change_babys_position:['How_Tos', '*'] // Slide 84
, How_to_roll_nipples:['How_Tos', '*'] // Slide 85
, How_to_make_bleach_solution:['How_Tos', '*'] // Slide 86
, How_to_take_temperature1:['How_Tos', '*'] // Slide 87
, How_to_take_temperature2:['How_Tos', '*'] // Slide 88
, How_to_take_temperature3:['How_Tos', '*'] // Slide 89
, How_to_make_rehydration_drink1:['How_Tos', '*'] // Slide 90
, How_to_make_rehydration_drink2:['How_Tos', '*'] // Slide 91-92
, How_to_make_rehydration_drink3:['How_Tos', '*'] // Slide 93
, How_to_help_get_woman_to_hospital:['How_Tos', '*'] // Slide 94
, Shock:['Danger_Signs_After_Birth', 'Danger_Signs_During_Pregnancy', 'Danger_Signs_During_Birth', 'How_Tos'] // Slide 95-97
, How_to_give_rectal_fluids1:['How_Tos', '*'] // Slide 98
, How_to_give_rectal_fluids2:['How_Tos', '*'] // Slide 99
, How_to_give_rectal_fluids3:['How_Tos', '*'] // Slide 100
, How_to_give_rectal_fluids4:['How_Tos', '*'] // Slide 101
, How_to_give_rectal_fluids5:['How_Tos', '*'] // Slide 102
, How_to_give_rectal_fluids6:['How_Tos', '*'] // Slide 103
, How_to_rub_the_womb:['How_Tos', '*'] // Slide 104
, How_to_suction1:['How_Tos', '*'] // Slide 105
, How_to_suction2:['How_Tos', '*'] // Slide 106
, How_to_suction3:['How_Tos', '*'] // Slide 107
, How_to_suction4:['How_Tos', '*'] // Slide 108
, How_to_give_castor_oil1:['How_Tos', '*'] // Slide 109
, How_to_give_castor_oil2:['How_Tos', '*'] // Slide 110
, How_to_inject_medicines_into_muscle:['How_Tos', '*'] // Slide 111
, Injection_from_ampule1:['How_Tos', '*'] // Slide 112
, Injection_from_ampule2:['How_Tos', '*'] // Slide 113
, Injection_from_ampule3:['How_Tos', '*'] // Slide 114
, Injection_from_bottle1:['How_Tos', '*'] // Slide 115
, Injection_from_bottle2:['How_Tos', '*'] // Slide 116
, Injection_from_bottle3:['How_Tos', '*'] // Slide 117
, How_to_inject_medicines_into_muscle4:['How_Tos', '*'] // Slide 118
, How_to_inject_medicines_into_muscle5:['How_Tos', '*'] // Slide 119
, How_to_inject_medicines_into_muscle6:['How_Tos', '*'] // Slide 120
, How_to_inject_medicines_into_muscle7:['How_Tos', '*'] // Slide 121
, How_to_give_magnesium_sulfate1:['How_Tos', '*'] // Slide 122
, How_to_give_magnesium_sulfate2:['How_Tos', '*'] // Slide 123
, How_to_give_medicine_to_stop_bleeding:['How_Tos', '*'] // Slide 124-125
, How_to_check_for_protein_in_urine1:['How_Tos', '*'] // Slide 126-127
, How_to_check_for_protein_in_urine2:['How_Tos', '*'] // Slide 128-129
, Foods_with_iron:['Staying_healthy_during_pregnancy'] // Slide 130
, Fever_during_pregnancy:['Staying_healthy_during_pregnancy'] // Slide 131-132
, Unnecessary_medicines:['Staying_healthy_during_pregnancy']
, How_to_treat_yeast_infections:['Staying_healthy_during_pregnancy','How_Tos']
, How_to_treat_infection_during_labor:['Danger_Signs_During_Birth','Danger_Signs_After_Birth','How_Tos']
};


text:
'use strict';

// Call this function when the page loads (the "ready" event)
$(document).ready(function() {
	initializePage();
})

/*
 * Function that is called when the document is ready.
 */
function initializePage() {
	$("#testjs").click(function(e) {
		$('.jumbotron h1').text("Javascript is connected, yay!");
		$("#testjs").text("We're no strangers to love.");
		$(".jumbotron p").toggleClass("active");
	});

	// Add any additional listeners here
	// example: $("#div-id").click(functionToCall);
	$("a.thumbnail").click(projectClick);

	$("#submitBtn").click(updateProject);

}

function projectClick(e) {
  // Cancel the default action, which prevents the page from reloading
    e.preventDefault();

    // In an event listener, $(this) is the leement that fired the event
    var projectTitle = $(this).find("p").text();
    var jumbotronHeader = $(".jumbotron h1");
    jumbotronHeader.text(projectTitle);

    var containingProject = $(this).closest(".project");
    var description = $(containingProject).find(".project-description");

    if (description.length == 0) {
        $(containingProject).append("

Description of the project.

");
    } else {
    	$(containingProject).fadeToggle();

    	/*
    	$(".project-description").fadeToggle();
        $(".project p").fadeToggle();
        $(".project img").fadeToggle();*/
    }

}

function updateProject(e) {
	var projectID = $('#project').val();
	$(projectID).animate({
		width: $('#width').val()
	});

	var newText = $('#description').val();
	$(projectID + " .project-description").text(newText);
}


text:
package com.sheetsj.test;

import static com.sheetsj.test.matchers.CustomMatchers.isStringInjected;
import static org.junit.Assert.assertThat;

import org.junit.Test;
import org.springframework.beans.factory.annotation.Value;

/**
 * Tests needed most for properties that are in the database.
 *
 * But also good for checking for badly spelled keys.
 *
 * And spring could be configured to ignore missing properties!
 */
public class PropertiesIT extends IntegrationTestBaseClass {

	@Value("${another.property}")
	private String anotherProperty;

	@Test
	public void testAnotherProperty() {
		assertThat(anotherProperty, isStringInjected());
	}
}


text:
package interview.javaquestions.seriliazable;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class Driver {
   public static void main(String[] args) throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException {

      Class refObj = Class.forName("interview.javaquestions.seriliazable.Employee");
      Employee employee = (Employee) refObj.newInstance();

      Employee s1 = new Employee(10001, "John");

      FileOutputStream fout = new FileOutputStream("D:/Demo/test.txt");
      ObjectOutputStream out = new ObjectOutputStream(fout);

      out.writeObject(s1);
      out.flush();
      out.close();

      s1.name = "I have changed your name";

      FileInputStream fin = new FileInputStream("D:/Demo/test.txt");
      ObjectInputStream in = new ObjectInputStream(fin);
      Employee s2 = (Employee) in.readObject();
      System.out.println(s2.getName());
      System.out.println(s2.name);
      in.close();
   }
}


text:
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>basic_signal_set::add (2 of 2 overloads)</title>
<link rel="stylesheet" href="../../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.76.1">
<link rel="home" href="../../../../boost_asio.html" title="Boost.Asio">
<link rel="up" href="../add.html" title="basic_signal_set::add">
<link rel="prev" href="overload1.html" title="basic_signal_set::add (1 of 2 overloads)">
<link rel="next" href="../async_wait.html" title="basic_signal_set::async_wait">

Home
Libraries
People
FAQ
More

basic_signal_set::add
          (2 of 2 overloads)

            Add a signal to a signal_set.

boost::system::error_code add(
    int signal_number,
    boost::system::error_code & ec);

            This function adds the specified signal to the set. It has no effect
            if the signal is already in the set.

            Parameters

signal_number

                  The signal to be added to the set.

ec

                  Set to indicate what error occurred, if any.

Copyright © 2003-2015 Christopher M.
      Kohlhoff

        Distributed under the Boost Software License, Version 1.0. (See accompanying
        file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)


text:
var gridOptions = {
    columnDefs: [
        { field: 'country', rowGroup: true, hide: true },
        { field: 'accountId', hide: true },
        { field: 'name' },
        { field: 'calls' },
        { field: 'totalDuration' }
    ],
    defaultColDef: {
        flex: 1
    },
    autoGroupColumnDef: {
        field: 'accountId'
    },
    animateRows: true,

    // use the server-side row model
    rowModelType: 'serverSide',
    serverSideStoreType: 'partial',

    // enable master detail
    masterDetail: true,

    detailCellRendererParams: {
        detailGridOptions: {
            columnDefs: [
                { field: 'callId' },
                { field: 'direction' },
                { field: 'duration', valueFormatter: "x.toLocaleString() + 's'" },
                { field: 'switchCode' },
                { field: 'number' },
            ],
            defaultColDef: {
                flex: 1
            }
        },
        getDetailRowData: function(params) {
            // supply details records to detail cell renderer (i.e. detail grid)
            params.successCallback(params.data.callRecords);
        }
    },
    onGridReady: function(params) {
        setTimeout(function() {
            // expand some master row
            var someRow = params.api.getRowNode("1");
            if (someRow) {
                someRow.setExpanded(true);
            }
        }, 1000);
    }
};

function ServerSideDatasource(server) {
    return {
        getRows: function(params) {
            console.log('[Datasource] - rows requested by grid: ', params.request);

            var response = server.getData(params.request);

            // adding delay to simulate real server call
            setTimeout(function() {
                if (response.success) {
                    // call the success callback
                    params.success({ rowData: response.rows, rowCount: response.lastRow });
                } else {
                    // inform the grid request failed
                    params.fail();
                }
            }, 200);
        }
    };
}

// setup the grid after the page has finished loading
document.addEventListener('DOMContentLoaded', function() {
    var gridDiv = document.querySelector('#myGrid');
    new agGrid.Grid(gridDiv, gridOptions);

    agGrid.simpleHttpRequest({ url: 'https://www.ag-grid.com/example-assets/call-data.json' }).then(function(data) {
        // setup the fake server with entire dataset
        var fakeServer = new FakeServer(data);

        // create datasource with a reference to the fake server
        var datasource = new ServerSideDatasource(fakeServer);

        // register the datasource with the grid
        gridOptions.api.setServerSideDatasource(datasource);
    });
});


text:
import {AddressInfo} from 'net';
import {WebSocketServer, WebSocket} from 'ws';

import {FlipperClient, FlipperWebSocket} from '../client';
import {RECONNECT_TIMEOUT} from '../consts';
import {WSMessageAccumulator} from './utils';

// Jest fake timer doesn't play well with process.nextTick.
// "ws" since version 8.6.0 uses process.nextTick for emitting "abortHandshake" event:
// https://github.com/websockets/ws/commit/d086f4bcbbe235f12f6fa2ddba5a8ce1342dac58.
// Because of that, "error" event is never emitted on websocket client when fake timer is used.
// To fix that we switched to "sinon" fake timer instead of jest.
// Sinon work just fine in this case.
import sinon from 'sinon';

describe('client', () => {
  let port: number;
  let wsServer: WebSocketServer;
  let client: FlipperClient;
  let urlBase: string;
  let clock: sinon.SinonFakeTimers;
  // TODO: Figure out why we need to convert ot unknown first
  const websocketFactory = (url: string) =>
    new WebSocket(url) as unknown as FlipperWebSocket;

  let allowConnection = true;
  const verifyClient = jest.fn().mockImplementation(() => allowConnection);
  beforeEach(() => {
    allowConnection = true;
  });

  beforeAll(() => {
    clock = sinon.useFakeTimers();
  });
  afterAll(() => {
    clock.restore();
  });

  beforeEach(async () => {
    wsServer = new WebSocketServer({
      port: 0,
      verifyClient,
    });
    await new Promise((resolve) => wsServer.on('listening', resolve));
    port = (wsServer.address() as AddressInfo).port;
    client = new FlipperClient();
    urlBase = `localhost:${port}`;
  });
  afterEach(async () => {
    client.stop();
    await new Promise((resolve) => wsServer.close(resolve));
  });

  describe('message handling', () => {
    describe('getPlugins', () => {
      it('returns a list of registered plugins', async () => {
        const serverReceivedMessages = new WSMessageAccumulator();
        wsServer.on('connection', (ws) => {
          ws.send(JSON.stringify({method: 'getPlugins', id: 0}));
          ws.on('message', (message) =>
            serverReceivedMessages.add(message.toString()),
          );
        });

        client.addPlugin({
          getId: () => '42',
          onConnect: () => undefined,
          onDisconnect: () => undefined,
        });

        await client.start('universe', {urlBase, websocketFactory});

        const expectedGetPluginsResponse = {
          id: 0,
          success: {
            plugins: ['42'],
          },
        };
        const actualGetPluginsReponse = await serverReceivedMessages.newMessage;
        expect(actualGetPluginsReponse).toBe(
          JSON.stringify(expectedGetPluginsResponse),
        );
      });
    });

    it('onError is called if message handling has failed, connection is closed, client reconnects', async () => {
      const onError = jest.fn();

      let resolveFirstConnectionPromise: () => void;
      const firstConnectionPromise = new Promise<void>((resolve) => {
        resolveFirstConnectionPromise = resolve;
      });
      wsServer.on('connection', (ws) => {
        resolveFirstConnectionPromise();
        // Send a malformed message to cause a failure
        ws.send('{{{');
      });

      // Capturing a moment when the client received an error
      const receivedErrorPromise = new Promise<void>((resolve) =>
        onError.mockImplementationOnce(() => {
          resolve();
        }),
      );

      await client.start('universe', {urlBase, websocketFactory, onError});

      // Capturing a moment when the client was closed because of the error
      const closedPromise = new Promise<void>((resolve) => {
        const originalOnclose = (client as any).ws.onclose;
        (client as any).ws.onclose = (data: unknown) => {
          originalOnclose(data);
          resolve();
        };
      });

      await receivedErrorPromise;
      expect(onError).toBeCalledTimes(1);

      // Make sure that the connection went through
      await firstConnectionPromise;

      wsServer.removeAllListeners('connection');

      let resolveSecondConnectionPromise: () => void;
      const secondConnectionPromise = new Promise<void>((resolve) => {
        resolveSecondConnectionPromise = resolve;
      });
      wsServer.on('connection', () => {
        resolveSecondConnectionPromise();
      });

      // Make sure the current client is closed
      // When it closes, it schedules a reconnection
      await closedPromise;

      // Now, once the reconnection is scheduled, we can advance timers to do the actual reconnection
      clock.tick(RECONNECT_TIMEOUT);

      // Make sure that the client reconnects
      await secondConnectionPromise;
    });
  });

  describe('connection', () => {
    it('onError is called if connection has failed, it is called every time Flipper fails to reconnect', async () => {
      allowConnection = false;

      const onError = jest.fn();

      expect(onError).toBeCalledTimes(0);
      client.start('universe', {urlBase, websocketFactory, onError});

      // Expect connection request to fail
      await new Promise((resolve) => onError.mockImplementationOnce(resolve));
      expect(onError).toBeCalledTimes(1);
      // Checking that the request went through to the server
      expect(verifyClient).toBeCalledTimes(1);

      // Exepect reconnection attempts to fail
      for (let i = 2; i < 10; i++) {
        clock.tick(RECONNECT_TIMEOUT);
        await new Promise((resolve) => onError.mockImplementationOnce(resolve));
        expect(onError).toBeCalledTimes(i);
        expect(verifyClient).toBeCalledTimes(i);
      }
    });
  });
});


text:
require 'sidebar'
require 'mp3_sidebar'

Mp3Sidebar.view_root = File.dirname(__FILE__) + '/app/views'


text:
import React from 'react'
import {Route, Link} from 'react-router-dom'
const MenuLink = ({ label, to, activeOnlyWhenExact }) => (
    <Route path={to} exact={activeOnlyWhenExact} children={({ match }) => (
        <li className={match ? 'active' : ''}>
            <Link to={to}>{label}</Link>
        </li>
    )}/>
)
export default MenuLink


text:
import unittest
import versioneer
from codecs import open
from os import path
from setuptools import setup, find_packages

def test_suite():
    test_loader = unittest.TestLoader()
    suite = test_loader.discover('tests', pattern='test_*.py')
    return suite

here = path.abspath(path.dirname(__file__))

with open(path.join(here, 'README.rst'), encoding='utf-8') as readme_file:
    readme = readme_file.read()

with open(path.join(here, 'HISTORY.rst'), encoding='utf-8') as history_file:
    history = history_file.read().replace('.. :changelog:', '')

requirements = [
]

test_requirements = [
]

setup(
    name='confusable_homoglyphs',
    version=versioneer.get_version(),
    cmdclass=versioneer.get_cmdclass(),
    description='Detect confusable usage of unicode homoglyphs, prevent homograph attacks.',
    long_description=readme + '\n\n' + history,
    author='Victor Felder',
    author_email='victorfelder@gmail.com',
    url='https://github.com/vhf/confusable_homoglyphs',
    packages=find_packages(exclude=['contrib', 'docs', 'tests']),
    entry_points={
        'console_scripts': [
            'confusable_homoglyphs=confusable_homoglyphs.cli:cli',
            ],
        },
    include_package_data=True,
    install_requires=requirements,
    license="MIT",
    keywords=['confusable', 'homoglyph', 'attack', 'homograph', 'unicode', 'spoofing'],
    classifiers=[
        'Development Status :: 5 - Production/Stable',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Natural Language :: English',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.5',
        'Topic :: Text Processing :: Filters',
        'Topic :: Text Processing',
        'Topic :: Utilities',
    ],
    test_suite='setup.test_suite',
    tests_require=test_requirements
)


text:
describe('Unit Test: myapp module', function() {
	var appCtrl;
	var $scope;
	var $location;

	beforeEach(module("myapp"));
	beforeEach(inject(function($rootScope, $controller, _$location_) {
		$location = _$location_;
		$scope = $rootScope.$new();
		appCtrl = $controller('AppController', {$scope: $scope});
	}));

	describe("Controller: App Controller", function() {
		it("should have a method to check if the path is active", function() {
			$location.path('/');
			expect($location.path()).toBe("/");
			expect($scope.isActive('/')).toBe(true);
			expect($scope.isActive('/people')).toBe(false);
		})
	});
});


text:
<?php

namespace Phpactor\WorseReflection\Tests\Benchmarks;

use Phpactor\WorseReflection\Core\ClassName;
use Phpactor\WorseReflection\Tests\Benchmarks\Examples\MethodClass;
use Phpactor\WorseReflection\Bridge\TolerantParser\Reflection\ReflectionClass;

/**
 * @Iterations(10)
 * @Revs(30)
 * @OutputTimeUnit("milliseconds", precision=2)
 */
class ReflectMethodBench extends BaseBenchCase
{
    /**
     * @var ReflectionClass
     */
    private $class;

    public function setUp(): void
    {
        parent::setUp();
        $this->class = $this->getReflector()->reflectClassLike(ClassName::fromString(MethodClass::class));
    }

    /**
     * @Subject()
     */
    public function method(): void
    {
        $this->class->methods()->get('methodNoReturnType');
    }

    /**
     * @Subject()
     */
    public function method_return_type(): void
    {
        $this->class->methods()->get('methodWithReturnType')->returnType();
    }

    /**
     * @Subject()
     */
    public function method_inferred_return_type(): void
    {
        $this->class->methods()->get('methodWithDocblockReturnType')->inferredReturnTypes()->best();
    }
}


text:
class RendererWorker
{
public:

};


text:
using System;
using System.Linq;
using System.Windows.Forms;
using ChangeWallpaper;

namespace DesktopSeasons
{
    partial class MainForm
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm));
            this.StartBtn = new System.Windows.Forms.Button();
            this.lblLine = new System.Windows.Forms.Label();
            this.lblImagePosition = new System.Windows.Forms.Label();
            this.cmbBoxStretch = new System.Windows.Forms.ComboBox();
            this.SuspendLayout();
            //
            // StartBtn
            //
            resources.ApplyResources(this.StartBtn, "StartBtn");
            this.StartBtn.Name = "StartBtn";
            this.StartBtn.UseVisualStyleBackColor = true;
            this.StartBtn.Click += new System.EventHandler(this.StartBtn_Click);
            //
            // lblLine
            //
            this.lblLine.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
            resources.ApplyResources(this.lblLine, "lblLine");
            this.lblLine.Name = "lblLine";
            //
            // lblImagePosition
            //
            resources.ApplyResources(this.lblImagePosition, "lblImagePosition");
            this.lblImagePosition.Name = "lblImagePosition";
            //
            // cmbBoxStretch
            //
            this.cmbBoxStretch.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.cmbBoxStretch.FormattingEnabled = true;
            resources.ApplyResources(this.cmbBoxStretch, "cmbBoxStretch");
            this.cmbBoxStretch.Name = "cmbBoxStretch";
            this.cmbBoxStretch.SelectedIndexChanged += new System.EventHandler(this.cmbBoxStretch_SelectedIndexChanged);
            var styles = Enum.GetValues(typeof(StretchStyle)).Cast<StretchStyle>().Select(style =>
                new StretchStyleView(style, resources.GetObject(style.ToString()).ToString())).ToList();
            cmbBoxStretch.DisplayMember = "StyleName";
            cmbBoxStretch.ValueMember = "Style";
            cmbBoxStretch.DataSource = styles;
            //
            // MainForm
            //
            resources.ApplyResources(this, "$this");
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.BackColor = System.Drawing.Color.LightYellow;
            this.Controls.Add(this.cmbBoxStretch);
            this.Controls.Add(this.lblImagePosition);
            this.Controls.Add(this.lblLine);
            this.Controls.Add(this.StartBtn);
            this.MaximizeBox = false;
            this.Name = "MainForm";
            this.ResumeLayout(false);
            this.PerformLayout();

            this.FormBorderStyle = FormBorderStyle.FixedSingle;
        }

        #endregion

        private System.Windows.Forms.Button StartBtn;
        private System.Windows.Forms.Label lblLine;
        private System.Windows.Forms.Label lblImagePosition;
        private System.Windows.Forms.ComboBox cmbBoxStretch;
    }
}


text:
import { assert, expect } from 'chai';

import * as fullscreen from './fullscreen';

class MockTerminal {}

describe('fullscreen addon', () => {
  describe('apply', () => {
    it('should do register the `toggleFullscreen` method', () => {
      fullscreen.apply(<any>MockTerminal);
      assert.equal(typeof (<any>MockTerminal).prototype.toggleFullScreen, 'function');
    });
  });
});


text:
// Copyright 2017 Trimble Inc. All Rights Reserved.

#ifndef SKETCHUP_MODEL_ENTITY_LIST_ITERATOR_H_
#define SKETCHUP_MODEL_ENTITY_LIST_ITERATOR_H_

#include <SketchUpAPI/model/defs.h>

#ifdef __cplusplus
extern "C" {
#endif

/**
@struct SUEntityListIteratorRef
@brief  References an entity list iterator object.
@since SketchUp 2018, API 6.0
*/

/**
@brief Creates an entity list iterator object.
@since SketchUp 2018, API 6.0
@param[in,out] iterator The entity list iterator object to be created.
@return
- \ref SU_ERROR_NONE on success
- \ref SU_ERROR_NULL_POINTER_OUTPUT if iterator is NULL
- \ref SU_ERROR_OVERWRITE_VALID if iterator already references a valid object
*/
SU_RESULT SUEntityListIteratorCreate(SUEntityListIteratorRef* iterator);

/**
@brief Releases a iterator object.
@since SketchUp 2018, API 6.0
@param[in,out] iterator The iterator object to be released.
@return
- \ref SU_ERROR_NONE on success
- \ref SU_ERROR_NULL_POINTER_INPUT if iterator is NULL
- \ref SU_ERROR_INVALID_INPUT if iterator does not reference a valid object
*/
SU_RESULT SUEntityListIteratorRelease(SUEntityListIteratorRef* iterator);

/**
@brief Retrieves the specified entity pointer from the given iterator.
@since SketchUp 2018, API 6.0
@param[in]  iterator The iterator from which to retrieve the entity.
@param[out] entity   The entity reference retrieved.
@return
- \ref SU_ERROR_NONE on success
- \ref SU_ERROR_INVALID_INPUT if iterator is not a valid object
- \ref SU_ERROR_NULL_POINTER_OUTPUT if entity is NULL
- \ref SU_ERROR_NO_DATA if the iterator references an invalid entity
*/
SU_RESULT SUEntityListIteratorGetEntity(SUEntityListIteratorRef iterator,
    SUEntityRef* entity);

/**
@brief Increments the provided iterator.
@since SketchUp 2018, API 6.0
@param[in,out] iterator The iterator to be incremented.
@return
- \ref SU_ERROR_NONE on success
- \ref SU_ERROR_INVALID_INPUT if iterator is not a valid object
- \ref SU_ERROR_OUT_OF_RANGE if reached the end of the collection
*/
SU_RESULT SUEntityListIteratorNext(SUEntityListIteratorRef iterator);

/**
@brief Checks if the iterator is still within range of the list.
@since SketchUp 2018, API 6.0
@param[in]  iterator The iterator to be queried.
@param[out] in_range A boolean indicating if the iterator is in range.
@return
- \ref SU_ERROR_NONE on success
- \ref SU_ERROR_INVALID_INPUT if iterator is not a valid object
- \ref SU_ERROR_NULL_POINTER_OUTPUT if in_range is NULL
- \ref SU_ERROR_OUT_OF_RANGE if the iterator is at the end of the collection
*/
SU_RESULT SUEntityListIteratorIsInRange(SUEntityListIteratorRef iterator,
    bool* in_range);

#ifdef __cplusplus
}  // extern "C"
#endif

#endif  // SKETCHUP_MODEL_ENTITY_LIST_ITERATOR_H_


text:
class Artifactory < Formula
  desc "Manages binaries"
  homepage "https://www.jfrog.com/artifactory/"
  # v7 is available but does contain a number of pre-builts that need to be avoided.
  # Note that just using the source archive is not sufficient.
  url "https://releases.jfrog.io/artifactory/bintray-artifactory/org/artifactory/oss/jfrog-artifactory-oss/6.23.28/jfrog-artifactory-oss-6.23.28.zip"
  sha256 "8103b759039d3bab2d574489d24e7c545bfdd3c39860196ae499a804caa72ba2"
  license "AGPL-3.0-or-later"

  livecheck do
    url "https://releases.jfrog.io/artifactory/bintray-artifactory/org/artifactory/oss/jfrog-artifactory-oss/"
    regex(/href=.*?v?(\d+(?:\.\d+)+)/i)
  end

  bottle do
    sha256 cellar: :any_skip_relocation, all: "7eb9248efd35855b9e5e0077338d497cd95dc499fb0d568de2eef9134c1ffd77"
  end

  depends_on "openjdk"

  def install
    # Remove Windows binaries
    rm_f Dir["bin/*.bat"]
    rm_f Dir["bin/*.exe"]

    # Prebuilts
    rm_rf "bin/metadata"

    # Set correct working directory
    inreplace "bin/artifactory.sh",
      'export ARTIFACTORY_HOME="$(cd "$(dirname "${artBinDir}")" && pwd)"',
      "export ARTIFACTORY_HOME=#{libexec}"

    libexec.install Dir["*"]

    # Launch Script
    bin.install libexec/"bin/artifactory.sh"
    # Memory Options
    bin.install libexec/"bin/artifactory.default"

    bin.env_script_all_files libexec/"bin", JAVA_HOME: Formula["openjdk"].opt_prefix
  end

  def post_install
    # Create persistent data directory. Artifactory heavily relies on the data
    # directory being directly under ARTIFACTORY_HOME.
    # Therefore, we symlink the data dir to var.
    data = var/"artifactory"
    data.mkpath

    libexec.install_symlink data => "data"
  end

  service do
    run opt_bin/"artifactory.sh"
    keep_alive true
    working_dir libexec
  end

  test do
    assert_match "Checking arguments to Artifactory", pipe_output("#{bin}/artifactory.sh check")
  end
end


text:
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://maven.apache.org/POM/4.0.0"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>com.wayneleo.quickstart</groupId>
        <artifactId>publish</artifactId>
        <version>0.2.0-SNAPSHOT</version>
    </parent>
    <artifactId>publish-dependencies</artifactId>
    <packaging>pom</packaging>

    <properties>
        <spring.boot.version>1.5.4.RELEASE</spring.boot.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>${project.groupId}</groupId>
            <artifactId>framework-apidocs</artifactId>
            <version>${project.version}</version>
        </dependency>
        <dependency>
            <groupId>${project.groupId}</groupId>
            <artifactId>publish-configuration</artifactId>
            <version>${project.version}</version>
        </dependency>
        <dependency>
            <groupId>${project.groupId}</groupId>
            <artifactId>framework-core</artifactId>
            <version>${project.version}</version>
        </dependency>
    </dependencies>

</project>


text:
import bz2
import gzip
import io
import os

from . import p7z
from ..errors import FileTypeError

def plain_reader(fn):
    return open(fn, 'rt', encoding='utf-8', errors='replace')

def plain_writer(fn):
    return open(fn, 'wt', encoding='utf-8', errors='replace')

FILE_READERS = {
    'gz': lambda fn: gzip.open(fn, 'rt', encoding='utf-8', errors='replace'),
    'bz2': lambda fn: bz2.open(fn, 'rt', encoding='utf-8', errors='replace'),
    '7z': p7z.reader
}
"""
Maps extensions to the strategy for opening/decompressing a file
"""

FILE_WRITERS = {
    'gz': lambda fn: gzip.open(fn, 'wt', encoding='utf-8', errors='replace'),
    'bz2': lambda fn: bz2.open(fn, 'wt', encoding='utf-8', errors='replace')
}
"""
Maps compression types to the strategy for opening/compressing a file
"""

def extract_extension(path):
    """
    Reads a file path and returns the extension or None if the path
    contains no extension.

    :Parameters:
        path : str
            A filesystem path
    """
    filename = os.path.basename(path)
    parts = filename.split(".")
    if len(parts) == 1:
        return filename, None
    else:
        return ".".join(parts[:-1]), parts[-1]

def normalize_path(path_or_f):
    """
    Verifies that a file exists at a given path and that the file has a
    known extension type.

    :Parameters:
        path_or_f : `str` | `file`
            the path to a dump file or a file handle

    """
    if hasattr(path_or_f, "read"):
        return path_or_f
    else:
        path = path_or_f

    path = os.path.expanduser(path)

    # Check if exists and is a file
    if os.path.isdir(path):
        raise IsADirectoryError("Is a directory: {0}".format(path))
    elif not os.path.isfile(path):
        raise FileNotFoundError("No such file: {0}".format(path))

    _, extension = extract_extension(path)

    return path

def normalize_dir(path):
    if os.path.exists(path) and not os.path.isdir(path):
        raise NotADirectoryError("Not a directory: {0}".format(path))
    else:
        os.makedirs(path, exist_ok=True)

    return path

def reader(path_or_f):
    """
    Turns a path to a compressed file into a file-like object of (decompressed)
    data.

    :Parameters:
        path : `str`
            the path to the dump file to read
    """
    if hasattr(path_or_f, "read"):
        return path_or_f
    else:
        path = path_or_f

    path = normalize_path(path)
    _, extension = extract_extension(path)

    if extension in FILE_READERS:
        reader_func = FILE_READERS[extension]
    else:
        reader_func = plain_reader

    return reader_func(path)

def output_dir_path(old_path, output_dir, compression):
    filename, extension = extract_extension(old_path)
    new_filename = filename + "." + compression
    return os.path.join(output_dir, new_filename)

def writer(path):
    """
    Creates a compressed file writer from for a path with a specified
    compression type.
    """
    filename, extension = extract_extension(path)
    if extension in FILE_WRITERS:
        writer_func = FILE_WRITERS[extension]
        return writer_func(path)
    else:
        return plain_writer(path)

class ConcatinatingTextReader(io.TextIOBase):

    def __init__(self, *items):
        self.items = [io.StringIO(i) if isinstance(i, str) else i
                      for i in items]

    def read(self, size=-1):
        return "".join(self._read(size))

    def readline(self):

        if len(self.items) > 0:
            line = self.items[0].readline()
            if line == "":
                self.items.pop(0)
        else:
            line = ""

        return line

    def _read(self, size):
        if size > 0:
            while len(self.items) > 0:
                byte_vals = self.items[0].read(size)
                yield byte_vals
                if len(byte_vals) < size:
                    size = size - len(byte_vals)  # Decrement bytes
                    self.items.pop(0)
                else:
                    break

        else:
            for item in self.items:
                yield item.read()

def concat(*stream_items):
    """
    Performs a streaming concatenation of `str` or `file`.
    :Parameters:
        \*stream_items : `str` | `file`
            A list of items to concatenate together
    """
    return ConcatinatingTextReader(*stream_items)


text:
from pandas.core.groupby.base import transformation_kernels

# tshift only works on time index and is deprecated
# There is no Series.cumcount or DataFrame.cumcount
series_transform_kernels = [
    x for x in sorted(transformation_kernels) if x not in ["tshift", "cumcount"]
]
frame_transform_kernels = [
    x for x in sorted(transformation_kernels) if x not in ["tshift", "cumcount"]
]


text:
// Copyright (C) 2001-2003
// William E. Kempf
//
// Permission to use, copy, modify, distribute and sell this software
// and its documentation for any purpose is hereby granted without fee,
// provided that the above copyright notice appear in all copies and
// that both that copyright notice and this permission notice appear
// in supporting documentation.  William E. Kempf makes no representations
// about the suitability of this software for any purpose.
// It is provided "as is" without express or implied warranty.
//////////////////////////////////////////////////////////////////////////////
//
// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/interprocess for documentation.
//
//////////////////////////////////////////////////////////////////////////////
#ifndef BOOST_INTERPROCESS_CONDITION_TEST_TEMPLATE_HPP
#define BOOST_INTERPROCESS_CONDITION_TEST_TEMPLATE_HPP

#include <boost/interprocess/detail/config_begin.hpp>
#include <boost/interprocess/detail/workaround.hpp>
#include <boost/interprocess/detail/os_thread_functions.hpp>
#include "boost_interprocess_check.hpp"
#include <boost/interprocess/sync/scoped_lock.hpp>
#include "util.hpp"
#include <iostream>

namespace boost{
namespace interprocess{
namespace test {

template <typename F, typename T>
class binder
{
public:
    binder(const F& f, const T& p)
        : func(f), param(p) { }
    void operator()() const { func(param); }

private:
    F func;
    T param;
};

template <typename F, typename T>
binder<F, T> bind_function(F func, T param)
{
    return binder<F, T>(func, param);
}

template <class Condition, class Mutex>
struct condition_test_data
{
   condition_test_data() : notified(0), awoken(0) { }

   ~condition_test_data()
   {}

   Mutex      mutex;
   Condition  condition;
   int notified;
   int awoken;
};

template <class Condition, class Mutex>
void condition_test_thread(condition_test_data<Condition, Mutex>* data)
{
    boost::interprocess::scoped_lock<Mutex>
      lock(data->mutex);
    BOOST_INTERPROCESS_CHECK(lock ? true : false);
    while (!(data->notified > 0))
        data->condition.wait(lock);
    BOOST_INTERPROCESS_CHECK(lock ? true : false);
    data->awoken++;
}

struct cond_predicate
{
    cond_predicate(int& var, int val) : _var(var), _val(val) { }

    bool operator()() { return _var == _val; }

    int& _var;
    int _val;
};

template <class Condition, class Mutex>
void condition_test_waits(condition_test_data<Condition, Mutex>* data)
{
    boost::interprocess::scoped_lock<Mutex>
      lock(data->mutex);
    BOOST_INTERPROCESS_CHECK(lock ? true : false);

    // Test wait.
    while (data->notified != 1)
        data->condition.wait(lock);
    BOOST_INTERPROCESS_CHECK(lock ? true : false);
    BOOST_INTERPROCESS_CHECK(data->notified == 1);
    data->awoken++;
    data->condition.notify_one();

    // Test predicate wait.
    data->condition.wait(lock, cond_predicate(data->notified, 2));
    BOOST_INTERPROCESS_CHECK(lock ? true : false);
    BOOST_INTERPROCESS_CHECK(data->notified == 2);
    data->awoken++;
    data->condition.notify_one();

    // Test timed_wait
    while (data->notified != 3)
        data->condition.timed_wait(lock, ptime_delay(5));
    BOOST_INTERPROCESS_CHECK(lock ? true : false);
    BOOST_INTERPROCESS_CHECK(data->notified == 3);
    data->awoken++;
    data->condition.notify_one();

    // Test predicate timed_wait.
    cond_predicate pred(data->notified, 4);
    bool ret = data->condition.timed_wait(lock, boost_systemclock_delay(5), pred);
    BOOST_INTERPROCESS_CHECK(ret);(void)ret;
    BOOST_INTERPROCESS_CHECK(lock ? true : false);
    BOOST_INTERPROCESS_CHECK(pred());
    BOOST_INTERPROCESS_CHECK(data->notified == 4);
    data->awoken++;
    data->condition.notify_one();

    // Test timed_wait
    while (data->notified != 5)
        data->condition.timed_wait(lock, std_systemclock_delay(5));
    BOOST_INTERPROCESS_CHECK(lock ? true : false);
    BOOST_INTERPROCESS_CHECK(data->notified == 5);
    data->awoken++;
    data->condition.notify_one();
}

template <class Condition, class Mutex>
void do_test_condition_notify_one()
{
   condition_test_data<Condition, Mutex> data;

   boost::interprocess::ipcdetail::OS_thread_t thread;
   boost::interprocess::ipcdetail::thread_launch(thread, bind_function(&condition_test_thread<Condition, Mutex>, &data));
   //Make sure thread is blocked
   boost::interprocess::ipcdetail::thread_sleep(1000);
   {
      boost::interprocess::scoped_lock<Mutex>
         lock(data.mutex);
      BOOST_INTERPROCESS_CHECK(lock ? true : false);
      data.notified++;
      data.condition.notify_one();
   }

   boost::interprocess::ipcdetail::thread_join(thread);
   BOOST_INTERPROCESS_CHECK(data.awoken == 1);
}

template <class Condition, class Mutex>
void do_test_condition_notify_all()
{
   const int NUMTHREADS = 3;

   boost::interprocess::ipcdetail::OS_thread_t thgroup[NUMTHREADS];
   condition_test_data<Condition, Mutex> data;

   for(int i = 0; i< NUMTHREADS; ++i){
      boost::interprocess::ipcdetail::thread_launch(thgroup[i], bind_function(&condition_test_thread<Condition, Mutex>, &data));
   }

   //Make sure all threads are blocked
   boost::interprocess::ipcdetail::thread_sleep(1000);
   {
      boost::interprocess::scoped_lock<Mutex>
         lock(data.mutex);
      BOOST_INTERPROCESS_CHECK(lock ? true : false);
      data.notified++;
   }
   data.condition.notify_all();

   for(int i = 0; i< NUMTHREADS; ++i){
      boost::interprocess::ipcdetail::thread_join(thgroup[i]);
   }
   BOOST_INTERPROCESS_CHECK(data.awoken == NUMTHREADS);
}

template <class Condition, class Mutex>
void do_test_condition_waits()
{
   condition_test_data<Condition, Mutex> data;
   boost::interprocess::ipcdetail::OS_thread_t thread;
   boost::interprocess::ipcdetail::thread_launch(thread, bind_function(&condition_test_waits<Condition, Mutex>, &data));

   {
      boost::interprocess::scoped_lock<Mutex>
         lock(data.mutex);
      BOOST_INTERPROCESS_CHECK(lock ? true : false);

      boost::interprocess::ipcdetail::thread_sleep(1000);
      data.notified++;
      data.condition.notify_one();
      while (data.awoken != 1)
         data.condition.wait(lock);
      BOOST_INTERPROCESS_CHECK(lock ? true : false);
      BOOST_INTERPROCESS_CHECK(data.awoken == 1);

      boost::interprocess::ipcdetail::thread_sleep(1000);
      data.notified++;
      data.condition.notify_one();
      while (data.awoken != 2)
         data.condition.wait(lock);
      BOOST_INTERPROCESS_CHECK(lock ? true : false);
      BOOST_INTERPROCESS_CHECK(data.awoken == 2);

      boost::interprocess::ipcdetail::thread_sleep(1000);
      data.notified++;
      data.condition.notify_one();
      while (data.awoken != 3)
         data.condition.wait(lock);
      BOOST_INTERPROCESS_CHECK(lock ? true : false);
      BOOST_INTERPROCESS_CHECK(data.awoken == 3);

      boost::interprocess::ipcdetail::thread_sleep(1000);
      data.notified++;
      data.condition.notify_one();
      while (data.awoken != 4)
         data.condition.wait(lock);
      BOOST_INTERPROCESS_CHECK(lock ? true : false);
      BOOST_INTERPROCESS_CHECK(data.awoken == 4);

      boost::interprocess::ipcdetail::thread_sleep(1000);
      data.notified++;
      data.condition.notify_one();
      while (data.awoken != 5)
         data.condition.wait(lock);
      BOOST_INTERPROCESS_CHECK(lock ? true : false);
      BOOST_INTERPROCESS_CHECK(data.awoken == 5);
   }

   boost::interprocess::ipcdetail::thread_join(thread);
   BOOST_INTERPROCESS_CHECK(data.awoken == 5);
}
/*
//Message queue simulation test
template <class Condition>
inline Condition &cond_empty()
{
   static Condition cond_empty;
   return cond_empty;
}

template <class Condition>
inline Condition &cond_full()
{
   static Condition cond_full;
   return cond_full;
}

template <class Mutex>
inline Mutex &mutex()
{
   static Mutex mut;
   return mut;
}
*/
static volatile int count = 0;
static volatile int waiting_readers = 0;
static volatile int waiting_writer  = 0;
const int queue_size    = 3;
const int thread_factor = 10;
const int NumThreads    = thread_factor*queue_size;

//Function that removes items from queue
template <class Condition, class Mutex>
struct condition_func
{
   condition_func(Condition &cond_full, Condition &cond_empty, Mutex &mutex)
      :  cond_full_(cond_full), cond_empty_(cond_empty), mutex_(mutex)
   {}

   void operator()()
   {
      boost::interprocess::scoped_lock<Mutex>lock(mutex_);
      while(count == 0){
         ++waiting_readers;
         cond_empty_.wait(lock);
         --waiting_readers;
      }
      --count;
      if(waiting_writer)
         cond_full_.notify_one();
   }
   Condition &cond_full_;
   Condition &cond_empty_;
   Mutex     &mutex_;
};

//Queue functions
template <class Condition, class Mutex>
void do_test_condition_queue_notify_one(void)
{
   //Force mutex and condition creation
   Condition cond_empty;
   Condition cond_full;
   Mutex mutex;

   //Create threads that will decrease count
   {
      //Initialize counters
      count = 0;
      waiting_readers = 0;
      waiting_writer  = 0;

      boost::interprocess::ipcdetail::OS_thread_t thgroup[NumThreads];
      for(int i = 0; i< NumThreads; ++i){
         condition_func<Condition, Mutex> func(cond_full, cond_empty, mutex);
         boost::interprocess::ipcdetail::thread_launch(thgroup[i], func);
      }

      //Add 20 elements one by one in the queue simulation
      //The sender will block if it fills the queue
      for(int i = 0; i < NumThreads; ++i){
         boost::interprocess::scoped_lock<Mutex> lock(mutex);
         while(count == queue_size){
            ++waiting_writer;
            cond_full.wait(lock);
            --waiting_writer;
         }
         count++;

         if(waiting_readers)
            cond_empty.notify_one();
      }
      for(int i = 0; i< NumThreads; ++i){
         boost::interprocess::ipcdetail::thread_join(thgroup[i]);
      }
      BOOST_INTERPROCESS_CHECK(count == 0);
      BOOST_INTERPROCESS_CHECK(waiting_readers == 0);
      BOOST_INTERPROCESS_CHECK(waiting_writer  == 0);
   }
}

//Queue functions
template <class Condition, class Mutex>
void do_test_condition_queue_notify_all(void)
{
   //Force mutex and condition creation
   Condition cond_empty;
   Condition cond_full;
   Mutex mutex;

   //Create threads that will decrease count
   {
      //Initialize counters
      count = 0;
      waiting_readers = 0;
      waiting_writer  = 0;

      boost::interprocess::ipcdetail::OS_thread_t thgroup[NumThreads];
      for(int i = 0; i< NumThreads; ++i){
         condition_func<Condition, Mutex> func(cond_full, cond_empty, mutex);
         boost::interprocess::ipcdetail::thread_launch(thgroup[i], func);
      }

      //Fill queue to the max size and notify all several times
      for(int i = 0; i < NumThreads; ++i){
         boost::interprocess::scoped_lock<Mutex>lock(mutex);
         while(count == queue_size){
            ++waiting_writer;
            cond_full.wait(lock);
            --waiting_writer;
         }
         count++;

         if(waiting_readers)
            cond_empty.notify_all();
      }
      for(int i = 0; i< NumThreads; ++i){
         boost::interprocess::ipcdetail::thread_join(thgroup[i]);
      }
      BOOST_INTERPROCESS_CHECK(count == 0);
      BOOST_INTERPROCESS_CHECK(waiting_readers == 0);
      BOOST_INTERPROCESS_CHECK(waiting_writer  == 0);
   }
}

template <class Condition, class Mutex>
bool do_test_condition()
{
   std::cout << "do_test_condition_notify_one<" << typeid(Condition).name() << "," << typeid(Mutex).name() << '\n' << std::endl;
   do_test_condition_notify_one<Condition, Mutex>();
   std::cout << "do_test_condition_notify_all<" << typeid(Condition).name() << "," << typeid(Mutex).name() << '\n' << std::endl;
   do_test_condition_notify_all<Condition, Mutex>();
   std::cout << "do_test_condition_waits<" << typeid(Condition).name() << "," << typeid(Mutex).name() << '\n' << std::endl;
   do_test_condition_waits<Condition, Mutex>();
   std::cout << "do_test_condition_queue_notify_one<" << typeid(Condition).name() << "," << typeid(Mutex).name() << '\n' << std::endl;
   do_test_condition_queue_notify_one<Condition, Mutex>();
   std::cout << "do_test_condition_queue_notify_all<" << typeid(Condition).name() << "," << typeid(Mutex).name() << '\n' << std::endl;
   do_test_condition_queue_notify_all<Condition, Mutex>();
   return true;
}

}  //namespace test
}  //namespace interprocess{
}  //namespace boost{

#include <boost/interprocess/detail/config_end.hpp>

#endif   //#ifndef BOOST_INTERPROCESS_CONDITION_TEST_TEMPLATE_HPP


text:
package httl.spi.methods;

import httl.spi.methods.cycles.*;
import httl.util.CollectionUtils;

import java.util.*;

/**
 * CollectionMethod. (SPI, Singleton, ThreadSafe)
 *
 * @author Liang Fei (liangfei0201 AT gmail DOT com)
 */
public class CollectionMethod {

    private CollectionMethod() {
    }

    public static <T> ListCycle<T> toCycle(Collection<T> values) {
        return new ListCycle<T>(values);
    }

    public static <T> ArrayCycle<T> toCycle(T[] values) {
        return new ArrayCycle<T>(values);
    }

    public static BooleanArrayCycle toCycle(boolean[] values) {
        return new BooleanArrayCycle(values);
    }

    public static CharArrayCycle toCycle(char[] values) {
        return new CharArrayCycle(values);
    }

    public static ByteArrayCycle toCycle(byte[] values) {
        return new ByteArrayCycle(values);
    }

    public static ShortArrayCycle toCycle(short[] values) {
        return new ShortArrayCycle(values);
    }

    public static IntArrayCycle toCycle(int[] values) {
        return new IntArrayCycle(values);
    }

    public static LongArrayCycle toCycle(long[] values) {
        return new LongArrayCycle(values);
    }

    public static FloatArrayCycle toCycle(float[] values) {
        return new FloatArrayCycle(values);
    }

    public static DoubleArrayCycle toCycle(double[] values) {
        return new DoubleArrayCycle(values);
    }

    public static int length(Map<?, ?> values) {
        return values == null ? 0 : values.size();
    }

    public static int length(Collection<?> values) {
        return values == null ? 0 : values.size();
    }

    public static int length(Object[] values) {
        return values == null ? 0 : values.length;
    }

    public static int length(boolean[] values) {
        return values == null ? 0 : values.length;
    }

    public static int length(char[] values) {
        return values == null ? 0 : values.length;
    }

    public static int length(byte[] values) {
        return values == null ? 0 : values.length;
    }

    public static int length(short[] values) {
        return values == null ? 0 : values.length;
    }

    public static int length(int[] values) {
        return values == null ? 0 : values.length;
    }

    public static int length(long[] values) {
        return values == null ? 0 : values.length;
    }

    public static int length(float[] values) {
        return values == null ? 0 : values.length;
    }

    public static int length(double[] values) {
        return values == null ? 0 : values.length;
    }

    public static <K, V> Map<K, V> sort(Map<K, V> map) {
        if (map == null) {
            return null;
        }
        return new TreeMap<K, V>(map);
    }

    @SuppressWarnings({"unchecked", "rawtypes"})
    public static <T> List<T> sort(List<T> list) {
        if (list == null) {
            return null;
        }
        list = new ArrayList<T>(list);
        Collections.sort((List) list);
        return list;
    }

    public static <T> Set<T> sort(Set<T> set) {
        if (set == null) {
            return null;
        }
        return new TreeSet<T>(set);
    }

    public static <T> Collection<T> sort(Collection<T> set) {
        if (set == null) {
            return null;
        }
        return new TreeSet<T>(set);
    }

    public static <T> T[] sort(T[] array) {
        if (array == null) {
            return null;
        }
        array = CollectionUtils.copyOf(array, array.length);
        Arrays.sort(array);
        return array;
    }

    public static char[] sort(char[] array) {
        if (array == null) {
            return null;
        }
        array = CollectionUtils.copyOf(array, array.length);
        Arrays.sort(array);
        return array;
    }

    public static byte[] sort(byte[] array) {
        if (array == null) {
            return null;
        }
        array = CollectionUtils.copyOf(array, array.length);
        Arrays.sort(array);
        return array;
    }

    public static short[] sort(short[] array) {
        if (array == null) {
            return null;
        }
        array = CollectionUtils.copyOf(array, array.length);
        Arrays.sort(array);
        return array;
    }

    public static int[] sort(int[] array) {
        if (array == null) {
            return null;
        }
        array = CollectionUtils.copyOf(array, array.length);
        Arrays.sort(array);
        return array;
    }

    public static long[] sort(long[] array) {
        if (array == null) {
            return null;
        }
        array = CollectionUtils.copyOf(array, array.length);
        Arrays.sort(array);
        return array;
    }

    public static float[] sort(float[] array) {
        if (array == null) {
            return null;
        }
        array = CollectionUtils.copyOf(array, array.length);
        Arrays.sort(array);
        return array;
    }

    public static double[] sort(double[] array) {
        if (array == null) {
            return null;
        }
        array = CollectionUtils.copyOf(array, array.length);
        Arrays.sort(array);
        return array;
    }

    public static <K, V> Map<K, V> recursive(Map<K, V> map) {
        Map<K, V> result = new HashMap<K, V>();
        _recursive(result, map);
        return result;
    }

    @SuppressWarnings("unchecked")
    private static <K, V> void _recursive(Map<K, V> result, Map<K, V> map) {
        if (map != null) {
            for (Map.Entry<K, V> entry : map.entrySet()) {
                V value = entry.getValue();
                if (value instanceof Map) {
                    _recursive(result, (Map<K, V>) entry.getValue());
                } else {
                    result.put(entry.getKey(), value);
                }
            }
        }
    }

    public static <T> List<T> recursive(Collection<T> set) {
        List<T> result = new ArrayList<T>();
        _recursive(result, set);
        return result;
    }

    @SuppressWarnings("unchecked")
    private static <T> void _recursive(Collection<T> result, Collection<T> set) {
        if (set != null) {
            for (T item : set) {
                if (item instanceof Collection) {
                    _recursive(result, (Collection<T>) item);
                } else {
                    result.add(item);
                }
            }
        }
    }

    public static <T> List<T> recursive(Collection<T> set, String children) {
        List<T> result = new ArrayList<T>();
        if (set != null) {
            for (T item : set) {
                _recursive(result, item, children);
            }
        }
        return result;
    }

    public static <T> List<T> recursive(T node, String children) {
        List<T> result = new ArrayList<T>();
        _recursive(result, node, children);
        return result;
    }

    @SuppressWarnings("unchecked")
    private static <T> void _recursive(Collection<T> result, T node, String children) {
        if (node != null) {
            result.add(node);
            Collection<T> set;
            try {
                set = (Collection<T>) node.getClass().getMethod(children, new Class<?>[0]).invoke(node, new Object[0]);
            } catch (RuntimeException e) {
                throw (RuntimeException) e;
            } catch (Exception e) {
                throw new RuntimeException(e.getMessage(), e);
            }
            if (set != null) {
                for (T item : set) {
                    _recursive(result, item, children);
                }
            }
        }
    }

}


text:
<?php

namespace Google\Service\YouTube;

class RelatedEntity extends \Google\Model
{
  protected $entityType = Entity::class;
  protected $entityDataType = '';

  /**
   * @param Entity
   */
  public function setEntity(Entity $entity)
  {
    $this->entity = $entity;
  }
  /**
   * @return Entity
   */
  public function getEntity()
  {
    return $this->entity;
  }
}

// Adding a class alias for backwards compatibility with the previous class name.
class_alias(RelatedEntity::class, 'Google_Service_YouTube_RelatedEntity');


text:
module Trello
  # A webhook is a URL called each time a specified model is updated
  #
  # @!attribute [r] id
  #   @return [String]
  # @!attribute [r] description
  #   @return [String]
  # @!attribute [r] id_model
  #   @return [String] A 24-character hex string
  # @!attribute [r] callback_url
  #   @return [String]
  # @!attribute [r] active
  #   @return [Boolean]
  class Webhook < BasicData
    register_attributes :id, :description, :id_model, :callback_url, :active,
      readonly: [ :id ]
    validates_presence_of :id, :id_model, :callback_url
    validates_length_of   :description,  in: 1..16384

    class << self
      # Find a specific webhook by its ID.
      #
      # @raise [Trello::Error] if a Webhook with the given ID can't be found.
      # @return [Trello::Webhook] the Webhook with the given ID.
      def find(id, params = {})
        client.find(:webhook, id, params)
      end

      # Create a new webhook and save it to Trello.
      #
      # @param [Hash] options
      #
      # @option options [String] :description (optional) A string with a length from 0 to 16384
      # @option options [String] :callback_url (required) A valid URL that is
      #    reachable with a HEAD request
      # @option options [String] :id_model (required) id of the model that should be hooked
      #
      # @raise [Trello::Error] if the Webhook could not be created.
      #
      # @return [Trello::Webhook]
      def create(options)
        client.create(:webhook,
            'description' => options[:description],
            'idModel'     => options[:id_model],
            'callbackURL' => options[:callback_url])
      end
    end

    # @return [Trello::Webhook] self
    def update_fields(fields)
      attributes[:id]              = fields['id']
      attributes[:description]     = fields['description']
      attributes[:id_model]        = fields['idModel']
      attributes[:callback_url]    = fields['callbackURL']
      attributes[:active]          = fields['active']
      self
    end

    # Save the webhook.
    #
    # @raise  [Trello::Error] if the Webhook could not be saved.
    #
    # @return [String] the JSON representation of the saved webhook.
    def save
      # If we have an id, just update our fields.
      return update! if id

      from_response client.post("/webhooks", {
        description: description,
        idModel: id_model,
        callbackURL: callback_url
      })
    end

    # Update the webhook.
    #
    # @raise  [Trello::Error] if the Webhook could not be saved.
    #
    # @return [String] the JSON representation of the updated webhook.
    def update!
      client.put("/webhooks/#{id}", {
        description: description,
        idModel: id_model,
        callbackURL: callback_url,
        active: active
      })
    end

    # Delete this webhook
    #
    # @return [String] the JSON response from the Trello API
    def delete
      client.delete("/webhooks/#{id}")
    end

    # Check if the webhook is activated
    #
    # @return [Boolean]
    def activated?
      active
    end
  end
end


text:
/*
global describe, beforeEach, afterEach, it, expect
*/

'use strict'

const sinon = require('sinon')
const adminurls = require('../../src/js/admin-urls')
const browser = require('../../src/js/browser')
const querystring = require('../../src/js/get-url-parameter')
const webAuth = require('../../src/js/models/auth0/webAuth')
const storage = require('../../src/js/sessionStorage')

describe('Index', () => {
  var Model = require('../../src/js/models/Index')
  let model = null // eslint-disable-line
  var stubbedBrowser
  var stubbedStorage

  beforeEach(() => {
    stubbedStorage = sinon.stub(storage, 'get')
    stubbedBrowser = sinon.stub(browser, 'redirect')
  })

  afterEach(() => {
    browser.redirect.restore()
    storage.get.restore()
    webAuth.isAuthenticated.restore()
  })

  describe('Not logged in', () => {
    beforeEach(() => {
      sinon.stub(webAuth, 'isAuthenticated').returns(false)
      sinon.stub(querystring, 'parameter')
        .withArgs('redirectUrl')
        .returns('https://site.com/password-reset/some-other-stuff?wang=fu')
      stubbedStorage
        .withArgs(webAuth.storageKeys.roles)
        .returns('')

      model = new Model()
    })

    afterEach(() => {
      querystring.parameter.restore()
    })

    it('should redirect to login', () => {
      var browserRedirectedWithExpectedUrl = stubbedBrowser.withArgs(adminurls.login).calledOnce
      expect(browserRedirectedWithExpectedUrl).toBeTruthy()
    })
  })

  describe('Has been redirected from password reset', () => {
    beforeEach(() => {
      sinon.stub(webAuth, 'isAuthenticated').returns(false)
      sinon.stub(querystring, 'parameter')
      stubbedStorage
        .withArgs(webAuth.storageKeys.roles)
        .returns('')

      model = new Model()
    })

    afterEach(() => {
      querystring.parameter.restore()
    })

    it('should redirect to login', () => {
      var browserRedirectedWithExpectedUrl = stubbedBrowser.withArgs(adminurls.login).calledOnce
      expect(browserRedirectedWithExpectedUrl).toBeTruthy()
    })
  })

  describe('has been authenticated', () => {
    beforeEach(() => {
      sinon.stub(webAuth, 'isAuthenticated').returns(true)
    })

    describe('as Super Admin', () => {
      beforeEach(() => {
        sinon.stub(querystring, 'parameter')

        stubbedStorage
          .withArgs(webAuth.storageKeys.roles)
          .returns('superadmin')

        model = new Model()
      })

      afterEach(() => {
        querystring.parameter.restore()
      })

      it('should redirect to dashboard', () => {
        var browserRedirectedWithExpectedUrl = stubbedBrowser.withArgs(adminurls.dashboardv2).calledOnce
        expect(browserRedirectedWithExpectedUrl).toBeTruthy()
      })
    })

    describe('- Org Admin', () => {
      beforeEach(() => {
        sinon.stub(querystring, 'parameter')
        stubbedStorage
          .withArgs(webAuth.storageKeys.roles)
          .returns('adminfor:coffee4craig')
        model = new Model()
      })

      afterEach(() => {
        querystring.parameter.restore()
      })

      it('should redirect to service provider page', () => {
        var browserRedirectedWithExpectedUrl = stubbedBrowser.withArgs(adminurls.dashboardv2).calledOnce
        expect(browserRedirectedWithExpectedUrl).toBeTruthy()
      })
    })

    describe('Charter Admin', () => {
      beforeEach(() => {
        sinon.stub(querystring, 'parameter')
        stubbedStorage
          .withArgs(webAuth.storageKeys.roles)
          .returns('charteradmin')
        model = new Model()
      })

      afterEach(() => {
        querystring.parameter.restore()
      })

      it('should redirect to charter page', () => {
        var browserRedirectedWithExpectedUrl = stubbedBrowser.withArgs(adminurls.charter).calledOnce
        expect(browserRedirectedWithExpectedUrl).toBeTruthy()
      })
    })

    describe('- with redirect url', () => {
      beforeEach(() => {
        sinon.stub(querystring, 'parameter')
          .returns('https://admin.streetsupport.net/previous-url/')
        sinon.stub(browser, 'origin')
          .returns('https://admin.streetsupport.net')

        stubbedStorage
          .withArgs(webAuth.storageKeys.roles)
          .returns('superadmin')

        model = new Model()
      })

      afterEach(() => {
        querystring.parameter.restore()
        browser.origin.restore()
      })

      it('should redirect to redirect url', () => {
        var browserRedirectedWithExpectedUrl = stubbedBrowser.withArgs('https://admin.streetsupport.net/previous-url/').calledOnce
        expect(browserRedirectedWithExpectedUrl).toBeTruthy()
      })
    })

    describe('- with invalid redirect url', () => {
      beforeEach(() => {
        sinon.stub(querystring, 'parameter')
          .returns('https://haxx0rz.l337/phishing/')
        sinon.stub(browser, 'origin')
          .returns('https://admin.streetsupport.net')
        stubbedStorage
          .withArgs(webAuth.storageKeys.roles)
          .returns('charteradmin')

        model = new Model()
      })

      afterEach(() => {
        querystring.parameter.restore()
        browser.origin.restore()
      })

      it('should redirect to relevant home page', () => {
        var browserRedirectedWithExpectedUrl = stubbedBrowser.withArgs(adminurls.charter).calledOnce
        expect(browserRedirectedWithExpectedUrl).toBeTruthy()
      })
    })
  })

  describe('session expired', () => {
    beforeEach(() => {
      sinon.stub(querystring, 'parameter')
      sinon.stub(webAuth, 'isAuthenticated').returns(false)
      model = new Model()
    })

    afterEach(() => {
      querystring.parameter.restore()
    })

    it('should redirect to login', () => {
      var browserRedirectedWithExpectedUrl = stubbedBrowser.withArgs(adminurls.login).calledOnce
      expect(browserRedirectedWithExpectedUrl).toBeTruthy()
    })
  })
})


text:
module Web.ApiAi.Requests
    ( module Import
    ) where

import Web.ApiAi.Requests.Query as Import


text:
Simple-Node-TypeScript-Mongoose-Model-Skeleton

First you need running mongo server instance.
Navigate to config/mongo.ts if you need to change your HOST

* npm i - also will install typings
* npm start - compile ts to es5 and run node instance


text:
import os
import pusher

CHANNEL = "response-updates"

client = pusher.Pusher(
    app_id=os.environ.get("PUSHER_APP_ID"),
    key=os.environ.get("PUSHER_KEY"),
    secret=os.environ.get("PUSHER_SECRET"),
    cluster='eu',
    ssl=True
) if "IS_PROD" in os.environ else None

def notify(msg_type, payload):
    """Notifies that a SurveyResponse has been created or modified"""

    if client is not None:
        client.trigger(CHANNEL, msg_type, payload)


text:
package net.utp4j.examples;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;

import net.utp4j.channels.futures.UtpReadListener;

public class SaveFileListener extends UtpReadListener {

	private int file;
	private volatile boolean append = false;

	public SaveFileListener(int i, boolean concat) {
		file = i;
		this.append = concat;
		createExtraThread = true;
	}

	public SaveFileListener(int i) {
		file = i;
	}

	public SaveFileListener() {}
	public SaveFileListener(boolean concat) {
		this.append = concat;
	}

	@Override
	public void actionAfterReading() {
		if (exception == null && byteBuffer != null) {
			try {
				byteBuffer.flip();
				File outFile = new File("testData/gotData_" + file + " .avi");
				FileOutputStream fileOutputStream = new FileOutputStream(outFile, append);
				FileChannel fchannel = fileOutputStream.getChannel();
				while(byteBuffer.hasRemaining()) {
					fchannel.write(byteBuffer);
				}
				fchannel.close();
				fileOutputStream.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		if (exception != null ) {
			exception.printStackTrace();
		}

	}

	@Override
	public String getThreadName() {
		return "listenerThread";
	}

}


text:
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
  <script src="bootstrap/js/bootstrap.min.js"></script>
</body>
</html>


text:
var numTests = 0;
var numCorrect = 0;

var locations = ['Hillsboro', 'Pearl', 'DowntownPDX', 'Buckman', 'PDXairport', 'Clackamas'];

// Test object array creation
if (typeof stores != 'undefined') {
  if (typeof stores === 'object') {
    console.log('Pizza store variable creation test: Pass!');
    numCorrect++;
  } else {
    console.log('Pizza store variable creation test: --- FAIL ---');
  }
} else {
  console.log('Fail. Undefined.');
}

numTests++;
console.log('You got ' + numCorrect + ' out of ' + numTests);

// Test names of each store
for (var i = 0; i < locations.length; i++) {
  if (typeof stores[i] != 'undefined') {
    if (stores[i].name === locations[i]) {
      console.log(locations[i] + ': Pass!');
      numCorrect++;
    } else {
      console.log(locations[i] + ': --- FAIL ---');
    }
  } else {
    console.log(locations[i] + ': --- FAIL ---');
  }
  numTests++;
}

console.log('You got ' + numCorrect + ' out of ' + numTests);


text:
<!DOCTYPE html>

  <title>Records</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link href="assets/css/bootstrap-responsive.css" rel="stylesheet">
  <link rel="stylesheet" type="text/css" href="../styles/styles.css">
  <link data-require="bootstrap-css@*" data-semver="3.1.1" rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" />
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <link rel="stylesheet" type="text/css" href="../styles/font-awesome.min.css">
  <link rel="stylesheet" type="text/css" href="..styles/bootstrap.min.css">

      <button type="button" class="navbar-toggle navbar-pills" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
        Toggle navigation

        '
      </button>

  <input type="hidden" id="selected_menu_item" value="=$selectedMenuId; ?>" />

Music

Biography

Media

Gallery

Links

Contact

Facebook

Apple

Spotify

YouTube

Booking

Records

Media

Contact

Created by DamirDrljaca.com with a lot of

Music

Leave Me At The Altar

Sweeter She Is

Roll Away The Stone

You're All I Need

Caribbean Gospel Rhythm

Thank You Lord for Your Blessing On Me

Jesus is Everything To Me

Jesus's Blood Covers It All

Give It All To Jesus

Best of George Banton Vol.1

Jesus Will Fix it For You

CARIBBEAN REVIVAL GOSPEL RHYTHMS VOL.1

LET US PRAISE THE LORD

THANK YOU LORD FOR YOUR BLESSINGS ON ME

Sax Instrumentals


text:
package org.spotter.core.test.dummies.satellites;

import org.lpe.common.config.ConfigParameterDescription;
import org.lpe.common.util.LpeSupportedTypes;
import org.spotter.core.measurement.AbstractMeasurmentExtension;
import org.spotter.core.measurement.IMeasurementAdapter;

public class DummyMeasurementExtension extends AbstractMeasurmentExtension{

	@Override
	public String getName() {
		return "DummyMeasurement";
	}

	@Override
	public IMeasurementAdapter createExtensionArtifact() {
		return new DummyMeasurement(this);
	}

	@Override
	protected void initializeConfigurationParameters() {
		ConfigParameterDescription parDescription = new ConfigParameterDescription("test.measurement.parameter", LpeSupportedTypes.Integer);
		addConfigParameter(parDescription);

	}

	@Override
	public boolean testConnection(String host, String port) {
		return true;
	}

	@Override
	public boolean isRemoteExtension() {
		return true;
	}

}