text:
"""
    Exercise questions from Think like a Computer Scientist
    http://www.greenteapress.com/thinkpython/html/index.html

    Exercises 4.2,4.3

    Uses polygon.py for basic polygon drawing operations
    Uses approach similar to http://www.greenteapress.com/thinkpython/code/pie.py and
    http://www.greenteapress.com/thinkpython/code/flower.py

"""
from polygon import arc, lt, pu, fd, pd, math, rt, Turtle, TurtleWorld, die, wait_for_user,bk

def petal(t, r, angle):
    """Draws a petal using two arcs.
        :param t: Turtle
        :param r: radius of the arcs
        :param angle: angle (degrees) that subtends the arcs
        """
    for i in range(2):
        arc(t, r, angle)
        lt(t, 180 - angle)

def flower(t, n, r, angle):
    """Draws a flower with n petals.
        :param t: Turtle
        :param n: number of petals
        :param r: radius of the arcs
        :param angle: angle (degrees) that subtends the arcs
        """
    for i in range(n):
        petal(t, r, angle)
        lt(t, 360.0 / n)

def move(t, length):
    """Move Turtle (t) forward (length) units without leaving a trail.
        Leaves the pen down.
        :param t: Turtle
        :param length: Length of turtle movement
        """
    pu(t)
    fd(t, length)
    pd(t)

def draw_pie(t, n, r):
    """Draws a pie, then moves into position to the right.

        :param t: Turtle
        :param n: number of segments
        :param r: length of the radial spokes
        """
    polypie(t, n, r)
    pu(t)
    fd(t, r * 2 + 10)
    pd(t)

def polypie(t, n, r):
    """Draws a pie divided into radial segments.
        :param t: Turtle
        :param n: number of segments
        :param r: length of the radial spokes
        """
    angle = 360.0 / n
    for i in range(n):
        isosceles(t, r, angle / 2)
        lt(t, angle)

def isosceles(t, r, angle):
    """Draws an isosceles triangle.
        The turtle starts and ends at the peak, facing the middle of the base.
        :param t: Turtle
        :param r: length of the equal legs
        :param angle: peak angle in degrees
        """
    y = r * math.sin(angle * math.pi / 180)

    rt(t, angle)
    fd(t, r)
    lt(t, 90 + angle)
    fd(t, 2 * y)
    lt(t, 90 + angle)
    fd(t, r)
    lt(t, 180 - angle)

# Answer to 4.2
world = TurtleWorld()
bob = Turtle()
bob.delay = 0

move(bob, -100)
flower(bob, 7, 60.0, 60.0)

move(bob, 100)
flower(bob, 10, 40.0, 80.0)

move(bob, 100)
flower(bob, 20, 140.0, 20.0)

die(bob)

wait_for_user()

# Answer to 4.3
world = TurtleWorld()
bob = Turtle()
bob.delay = 0
pu(bob)
bk(bob, 130)
pd(bob)

size = 40
draw_pie(bob, 5, size)
draw_pie(bob, 6, size)
draw_pie(bob, 7, size)

die(bob)

wait_for_user()


text:
class AccountDao{
  findOrNull(userId){
    return null;
  }
}

class Account {
  constructor(name, password){
    this.name = name;
    this.password = password;
  }
}

redpajama_set_name: RedPajamaGithub


text:
class Bookmark < ActiveRecord::Base
  validates :user_id, :bookmarkable_type, :bookmarkable_id, :presence => true
  attr_protected :user_id, :bookmarkable_type, :bookmarkable_id

  belongs_to :user
  belongs_to :bookmarkable, :polymorphic => true
end
# == Schema Information
#
# Table name: bookmarks
#
#  id                :integer         not null, primary key
#  user_id           :integer
#  bookmarkable_type :string(255)
#  bookmarkable_id   :integer
#  created_at        :datetime
#  updated_at        :datetime
#


text:
	<title>Olivia Williams's panel show appearances</title>

	<link rel="stylesheet" media="all" href="../style.css" type="text/css"/>

Olivia Williams's panel show appearances

Olivia Williams (born 1968-07-26[ref]) has appeared in 1 episodes between 2010-2010.  Olivia Williams on IMDB. Olivia Williams on Wikipedia.

2010

2010-01-08 / Loose Women


text:
This package contains four Python modules containing
* the Shape class and its associated methods and functions,
* the PhyloTree class and its associated methods and functions,
* the Probs module with all the probability functions.
* the newick module, which can also be found in https://github.com/glottobank/python-newick
It also contains the HTML documentation of all three Python modules of my own, and an HTML containing a minimal version of instructions for using these modules.
It contains the LICENSE associated to the python-newick class (it can be found in https://github.com/glottobank/python-newick ) and Derivative Works, such as this one.


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.androidbinarysender.MainActivity" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    <Button
        android:id="@+id/button01"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView1"
        android:layout_below="@+id/textView1"
        android:layout_marginTop="96dp"
        android:text="Open File" />

    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/button01"
        android:layout_below="@+id/textView1"
        android:layout_marginTop="34dp"
        android:ems="10" >

        <requestFocus />
    </EditText>

    <Button
        android:id="@+id/installed"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/button01"
        android:layout_centerVertical="true"
        android:text="Check if Usbong is installed" />

</RelativeLayout>


text:
package org.sparkcommerce.core.web.api.wrapper;

import org.sparkcommerce.core.catalog.domain.Category;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

/**
 * This is a JAXB wrapper class for wrapping a collection of categories.
 */
@XmlRootElement(name = "categories")
@XmlAccessorType(value = XmlAccessType.FIELD)
public class CategoriesWrapper extends BaseWrapper implements APIWrapper<List<Category>> {

    @XmlElement(name = "category")
    protected List<CategoryWrapper> categories = new ArrayList<CategoryWrapper>();

    @Override
    public void wrapDetails(List<Category> cats, HttpServletRequest request) {
        for (Category category : cats) {
            CategoryWrapper wrapper = (CategoryWrapper) context.getBean(CategoryWrapper.class.getName());
            wrapper.wrapSummary(category, request);
            categories.add(wrapper);
        }
    }

    @Override
    public void wrapSummary(List<Category> cats, HttpServletRequest request) {
        wrapDetails(cats, request);
    }
}


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;

namespace MICore
{
    public static class PlatformUtilities
    {
        private enum RuntimePlatform
        {
            Unset = 0,
            Unknown,
            Windows,
            MacOSX,
            Unix,
        }

        private static RuntimePlatform s_runtimePlatform;

        private static RuntimePlatform GetRuntimePlatform()
        {
            if (s_runtimePlatform == RuntimePlatform.Unset)
            {
                s_runtimePlatform = CalculateRuntimePlatform();
            }
            return s_runtimePlatform;
        }

#if !CORECLR
        [DllImport("libc")]
        static extern int uname(IntPtr buf);

        private static RuntimePlatform GetUnixVariant()
        {
            IntPtr buf = Marshal.AllocHGlobal(8192);
            try
            {
                if (uname(buf) == 0)
                {
                    string os = Marshal.PtrToStringAnsi(buf);
                    if (String.Equals(os, "Darwin", StringComparison.Ordinal))
                    {
                        return RuntimePlatform.MacOSX;
                    }
                }
            }
            finally
            {
                if (buf != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(buf);
                }
            }

            return RuntimePlatform.Unix;
        }
#endif

        private static RuntimePlatform CalculateRuntimePlatform()
        {
#if CORECLR
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                return RuntimePlatform.Windows;
            }
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
            {
                return RuntimePlatform.MacOSX;
            }
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            {
                return RuntimePlatform.Unix;
            }
            return RuntimePlatform.Unknown;
#else
            const PlatformID MonoOldUnix = (PlatformID)128;

            switch (Environment.OSVersion.Platform)
            {
                case PlatformID.Win32NT:
                    return RuntimePlatform.Windows;
                case PlatformID.Unix:
                case MonoOldUnix:
                    // Mono returns PlatformID.Unix on OSX for compatibility
                    return PlatformUtilities.GetUnixVariant();
                case PlatformID.MacOSX:
                    return RuntimePlatform.MacOSX;
                default:
                    return RuntimePlatform.Unknown;
            }
#endif
        }

        /*
         * Is this Windows?
         */
        public static bool IsWindows()
        {
            return GetRuntimePlatform() == RuntimePlatform.Windows;
        }

        /*
         * Is this OS X?
         */
        public static bool IsOSX()
        {
            return GetRuntimePlatform() == RuntimePlatform.MacOSX;
        }

        /*
         * Is this Linux?
         */
        public static bool IsLinux()
        {
            return GetRuntimePlatform() == RuntimePlatform.Unix;
        }

        // Abstract API call to add an environment variable to a new process
        public static void SetEnvironmentVariable(this ProcessStartInfo processStartInfo, string key, string value)
        {
#if CORECLR
            processStartInfo.Environment[key] = value;
#else
            // Desktop CLR has the Environment property in 4.6+, but Mono is currently based on 4.5.
            processStartInfo.EnvironmentVariables[key] = value;
#endif
        }

        // Abstract API call to add an environment variable to a new process
        public static string GetEnvironmentVariable(this ProcessStartInfo processStartInfo, string key)
        {
#if CORECLR
            if (processStartInfo.Environment.ContainsKey(key))
                return processStartInfo.Environment[key];
#else
            // Desktop CLR has the Environment property in 4.6+, but Mono is currenlty based on 4.5.
            if (processStartInfo.EnvironmentVariables.ContainsKey(key))
                return processStartInfo.EnvironmentVariables[key];
#endif
            return null;
        }
    }
}


text:
package com.linkedin.thirdeye.datalayer.pojo;

import java.util.Objects;

/**
 * This class corresponds to data completeness config.
 */
public class DataCompletenessConfigBean extends AbstractBean {

  private String dataset;
  private long dateToCheckInMS;
  private String dateToCheckInSDF;
  private long countStar = 0;
  private boolean dataComplete = false;
  private double percentComplete = 0;
  private int numAttempts = 0;
  private boolean delayNotified = false;
  private boolean timedOut = false;

  public String getDataset() {
    return dataset;
  }

  public void setDataset(String dataset) {
    this.dataset = dataset;
  }

  public long getDateToCheckInMS() {
    return dateToCheckInMS;
  }

  public void setDateToCheckInMS(long dateToCheckInMS) {
    this.dateToCheckInMS = dateToCheckInMS;
  }

  public String getDateToCheckInSDF() {
    return dateToCheckInSDF;
  }

  public void setDateToCheckInSDF(String dateToCheckInSDF) {
    this.dateToCheckInSDF = dateToCheckInSDF;
  }

  public long getCountStar() {
    return countStar;
  }

  public void setCountStar(long countStar) {
    this.countStar = countStar;
  }

  public boolean isDataComplete() {
    return dataComplete;
  }

  public void setDataComplete(boolean dataComplete) {
    this.dataComplete = dataComplete;
  }

  public double getPercentComplete() {
    return percentComplete;
  }

  public void setPercentComplete(double percentComplete) {
    this.percentComplete = percentComplete;
  }

  public int getNumAttempts() {
    return numAttempts;
  }

  public void setNumAttempts(int numAttempts) {
    this.numAttempts = numAttempts;
  }

  public boolean isDelayNotified() {
    return delayNotified;
  }

  public void setDelayNotified(boolean delayNotified) {
    this.delayNotified = delayNotified;
  }

  public boolean isTimedOut() {
    return timedOut;
  }

  public void setTimedOut(boolean timedOut) {
    this.timedOut = timedOut;
  }

  @Override
  public boolean equals(Object o) {
    if (!(o instanceof DataCompletenessConfigBean)) {
      return false;
    }
    DataCompletenessConfigBean dc = (DataCompletenessConfigBean) o;
    return Objects.equals(getId(), dc.getId()) && Objects.equals(dataset, dc.getDataset())
        && Objects.equals(dateToCheckInMS, dc.getDateToCheckInMS())
        && Objects.equals(dateToCheckInSDF, dc.getDateToCheckInSDF())
        && Objects.equals(countStar, dc.getCountStar()) && Objects.equals(dataComplete, dc.isDataComplete())
        && Objects.equals(percentComplete, dc.getPercentComplete()) && Objects.equals(numAttempts, dc.getNumAttempts())
        && Objects.equals(delayNotified, dc.isDelayNotified()) && Objects.equals(timedOut, dc.isTimedOut());
  }

  @Override
  public int hashCode() {
    return Objects.hash(getId(), dataset, dateToCheckInMS, dateToCheckInSDF, countStar, dataComplete, percentComplete,
        numAttempts, delayNotified, timedOut);
  }
}


text:
layout: narrative

title: >
    Butchering Brains
source:
---

# "Butchering Brains."
 *Motion Picture Magazine* (May 1928)
 By Winnifred Eaton Reeve (Onoto Watanna)

   	The train from New York is due. Hollywood prepares to make one of its typical publicity gestures. Not, it is true, of the magnitude or hysterical and blatant quality such as is accorded a Star, a Movie Executive or a Peaches Browning[^n1], but taken all in all, a nice refined little hullabaloo. After all, it is only an Eminent Author who is arriving in Hollywood. He is met at the train by cameramen, reporters, a star or two, maybe a director, perhaps even the Mayor and a bunch of minor and major Movie folk that the publicity director has managed to round up for the occasion.

 	For a few days at least our Eminent Author basks in the sunshine and favor of the City of Props. He is wined and dined, photographed, touted, exploited, interviewed, quoted, misquoted. Every prospect pleases. He has a remarkable contract in his pocket. Five hundred dollars a week for the first three months; seven hundred and fifty dollars for the next six; one thousand dollars a week for the next year and so on ad nauseam. Small wonder that he gives forth an interview to the effect that he is charmed with Hollywood and intends to devote the rest of his literary life to the Great Art of Motion Pictures.

 	Like fun he is! At the end of the three months, he will get a little note to the effect that the option on his contract is not to be exercised by the Producer.

 	To one author who remains in Hollywood, there are a score who make their silent exit at the end of the three months. Not all go silently. Many fare forth shooting verbal fireworks behind them.

 	"The survival of the fittest" does not apply in Hollywood, so far as authors are concerned. The touchstone to success is not creative brains, talent, or inventive genius. The inspirational writer, however big his dreams and his product, cannot hope to compete with those possessed of sharp wits, craft, salesmanship, pull, politics, and the thousand and one petty tricks that contribute to one's influence in this game.

 	About a week after his arrival our Eminent Author finds himself parked in an ugly little office in a noisy rackety-    packetty building. (Some studios are beginning to grant the authors offices as good as the secretaries of the executives.) The refined hullabaloo aforementioned has become a thing of the dazzling past. Our author has been patted on the back for the last time.

 [^n1]:  Actress Peaches Browning (1910-1956), born Frances Belle Heenan, married 51-year-old real estate tycoon Edward Browning when she was only fifteen years old. Only a year later, she sued for divorce; the case became a nationwide sensation.

## An Original by Susy Swipes

  	He sits in his office and scans, with bulging eyes, his first assignment. He is presently either convulsed with wild mirth or is stricken dumb with incoherent wrath. He has been assigned to adapt and treat an "original" by one Susy Swipes or Davy Jones of Hollywood. It is an amazing, an incredible document. Its language is almost beyond credence. It is a nightmare patchwork that contains incidents and characters and gags and plots of a hundred or more stories that are horribly reminiscent to the Eminent Author.

 	A wise and prudent Eminent Author will set right to work upon Susy's or Davy's story. Sometimes, however, he bolts out of his office and dashes across the lot to the opulent administration building, where in ornately luxurious offices the favorites and powers that be hold forth.

 	"Fools rush in where angels fear to tread." "Whom the gods destroy they first make mad." Alas! How sadly these adages apply to the Eminent Author in Hollywood as he forces his way into the sanctum sanctorum of a supervisor, or even such movie royalty as the producer.

 	Let us draw a kindly veil over what ensues. We will change the subject.

 	Talking about supervisors. Some are human beings, speaking the author's own language, possessed of a sense of humor, keen, sympathetic, and kind. Others belong to that clan that a departing author (was it not Will Irwin[^n2]?) quaintly dubbed "the dese and dose and dem boys." These bright young fellows sometimes mistake Maeterlinck for a patent medicine and have been known to reject a story by Victor Hugo because he "keeps a restaurant down town." Usually they have a low opinion of authors, consider them pests and bugs and duck out of their way when they see one coming.    They are the big guns that the author must propitiate, defer to, conciliate, flatter, beguile, if he would remain in Hollywood.

  [^n2]:  Will Irwin (1873-1948), well-known journalist and author of numerous books including *Pictures of Old Chinatown* (1908; with photographs by Arthur Genthe), *Columbine Time* (1921), *Herbert Hoover: A Reminiscent Autobiography* (1928), and *The House that Shadows Built* (1928). Maurice Maeterlinck (1862-1949), playwright, a Belgian by birth and active in France, won the Nobel Prize for Literature in 1911.

## Golden Rules for Writers

  	Gladys Unger, playwright and author of "Romance," "Starlight" and many other well-known plays, gives the following recipe to aspiring movie writers:

 	"Study pantomime, fencing, boxing, Yiddish, Russian, and German. Forget English, American, reading, and writing."

 	The situation is not devoid of edification to the author. He is filled with unholy joy and admiration as he scans the patent medicine advertisements of his new contemporaries.  I AM AN AUTHOR AND I CAN PROVE IT!  	Thus ingenuously proclaims Bennie Balonsky in a full-page ad in a film trade paper.  I WANT THE WORLD TO KNOW THAT IT WAS I WHO WROTE: "I AM YOUR WIFE!"

  	Thus another Susy Swipes. Her number is legion in Hollywood. She is perched on the softest and plumpest of the seats of the mighty, and sometimes, so I have heard, she is perched upon the knee of a movie executive.

 	Irvin Cobb[^n3] is credited with a classic utterance at the end of a chaotic conference. I dare not misquote him, but I do know that his words conveyed a cordial invitation to the manhandlers of his brain product to cut a chunk of their throats and take the trail to a certain city whose temperature is high.

 	Michael Arlen left Hollywood gasping and smarting.

 	Hergesheimer studied Hollywood through his shining specs, with resulting excellent publicity for the charming Aileen Pringle. Clever girl, Aileen. The first of the stars to become known as "The Authors' Friend!"

 	George Jean Nathan dodged the limelight in the company of a modest blazing star.

 	Laurence Stallings chucked his tongue in his cheek. Occasionally gargantuan laughter proclaimed his appreciation of the whole large humor of Hollywood.

 	Once, as scenario editor, I recommended Ellis Parker Butler's classic: *Pigs Is Pigs*." I was shouted down with the objection that the censors and Will Hays[^n4] would never stand for a picture about hogs.

 	Dixie Wilson blew into Hollywood—if one of bouffant form may be said to blow, waving triumphantly an extraordinary contract. No mere scenario writer was this girl from the Ringling Circus to be, but a full-fledged director—so said Dixie. Three or six months later, Dixie exited as silently as a mouse.

 	Carl Van Vechten peeped in at the window, cocked a quizzical eyebrow and, tongue in cheek, extolled the virtues of the movie city, which he proposed to send down to posterity via the pages of his next book.

  [^n3]:  The authors listed in this section were all popular—some exceedingly so—at the time this article was published.

 [^n4]:  Will Hays, head of the Studio Relations Committee, the arm of the Motion Pictures Producers and Distributors Association (MPPDA) that issued the 1930 "production code" that attempted to regulate film content over concern over illicit language and subject matter.

## Edmund Goulding Prospers

  	Edmund Goulding[^n5] dropped in merely to have a look around. He expected to stay a day or two. He remained to become one of its greatest scenarists and directors. Now he is back in New York, with two of his plays in rehearsal and a novel on the press. He will return to Hollywood. Hollywood is not Hollywood without him, and there are a score of down-and-outers who miss the lift, the encouraging, snappy word and the dollar or two that Eddie was wont to slip into their hands so generously.

 	"Well, how do you like it?" asked a fa-    mous producer of Clarence Budington Kelland, after he had permitted the author to see the screen version of one of his stories. Falling into the producer's own idiom, Kelland replied:

 	"I ain't a-going to kiss you!"

 	Dorothy Farnum reminds one of Anita Loos[^n6]. She looks like a schoolgirl, a very pretty blonde one, and has the brain of a literary Napoleon. She tripped out of magazine writing and insinuated her way deftly to the very peak of scenario writing. Only master scripts are assigned her. "Beau Brummel," "Tess of the D'Urbervilles," the Garbo opuses, are from her pen. Like Frances Marion, she is possessed of exceptional beauty and brains. Frances Marion, incidentally, is without a doubt the greatest of the scenario writers. She is also a novelist.

 	Winifred Dunn, who wrote for the better class magazines before the movies captured her, looks like what we imagine Jane Eyre did. It seems incredible that this fragile girl is responsible for that epic of a pug, "The Patent-Leather Kid." "Sparrows" is another original of Miss Dunn's.

 	Donald McGibney stayed long enough to adapt his Saturday Evening Post story, "Two Arabian Knights," and hurried back to New York. But Hollywood had gotten into his blood. He is back now. He says he is competing with the butcher, the janitor, the mayor, the plumber and every other person in Hollywood as a scenarist.

  [^n5]:  Edmund Goulding (1891-1959) was an actor and playwright in his native England, but gained fame as a screenwriter and director in Hollywood, where he was credited with establishing MGM's reputation as a producer of elegant and tasteful films such as *Grand Hotel* (1932), starring Greta Garbo, John Barrymore, and Joan Crawford.

 [^n6]:  Anita Loos (1893-1981) and Frances Marion (1886-1973), mentioned later in the paragraph, were two of the grande dames of Hollywood screenwriting beginning in the 1910s.

## Doty Thought Dotty

  	Douglas Doty, be-spectacled, scholarly high-brow writer and editor of the Century Magazine, startled the sober and respectable world of which he was a prized ornament by suddenly breaking the chains and shackles that bound him to his editorial chair and home. He shot out for Hollywood. There he appeared with all the bubbling spirits and jazzy clothes of a college youth. What an exhilarating season followed. The former editor dropped ten years of his age, and even acquired height.He no longer indites high-brow editorials, but sparkling scenarios, and, moreover, he has acquired the prettiest little movie wife imaginable and an adorable Doty Junior.

 	This, however, is only one and an unusually exceptional instance of a professional writer's successful assimilation into the motion picture industry. The average literary man finds himself quite unable to cope with the viewpoint of the film-makers. Too, he is not infrequently aghast at their conception of him and his work.

 	Was it not Arthur Stringer[^n7] who submitted "Perils of the Deep" to a well-known producer, and was nearly paralyzed when said producer threw it back at him with:

 	"Naw! Don't want no more stories about pearls!"

 	Said an Eminent Author to an Eminent Producer:

 	"May I have the honor of dedicating my new book to you?"

 	"Certainly," replied the flattered producer. "When do you wish me to be ready and where does the ceremony take place?"

 	The author was young and he had been born in Australia. The supervisor was also young, and he had been born on Ellis Island. Said the supervisor:

 	"You come from Australia?"

 	"Yes, sir."

 	"Hm. Speak Austrian, heh?"

 	"Why, no, sir."

 	"How long have you been in this country?"

 	"One month."

 	"What! Where you learn to speak English so quick?"

 [^n7]:  Arthur Stringer (1874-1950), one of the best-known Canadian authors of his day, was an acquaintance of Eaton's.


text:
<?php declare(strict_types=1);

printf('resources.store %s', Siler\Http\Request\post('foo'));


text:
package com.viesis.viescraft.common.items.crafting;

import com.google.common.collect.Lists;

import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.InventoryCraftResult;
import net.minecraft.inventory.InventoryCrafting;
import net.minecraft.inventory.Slot;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.CraftingManager;
import net.minecraft.item.crafting.IRecipe;
import net.minecraft.util.NonNullList;

public class SlotCraftingVC extends Slot
{
    /** The craft matrix inventory linked to this result slot. */
    private final InventoryCrafting craftMatrix;
    /** The player that is using the GUI where this slot resides. */
    private final EntityPlayer player;
    /** The number of items that have been crafted so far. Gets passed to ItemStack.onCrafting before being reset. */
    private int amountCrafted;

    public SlotCraftingVC(EntityPlayer player, InventoryCrafting craftingInventory, IInventory inventoryIn, int slotIndex, int xPosition, int yPosition)
    {
        super(inventoryIn, slotIndex, xPosition, yPosition);
        this.player = player;
        this.craftMatrix = craftingInventory;
    }

    /**
     * Check if the stack is allowed to be placed in this slot, used for armor slots as well as furnace fuel.
     */
    public boolean isItemValid(ItemStack stack)
    {
        return false;
    }

    /**
     * Decrease the size of the stack in slot (first int arg) by the amount of the second int arg. Returns the new
     * stack.
     */
    public ItemStack decrStackSize(int amount)
    {
        if (this.getHasStack())
        {
            this.amountCrafted += Math.min(amount, this.getStack().getCount());
        }

        return super.decrStackSize(amount);
    }

    /**
     * the itemStack passed in is the output - ie, iron ingots, and pickaxes, not ore and wood. Typically increases an
     * internal count then calls onCrafting(item).
     */
    protected void onCrafting(ItemStack stack, int amount)
    {
        this.amountCrafted += amount;
        this.onCrafting(stack);
    }

    protected void onSwapCraft(int p_190900_1_)
    {
        this.amountCrafted += p_190900_1_;
    }

    /**
     * the itemStack passed in is the output - ie, iron ingots, and pickaxes, not ore and wood.
     */
    protected void onCrafting(ItemStack stack)
    {
        if (this.amountCrafted > 0)
        {
            stack.onCrafting(this.player.world, this.player, this.amountCrafted);
            net.minecraftforge.fml.common.FMLCommonHandler.instance().firePlayerCraftingEvent(this.player, stack, craftMatrix);
        }

        this.amountCrafted = 0;
        InventoryCraftResult inventorycraftresult = (InventoryCraftResult)this.inventory;
        IRecipe irecipe = inventorycraftresult.getRecipeUsed();

        if (irecipe != null && !irecipe.isHidden())
        {
            this.player.unlockRecipes(Lists.newArrayList(irecipe));
            inventorycraftresult.setRecipeUsed((IRecipe)null);
        }
    }

    public ItemStack onTake(EntityPlayer thePlayer, ItemStack stack)
    {
        this.onCrafting(stack);
        net.minecraftforge.common.ForgeHooks.setCraftingPlayer(thePlayer);
        NonNullList<ItemStack> nonnulllist = CraftingManager.getRemainingItems(this.craftMatrix, thePlayer.world);
        net.minecraftforge.common.ForgeHooks.setCraftingPlayer(null);

        for (int i = 0; i < nonnulllist.size(); ++i)
        {
            ItemStack itemstack = this.craftMatrix.getStackInSlot(i);
            ItemStack itemstack1 = nonnulllist.get(i);

            if (!itemstack.isEmpty())
            {
                this.craftMatrix.decrStackSize(i, 1);
                itemstack = this.craftMatrix.getStackInSlot(i);
            }

            if (!itemstack1.isEmpty())
            {
                if (itemstack.isEmpty())
                {
                    this.craftMatrix.setInventorySlotContents(i, itemstack1);
                }
                else if (ItemStack.areItemsEqual(itemstack, itemstack1) && ItemStack.areItemStackTagsEqual(itemstack, itemstack1))
                {
                    itemstack1.grow(itemstack.getCount());
                    this.craftMatrix.setInventorySlotContents(i, itemstack1);
                }
                else if (!this.player.inventory.addItemStackToInventory(itemstack1))
                {
                    this.player.dropItem(itemstack1, false);
                }
            }
        }

        return stack;
    }
}


text:
package com.hazelcast.config;

import java.util.Properties;

/**
 * Management Center mutual authentication configuration.
 * Config required to setup custom key & trust stores for the outgoing connections of the member towards the Management Center.
 * A custom SSLContextFactory can also be provided for special needs.
 */
public final class MCMutualAuthConfig {

    private boolean enabled;
    private String factoryClassName;
    private Object factoryImplementation;
    private Properties properties = new Properties();

    /**
     * Returns the name of the implementation class.
     *

     * Class can either be an  {@link com.hazelcast.nio.ssl.SSLContextFactory}.
     *
     * @return the name implementation class
     */
    public String getFactoryClassName() {
        return factoryClassName;
    }

    /**
     * Sets the name for the implementation class.
     *

     * Class can either be an  {@link com.hazelcast.nio.ssl.SSLContextFactory}.
     *
     * @param factoryClassName the name implementation class
     */
    public MCMutualAuthConfig setFactoryClassName(String factoryClassName) {
        this.factoryClassName = factoryClassName;
        return this;
    }

    /**
     * Returns if this configuration is enabled.
     *
     * @return {@code true} if enabled, {@code false} otherwise
     */
    public boolean isEnabled() {
        return enabled;
    }

    /**
     * Enables and disables this configuration.
     *
     * @param enabled {@code true} to enable, {@code false} to disable
     */
    public MCMutualAuthConfig setEnabled(boolean enabled) {
        this.enabled = enabled;
        return this;
    }

    /**
     * Sets the implementation object.
     *

     * Object must be instance of an {@link com.hazelcast.nio.ssl.SSLContextFactory}.
     *
     * @param factoryImplementation the implementation object
     * @return this MCMutualAuthConfig instance
     */
    public MCMutualAuthConfig setFactoryImplementation(Object factoryImplementation) {
        this.factoryImplementation = factoryImplementation;
        return this;
    }

    /**
     * Returns the factory implementation object.
     *

     * Object is instance of an {@link com.hazelcast.nio.ssl.SSLContextFactory}
     * @return the factory implementation object
     */
    public Object getFactoryImplementation() {
        return factoryImplementation;
    }

    /**
     * Sets a property.
     *
     * @param name  the name of the property to set
     * @param value the value of the property to set
     * @return the updated MCMutualAuthConfig
     * @throws NullPointerException if name or value is {@code null}
     */
    public MCMutualAuthConfig setProperty(String name, String value) {
        properties.put(name, value);
        return this;
    }

    /**
     * Gets a property.
     *
     * @param name the name of the property to get
     * @return the value of the property, null if not found
     * @throws NullPointerException if name is {@code null}
     */
    public String getProperty(String name) {
        return properties.getProperty(name);
    }

    /**
     * Gets all properties.
     *
     * @return the properties
     */
    public Properties getProperties() {
        return properties;
    }

    /**
     * Sets the properties.
     *
     * @param properties the properties to set
     * @return the updated MCMutualAuthConfig
     * @throws IllegalArgumentException if properties is {@code null}
     */
    public MCMutualAuthConfig setProperties(Properties properties) {
        if (properties == null) {
            throw new IllegalArgumentException("properties can't be null");
        }
        this.properties = properties;
        return this;
    }

    @Override
    public String toString() {
        return "MCMutualAuthConfig{"
                + "className='" + factoryClassName + '\''
                + ", enabled=" + enabled
                + ", implementation=" + factoryImplementation
                + ", properties=" + properties
                + '}';
    }
}


text:
require 'active_support/concern'
require 'deferred_loader/proxy'
module DeferedLoader
  module Deferrable
    extend ActiveSupport::Concern
    included do
      def deferred_load
        DeferredLoader::Proxy.new(self)
      end
    end
  end
end


text:
var Bot = require('../').Bot;
var Bot_Github = require('../').Bot_Github;
var utils = require('../').utils;

describe('The utils object', function () {

    describe('maxVersion method', function () {

        it('should return the max version out of an array', function () {

            var versions = [
                '1.1.0',
                '1.1.3',
                '1.1.2',
                '2.1.2',
                '2.1.0',
                '2.3.2'
            ];

            var max = utils.maxVersion(versions, '1.1.x');
            max.should.equal('1.1.3');

            max = utils.maxVersion(versions, '2.1.x');
            max.should.equal('2.1.2');

            max = utils.maxVersion(versions, '2.3.x');
            max.should.equal('2.3.2');

            max = utils.maxVersion(versions, 'x.x.x');
            max.should.equal('2.3.2');

            max = utils.maxVersion(versions, '4.x.x');
            (max === null).should.be.true;
        });
    });

    describe('versionToString method', function () {

        it('should return version string with in a formatted', function () {

            var str = utils.versionToString('4.1.1', 'major-minor');
            str.should.equal('4-1');

            str = utils.versionToString('4erwerwe.1.1', 'major-minor');
            str.should.equal('');

            str = utils.versionToString('4.1.5', 'major-minor+patch');
            str.should.equal('4-1+5');
        });
    });
});

describe('The github bot object', function () {

    describe('Constructor', function () {

        it ('should be an instance of Bot', function () {

            var bot = new Bot_Github({group: 'salazar', repository: 'https://github.com/x/y'});

            bot.should.be.an.instanceof(Bot);

            bot.project.should.have.property('name', 'Unknown');
        });

        it ('should throw without a valid github url', function () {

            (function () {
                new Bot_Github({group: 'salazar', repository: '//github.com/x/y'});
            }).should.throw(/repository url is not from Github/);

            (function () {
                new Bot_Github({group: 'salazar'});
            }).should.throw(/repository url is not from Github/);

            (function () {
                new Bot_Github({group: 'salazar', repository: 'https://github.com/y'});
            }).should.throw(/repository url is not from Github/);

            (function () {
                new Bot_Github({group: 'salazar', repository: 'https://github.com/y/'});
            }).should.throw(/repository url is not from Github/);

            (function () {
                new Bot_Github({group: 'salazar', repository: 'https://github.com'});
            }).should.throw(/repository url is not from Github/);
        });
    });

    describe('the url methods', function () {

        it ('should build the url for the commits on a branch', function () {
            var bot = new Bot_Github({group: 'salazar', repository: 'https://github.com/x/y'});
            bot.urlForCommits('zot').should.equal('https://github.com/x/y/commits/zot')
        });

        it ('should build the url for a tag', function () {
            var bot = new Bot_Github({group: 'salazar', repository: 'https://github.com/x/y'});
            bot.urlForTag('zot').should.equal('https://github.com/x/y/releases/tag/zot')
        });

        it ('should build the url for a download', function () {
            var bot = new Bot_Github({group: 'salazar', repository: 'https://github.com/x/y'});
            bot.urlForDownload('zot-10.3').should.equal('https://github.com/x/y/archive/zot-10.3.tar.gz')
        });
    });
});

describe('The bot object', function () {

    describe('Constructor', function () {

        it ('should throw without initialization object', function () {
            (function () {
                new Bot();
            }).should.throw(/empty or wrong project/);
        });

        it ('should throw with a wrong initialization object', function () {
            (function () {
                new Bot("zot");
            }).should.throw(/empty or wrong project/);
        });

        it ('should throw with an unknown property', function () {
            (function () {
                new Bot({zot: 23});
            }).should.throw(/wrong key in project/);
        });

        it ('should set the right defaults', function () {

            var bot = new Bot({group: 'salazar'});

            bot.project.should.have.property('group', 'salazar');
            bot.project.should.have.property('name', 'Unknown');
            bot.project.should.have.property('description', '');
            bot.project.should.have.property('website', '');
            bot.project.should.have.property('repository', '');
        });

        it ('should set the right project properties', function () {

            var bot = new Bot({group: 'salazar', name: 'gargantua', description: 'sottile', website: 'google.com', repository: 'somewhere'});

            bot.project.should.have.property('group', 'salazar');
            bot.project.should.have.property('name', 'gargantua');
            bot.project.should.have.property('description', 'sottile');
            bot.project.should.have.property('website', 'google.com');
            bot.project.should.have.property('repository', 'somewhere');
        });
    });

    describe('set method', function () {

        it ('should throw on wrong parameters', function () {

            var bot = new Bot({group: 'foobar'});

            (function () {
                bot.set();
            }).should.throw(/wrong parameter/);

            (function () {
                bot.set('bazzinga');
            }).should.throw(/wrong parameter/);

            (function () {
                bot.set('bazzinga', 23);
            }).should.throw(/unknown result key/);
        });

        it ('should throw on a double set', function () {

            var bot = new Bot({group: 'foobar'});

            (function () {
                bot.set('currentVersion', 23);
                bot.set('currentVersion', 23);
            }).should.throw(/result key already set/);
        });

        it ('should set a result key', function () {

            var bot = new Bot({group: 'foobar'});

            bot.set('currentVersion', 123);

            bot.results.should.have.property('currentVersion', '123');
        });

        it ('should set a result key with dynamic parameters', function () {

            var bot = new Bot({group: 'foobar'});

            bot.set('downloadUrl', "http://%s/zot", "google.com");

            bot.results.should.have.property('downloadUrl', "http://google.com/zot");
        });
    });

    describe('get method', function () {

        it ('should throw on wrong parameters', function () {

            var bot = new Bot({group: 'foobar'});

            (function () {
                bot.get();
            }).should.throw(/wrong parameter/);

            (function () {
                bot.get('bazzinga');
            }).should.throw(/unknown result key/);
        });

        it ('should get a result key', function () {

            var bot = new Bot({group: 'foobar'});

            bot.set('currentVersion', 123);

            bot.get('currentVersion').should.equal('123');
        });
    });
});


text:
function [figwords] = calc_jasa_words_figures(figSizeArray, cols)

% figSizeArray is an array of figure dimensions:
% [width1 height1; width2 height2] etc

% cols is a cell array that indicates whether each figure is 'single'
% column or 'double' column. Default is single column.

if nargin < 3 || isemtpy(cols), cols = cell(size(figSizeArray,1),1); cols(:) = {'single'}; end

for f = 1:size(figSizeArray,1)
    tw = figSizeArray(f,1);
    th = figSizeArray(f,2);
    asprat = tw/th;
    if strcmpi(cols{f},'single')
        figwords(f) = (150/asprat) + 20;
    elseif strcmpi(cols{f},'double')
        figwords(f) = (150/asprat) + 40; % guidance actually says 300/0.5 x aspect ratio + 40...not sure how 300/0.5 isn't 150?
    else
        error('must specify single or double column for all figures in cols variable')
    end
end


text:
<?php

namespace AppBundle\Controller;

use AppBundle\Form\Type\UserType;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

use AppBundle\Entity\users;
use Symfony\Component\HttpFoundation\Session\Session;

class LoginController extends Controller
{
    /**
     * @Route("/login", name="login")
     */
    public function login(Request $request)
    {
        if (isset($_POST['verzenden'])){
            $em = $this->getDoctrine()->getEntityManager();
            $user = $em->getRepository('AppBundle:users')->findBy(array('gebruikersnaam' => $_POST['gebruikersnaam']));
            if (!$user){
                return new Response($this->render('login/login.html.twig', array('loginfail' => 1)));
            }
            elseif ($user[0]->getWachtwoord() != $_POST['wachtwoord']){
                return new Response($this->render('login/login.html.twig', array('loginfail' => 2)));
            }
            elseif ($user[0]->getWachtwoord() == $_POST['wachtwoord']){
                $session = new Session();

                $session->set('gebruikersnaam', $user[0]->getGebruikersnaam());
                $session->set('rol', $user[0]->getRol());

                if ($session->get('rol') == 1){
                    return $this->redirect($this->generateurl("alleartikelen"));
                }
                elseif ($session->get('rol') == 2){
                    return $this->redirect($this->generateurl("alleartikelenmazijn"));
                }
                elseif ($session->get('rol') == 3){
                    return $this->redirect($this->generateurl("alleartikelenverkoper"));
                }
                elseif ($session->get('rol') == 4){
                    return $this->redirect($this->generateurl("allegebruikers"));
                }
                elseif ($session->get('rol') == 5){
                    return $this->redirect($this->generateurl("financieel"));
                }

                //return new Response($session->get('rol'));
            }
        }
        else{
            return new Response($this->render('login/login.html.twig'));
        }

    }

    /**
     * @Route("/logout", name="logout")
     */
    public function logout(Request $request)
    {
        $session = $this->get('session');
        $session->remove('gebruikersnaam');
        $session->remove('rol');
        return new Response($this->render('login/login.html.twig'));
    }

    /**
     * @Route("/loginprocess", name="loginprocess")
     */
    public function loginprocess(Request $request)
    {
        return new Response("Hallo wereld");
    }

    /**
     * @Route("/admin/nieuwegebruiker", name="nieuwegebruiker")
     */
    public function nieuwegebruiker(Request $request) {
        $session = $this->get('session');
        if ($session->get('rol') == 4) {
            //todo: gebruikerrol
            $nieuwegebruiker = new users();
            $form = $this->createForm(UserType::class, $nieuwegebruiker);

            $form->handleRequest($request);
            if ($form->isSubmitted() && $form->isValid()) {
                $em = $this->getDoctrine()->getManager();
                $em->persist($nieuwegebruiker);
                $em->flush();
                return $this->redirect($this->generateurl("nieuwegebruiker"));
            }
            return new Response($this->render('login/nieuwe_gebruiker.html.twig', array('form' => $form->createView())));
        }
        else{
            return new Response('Geen toegang.');
        }
    }

    /**
     * @Route("/admin/gebruiker/wijzig/{gebruikerid}", name="gebruikerwijzigen")
     */
    public function wijzigArtikel(Request $request, $gebruikerid) {
        $session = $this->get('session');
        if ($session->get('rol') == 4) {
            $gebruiker = $this->getDoctrine()->getRepository("AppBundle:users")->find($gebruikerid);
            $form = $this->createForm(UserType::class, $gebruiker);

            $form->handleRequest($request);
            if ($form->isSubmitted() && $form->isValid()) {
                $em = $this->getDoctrine()->getManager();
                $em->persist($gebruiker);
                $em->flush();
                return $this->redirect($this->generateurl("allegebruikers"));
            }

            return new Response($this->render('login/nieuwe_gebruiker.html.twig', array('form' => $form->createView())));
        }
        else{
            return new Response('Geen toegang.');
        }
    }

    /**
     * @Route("/admin/gebruikers", name="allegebruikers")
     */
    public function alleGebruikers(Request $request){
        $session = $this->get('session');
        if ($session->get('rol') == 4) {
            //alle artikelen omhalen
            $gebruikers = $this->getDoctrine()->getRepository("AppBundle:users")->findAll();
            //wegschrijven naar html bestand met de artikelen variable
            return new Response($this->render('login/alle_gebruikers.html.twig', array('gebruikers' => $gebruikers)));
        }
        else{
            return new Response('Geen toegang.');
        }
    }

}


text: <!DOCTYPE html>


text:
using System;
using System.Collections;
using System.Diagnostics;

namespace ScriptSharp.CodeModel {

    /// <summary>
    /// The root of the parse tree hierarchy.
    /// Note that any ParseNode can be treated as a ListTree.
    /// A null value corresponds to an empty list. A non-ListTree
    /// ParseNode is a list of 1 element. While a ListTree is used
    /// for lists containing more than 1 element.
    /// </summary>
    internal abstract class ParseNode {

        public ParseNodeType nodeType;
        public Token token;
        public ParseNode parent;

        protected ParseNode(ParseNodeType nodeType, Token token) {
            this.nodeType = nodeType;
            this.token = token;
        }

        public ParseNodeType NodeType {
            get {
                return nodeType;
            }
        }

        public ParseNode Parent {
            get {
                return parent;
            }
        }

        public Token Token {
            get {
                return token;
            }
        }

        protected ParseNode GetParentedNode(ParseNode child) {
            if (child != null) {
                child.SetParent(this);
            }
            return child;
        }

        protected ParseNodeList GetParentedNodeList(ParseNodeList nodeList) {
            nodeList.SetParent(this);
            return nodeList;
        }

        internal void SetParent(ParseNode node) {
            parent = node;
        }
    }
}


text:
package Paws::CloudFront::UntagResource;
  use Moose;
  has Resource => (is => 'ro', isa => 'Str', query_name => 'Resource', traits => ['ParamInQuery'], required => 1);
  has TagKeys => (is => 'ro', isa => 'Paws::CloudFront::TagKeys', required => 1);

  use MooseX::ClassAttribute;

  class_has _api_call => (isa => 'Str', is => 'ro', default => 'UntagResource');
  class_has _api_uri  => (isa => 'Str', is => 'ro', default => '/2017-03-25/tagging?Operation=Untag');
  class_has _api_method  => (isa => 'Str', is => 'ro', default => 'POST');
  class_has _returns => (isa => 'Str', is => 'ro', default => 'Paws::API::Response');
  class_has _result_key => (isa => 'Str', is => 'ro');

1;

### main pod documentation begin ###

=head1 NAME

Paws::CloudFront::UntagResource - Arguments for method UntagResource on Paws::CloudFront

=head1 DESCRIPTION

This class represents the parameters used for calling the method UntagResource2017_03_25 on the
Amazon CloudFront service. Use the attributes of this class
as arguments to method UntagResource2017_03_25.

You shouldn't make instances of this class. Each attribute should be used as a named argument in the call to UntagResource2017_03_25.

As an example:

  $service_obj->UntagResource2017_03_25(Att1 => $value1, Att2 => $value2, ...);

Values for attributes that are native types (Int, String, Float, etc) can passed as-is (scalar values). Values for complex Types (objects) can be passed as a HashRef. The keys and values of the hashref will be used to instance the underlying object.

=head1 ATTRIBUTES

=head2 B<REQUIRED> Resource => Str

An ARN of a CloudFront resource.

=head2 B<REQUIRED> TagKeys => L<Paws::CloudFront::TagKeys>

A complex type that contains zero or more C<Tag> key elements.

=head1 SEE ALSO

This class forms part of L<Paws>, documenting arguments for method UntagResource2017_03_25 in L<Paws::CloudFront>

=head1 BUGS and CONTRIBUTIONS

The source code is located here: https://github.com/pplu/aws-sdk-perl

Please report bugs to: https://github.com/pplu/aws-sdk-perl/issues

=cut


text:
@implementation UserInfoResponseSerializer

-(id)responseObjectForResponse:(NSURLResponse *)response
                          data:(NSData *)data
                         error:(NSError *__autoreleasing *)error
{
    NSString *rawHtml = [super responseObjectForResponse: response
                                                    data: data
                                                   error: error];
    rawHtml = [rawHtml stringByReplacingOccurrencesOfString: @"\r\n" withString: @"\n"];

    NSRegularExpression *regex = [NSRegularExpression
                                  regularExpressionWithPattern: @"
\n(.*?)
.*回帖数 (\\d+).*主题数 (\\d+).*target=\"_blank\">(.*?).*注册时间(.*?)
"
                                  options: NSRegularExpressionDotMatchesLineSeparators
                                  error: error];

    __block ForumUser *user = [[ForumUser alloc] init];

    [regex enumerateMatchesInString: rawHtml
                            options: 0
                              range: NSMakeRange(0, rawHtml.length)
                         usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {

                             NSString *username = [rawHtml substringWithRange: [result rangeAtIndex: 1]];
                             NSString *reply = [rawHtml substringWithRange: [result rangeAtIndex: 2]];
                             NSString *post = [rawHtml substringWithRange: [result rangeAtIndex: 3]];
                             NSString *level = [rawHtml substringWithRange: [result rangeAtIndex: 4]];
                             NSString *date = [rawHtml substringWithRange: [result rangeAtIndex: 5]];

                             NSString *dateFormatString = @"yyyy-M-d HH:mm";
                             NSString *timeZoneName = @"Asian/Shanghai";
                             NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
                             [dateFormatter setDateFormat: dateFormatString];
                             [dateFormatter setTimeZone: [NSTimeZone timeZoneWithName: timeZoneName]];
                             NSDate *regDate = [dateFormatter dateFromString: date];

                             user.name = username;
                             user.numberOfReply = [reply integerValue];
                             user.numberOfPost = [post integerValue];
                             user.level = level;
                             user.registerDate = regDate;

                         }];
    return user;
}

@end


text:
package org.springframework.security.config.annotation.web.configurers;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.test.SpringTestContext;
import org.springframework.security.config.test.SpringTestContextExtension;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.test.web.servlet.MockMvc;

import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.authentication;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.forwardedUrl;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

/**
 * Tests to verify that all the functionality of <access-denied-handler> attributes
 * is present
 *
 * @author Rob Winch
 * @author Josh Cummings
 *
 */
@ExtendWith(SpringTestContextExtension.class)
public class NamespaceHttpServerAccessDeniedHandlerTests {

	public final SpringTestContext spring = new SpringTestContext(this);

	@Autowired
	MockMvc mvc;

	@Test
	public void requestWhenCustomAccessDeniedPageThenBehaviorMatchesNamespace() throws Exception {
		this.spring.register(AccessDeniedPageConfig.class).autowire();
		// @formatter:off
		this.mvc.perform(get("/").with(authentication(user())))
				.andExpect(status().isForbidden())
				.andExpect(forwardedUrl("/AccessDeniedPageConfig"));
		// @formatter:on
	}

	@Test
	public void requestWhenCustomAccessDeniedPageInLambdaThenForwardedToCustomPage() throws Exception {
		this.spring.register(AccessDeniedPageInLambdaConfig.class).autowire();
		// @formatter:off
		this.mvc.perform(get("/").with(authentication(user())))
				.andExpect(status().isForbidden())
				.andExpect(forwardedUrl("/AccessDeniedPageConfig"));
		// @formatter:on
	}

	@Test
	public void requestWhenCustomAccessDeniedHandlerThenBehaviorMatchesNamespace() throws Exception {
		this.spring.register(AccessDeniedHandlerRefConfig.class).autowire();
		this.mvc.perform(get("/").with(authentication(user())));
		verifyBean(AccessDeniedHandler.class).handle(any(HttpServletRequest.class), any(HttpServletResponse.class),
				any(AccessDeniedException.class));
	}

	@Test
	public void requestWhenCustomAccessDeniedHandlerInLambdaThenBehaviorMatchesNamespace() throws Exception {
		this.spring.register(AccessDeniedHandlerRefInLambdaConfig.class).autowire();
		this.mvc.perform(get("/").with(authentication(user())));
		verify(AccessDeniedHandlerRefInLambdaConfig.accessDeniedHandler).handle(any(HttpServletRequest.class),
				any(HttpServletResponse.class), any(AccessDeniedException.class));
	}

	private static Authentication user() {
		return UsernamePasswordAuthenticationToken.authenticated("user", null, AuthorityUtils.NO_AUTHORITIES);
	}

	private <T> T verifyBean(Class<T> beanClass) {
		return verify(this.spring.getContext().getBean(beanClass));
	}

	@EnableWebSecurity
	static class AccessDeniedPageConfig extends WebSecurityConfigurerAdapter {

		@Override
		protected void configure(HttpSecurity http) throws Exception {
			// @formatter:off
			http
				.authorizeRequests()
					.anyRequest().denyAll()
					.and()
				.exceptionHandling()
					.accessDeniedPage("/AccessDeniedPageConfig");
			// @formatter:on
		}

	}

	@EnableWebSecurity
	static class AccessDeniedPageInLambdaConfig extends WebSecurityConfigurerAdapter {

		@Override
		protected void configure(HttpSecurity http) throws Exception {
			// @formatter:off
			http
				.authorizeRequests((authorizeRequests) ->
					authorizeRequests
						.anyRequest().denyAll()
				)
				.exceptionHandling((exceptionHandling) ->
					exceptionHandling.accessDeniedPage("/AccessDeniedPageConfig")
				);
			// @formatter:on
		}

	}

	@EnableWebSecurity
	static class AccessDeniedHandlerRefConfig extends WebSecurityConfigurerAdapter {

		@Override
		protected void configure(HttpSecurity http) throws Exception {
			// @formatter:off
			http
				.authorizeRequests()
					.anyRequest().denyAll()
					.and()
				.exceptionHandling()
					.accessDeniedHandler(accessDeniedHandler());
			// @formatter:on
		}

		@Bean
		AccessDeniedHandler accessDeniedHandler() {
			return mock(AccessDeniedHandler.class);
		}

	}

	@EnableWebSecurity
	static class AccessDeniedHandlerRefInLambdaConfig extends WebSecurityConfigurerAdapter {

		static AccessDeniedHandler accessDeniedHandler = mock(AccessDeniedHandler.class);

		@Override
		protected void configure(HttpSecurity http) throws Exception {
			// @formatter:off
			http
				.authorizeRequests((authorizeRequests) ->
					authorizeRequests
						.anyRequest().denyAll()
				)
				.exceptionHandling((exceptionHandling) ->
						exceptionHandling.accessDeniedHandler(accessDeniedHandler())
				);
			// @formatter:on
		}

		@Bean
		AccessDeniedHandler accessDeniedHandler() {
			return accessDeniedHandler;
		}

	}

}


text:
import Ember from 'ember';

const {
  computed: {alias}
} = Ember;

import Model                from 'ember-data/model';
import attr                 from 'ember-data/attr';
import {belongsTo, hasMany} from 'ember-data/relationships';

export default Model.extend({

  // ----- Attributes -----
  description: attr('string'),
  line:        attr('number'),

  isMain:      attr('boolean'),
  itemType:    attr('string'),
  tag:         attr('string'),
  deprecated:  attr('boolean'),

  // ----- Relationships -----
  version:      belongsTo('yuidoc-version', {async: false}),
  parentModule: belongsTo('yuidoc-module',  {async: false, inverse: 'submodules'}),
  file:         belongsTo('yuidoc-file',    {async: false}),

  classes:    hasMany('yuidoc-class',      {async: false}),
  classItems: hasMany('yuidoc-class-item', {async: false}),
  namespaces: hasMany('yuidoc-namespace',  {async: false}),
  submodules: hasMany('yuidoc-module',     {async: false, inverse: 'parentModule'}),

  // ----- Computed properties -----
  name: alias('id')
});


text:
extern char* city_lasterror;

int find_png_filename(const char* filename, char* o_f);

int loadsramcity (const char* sfname, uint16_t* citydata, int citynum, char* o_cityname);
int write_new_city(const char* sfname, const uint16_t* citydata, const char* cityname, int citynum);
int replace_city(const char* sfname, const uint16_t* citydata, int citynum);

int newcity(const char* sfname, const char* mfname, const char* cityname, int improve, int improve_flags);
int png2city (const char* sfname, const char* mfname, int citynum, int improve, int improve_flags);

int city2png (const char* sfname, const char* mfname, int citynum);
int fixsram (const char* sfname);

int describe_cities (const char* sfname, char* city1, char* city2);

#endif


text:
using Microsoft.AspNet.Identity.EntityFramework;

namespace Staffinfo.API
{
    public class AuthContext: IdentityDbContext<IdentityUser>
    {
        public AuthContext(): base("AuthContext")
        { }
    }
}


text:
SELECT * FROM account;
INSERT INTO `crux`.`account` (`id`, `first_name`, `last_name`, `email`, `is_active`, `created_at`, `updated_at`) VALUES (NULL, 'John', 'Doe', 'john@doe.com', '1', '', '');


text:
<?xml version="1.0" encoding="utf-8"?>
<set android:interpolator="@android:anim/accelerate_interpolator"
  xmlns:android="http://schemas.android.com/apk/res/android">
    <translate android:duration="350" android:fromXDelta="0.0" android:toXDelta="0.0" android:fromYDelta="0.0" android:toYDelta="100.0%" />
</set>


text:
#ifndef GLVERTEXARRAY_H
#define GLVERTEXARRAY_H

#include <set>
#include <functional>
#include <GL/glew.h>
#include "handle.h"
#include "glbuffer.h"

namespace GL {
	/**
	* Handles and simplifies interacting with OpenGL VBOs
	* TODO: Add function for assigning the VBO, don't just take whatever is currently bound
	*/
	class VertexArray {
	public:
		/**
		* Create a VAO for use
		*/
		VertexArray();
		/**
		* Set the element buffer for indexed rendering, if desired
		* if the indices version is used a new element buffer will be made
		* if an existing element buffer is passed, it will be used
		*/
		template<size_t N>
		void elementBuffer(const std::array<unsigned short, N> &indices){
			glBindVertexArray(mHandle);
			mElemBuf = ElementBuffer(indices, USAGE::STATIC_DRAW);
		}
		void elementBuffer(const std::vector<unsigned short> &indices);
		void elementBuffer(ElementBuffer &e);
		//Get the number of elements in the element buffer
		size_t numElements();
		/**
		* Set some attribute to use values taken from a vbo given some
		* size of components to take, a type, if the values are normalize
		* a byte stride and an offset
		* @param b Vertex Buffer containing the data for this attribute
		* @param attrib The name of the attribute to set
		* @param vao The vertex array to get the values from
		* @param size The number of components per attribute
		* @param type The type of data in the vbo
		* @param normalized Specifies that fixed point values should be normalized if true, default false
		* @param stried The byte offset between attributes, default 0
		* @param offset The byte offset to begin reading attributes, default 0
		*/
		void setAttribPointer(VertexBuffer &b, GLint attrib, size_t size, GLenum type,
			bool normalized = GL_FALSE, size_t stride = 0, void *offset = 0);
		/**
		* Implicitly convert to a GLuint if trying to use
		* the program as such
		*/
		operator GLuint();

	private:
		///The VAO handle
		Handle mHandle;
		///The VBOs the VAO is referencing, we use a set to store two references to the same vbo
		std::set<VertexBuffer> mVbos;
		ElementBuffer mElemBuf;
		///A function to delete a single vao
		const static std::function<void(GLuint*)> sDeleter;
	};
}

#endif


text:
inline const unsigned char * toUChar(const QByteArray & a) { return reinterpret_cast<const unsigned char *>(a.operator const char *()); };

Krypto::Krypto()
{

}

void Krypto::createCert(QByteArray &priv, QByteArray &request, const QString common) {
	mbedtls_entropy_context entropy;
	mbedtls_ctr_drbg_context ctr_drbg;
	mbedtls_pk_context pk; //rsa key pair
	mbedtls_x509write_csr req;
	unsigned char output[4096];
	mbedtls_pk_init(&pk);
	mbedtls_pk_setup(&pk, mbedtls_pk_info_from_type(MBEDTLS_PK_RSA));

	//generate RSA pair
	const char *pers = "rsa_genkey";
	mbedtls_ctr_drbg_init(&ctr_drbg);
	mbedtls_entropy_init(&entropy);
	if (mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func, &entropy,(const unsigned char *)pers,strlen(pers))
		!= 0)
	{
		mbedtls_ctr_drbg_free(&ctr_drbg);
		mbedtls_entropy_free(&entropy);
		throw new KryptoException("Generating entropy for RSA pair failed.");
	}

	if (mbedtls_rsa_gen_key(mbedtls_pk_rsa(pk), mbedtls_ctr_drbg_random, &ctr_drbg, RSA_SIZE, RSA_EXPONENT)
		!= 0)
	{
		mbedtls_ctr_drbg_free(&ctr_drbg);
		mbedtls_entropy_free(&entropy);
		throw new KryptoException("Generating RSA pair failed.");
	}

	//generate cert request

	mbedtls_x509write_csr_init(&req);
	mbedtls_x509write_csr_set_md_alg(&req, MBEDTLS_MD_SHA256);

	mbedtls_x509write_csr_set_subject_name(&req, common.toStdString().c_str());
	mbedtls_x509write_csr_set_key(&req, &pk);

	//exporting key and cert req

	memset(output, 0, 4096);
	mbedtls_x509write_csr_pem(&req, output, 4096, mbedtls_ctr_drbg_random, &ctr_drbg);
	request = QByteArray(reinterpret_cast<const char *>(output), strlen(reinterpret_cast<const char *>(output)));
	memset(output, 0, 4096);
	mbedtls_pk_write_key_pem(&pk, output, 4096);
	priv = QByteArray(reinterpret_cast<const char *>(output), strlen(reinterpret_cast<const char *>(output)));

	//clean
	mbedtls_pk_free(&pk);
	mbedtls_ctr_drbg_free(&ctr_drbg);
	mbedtls_entropy_free(&entropy);
}

SessionKey::HelperMpi SessionKey::helper;

void SessionKey::setDH(QByteArray dh) {
    std::lock_guard<std::mutex> dhmLock(dhmUse);
    if (mbedtls_dhm_read_public(&dhmc, toUChar(dh), dh.length())) throw KryptoException("setDH: can't read DH");
    other = true;
}

QByteArray SessionKey::getDH() {
    QByteArray ret;

    std::lock_guard<std::mutex> dhmLock(dhmUse);
    ret.resize(dhmc.len);
    if (mbedtls_dhm_make_public(&dhmc, ENCRYPTION_KEY_SIZE, reinterpret_cast<uchar *>(ret.data()), dhmc.len, mbedtls_ctr_drbg_random, &random)) throw KryptoException("getDH: can't generate public dh.");
    my = true;
    return ret;
}

QByteArray SessionKey::conditionalGetDH() {
    QByteArray ret;

    std::lock_guard<std::mutex> dhmLock(dhmUse);
    if (my) return ret;
    ret.resize(dhmc.len);
    if (mbedtls_dhm_make_public(&dhmc, ENCRYPTION_KEY_SIZE, reinterpret_cast<uchar *>(ret.data()), dhmc.len, mbedtls_ctr_drbg_random, &random)) throw KryptoException("getDH: can't generate public dh.");
    my = true;
    return ret;
}

QByteArray SessionKey::protect(const QByteArray & message, const QByteArray & data) {
    mbedtls_gcm_context ctx;
    mbedtls_gcm_init(&ctx);

    {
        std::lock_guard<std::mutex> keyLock(keyUse);
        if (key_enc_uses.fetch_add(1) >= MAX_MESSAGES_WITH_ONE_KEY) throw KryptoOveruseException("Key was already used for max amount of encryptions.");
        mbedtls_gcm_setkey(&ctx, MBEDTLS_CIPHER_ID_AES, toUChar(currentkey), 256);
    }

    unsigned char iv[IV_LENGTH], tag[TAG_LENGTH];
    mbedtls_ctr_drbg_random(&random, iv, IV_LENGTH);

    QByteArray ret(1, keyid);
    ret.resize(1 + IV_LENGTH + TAG_LENGTH + message.length()); // 1 for keyid + IV + tag + message
    ret.replace(1, IV_LENGTH, reinterpret_cast<const char *>(iv), IV_LENGTH);

    mbedtls_gcm_crypt_and_tag(&ctx, MBEDTLS_GCM_ENCRYPT, message.length(), iv, IV_LENGTH, toUChar(data), data.length(), toUChar(message), reinterpret_cast<uchar *>(ret.data() + 1 + IV_LENGTH + TAG_LENGTH), TAG_LENGTH, tag);

    ret.replace(1 + IV_LENGTH, TAG_LENGTH, reinterpret_cast<const char *>(tag), TAG_LENGTH);
    mbedtls_gcm_free(&ctx);
    return ret;
}

QByteArray SessionKey::unprotect(const QByteArray & message, const QByteArray & data) {
    //message = keyId(1)/iv(16)/tag(TAG_LENGTH)/encData

    unsigned char messageKeyId = message[0];
    mbedtls_gcm_context ctx;
    mbedtls_gcm_init(&ctx);

    {
        std::lock_guard<std::mutex> keyLock(keyUse);
        if (messageKeyId == keyid) {
            if (key_dec_uses.fetch_add(1) >= MAX_MESSAGES_WITH_ONE_KEY) throw KryptoOveruseException("Key was already used for 10 decryptions.");
            mbedtls_gcm_setkey(&ctx, MBEDTLS_CIPHER_ID_AES, toUChar(currentkey), 256);
        }
        else if (messageKeyId == keyid - 1) {
            if (key_old_dec_uses.fetch_add(1) >= MAX_MESSAGES_WITH_ONE_KEY) throw KryptoOveruseException("Key was already used for 10 decryptions.");
            mbedtls_gcm_setkey(&ctx, MBEDTLS_CIPHER_ID_AES, toUChar(oldkey), 256);
        }
        else {
            throw KryptoException("key is too old");
        }
    }

    size_t dataLength = message.length() - IV_LENGTH - TAG_LENGTH - 1; // iv + tag + keyId
    unsigned char * output = new unsigned char[dataLength];

    int ret_success;
    if ((ret_success = mbedtls_gcm_auth_decrypt(&ctx, dataLength, toUChar(message) + 1, IV_LENGTH, toUChar(data), data.length(), toUChar(message) + 1 + IV_LENGTH, TAG_LENGTH, toUChar(message) + 1 + IV_LENGTH +TAG_LENGTH, output))) {
		if (ret_success == MBEDTLS_ERR_GCM_AUTH_FAILED)	{
			mbedtls_gcm_free(&ctx);
			throw KryptoException("Authentication of message failed");
		}
		else if (ret_success == MBEDTLS_ERR_GCM_BAD_INPUT) {
			mbedtls_gcm_free(&ctx);
			throw KryptoException("Bad message data for unprotect");
		}
		else {
			mbedtls_gcm_free(&ctx);
			throw KryptoException("Unknown Error");
		}
    }

    QByteArray ret(reinterpret_cast<const char *> (output), dataLength);
    delete[] output;
    mbedtls_gcm_free(&ctx);
    return ret;
}

template <class T>
class ScopedLock {
	T & a;
	T & b;
public:
	ScopedLock(T & a, T & b) : a(a), b(b) {
		std::lock(a, b);
	}
	ScopedLock(const ScopedLock &) = delete;
	ScopedLock(ScopedLock &&) = delete;
	~ScopedLock() {
		a.unlock();
		b.unlock();
	}
};

bool SessionKey::generateKey() {
	ScopedLock<std::mutex> lock(dhmUse, keyUse);
    if (!my || !other) return false;

    oldkey = currentkey;
    ++keyid;

    size_t olen;
    currentkey.resize(ENCRYPTION_KEY_SIZE);
    if (mbedtls_dhm_calc_secret(&dhmc, reinterpret_cast<unsigned char *>(currentkey.data()), ENCRYPTION_KEY_SIZE, &olen, mbedtls_ctr_drbg_random, &random)) throw KryptoException("generateKey: Can't calculate secret.");
    my = other = false;
    key_old_dec_uses = key_dec_uses.exchange(0);
    key_enc_uses = 0;
	keysReady = true;
    return true;
}


text:
<?php

namespace CB\Database\Table;

use CBLib\Database\Table\Table;

defined('CBLIB') or die();

/**
 * CB\Database\Table\ComprofilerTable Class implementation
 *
 */
class ComprofilerTable extends Table
{
	/** @var int */
	public $id						=	null;
	/** @var int */
	public $user_id					=	null;
	/** @var string */
	public $firstname				=	null;
	/** @var string */
	public $middlename				=	null;
	/** @var string */
	public $lastname				=	null;
	/** @var int */
	public $hits					=	null;
	/** @var string (SQL:Date) */
	public $message_last_sent		=	null;
	/** @var int */
	public $message_number_sent		=	null;
	/** @var string */
	public $avatar					=	null;
	/** @var int */
	public $avatarapproved			=	null;
	/** @var int */
	public $approved				=	null;
	/** @var int */
	public $confirmed				=	null;
	/** @var string (SQL:Date) */
	public $lastupdate				=	null;
	/** @var string */
	public $registeripaddr			=	null;
	/** @var string */
	public $cbactivation			=	null;
	/** @var int */
	public $banned					=	null;
	/** @var string (SQL:Date) */
	public $banneddate				=	null;
	/** @var string (SQL:Date) */
	public $unbanneddate			=	null;
	/** @var int */
	public $bannedby				=	null;
	/** @var int */
	public $unbannedby				=	null;
	/** @var string */
	public $bannedreason			=	null;
	/** @var int */
	public $acceptedterms			=	null;

	/**
	 * Table name in database
	 * @var string
	 */
	protected $_tbl				=	'#__comprofiler';

	/**
	 * Primary key(s) of table
	 * @var string
	 */
	protected $_tbl_key			=	'id';

	/**
	 * Inserts a new row in the database table
	 * Only for use by UserTable !
	 *
	 * @return boolean  TRUE if successful otherwise FALSE
	 */
	public function storeNew() {
		$ok					=	$this->_db->insertObject( $this->_tbl, $this, $this->_tbl_key );
		if ( ! $ok ) {
			$this->_error	=	strtolower(get_class($this))."::storeNew failed: " . $this->_db->getErrorMsg();
		}
		return $ok;
	}
}


text:
package nl.tudelft.pl2016gr2.gui.view.selection;

import javafx.beans.property.SimpleObjectProperty;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.control.Separator;
import javafx.scene.image.ImageView;
import javafx.scene.layout.AnchorPane;
import javafx.scene.text.Text;

import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Right now this class mainly just shows the selection(s).
 *
 *

 * It has some code ready for doing a comparison, but consider this more of a
 * proof of concept. There has to be an easy way for the user to compare the two
 * selections he has made.
 *

 *
 */
public class SelectionPaneController implements Initializable {

  @FXML
  private AnchorPane mainAnchor;
  @FXML
  private AnchorPane primarySelectionPane;
  @FXML
  private Separator separaror;
  @FXML
  private AnchorPane secondarySelectionPane;
  @FXML
  private ImageView copyButton;

  private SimpleObjectProperty<ISelectable> primarySelection;
  private SimpleObjectProperty<ISelectable> secondarySelection;

  /**
   * Method wrapper for an exception.
   *
   *

   * This method calls {@link ISelectionInfo#getNode()} on the given {@link ISelectionInfo}
   * and catches its {@link IOException}. In the latter case it will return a simple
   * {@link Text} with an error.
   *

   *
   * @param info the given {@link ISelectionInfo}
   * @return a {@link Node} that can be displayed
   */
  private Node safeGetDescription(ISelectionInfo info) {
    try {
      return info.getNode();
    } catch (IOException e) {
      Logger.getLogger(SelectionPaneController.class.getName()).log(Level.SEVERE, null, e);
      return new Text("Something went wrong when loading a file.");
    }
  }

  @Override
  public void initialize(URL url, ResourceBundle resourceBundle) {
    this.primarySelection = new SimpleObjectProperty<>();
    this.secondarySelection = new SimpleObjectProperty<>();
    initializeSeparatorAnchor();

    primarySelectionPane.prefWidthProperty().bind(mainAnchor.widthProperty(
    ).add(separaror.widthProperty().negate()).divide(2.0));
    secondarySelectionPane.prefWidthProperty().bind(mainAnchor.widthProperty()
        .add(separaror.widthProperty().negate()).divide(2.0));
    copyButton.translateXProperty().bind(
        mainAnchor.widthProperty().divide(2.0).add(copyButton.fitWidthProperty().negate()));

    primarySelection.addListener((observable, oldValue, newValue) -> {
      expandInAnchorPane(safeGetDescription(newValue.getSelectionInfo()), primarySelectionPane);
    });
    secondarySelection.addListener((observable, oldValue, newValue) -> {
      expandInAnchorPane(safeGetDescription(newValue.getSelectionInfo()), secondarySelectionPane);
    });

    primarySelection.set(SelectionManager.NO_SELECTION);
    secondarySelection.set(SelectionManager.NO_SELECTION);
  }

  /**
   * Initialize the anchor of the separator so it will always be in the middle of the screen.
   */
  private void initializeSeparatorAnchor() {
    mainAnchor.widthProperty().addListener((obs, old, newValue) -> {
      AnchorPane.setLeftAnchor(separaror, (newValue.doubleValue() - separaror.getWidth()) / 2.0);
    });
  }

  /**
   * Sets up this controller.
   *
   * @param selectionManager a selection manager is needed.
   */
  public void setup(SelectionManager selectionManager) {
    selectionManager.addListener((observable, oldValue, newValue) -> {
      primarySelection.set(newValue);
    });

    copyButton.setOnMouseClicked(event -> {
      secondarySelection.set(primarySelection.getValue());
    });
  }

  /**
   * Sets all anchors to 0 and adds.
   */
  private void expandInAnchorPane(Node content, AnchorPane anchorPane) {
    anchorPane.getChildren().clear();
    if (content != null) {
      AnchorPane.setTopAnchor(content, 0.0d);
      AnchorPane.setBottomAnchor(content, 0.0d);
      AnchorPane.setLeftAnchor(content, 0.0d);
      AnchorPane.setRightAnchor(content, 0.0d);
      anchorPane.getChildren().add(content);
    }
  }
}


text: service $1 status


text:
import { Controller } from 'aurelia-templating';
import { Renderer } from './renderer';
import { NotificationCancelableOperationResult, NotificationCloseResult, NotificationCancelResult } from './notification-result';
import { NotificationSettings } from './notification-settings';
import { NotificationCloseError } from './notification-close-error';
/**
 * A controller object for a notification instance.
 */
export declare class NotificationController {
    private resolve;
    private reject;
    /**
     * @internal
     */
    closePromise: Promise<any> | undefined;
    /**
     * The settings used by this controller.
     */
    settings: NotificationSettings;
    renderer: Renderer;
    controller: Controller;
    /**
     * @internal
     */
    static inject: (typeof Renderer)[];
    /**
     * Creates an instance of NotificationController.
     */
    constructor(renderer: Renderer, settings: NotificationSettings, resolve: (data?: any) => void, reject: (reason: any) => void);
    /**
     * @internal
     */
    releaseResources(result: NotificationCloseResult | NotificationCloseError): Promise<void>;
    /**
     * @internal
     */
    cancelOperation(): NotificationCancelResult;
    /**
     * Closes the notification with a successful output.
     * @param output The returned success output.
     */
    ok(output?: any): Promise<NotificationCancelableOperationResult>;
    /**
     * Closes the notification with a cancel output.
     * @param output The returned cancel output.
     */
    cancel(output?: any): Promise<NotificationCancelableOperationResult>;
    /**
     * Closes the notification with an error output.
     * @param output A reason for closing with an error.
     * @returns Promise An empty promise object.
     */
    error(output: any): Promise<void>;
    /**
     * Closes the notification.
     * @param ok Whether or not the user input signified success.
     * @param output The specified output.
     * @returns Promise An empty promise object.
     */
    close(ok: boolean, output?: any): Promise<NotificationCancelableOperationResult>;
}


text:
{-# LANGUAGE FlexibleContexts #-}
{-|
Module:      Y2021.D06
Description: Advent of Code 2021 Day 06 Solutions.
License:     MIT
Maintainer:  @tylerjl

Solutions to the 2021 day 06 set of problems for <adventofcode.com>.
-}
module Y2021.D06 where

import Data.Either.Utils (fromRight)
import Data.Text (Text)
import qualified Data.Text as T
import Text.Parsec hiding (Empty)
import Y2015.Util (regularParse', intParser')

import qualified Data.IntMap.Strict as M
import qualified Data.Vector.Unboxed.Mutable as V
import Control.Monad (forM_, replicateM_)
import Control.Monad.ST (runST)
import qualified Data.Sequence as Seq
import Data.Sequence (Seq(..))
import Data.List (elemIndices)
import Witch
import qualified Data.Attoparsec.Text as AP

-- |Solve part A
part6A :: Text -> Int
part6A = solve6 80 . parseFish

-- |Solve part A, with unboxed mutable vectors
part6AMV :: Text -> Int
part6AMV = solve6MV 80 . parseFish

-- |Solve part A, with sequences
part6ASeq :: Text -> Int
part6ASeq = solve6Seq 80 . Seq.fromFunction 9 . build . parseFish
  where build fish n = length $ elemIndices n fish

-- |Solve part B
part6B :: Text -> Int
part6B = solve6 256 . parseFish

-- |Solve part B, with unboxed mutable vectors
part6BMV :: Text -> Int
part6BMV = solve6MV 256 . parseFish

-- |Solve part B, with sequences
part6BSeq :: Text -> Int
part6BSeq = solve6Seq 256 . Seq.fromFunction 9 . build . parseFish
  where build fish n = length $ elemIndices n fish

solve6Seq :: Int -> Seq Int -> Int
solve6Seq n fish = Seq.foldlWithIndex sum' 0 $ iterate solve6Seq' fish !! n
  where sum' acc _ el = acc + el

solve6Seq' :: Seq Int -> Seq Int
solve6Seq' (a:<|b:<|c:<|d:<|e:<|f:<|g:<|h:<|i:<|Empty)=
  b:<|c:<|d:<|e:<|f:<|g:<|h+a:<|i:<|a:<|Empty
solve6Seq' _ = error "unexpected fish sequence size"

-- |Solution algorithm using super aggressive mutable unboxed vectors.
solve6MV :: Int -> [Int] -> Int
solve6MV days fish = runST $ do
  vec <- V.replicate 9 0
  forM_ fish $ \fish' -> do
    V.modify vec (+ 1) fish'
  replicateM_ days $ do
    newFish <- V.read vec 0
    V.move (V.slice 0 8 vec) (V.slice 1 8 vec)
    V.write vec 8 newFish
    V.modify vec (+ newFish) 6
  V.foldl' (+) 0 vec

-- |Iterate for a given number of days given a starting value and return the
-- total.
solve6 :: Int -> [Int] -> Int
solve6 n
  = M.foldl' (+) 0
  . flip (!!) n
  . iterate breed
  . M.fromListWith (+)
  . flip zip (repeat 1)

-- |Simulate one day passing for the collection of fish.
breed :: Num a => M.IntMap a -> M.IntMap a
breed fish =
  M.insert 8 newFish $
  M.mapKeysWith (+) step fish
  where
    step (pred -> age) | age < 0   = 6
                       | otherwise = age
    newFish = M.findWithDefault 0 0 fish

-- |Parse puzzle input into a list of `Int`s.
parseFish :: Text -> [Int]
parseFish = fromRight . regularParse' fishParser
  where fishParser = intParser' `sepBy1` char ',' <* newline <* eof

-- |Parse puzzle input into a list of `Int`s but do so with a dumb parser.
parseFish' :: Text -> [Int]
parseFish' = map (read . into @String) . T.splitOn ","

-- |Parse puzzle input into a list of `Int`s but do so with a dumb parser.
parseFish'' :: Text -> [Int]
parseFish'' = fromRight . AP.parseOnly parser
  where parser = AP.decimal `AP.sepBy` AP.char ',' <* AP.endOfLine


text:
/**
 * Provides Form and input features.
 *
 * @module furnace
 * @submodule furnace-forms
 */
import Ember from 'ember';
import Control from './input';
import ControlSupport from 'furnace-forms/mixins/controls/control-support';
import getControl from 'furnace-forms/utils/get-control';

/**
 * Input control component proxy
 *
 * @class Input
 * @namespace Furnace.Forms.Controls
 * @extends Furnace.Forms.Controls.Abstract
 * @protected
 */
export default Control.extend(ControlSupport,{
	_isList : true,

	_decoratorName : 'list',

	_itemControls : null,

	sortProperties: null,

	_currentSortProperties: null,

	sortAscending: true,

	isSorted: Ember.computed.notEmpty('sortProperties'),

//	orderBy:Ember.Enumerable.mixins[0].properties.sortBy,
//	sortFunction:Ember.SortableMixin.mixins[1].properties.sortFunction,

	init : function() {
		this.set('_itemControls',Ember.A());
		this._super();
		if(this.filterBy) {
			this.addObserver('value.[].'+this.filterBy.key,this,function(){
				Ember.run.scheduleOnce('actions',this,this._loadItemControls);
			});
		}
		this._loadItemControls();
	},

	itemControls : Ember.computed({
		get  : function() {
			if(!this._itemControls) {
				return Ember.A();
			}
			var content = this._itemControls;
			var isSorted = this.get('isSorted');
			if (content && isSorted) {
				return content.sortBy.apply(content,this.sortProperties);
			}

			return content;
		}
	}).readOnly(),

	_sortObserver: Ember.observer('sortProperties',function() {
		if(this._currentSortProperties) {
			this._currentSortProperties.forEach(function(prop) {
				this.removeObserver('value.@each.'+prop,this,this._notifySortChanged);
			},this);
		}
		this._currentSortProperties=this.get('sortProperties');
		if(this._currentSortProperties) {
			this._currentSortProperties.forEach(function(prop) {
				this.addObserver('value.@each.'+prop,this,this._notifySortChanged);
			},this);
		}
	}),

	_sortInit: Ember.on('init',function() {
		this._sortObserver();
	}),

	_notifySortChanged() {
		Ember.run.scheduleOnce('actions',this,this.notifyPropertyChange,'itemControls');
	},

	_loadItemControls : function() {
		var control=this;
		var value=this.get('value');

		var itemControls=this._itemControls;
		var oldControls=itemControls.toArray();

		Ember.assert('List control '+this+' doest not have its itemControl property set. Did you forget to call .item() in your form?',this._itemControlMeta || this._itemControlFn);
		if(this.isDestroying) {
			return;
		}
		if(Ember.Enumerable.detect(value)) {
			var values;
			var _value=value;
			if(this.filter) {
				values=value.filter(this.filter);
			} else if(this.filterBy) {
				values=value.filterBy(this.filterBy.key,this.filterBy.value);
			} else {
				values=value;
			}

			values=values.toArray();
			// Reuse controls with existing values;
			values.toArray().forEach(function(value) {
				var oldControl=oldControls ? oldControls.findBy('for',value) : undefined;
				if(oldControl) {
					oldControls.removeObject(oldControl);
					values.removeObject(value);
				}
			});
			// Reuse existing controls or create new control
			values.toArray().forEach(function(value) {
				var index=_value.indexOf(value);
				var meta = control._itemControlMeta || control._itemControlFn.call(this,value);
				if(meta instanceof Ember.ComputedProperty) {
					Ember.deprecate('furnace-forms: list item control can no longer be a computed property, please only return meta',undefined,{id:'furnace-forms:computed-item-control',until:'3.0.0'});
					meta=meta._meta;
				}
				if(oldControls.length) {
					let _control=oldControls.shiftObject();
					_control.set('for',value);
				} else {
					itemControls.pushObject(getControl.call(control,index,meta,{'for' : value}));
				}
			})
		}
		if(oldControls) {
			oldControls.forEach(function(oldControl) {
				itemControls.removeObject(oldControl);
				oldControl.destroy();
			});
		}
		Ember.run.scheduleOnce('actions',this,this.notifyPropertyChange,'itemControls');
	},

	_valueObserver:function() {
		this._cleanControls();
		this._super(...arguments);
		Ember.run.scheduleOnce('actions',this,this._loadItemControls);
	},

	_reset: function(modelChanged) {
// Both valueObserver and reset would trigger clean controls
// We don't want that, but if I recall correctly there was a reason to clean controls in reset
		if(modelChanged) {
			this._cleanControls();
		}
		this._super(modelChanged);
	},

	_cleanControls : function() {
		// Immediately remove controls that are no longer backed by a value:
		// Our child controls won't like it when their property gets yanked
		var toRemove=Ember.A();
		var property=this.get('property');
		if(!property) {
			toRemove=this._itemControls.toArray();
		} else if(property instanceof Ember.RSVP.Promise || Ember.PromiseProxyMixin.detect(property)) {
			//toRemove=this._itemControls.toArray();
		} else {
			// Simply removing controls based on their content has severy decremental effects on performance
			// Remove controls based on their length
			if(this._itemControls.length>property.length) {
				toRemove=this._itemControls.slice(property.length,this._itemControls.length);
			}
		}
		if(toRemove.length) {
			toRemove.invoke('destroy');
			this._itemControls.removeObjects(toRemove);
			Ember.run.scheduleOnce('actions',this,this.notifyPropertyChange,'itemControls');
		}
	},

	controls: Ember.computed.union('_controls','_itemControls').readOnly(),

	// We alias the for property for panels and forms
	'_model' : Ember.computed.alias('value'),

// These terrible workaround seem no long necessary.
//	_controlDirtyObserver: Ember.observer('_controls.@each.isDirty,_itemControls.@each.isDirty',function(){
//		this._super();
//	}),

//	_controlValidObserver: Ember.observer('_controls.@each.isValid,_itemControls.@each.isValid',function(){
//		this._super();
//	}),

	willDestroy : function() {
		var controls=this._itemControls;
		if(controls && controls.length) {
			controls.invoke('willDestroy');
		}
		this._super();
	},

	destroy : function() {
		var controls=this._itemControls;
		if(controls && controls.length) {
			controls.invoke('destroy');
		}
		this._super();
	},

}).reopenClass({
	filter : function(callback) {
		this.reopen({
			filter:callback
		});
		return this;
	},
	filterBy: function(key,value) {
		this.reopen({
			filterBy:{key:key,value:value}
		});
		return this;
	},

	generate : function(mixins,meta) {
		mixins=mixins || [];
		mixins.push(meta.options);
		var typeKey=this.typeKey;
		var control = this.extend.apply(this,mixins);
		control.typeKey=typeKey;
		return control;
	}
});


text:
require './test/helper'

class StringioFileProxyTest < Test::Unit::TestCase
  context "a new instance" do
    setup do
      @contents = "abc123"
      @stringio = StringIO.new(@contents)
      @subject = Paperclip.io_adapters.for(@stringio)
    end

    should "return a file name" do
      assert_equal "stringio.txt", @subject.original_filename
    end

    should "return a content type" do
      assert_equal "text/plain", @subject.content_type
    end

    should "return the size of the data" do
      assert_equal 6, @subject.size
    end

    should "generate an MD5 hash of the contents" do
      assert_equal Digest::MD5.hexdigest(@contents), @subject.fingerprint
    end

    should "generate correct fingerprint after read" do
      fingerprint = Digest::MD5.hexdigest(@subject.read)
      assert_equal fingerprint, @subject.fingerprint
    end

    should "generate same fingerprint" do
      assert_equal @subject.fingerprint, @subject.fingerprint
    end

    should "return the data contained in the StringIO" do
      assert_equal "abc123", @subject.read
    end

    should 'accept a content_type' do
      @subject.content_type = 'image/png'
      assert_equal 'image/png', @subject.content_type
    end

    should 'accept an original_filename' do
      @subject.original_filename = 'image.png'
      assert_equal 'image.png', @subject.original_filename
    end

    should "not generate filenames that include restricted characters" do
      @subject.original_filename = 'image:restricted.png'
      assert_equal 'image_restricted.png', @subject.original_filename
    end

    should "not generate paths that include restricted characters" do
      @subject.original_filename = 'image:restricted.png'
      assert_no_match /:/, @subject.path
    end

  end
end


text:
<?php

namespace yii\debug;

use Yii;
use yii\base\Widget;
use yii\helpers\Html;

/**
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
class Toolbar extends Widget
{
	public $debugAction = 'debug';
	public $enabled = YII_DEBUG;

	public function run()
	{
		if ($this->enabled) {
			$id = 'yii-debug-toolbar';
			$url = Yii::$app->getUrlManager()->createUrl($this->debugAction, array(
				'tag' => Yii::getLogger()->tag,
			));
			$this->view->registerJs("yii.debug.load('$id', '$url');");
			$this->view->registerAssetBundle('yii/debug');
			echo Html::tag('div', '', array(
				'id' => $id,
				'style' => 'display: none',
			));
		}
	}
}