text:
package org.unitedinternet.cosmo.model.mock;

import net.fortuna.ical4j.model.Calendar;

import org.unitedinternet.cosmo.model.AvailabilityItem;
import org.unitedinternet.cosmo.model.ICalendarItem;
import org.unitedinternet.cosmo.model.Item;

/**
 * Extends {@link ICalendarItem} to represent a VAVAILABILITY item.
 */
public class MockAvailabilityItem extends MockICalendarItem implements AvailabilityItem {

    /**
     * Constructor.
     */
    public MockAvailabilityItem() {
    }

    /**
     * Copy.
     * {@inheritDoc}
     * @return item.
     */
    @Override
    public Item copy() {
        AvailabilityItem copy = new MockAvailabilityItem();
        copyToItem(copy);
        return copy;
    }

    /* (non-Javadoc)
     * @see org.unitedinternet.cosmo.model.copy.InterfaceAvailabilityItem#getAvailabilityCalendar()
     */
    /**
     * Gets availability calendar.
     * @return Calendar.
     */
    public Calendar getAvailabilityCalendar() {
        return getCalendar();
    }

    /* (non-Javadoc)
     * @see org.unitedinternet.cosmo.model.copy.InterfaceAvailabilityItem#setAvailabilityCalendar(net.fortuna.ical4j.model.Calendar)
     */
    /**
     * Sets availability calendar.
     * @param calendar The calendar.
     */
    public void setAvailabilityCalendar(Calendar calendar) {
        setCalendar(calendar);
    }

}

redpajama_set_name: RedPajamaGithub


text:
extern crate derive_builder;

#[derive(Clone, Debug)]
struct Resolution {
    width: u32,
    height: u32,
}

impl Default for Resolution {
    fn default() -> Resolution {
        Resolution {
            width: 1920,
            height: 1080,
        }
    }
}

#[derive(Debug, Default, Builder)]
#[builder(field(private), setter(into))]
struct GameConfig {
    #[builder(default)]
    resolution: Resolution,
    save_dir: Option<String>,
    #[builder(default)]
    autosave: bool,
    fov: f32,
    render_distance: u32,
}

fn main() {
    println!("24 Days of Rust vol. 2 - derive_builder");
    let conf = GameConfigBuilder::default()
        .save_dir("saves".to_string())
        .fov(70.0)
        .render_distance(1000u32)
        .build()
        .unwrap();
    println!("{:?}", conf);
}


text:
curl \
    http://geneontology.org/ontology/go.owl \
    -o go.owl


text:
  Hargarten-aux-Mines est
      une ville localisée dans le département de Moselle en Lorraine. Elle totalisait 1 133 habitants en 2008.

À coté de Hargarten-aux-Mines sont localisées les villes de
Guerting à 3 km, 858 habitants,
Téterchen à 3 km, 613 habitants,
Falck située à 2 km, 2 596 habitants,
Tromborn située à 4 km, 326 habitants,
Coume située à 3 km, 640 habitants,
Ham-sous-Varsberg située à 5 km, 2 732 habitants,
 entre autres. De plus, Hargarten-aux-Mines est située à seulement 21 km de Forbach.

La ville compte quelques  équipements sportifs, elle dispose, entre autres, de un terrain de sport.

À Hargarten-aux-Mines, la valeur moyenne à l'achat d'un appartement se situe à zero € du m² en vente. La valeur moyenne d'une maison à l'achat se situe à 1 274 € du m². À la location la valeur moyenne se situe à 0 € du m² mensuel.

Le nombre de logements, à Hargarten-aux-Mines, était réparti en 2011 en 57 appartements et 443 maisons soit
 un marché relativement équilibré.


text:
"""Google Cloud Game Servers sample for deleting a game server cluster.

Example usage:
    python delete_cluster.py --project-id <project-id> --location --realm-id <realm-id> --cluster-id <cluster-id>
"""

import argparse

from google.cloud import gaming
from google.cloud.gaming_v1.types import game_server_clusters

# [START cloud_game_servers_cluster_delete]
def delete_cluster(project_id, location, realm_id, cluster_id):
    """Deletes a game server cluster."""

    client = gaming.GameServerClustersServiceClient()

    request = game_server_clusters.DeleteGameServerClusterRequest(
        name=f"projects/{project_id}/locations/{location}/realms/{realm_id}/gameServerClusters/{cluster_id}",
    )

    operation = client.delete_game_server_cluster(request)
    print(f"Delete cluster operation: {operation.operation.name}")
    operation.result(timeout=120)

# [END cloud_game_servers_cluster_delete]

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--project-id", help="Your cloud project ID.", required=True)
    parser.add_argument("--location", help="Your realm location.", required=True)
    parser.add_argument("--realm-id", help="Your realm ID.", required=True)
    parser.add_argument(
        "--cluster-id", help="Your game server cluster ID.", required=True
    )

    args = parser.parse_args()

    delete_cluster(args.project_id, args.location, args.realm_id, args.cluster_id)


text:
var EQ = require('../src/ElementQueries');
var ResizeSensor = require('../src/ResizeSensor');

EQ.listen();

var ResizerDemo = new Class({
    y: null,
    initialize: function(container) {
        this.container = container;
        this.setupLayout();
    },

    setupLayout: function(){
        this.handler = new Element('div', {
            'class': 'resizerDemo-handler'
        }).inject(this.container);

        this.container.makeResizable({
            snap: 0,
            handle: this.handler,
            modifiers: {
                'x': 'width',
                'y': this.y
            }
        });
    }
});

var ResizeDemoXY = new Class({
    Extends: ResizerDemo,
    y: 'height'
});

window.addEvent('domready', function(){
    $$('.examplesResizerDemos').each(function(resizer){
        new ResizerDemo(resizer);
    });
    $$('.examplesResizerDemosXY').each(function(resizer){
        new ResizeDemoXY(resizer);
    });

    perfTest();
    example3();
    example4();
    example5();
});

function perfTest(){
    var container = $('dynamicContainer');
    var dynamicCount = $('dynamicCount');
    var dynamicCounter = $('dynamicCounter');

    window.detachDynamic = function() {
        container.getChildren().each(function(element) {
            ResizeSensor.detach(element);
        });
    };

    window.removeDynamic = function() {
        container.empty();
    };

    window.addDynamic = function() {
        container.empty();
        var i = 0, to = dynamicCount.value, div, counter = 0;
        for (; i < to; i++) {
            div = new Element('div', {
                'class': 'dynamicElement',
                text: '#' + i
            }).inject(container);

            new ResizeSensor(div, function(){
                counter++;
                dynamicCounter.set('text', counter + ' changes.');
            });
        }
    }
}

function example3(){

    var logger = document.id('example-3-log');
    var box = document.id('example-3-box');
    document.id('startStop3').addEvent('click', function(){
        if (box.hasClass('example-3-box-start')) {
            box.removeClass('example-3-box-start');
        } else {
            box.addClass('example-3-box-start');
        }
    });
    new ResizeSensor(box, function(el){
        logger.set('html', 'Changed to ' + box.getSize().x+'px width.');
    });

}

function example4(){
    var logger = document.id('example-4-log');
    var box = document.id('example-4-box');
    document.id('startStop4').addEvent('click', function(){
        if (box.hasClass('example-4-box-start')) {
            box.removeClass('example-4-box-start');
        } else {
            box.addClass('example-4-box-start');
        }
    });
    new ResizeSensor(box, function(){
        logger.set('html', 'Changed to ' + box.getSize().y+'px height.');
    });
}

function example5(){
    var box = document.id('example-5');
    var changed = 0;
    new ResizeSensor(box.getParent(), function(){
        box.innerHTML = (++changed) + ' changes. ' + box.getParent().getSize().x+'px/'+box.getParent().getSize().y+'px';
    });
}


text:
<!DOCTYPE HTML>

<title>EventFilterHandler (Service Base 1.6.2 API)</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="dc.created" content="2020-06-15">
<meta name="description" content="declaration: package: com.brettonw.bedrock.service, interface: EventFilterHandler">
<meta name="generator" content="javadoc/ClassWriterImpl">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
<link rel="stylesheet" type="text/css" href="../../../../script-dir/jquery-ui.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Package

Class

Use

Tree

Deprecated

Index

Help

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

SEARCH:
<input type="text" id="search" value="search" disabled="disabled">
<input type="reset" id="reset" value="reset" disabled="disabled">

Package com.brettonw.bedrock.service

Interface EventFilterHandler

All Known Implementing Classes:

EventFilter

public interface EventFilterHandler

Method Summary

<button role="tab" aria-selected="true" aria-controls="memberSummary_tabpanel" tabindex="0" onkeydown="switchTab(event)" id="t0" class="activeTableTab">All Methods</button><button role="tab" aria-selected="false" aria-controls="memberSummary_tabpanel" tabindex="-1" onkeydown="switchTab(event)" id="t2" class="tableTab" onclick="show(2);">Instance Methods</button><button role="tab" aria-selected="false" aria-controls="memberSummary_tabpanel" tabindex="-1" onkeydown="switchTab(event)" id="t3" class="tableTab" onclick="show(4);">Abstract Methods</button>

Modifier and Type
Method
Description

boolean
isAllowedEvent(Event event,
BagObject filterConfiguration)

Method Details

isAllowedEvent

boolean isAllowedEvent(Event event,
BagObject filterConfiguration)

Skip navigation links

Package

Class

Use

Tree

Deprecated

Index

Help

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Copyright © 2020. All rights reserved.


text:
import {
  StylebotOptions,
  StylebotCommands,
  ReadabilitySettings,
  StylebotEditorCommands,
} from '@stylebot/types';

export const defaultOptions: StylebotOptions = {
  mode: 'basic',
  contextMenu: true,
  fonts: [
    'Helvetica',
    'Montserrat',
    'Droid Sans',
    'Droid Serif',
    'Merriweather',
    'Playfair Display',
    'Fira Code',
    'Inconsolata',
  ],
  basicModeSections: {
    text: true,
    colors: true,
    layout: true,
    border: false,
  },
  layout: {
    width: 350,
    adjustPageLayout: false,
    dockLocation: 'right',
  },
  colorPalette: 'basic',
};

export const defaultCommands: StylebotCommands = {
  style: 'alt+shift+t',
  stylebot: 'alt+shift+m',
  grayscale: '',
  readability: '',
};

export const defaultEditorCommands: StylebotEditorCommands = {
  inspect: 'i',
  basic: 'b',
  magic: 'm',
  code: 'c',
  help: '?',
  hide: 'h',
  resize: 's',
  dockLeft: 'l',
  dockRight: 'r',
  pageLayout: 'p',
  close: 'Escape',
};

export const defaultReadabilitySettings: ReadabilitySettings = {
  size: 16,
  width: 36,
  theme: 'light',
  lineHeight: 1.6,
  font: 'Helvetica',
};


text:
t
=======

`t` is a command-line todo list manager for people that want to *finish* tasks,
not organize them.

Why t?
------

Yeah, I know, *another* command-line todo list manager.  Several others already
exist ([todo.txt][] and [TaskWarrior][] come to mind), so why make another one?

[todo.txt]: http://ginatrapani.github.com/todo.txt-cli/
[TaskWarrior]: http://taskwarrior.org/projects/show/taskwarrior/

### It Does the Simplest Thing That Could Possibly Work

Todo.txt and TaskWarrior are feature-packed.  They let you tag tasks, split
them into projects, set priorities, order them, color-code them, and much more.

**That's the problem.**

It's easy to say "I'll just organize my todo list a bit" and spend 15 minutes
tagging your tasks.  In those 15 minutes you probably could have *finished*
a couple of them.

`t` was inspired by [j][].  It's simple, messy, has almost no features, and is
extremely effective at the one thing it does.  With `t` the only way to make
your todo list prettier is to **finish some damn tasks**.

[j]: http://github.com/rupa/j2/

### It's Flexible

`t`'s simplicity makes it extremely flexible.

Want to edit a bunch of tasks at once?  Open the list in a text editor.

Want to view the lists on a computer that doesn't have `t` installed?  Open the
list in a text editor.

Want to synchronize the list across a couple of computers?  Keep your task
lists in a [Dropbox][] folder.

Want to use it as a distributed bug tracking system like [BugsEverywhere][]?
Make the task list a `bugs` file in the project repository.

[Dropbox]: https://www.getdropbox.com/
[BugsEverywhere]: http://bugseverywhere.org/

### It Plays Nice with Version Control

Other systems keep your tasks in a plain text file.  This is a good thing, and
`t` follows their lead.

However, some of them append new tasks to the end of the file when you create
them.  This is not good if you're using a version control system to let more
than one person edit a todo list.  If two people add a task and then try to
merge, they'll get a conflict and have to resolve it manually.

`t` uses random IDs (actually SHA1 hashes) to order the todo list files.  Once
the list has a couple of tasks in it, adding more is far less likely to cause
a merge conflict because the list is sorted.

Installing t
------------

`t` requires [Python][] 2.5 or newer, and some form of UNIX-like shell (bash
works well).  It works on Linux, OS X, and Windows (with [Cygwin][]).

[Python]: http://python.org/
[Cygwin]: http://www.cygwin.com/

Installing and setting up `t` will take about one minute.

First, [download][] the newest version or clone the Mercurial repository
(`hg clone http://bitbucket.org/sjl/t/`).  Put it anywhere you like.

[download]: http://bitbucket.org/sjl/t/get/tip.zip

Next, decide where you want to keep your todo lists.  I put mine in `~/tasks`.
Create that directory:

    mkdir ~/tasks

Finally, set up an alias to run `t`.  Put something like this in your
`~/.bashrc` file:

    alias t='python ~/path/to/t.py --task-dir ~/tasks --list tasks'

Make sure you run `source ~/.bashrc` or restart your terminal window to make
the alias take effect.

Using t
-------

`t` is quick and easy to use.

### Add a Task

To add a task, use `t [task description]`:

    $ t Clean the apartment.
    $ t Write chapter 10 of the novel.
    $ t Buy more beer.
    $

### List Your Tasks

Listing your tasks is even easier -- just use `t`:

    $ t
    9  - Buy more beer.
    30 - Clean the apartment.
    31 - Write chapter 10 of the novel.
    $

`t` will list all of your unfinished tasks and their IDs.

### Finish a Task

After you're done with something, use `t -f ID` to finish it:

    $ t -f 31
    $ t
    9  - Buy more beer.
    30 - Clean the apartment.
    $

### Edit a Task

Sometimes you might want to change the wording of a task.  You can use
`t -e ID [new description]` to do that:

    $ t -e 30 Clean the entire apartment.
    $ t
    9  - Buy more beer.
    30 - Clean the entire apartment.
    $

Yes, nerds, you can use sed-style substitution strings:

    $ t -e 9 /more/a lot more/
    $ t
    9  - Buy a lot more beer.
    30 - Clean the entire apartment.
    $

### Delete the Task List if it's Empty

If you keep your task list in a visible place (like your desktop) you might
want it to be deleted if there are no tasks in it.  To do this automatically
you can use the `--delete-if-empty` option in your alias:

    alias t='python ~/path/to/t.py --task-dir ~/Desktop --list todo.txt --delete-if-empty'

Tips and Tricks
---------------

`t` might be simple, but it can do a lot of interesting things.

### Count Your Tasks

Counting your tasks is simple using the `wc` program:

    $ t | wc -l
          2
    $

### Put Your Task Count in Your Bash Prompt

Want a count of your tasks right in your prompt?  Edit your `~/.bashrc` file:

    export PS1="[$(t | wc -l | sed -e's/ *//')] $PS1"

Now you've got a prompt that looks something like this:

    [2] $ t -f 30
    [1] $ t Feed the cat.
    [2] $

### Multiple Lists

`t` is for people that want to *do* tasks, not organize them.  With that said,
sometimes it's useful to be able to have at least *one* level of organization.
To split up your tasks into different lists you can add a few more aliases:

    alias g='python ~/path/to/t.py --task-dir ~/tasks --list groceries'
    alias m='python ~/path/to/t.py --task-dir ~/tasks --list music-to-buy'
    alias w='python ~/path/to/t.py --task-dir ~/tasks --list wines-to-try'

### Distributed Bugtracking

Like the idea of distributed bug trackers like [BugsEverywhere][], but don't
want to use such a heavyweight system?  You can use `t` instead.

Add another alias to your `~/.bashrc` file:

    alias b='python ~/path/to/t.py --task-dir . --list bugs'

Now when you're in your project directory you can use `b` to manage the list of
bugs/tasks for that project.  Add the `bugs` file to version control and you're
all set.

Even people without `t` installed can view the bug list, because it's plain text.

Problems, Contributions, Etc
----------------------------

`t` was hacked together in a couple of nights to fit my needs.  If you use it
and find a bug, please let me know.

If you want to request a feature feel free, but remember that `t` is meant to
be simple.  If you need anything beyond the basics you might want to look at
[todo.txt][] or [TaskWarrior][] instead.  They're great tools with lots of
bells and whistles.

If you want to contribute code to `t`, that's great!  Fork the
[Mercurial repository][] on BitBucket or the [git mirror][] on GitHub and send me
a pull request.

[Mercurial repository]: http://bitbucket.org/sjl/t/
[git mirror]: http://github.com/sjl/t/


text:
import * as angular from 'angular';

import ApplicationService from '../../../../services/applications.service';
import NotificationService from '../../../../services/notification.service';
import RoleService from '../../../../services/role.service';

class ApplicationMembersController {
  private application: any;
  private members: any;
  private roles: any;

  constructor(
    private ApplicationService: ApplicationService,
    private NotificationService: NotificationService,
    private $mdDialog: angular.material.IDialogService,
    private $state: ng.ui.IStateService,
    private RoleService: RoleService
  ) {
    'ngInject';

    const that = this;
    RoleService.list('APPLICATION').then(function (roles) {
      that.roles = roles;
    });
  }

  updateMember(member) {
    if (member.role) {
      this.ApplicationService.addOrUpdateMember(this.application.id, member).then(() => {
        this.NotificationService.show(`Member ${member.username} has been updated with role ${member.role}`);
      });
    }
  }

  deleteMember(member) {
    let index = this.members.indexOf(member);
    this.ApplicationService.deleteMember(this.application.id, member.username).then(() => {
      this.members.splice(index, 1);
      this.NotificationService.show(`${member.username} has been removed`);
    });
  }

  showDeleteMemberConfirm(ev, member) {
    ev.stopPropagation();
    let that = this;
    this.$mdDialog.show({
      controller: 'DialogConfirmController',
      controllerAs: 'ctrl',
      template: require('../../../../components/dialog/confirm.dialog.html'),
      clickOutsideToClose: true,
      locals: {
        title: 'Would you like to remove the member ?',
        msg: '',
        confirmButton: 'Remove'
      }
    }).then(function (response) {
      if (response) {
        that.deleteMember(member);
      }
    });
  }

  showAddMemberModal(ev) {
    let that = this;
    this.$mdDialog.show({
      controller: 'DialogAddMemberController',
      template: require('./addMember.dialog.html'),
      parent: angular.element(document.body),
      targetEvent: ev,
      clickOutsideToClose: true,
      locals: {
        application: that.application,
        applicationMembers: that.members
      }
    }).then(function (application) {
      if (application) {
        that.$state.go('management.applications.portal.members', {applicationId: that.application.id}, {reload: true});
      }
    }, function() {
       // You cancelled the dialog
    });
  }

  showPermissionsInformation() {
    this.$mdDialog.show({
      controller: 'DialogApplicationPermissionsHelpController',
      controllerAs: 'ctrl',
      template: require('./permissions.dialog.html'),
      parent: angular.element(document.body),
      clickOutsideToClose:true
    });
  }
}

export default ApplicationMembersController;


text:
package net.goldolphin.cate;

/**
 * @author goldolphin
 *         2014-09-07 00:33
 */
public class Func0Task<TResult> extends Task<Unit, TResult> {
    private final Func0<TResult> func;

    public Func0Task(Func0<TResult> func) {
        this.func = func;
    }

    @Override
    public IContinuation buildContinuation(final IContinuation cont) {
        return new IContinuation() {
            @Override
            public void apply(Object state, Environment environment, IScheduler scheduler) {
                cont.apply(func.apply(), environment, scheduler);
            }
        };
    }
}


text:
function checkNumericChar(aChar)
{
    return (aChar >= '0' &&  aChar <= '9')
         || aChar == '*'
         || aChar == '#'
         || aChar == '+'
}

function checkNumericString(aString)
{
    for (var i=0; i<aString.length; i++)
        if (!checkNumericChar(aString.charAt(i)))
            return false;
    return true;
}

function checkString(aString, minChars, maxChars, isNumeric)
{
    if (minChars != -1 && aString.length < minChars)
        return false;
    if (maxChars != -1 && aString.length > maxChars)
        return false;
    if (isNumeric)
        return checkNumericString(aString);
    return true;
}


text:
void TC5_Handler();

#endif


text:
DIST_SUBDIR=	src/preproc/html

PROG_CXX=	pre-grohtml
SRCS=		pre-html.cpp pushback.cpp
NOMAN=		YES

.include <bsd.prog.mk>


text:
package com.intellij.java.codeInsight.daemon;

import com.intellij.JavaTestUtil;
import com.intellij.codeInsight.daemon.impl.IdentifierHighlighterPass;
import com.intellij.codeInsight.intention.IntentionAction;
import com.intellij.codeInspection.deadCode.UnusedDeclarationInspection;
import com.intellij.pom.java.LanguageLevel;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.testFramework.IdeaTestUtil;
import com.intellij.testFramework.LightProjectDescriptor;
import com.intellij.testFramework.fixtures.LightJavaCodeInsightFixtureTestCase;
import org.jetbrains.annotations.NotNull;

public class LightPatternsForSwitchHighlightingTest extends LightJavaCodeInsightFixtureTestCase {
  @Override
  protected String getBasePath() {
    return JavaTestUtil.getRelativeJavaTestDataPath() + "/codeInsight/daemonCodeAnalyzer/advHighlightingPatternsInSwitch";
  }

  @NotNull
  @Override
  protected LightProjectDescriptor getProjectDescriptor() {
    return JAVA_17;
  }

  public void testPatternsInSwitchIn16Java() {
    IdeaTestUtil.withLevel(getModule(), LanguageLevel.JDK_16, this::doTest);
  }

  public void testPatternsInSwitchIn11Java() {
    IdeaTestUtil.withLevel(getModule(), LanguageLevel.JDK_11, this::doTest);
  }

  public void testPatternsInSwitchIn19Java() {
    IdeaTestUtil.withLevel(getModule(), LanguageLevel.JDK_19_PREVIEW, this::doTest);
  }

  public void testMismatchedDeconstructionIn19Java() {
    IdeaTestUtil.withLevel(getModule(), LanguageLevel.JDK_19_PREVIEW, this::doTest);
  }

  public void testIllegalFallthroughIn19Java() {
    IdeaTestUtil.withLevel(getModule(), LanguageLevel.JDK_19_PREVIEW, this::doTest);
  }

  public void testUnconditionalDestructuringAndDefaultIn19Java() {
    IdeaTestUtil.withLevel(getModule(), LanguageLevel.JDK_19_PREVIEW, this::doTest);
  }

  public void testSwitchExhaustivenessIn19Java() {
    IdeaTestUtil.withLevel(getModule(), LanguageLevel.JDK_19_PREVIEW, this::doTest);
  }

  public void testSwitchExhaustivenessWithGenericsIn19Java() {
    IdeaTestUtil.withLevel(getModule(), LanguageLevel.JDK_19_PREVIEW, this::doTest);
  }

  public void testSwitchDominanceIn19Java() {
    IdeaTestUtil.withLevel(getModule(), LanguageLevel.JDK_19_PREVIEW, this::doTest);
  }

  public void testPatternMatchingInSwitch() {
    doTest();
    IntentionAction action = myFixture.getAvailableIntention("Remove 'default' branch");
    assertNotNull(action);
  }

  public void testPatternMatchingInSwitchJava18() {
    IdeaTestUtil.withLevel(getModule(), LanguageLevel.JDK_18_PREVIEW, this::doTest);
  }

  public void testPatternMatchingWithGuard() {
    doTest();
  }

  public void testPatternMatchingScope() {
    doTest();
  }

  public void testPatternMatchingInSwitchWithIfPatternMatching() {
    doTest();
  }

  public void testReachability() {
    doTest();
  }

  public void testEffectivelyFinal() {
    doTest();
  }

  public void testEffectivelyFinalWhen() {
    IdeaTestUtil.withLevel(getModule(), LanguageLevel.JDK_19_PREVIEW, this::doTest);
  }

  public void testSameVariableNameInPatternMatchingInSwitch() {
    doTest();
  }

  public void testFallthroughPatternMatchingSwitch() {
    doTest();
  }

  public void testGuardedPatterns() {
    doTest();
  }

  public void testSwitchExprHasResult() {
    doTest();
  }

  public void testHighlighterForPatternVariableInSwitch() {
    testIdentifierHighlighter(3);
  }

  public void testHighlighterForPatternVariableInIf() {
    testIdentifierHighlighter(2);
  }

  public void testHighlighterForPatternVariableInIfElse() {
    testIdentifierHighlighter(4);
  }

  public void testHighlighterForPatternVariableInLocalVariable() {
    testIdentifierHighlighter(2);
  }

  public void testGuardWithInstanceOfPatternMatching() {
    doTest();
  }

  public void testMultipleReferencesToPatternVariable() {
    doTest();
  }

  public void testBreakAndOtherStopWords() {
    doTest();
  }

  public void testFallthroughDefault() {
    doTest();
  }

  public void testUnusedPatternVariable() {
    myFixture.enableInspections(new UnusedDeclarationInspection());
    doTest();
    assertNotNull(myFixture.getAvailableIntention("Rename 's' to 'ignored'"));
  }

  public void testMalformedReferenceExpression() {
    doTest();
  }

  public void testBrokenSealedHierarchy() {
    doTest();
  }

  public void testRecordPatternsAndWhenGuardsInJava18() {
    IdeaTestUtil.withLevel(getModule(), LanguageLevel.JDK_18_PREVIEW, this::doTest);
  }

  public void testRecordPatternsAndWhenGuardsInJava19() {
    IdeaTestUtil.withLevel(getModule(), LanguageLevel.JDK_19_PREVIEW, this::doTest);
  }

  public void testWhenExpressionIsFalse() {
    IdeaTestUtil.withLevel(getModule(), LanguageLevel.JDK_19_PREVIEW, this::doTest);
  }

  private void doTest() {
    myFixture.configureByFile(getTestName(false) + ".java");
    myFixture.checkHighlighting();
  }

  private void testIdentifierHighlighter(int expectedUsages) {
    PsiFile file = myFixture.configureByFile(getTestName(false) + ".java");
    PsiElement element = myFixture.getElementAtCaret();
    assertSize(expectedUsages, IdentifierHighlighterPass.getUsages(element, file, true));
  }
}


text:
---
title: Wake-on-lan Status Inspectors
---

Use these Inspectors to query information about the Wake-on-lan capability on the Client.

---

## BES WakeOnlan Status

These Windows Inspectors return the status of the BES WakeOnLan feature.

Click [here](/relevance/reference/bes-wakeonlan-status.html) to access the page describing these inspectors.

**Examples**

```relevance
(database id of it, enabled of it) of bes wakeonlan statuses
```

Returns a list of database IDs and the WoL status for each, such as:
* 1, True
* 2, False.


text:
@implementation CGBaseSearchBar

-(instancetype)initWithSearchBarPlaceholder:(NSString *)placeholder
{
    self = [super init];
    if (self)
    {
            if (@available(iOS 13.0, *))
            {
                self.searchTextField.backgroundColor = [CGBaseGobalTools AppCellBGColor];
                self.searchTextField.clearButtonMode = UITextFieldViewModeNever;
                self.searchTextField.textColor = [CGBaseGobalTools AppColor];
                [self.searchTextField setTintColor:[CGBaseGobalTools AppColor]];
                self.searchTextField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:placeholder attributes:@{NSFontAttributeName: AppFontNormal,NSForegroundColorAttributeName:[CGBaseGobalTools AppGray]}];
                self.searchBarOutViewColor = kClearColor;
                self.backgroundImage = [Utils createImageWithColor:[CGBaseGobalTools AppCellBGColor]];
                [self setImage:kImageNamed(@"image_main_search") forSearchBarIcon:UISearchBarIconSearch state:UIControlStateNormal];
                kViewBorderRadius(self.searchTextField, 15, 1, [CGBaseGobalTools AppGray]);
            }
            else
            {
                self.searchBarOutViewColor = [CGBaseGobalTools AppCellBGColor];
                self.searchPlaceholderColor = [CGBaseGobalTools AppGray];
                self.searchPlaceholder = placeholder;
                self.searchPlaceholderFont = AppFontNormal;
                self.searchTextColor = [CGBaseGobalTools AppColor];
                self.searchBarImage = kImageNamed(@"image_main_search");
                self.searchTextFieldBackgroundColor = [CGBaseGobalTools AppCellBGColor];
                self.searchBarTextFieldCornerRadius = 15;
                self.cursorColor = [CGBaseGobalTools AppColor];
                self.searchBarTextFieldBorderColor = [CGBaseGobalTools AppGray];
            }

    }
    return self;
}

@end


text:
#include <boost/format.hpp>

#include "common.h"
#include "thread.h"

#include "generic_type.h"
#include "NUMA_vector.h"
#include "data_frame.h"
#include "mem_worker_thread.h"
#include "local_vec_store.h"
#include "matrix_store.h"
#include "NUMA_dense_matrix.h"

namespace fm
{

namespace detail
{

template<class T>
T ceil_divide(T v1, T v2)
{
	return ceil(((double) v1) / v2);
}

/*
 * This interface is to set the data in the vector of arrays.
 */
class set_range_operate
{
public:
	/*
	 * @buf: the buffer where to initialize data.
	 * @size: the size of the buffer (the number of bytes).
	 * @local_off: the offset of the buffer in an array (the number of bytes).
	 * @arr_id: the id of the array where the buffer is.
	 */
	virtual void set(char *buf, size_t size, off_t local_off,
			int arr_id) const = 0;
};

class reset_data_task: public thread_task
{
	chunked_raw_array arr;
public:
	reset_data_task(chunked_raw_array &_arr): arr(_arr) {
	}

	void run() {
		arr.reset_data();
	}
};

class set_data_task: public thread_task
{
	chunked_raw_array &to_buf;
	off_t to_off;
	size_t to_size;
	int node_id;
	const set_range_operate &set_range;
	size_t range_size;
public:
	// `to_off', `to_size' and `range_size' are in the number of bytes.
	set_data_task(chunked_raw_array &_arr, off_t to_off, size_t to_size, int node_id,
			const set_range_operate &_set_range, size_t range_size): to_buf(
				_arr), set_range(_set_range) {
		this->to_off = to_off;
		this->to_size = to_size;
		this->node_id = node_id;
		this->range_size = range_size;
	}

	void run() {
		for (size_t rel_off = 0; rel_off < to_size; rel_off += range_size) {
			size_t size = std::min(to_size - rel_off, range_size);
			off_t off = to_off + rel_off;
			set_range.set(to_buf.get_raw(off), size, off, node_id);
		}
	}
};

/*
 * Reset all elements in the arrays.
 */
void reset_arrays(std::vector<chunked_raw_array> &arrs);
/*
 * Set the elements in the arrays.
 * @mapper: defines how the elements are distributed in the arrays.
 * @length: the total number of elements in the arrays.
 * @entry_size: the size of an element.
 * @set_range: the function to set elements.
 * @arrs: the arrays.
 */
void set_array_ranges(const NUMA_mapper &mapper, size_t length,
		size_t entry_size, const set_range_operate &set_range,
		std::vector<chunked_raw_array> &arrs);

void reset_arrays(std::vector<chunked_raw_array> &arrs)
{
	// TODO This only runs a thread for each NUMA node.
	mem_thread_pool::ptr mem_threads
		= mem_thread_pool::get_global_mem_threads();
	for (size_t i = 0; i < arrs.size(); i++) {
		assert(arrs[i].get_node_id() >= 0);
		mem_threads->process_task(arrs[i].get_node_id(),
				new reset_data_task(arrs[i]));
	}
	mem_threads->wait4complete();
}

void set_array_ranges(const NUMA_mapper &mapper, size_t length,
		size_t entry_size, const set_range_operate &set_range,
		std::vector<chunked_raw_array> &arrs)
{
	// The number of threads per NUMA node.
	detail::mem_thread_pool::ptr mem_threads
		= detail::mem_thread_pool::get_global_mem_threads();
	size_t nthreads_per_node
		= mem_threads->get_num_threads() / matrix_conf.get_num_nodes();
	std::vector<size_t> local_lens = mapper.cal_local_lengths(length);
	for (size_t i = 0; i < arrs.size(); i++) {
		size_t num_local_bytes = local_lens[i] * entry_size;
		// The number of ranges in array of the node.
		size_t nranges = ceil_divide(local_lens[i], mapper.get_range_size());
		// The number of ranges a thread should get.
		size_t nranges_per_thread = ceil_divide(nranges, nthreads_per_node);
		// The number of bytes a thread should get.
		size_t nbytes_per_thread
			= nranges_per_thread * mapper.get_range_size() * entry_size;
		for (size_t j = 0; j < nthreads_per_node; j++) {
			if (num_local_bytes <= nbytes_per_thread * j)
				continue;
			// The number of bytes a thread actually gets.
			size_t local_nbytes = std::min(nbytes_per_thread,
					num_local_bytes - nbytes_per_thread * j);
			assert(arrs[i].get_node_id() >= 0);
			mem_threads->process_task(arrs[i].get_node_id(),
					new set_data_task(arrs[i], nbytes_per_thread * j,
						local_nbytes, arrs[i].get_node_id(), set_range,
						mapper.get_range_size() * entry_size));
		}
	}
	mem_threads->wait4complete();
}

NUMA_vec_store::ptr NUMA_vec_store::create(size_t length, const scalar_type &type,
		const std::vector<chunked_raw_array> &data, const NUMA_mapper &mapper)
{
	if (mapper.get_num_nodes() != data.size()) {
		BOOST_LOG_TRIVIAL(error)
			<< "can't create a NUMA vector. Each NUMA node should have a data array";
		return ptr();
	}
	size_t off = length - 1;
	// We should check if the last ranges can be mapped to the data arrays.
	for (size_t i = 0; i < data.size(); i++) {
		auto phy_off = mapper.map2physical(off);
		if (phy_off.second * type.get_size() >= data[phy_off.first].get_num_bytes()) {
			BOOST_LOG_TRIVIAL(error) << boost::format(
					"Data array %ld doesn't have enough bytes") % phy_off.first;
			return ptr();
		}

		if (off < mapper.get_range_size())
			break;
		off -= mapper.get_range_size();
	}
	return ptr(new NUMA_vec_store(length, type, data, mapper));
}

NUMA_vec_store::ptr NUMA_vec_store::cast(vec_store::ptr vec)
{
	if (!vec->is_in_mem()
			|| std::static_pointer_cast<mem_vec_store>(vec)->get_num_nodes() < 0) {
		BOOST_LOG_TRIVIAL(error) << "The vector isn't a NUMA vector";
		return NUMA_vec_store::ptr();
	}
	return std::static_pointer_cast<NUMA_vec_store>(vec);
}

NUMA_vec_store::NUMA_vec_store(const NUMA_vec_store &vec): mem_vec_store(
		vec.get_length(), vec.get_type()), mapper(vec.mapper)
{
	data = vec.data;
}

NUMA_vec_store::NUMA_vec_store(size_t length, size_t num_nodes,
		const scalar_type &type): mem_vec_store(length, type), mapper(num_nodes,
			NUMA_range_size_log)
{
	data.resize(num_nodes);
	size_t num_eles_per_node = ceil_divide(length, num_nodes);
	num_eles_per_node = ROUNDUP(num_eles_per_node, mapper.get_range_size());
	size_t size_per_node = num_eles_per_node * type.get_size();
	size_t block_bytes = mapper.get_range_size() * type.get_size();
	for (size_t node_id = 0; node_id < num_nodes; node_id++)
		data[node_id] = detail::chunked_raw_array(size_per_node, block_bytes,
				node_id);
}

void NUMA_vec_store::reset_data()
{
	reset_arrays(data);
}

namespace
{

class set_ele_operate: public detail::set_range_operate
{
	const set_vec_operate &op;
	const NUMA_mapper &mapper;
	size_t entry_size;
public:
	set_ele_operate(const set_vec_operate &_op, const NUMA_mapper &_mapper,
			size_t entry_size): op(_op), mapper(_mapper) {
		this->entry_size = entry_size;
	}

	void set(char *buf, size_t size, off_t local_off, int node_id) const {
		assert(local_off % entry_size == 0);
		assert(size % entry_size == 0);
		size_t num_eles = size / entry_size;
		size_t local_ele_idx = local_off / entry_size;
		size_t global_ele_idx = mapper.map2logical(node_id, local_ele_idx);
		op.set(buf, num_eles, global_ele_idx);
	}
};

}

void NUMA_vec_store::set_data(const set_vec_operate &op)
{
	set_ele_operate set_ele(op, mapper, get_entry_size());
	set_array_ranges(mapper, get_length(), get_entry_size(), set_ele, data);
}

const char *NUMA_vec_store::get_sub_arr(off_t start, off_t end) const
{
	// The start and end needs to fall into the same range.
	if (mapper.get_logical_range_id(start)
			!= mapper.get_logical_range_id(end - 1)) {
		BOOST_LOG_TRIVIAL(error) << boost::format(
				"[%1%, %2%) isn't in the same range") % start % end;
		return NULL;
	}
	if ((size_t) start >= get_length() || (size_t) end > get_length()) {
		BOOST_LOG_TRIVIAL(error)
			<< boost::format("[%1%, %2%) is out of boundary") % start % end;
		return NULL;
	}

	std::pair<int, size_t> loc = mapper.map2physical(start);
	size_t off = loc.second * get_entry_size();
	return data[loc.first].get_raw(off);
}

char *NUMA_vec_store::get_sub_arr(off_t start, off_t end)
{
	const NUMA_vec_store *const_this = this;
	return (char *) const_this->get_sub_arr(start, end);
}

bool NUMA_vec_store::is_sub_vec() const
{
	return false;
}

bool NUMA_vec_store::append(std::vector<vec_store::const_ptr>::const_iterator vec_it,
		std::vector<vec_store::const_ptr>::const_iterator vec_end)
{
	// TODO
	assert(0);
}

bool NUMA_vec_store::append(const vec_store &vec)
{
	// TODO
	assert(0);
}

namespace
{

class sort_task: public thread_task
{
	const scalar_type &type;
	char *buf;
	size_t num_eles;
public:
	sort_task(char *buf, size_t num_eles,
			const scalar_type &_type): type(_type) {
		this->buf = buf;
		this->num_eles = num_eles;
	}

	void run() {
		type.get_sorter().serial_sort(buf, num_eles, false);
	}
};

/*
 * This task is to copy some data in the from buffer to the right ranges.
 */
class copy_operate: public detail::set_range_operate
{
	const char *from_buf;
	size_t entry_size;
	const NUMA_mapper &mapper;
public:
	copy_operate(const NUMA_mapper &_mapper, size_t entry_size,
			const char *from_buf): mapper(_mapper) {
		this->entry_size = entry_size;
		this->from_buf = from_buf;
	}

	virtual void set(char *buf, size_t size, off_t local_off,
			int node_id) const {
		assert(size % entry_size == 0);
		assert(local_off % entry_size == 0);
		size_t from_off = mapper.map2logical(node_id, local_off / entry_size);
		memcpy(buf, from_buf + from_off * entry_size, size);
	}
};

}

void NUMA_vec_store::sort()
{
	assert(!is_sub_vec());
	// The number of threads per NUMA node.
	typedef std::pair<const char *, const char *> arr_pair;
	std::vector<arr_pair> arrs;
	detail::mem_thread_pool::ptr mem_threads
		= detail::mem_thread_pool::get_global_mem_threads();
	std::vector<size_t> local_lens = mapper.cal_local_lengths(get_length());
	// We first split data into multiple partitions and sort each partition
	// independently.
	size_t entry_size = get_type().get_size();
	for (size_t i = 0; i < data.size(); i++) {
		for (size_t j = 0; j < data[i].get_num_chunks(); j++) {
			auto chunk = data[i].get_chunk(j);
			assert(chunk.second % entry_size == 0);
			size_t size = std::min(local_lens[i] * entry_size, chunk.second);
			local_lens[i] -= size / entry_size;
			arrs.push_back(arr_pair(chunk.first, chunk.first + size));
			mem_threads->process_task(data[i].get_node_id(),
					new sort_task(chunk.first, size / entry_size, get_type()));
		}
		assert(local_lens[i] == 0);
	}
	mem_threads->wait4complete();

	// Now we should merge the array parts together.
	size_t tot_num_bytes = get_length() * get_entry_size();
	std::unique_ptr<char[]> tmp(new char[tot_num_bytes]);
	get_type().get_sorter().merge(arrs, tmp.get(), get_length());

	// We need to copy the result back.
	copy_from(tmp.get(), tot_num_bytes);
}

bool NUMA_vec_store::copy_from(const char *buf, size_t num_bytes)
{
	if (num_bytes % get_entry_size() != 0
			|| num_bytes / get_entry_size() != get_length())
		return false;

	copy_operate cp(mapper, get_entry_size(), buf);
	set_array_ranges(mapper, get_length(), get_entry_size(), cp, data);
	return true;
}

vec_store::ptr NUMA_vec_store::sort_with_index()
{
	assert(!is_sub_vec());
	// TODO
	assert(0);
}

bool NUMA_vec_store::is_sorted() const
{
	// TODO
	assert(0);
}

vec_store::ptr NUMA_vec_store::deep_copy() const
{
	// TODO I need to make it in parallel.
	NUMA_vec_store *ret = new NUMA_vec_store(*this);
	for (size_t i = 0; i < data.size(); i++)
		ret->data[i] = data[i].deep_copy();
	return vec_store::ptr(ret);
}

local_vec_store::const_ptr NUMA_vec_store::get_portion(off_t start,
		size_t length) const
{
	const char *raw_data = get_sub_arr(start, start + length);
	if (raw_data == NULL)
		return local_vec_store::const_ptr();

	std::pair<int, size_t> loc = mapper.map2physical(start);
	return local_vec_store::const_ptr(new local_cref_vec_store(raw_data,
				start, length, get_type(), data[loc.first].get_node_id()));
}

local_vec_store::ptr NUMA_vec_store::get_portion(off_t start, size_t length)
{
	char *raw_data = get_sub_arr(start, start + length);
	if (raw_data == NULL)
		return local_vec_store::ptr();

	std::pair<int, size_t> loc = mapper.map2physical(start);
	return local_vec_store::ptr(new local_ref_vec_store(raw_data,
				start, length, get_type(), data[loc.first].get_node_id()));
}

namespace
{

class vec2mat_set_operate: public set_operate
{
	const NUMA_vec_store &vec;
	bool byrow;
	// #rows and cols of the output matrix.
	size_t num_rows;
	size_t num_cols;
public:
	vec2mat_set_operate(const NUMA_vec_store &_vec, bool byrow,
			size_t num_rows, size_t num_cols): vec(_vec) {
		this->byrow = byrow;
		this->num_rows = num_rows;
		this->num_cols = num_cols;
	}
	virtual void set(void *arr, size_t num_eles, off_t row_idx,
			off_t col_idx) const;
	virtual const scalar_type &get_type() const {
		return vec.get_type();
	}
};

void vec2mat_set_operate::set(void *arr, size_t num_eles,
		off_t row_idx, off_t col_idx) const
{
	// The start offset in the vector.
	off_t vec_off;
	if (byrow)
		vec_off = num_cols * row_idx + col_idx;
	else
		vec_off = num_rows * col_idx + row_idx;

	while (num_eles > 0) {
		off_t next_range_start = ROUNDUP(vec_off + 1,
				vec.get_mapper().get_range_size());
		off_t end = std::min(next_range_start, (off_t) vec.get_length());
		size_t num_avails = end - vec_off;
		num_avails = std::min(num_eles, num_avails);
		const void *sub_arr = vec.get_sub_arr(vec_off, end);
		assert(sub_arr);
		memcpy(arr, sub_arr, num_avails * vec.get_entry_size());

		arr = ((char *) arr) +  num_avails * vec.get_entry_size();
		vec_off += num_avails;
		num_eles -= num_avails;
	}
}

}

matrix_store::ptr NUMA_vec_store::conv2mat(size_t nrow, size_t ncol, bool byrow)
{
	if (nrow > 1 && ncol > 1) {
		matrix_store::ptr res;
		if (byrow)
			res = NUMA_matrix_store::create(nrow, ncol, get_num_nodes(),
					matrix_layout_t::L_ROW, get_type());
		else
			res = NUMA_matrix_store::create(nrow, ncol, get_num_nodes(),
					matrix_layout_t::L_COL, get_type());
		res->set_data(vec2mat_set_operate(*this, byrow, nrow, ncol));
		return res;
	}

	matrix_store::ptr mat;
	if (nrow == 1 && byrow) {
		std::vector<NUMA_vec_store::ptr> cols(1);
		cols[0] = NUMA_vec_store::ptr(new NUMA_vec_store(*this));
		NUMA_col_tall_matrix_store::ptr tmp
			= NUMA_col_tall_matrix_store::create(cols);
		mat = NUMA_row_wide_matrix_store::create_transpose(*tmp);
	}
	else if (ncol == 1 && !byrow) {
		std::vector<NUMA_vec_store::ptr> cols(1);
		cols[0] = NUMA_vec_store::ptr(new NUMA_vec_store(*this));
		mat = NUMA_col_tall_matrix_store::create(cols);
	}
	else if (ncol == 1 && byrow)
		mat = NUMA_row_tall_matrix_store::create(data, nrow, ncol, mapper,
				get_type());
	else {
		assert(nrow == 1 && !byrow);
		NUMA_row_tall_matrix_store::ptr tmp = NUMA_row_tall_matrix_store::create(
				data, ncol, nrow, mapper, get_type());
		mat = NUMA_col_wide_matrix_store::create_transpose(*tmp);
	}
	return mat;
}

}

}


text:
typedef NS_ENUM(NSUInteger, GameOverStatus) {
    kGameOverWon = 0,
    kGameOverDraw,
    kGameOverLost
};

#pragma mark - Private
@interface ViewController () <UICollectionViewDelegate, UIAlertViewDelegate>

@property (weak, nonatomic) IBOutlet UIView *gameOverOverlay;
@property (weak, nonatomic) IBOutlet UILabel *gameOverStatusLabel;
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
@property (strong, nonatomic) GameController *gameController;
@property (weak, nonatomic) IBOutlet UIButton *restartButton;
@property (strong, nonatomic)UIAlertView *promptRestartAlert;

@end

#pragma mark - Implemnetation
@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    // Game Controller binded to this view controller
    self.gameController = [[GameController alloc] init];

    // Register reusable cells resources
    NSString *nibName = [Utilities resourceNamewithBaseName:@"Tile"];
    [self.collectionView registerNib:[UINib nibWithNibName:nibName bundle:[NSBundle mainBundle]] forCellWithReuseIdentifier:NSStringFromClass([Tile class])];

    // Settings localized string to the restart button
    [self.restartButton setTitle:NSLocalizedString(@"Restart", @"Restart Label") forState:UIControlStateNormal];
    self.restartButton.layer.cornerRadius = 2.0f;

    // Prompt Restart Alert
    NSString *alertTitle = NSLocalizedString(@"Confirm", @"Restart alert title");
    NSString *alertMesage = NSLocalizedString(@"Do you want to exit the current game and restart a new one?", @"Restart alert message");
    NSString *okButtonTitle = NSLocalizedString(@"OK", @"OK button title");
    NSString *cancelButtonTitle = NSLocalizedString(@"Cancel", @"Cancel button title");
    self.promptRestartAlert = [[UIAlertView alloc] initWithTitle:alertTitle message:alertMesage delegate:self cancelButtonTitle:nil otherButtonTitles:cancelButtonTitle, okButtonTitle, nil];
    self.promptRestartAlert.delegate = self;

    // When the view laods for the firs time, starts a new game
    [self newGame];
}

- (void)newGame {
    [self.gameController reset];
    self.gameOverOverlay.hidden = YES;
    [self.collectionView reloadData];
}

- (void)presentGameOverScreen:(GameOverStatus)gameOverStatus {

    NSString *statusText;
    switch(gameOverStatus) {
        case kGameOverWon:
            statusText = NSLocalizedString(@"You won", @"Winning label");
            break;

        case kGameOverDraw:
            statusText = NSLocalizedString(@"Draw Game", @"Draw Label");
            break;

        case kGameOverLost:
            statusText = NSLocalizedString(@"Youn lost", @"Losing label");
            break;

        default:
            break;
    }

    self.gameOverStatusLabel.text = statusText;

    [UIView animateWithDuration:0.3f animations:^{
        self.gameOverOverlay.alpha = 0.4f;
        self.gameOverOverlay.hidden = NO;
    }];
}

- (IBAction)onRestartButtonPressed:(id)sender {
    if(self.gameController.status == kGameInProgress) {
        [self.promptRestartAlert show];
    }
    else {
        [self newGame];
    }
}

#pragma mark - UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {

    Tile *selectedCell = (Tile *)[collectionView cellForItemAtIndexPath:indexPath];
    if(!selectedCell.checked) {
        [selectedCell checkTile:YES];

        // TODO: Check if this is a winning move
        if([self.gameController checkIfWinningMove:indexPath forPlayer:YES]) {
            // Player won
            [self presentGameOverScreen:kGameOverWon];
        }
        else if([self.gameController isDraw]) {
            [self presentGameOverScreen:kGameOverDraw];
        }
        else {
            // Computer's turn to play
            NSIndexPath *computerChoice = [self.gameController computerPlay];

            Tile *computerSelectedCell = (Tile *)[collectionView cellForItemAtIndexPath:computerChoice];
            [computerSelectedCell checkTile:NO];

            if([self.gameController checkIfWinningMove:computerChoice forPlayer:NO]) {
                [self presentGameOverScreen:kGameOverLost];
            }
            else if([self.gameController isDraw]) {
                [self presentGameOverScreen:kGameOverDraw];
            }
        }
    }
}

#pragma mark - UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
    if(buttonIndex == 1) {
        [self newGame];
    }
}

@end


text:
export default [
  { route: ['','login'],    name: 'login',        moduleId: 'pages/login',     nav: false, auth: false, title:'Login' },
  { route: 'signup',        name: 'signup',       moduleId: 'pages/signup',    nav: false, auth: false, title:'Signup' },
  { route: 'users',         name: 'users',        moduleId: 'pages/users',     nav: true,  auth: true,  title:'Github Users' },
  { route: 'logout',        name: 'logout',       moduleId: 'pages/logout',    nav: true,  auth: true,  title:'Logout' }
];


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using System;
using System.Threading;
using Azure.AI.MetricsAdvisor.Models;
using Azure.Core;

namespace Azure.AI.MetricsAdvisor.Administration
{
    /// <summary>
    /// Describes an InfluxDB data source which ingests data into a <see cref="DataFeed"/> for anomaly detection.
    /// </summary>
    public class InfluxDbDataFeedSource : DataFeedSource
    {
        private string _connectionString;

        private string _password;

        /// <summary>
        /// Initializes a new instance of the <see cref="InfluxDbDataFeedSource"/> class.
        /// </summary>
        /// <param name="connectionString">The connection string.</param>
        /// <param name="database">The name of the database.</param>
        /// <param name="username">The access username.</param>
        /// <param name="password">The access password.</param>
        /// <param name="query">The query to retrieve the data to be ingested.</param>
        /// <exception cref="ArgumentNullException"><paramref name="connectionString"/>, <paramref name="database"/>, <paramref name="username"/>, <paramref name="password"/>, or <paramref name="query"/> is null.</exception>
        /// <exception cref="ArgumentException"><paramref name="connectionString"/>, <paramref name="database"/>, <paramref name="username"/>, <paramref name="password"/>, or <paramref name="query"/> is empty.</exception>
        public InfluxDbDataFeedSource(string connectionString, string database, string username, string password, string query)
            : base(DataFeedSourceKind.InfluxDb)
        {
            Argument.AssertNotNullOrEmpty(connectionString, nameof(connectionString));
            Argument.AssertNotNullOrEmpty(database, nameof(database));
            Argument.AssertNotNullOrEmpty(username, nameof(username));
            Argument.AssertNotNullOrEmpty(password, nameof(password));
            Argument.AssertNotNullOrEmpty(query, nameof(query));

            ConnectionString = connectionString;
            Database = database;
            Username = username;
            Password = password;
            Query = query;
        }

        internal InfluxDbDataFeedSource(InfluxDBParameter parameter)
            : base(DataFeedSourceKind.InfluxDb)
        {
            Argument.AssertNotNull(parameter, nameof(parameter));

            ConnectionString = parameter.ConnectionString;
            Database = parameter.Database;
            Username = parameter.UserName;
            Password = parameter.Password;
            Query = parameter.Query;
        }

        /// <summary>
        /// The name of the database.
        /// </summary>
        public string Database { get; set; }

        /// <summary>
        /// The access username.
        /// </summary>
        public string Username { get; set; }

        /// <summary>
        /// The query to retrieve the data to be ingested.
        /// </summary>
        public string Query { get; set; }

        /// <summary>
        /// The connection string.
        /// </summary>
        internal string ConnectionString
        {
            get => Volatile.Read(ref _connectionString);
            private set => Volatile.Write(ref _connectionString, value);
        }

        /// <summary>
        /// The access password.
        /// </summary>
        internal string Password
        {
            get => Volatile.Read(ref _password);
            private set => Volatile.Write(ref _password, value);
        }

        /// <summary>
        /// Updates the connection string.
        /// </summary>
        /// <param name="connectionString">The new connection string to be used for authentication.</param>
        /// <exception cref="ArgumentNullException"><paramref name="connectionString"/> is null.</exception>
        /// <exception cref="ArgumentException"><paramref name="connectionString"/> is empty.</exception>
        public void UpdateConnectionString(string connectionString)
        {
            Argument.AssertNotNullOrEmpty(connectionString, nameof(connectionString));
            ConnectionString = connectionString;
        }

        /// <summary>
        /// Updates the password.
        /// </summary>
        /// <param name="password">The new password to be used for authentication.</param>
        /// <exception cref="ArgumentNullException"><paramref name="password"/> is null.</exception>
        /// <exception cref="ArgumentException"><paramref name="password"/> is empty.</exception>
        public void UpdatePassword(string password)
        {
            Argument.AssertNotNullOrEmpty(password, nameof(password));
            Password = password;
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <RelativeLayout

        android:background="@color/statusBar"
        android:layout_width="match_parent"
        android:layout_height="48dp" >
        <Button
            android:id="@+id/btn_fanhui"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:drawableLeft="@mipmap/arrow_left1"
            android:background="@color/statusBar"
            android:text="返回"
            android:textColor="@color/white"
            android:gravity="left|center_vertical"
            android:textSize="17sp"/>

        <TextView
            android:textColor="@color/white"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:text="组别标签"
            android:textSize="20sp" />

        <Button
            android:id="@+id/btn_xinjian"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@color/statusBar"
            android:text="新建"
            android:layout_marginRight="15dp"
            android:gravity="right|center_vertical"
            android:textSize="17sp"
            android:layout_alignParentRight="true"
            android:textColor="@color/white"/>
    </RelativeLayout>
    <LinearLayout
        android:paddingBottom="10dp"
        android:paddingTop="10dp"
        android:paddingRight="15dp"
        android:paddingLeft="15dp"
        android:background="@color/white"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:paddingBottom="15dp"
            android:paddingTop="15dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="17sp"
            android:text="校上行设计组(5)"/>
        <View
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:background="@color/border"/>
        <TextView
            android:paddingBottom="15dp"
            android:paddingTop="15dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="广告1201(32)"
            android:textSize="17sp"/>
        <View
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:background="@color/border"/>
        <TextView
            android:paddingBottom="15dp"
            android:paddingTop="15dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="17sp"
            android:text="无锡实训基地(8)"/>
    </LinearLayout>
    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="@color/border"/>

</LinearLayout>


text:
require 'rails_helper'

describe PackageViewModel do
  before(:each) do
    @metadata = PackageConfigurations.new
    @metadata.addConfiguration(PackageConfiguration.new("key1").with(PackageConfiguration::SECURE, false).with(PackageConfiguration::DISPLAY_NAME, "Key 1"))
    @metadata.addConfiguration(PackageConfiguration.new("key2").with(PackageConfiguration::SECURE, false).with(PackageConfiguration::DISPLAY_NAME, "Key 2"))
    @metadata.addConfiguration(PackageConfiguration.new("key3_secure").with(PackageConfiguration::SECURE, true).with(PackageConfiguration::DISPLAY_NAME, "Key 3 Secure"))

    p1 = ConfigurationProperty.new(ConfigurationKey.new("key1"), ConfigurationValue.new("value1"), nil, nil)
    p2 = ConfigurationProperty.new(ConfigurationKey.new("key2"), ConfigurationValue.new("value2"), nil, nil)
    p3_secure = ConfigurationProperty.new(ConfigurationKey.new("key3_secure"), nil, EncryptedConfigurationValue.new("secure"), nil)
    @package = PackageDefinition.new("go", "package-name", Configuration.new([p1, p2, p3_secure].to_java(ConfigurationProperty)))
  end

  it "should create package view model from metadata and package configuration" do
    model = PackageViewModel.new @metadata, @package
    expect(model.name).to eq("package-name")
    expect(model.properties.size).to eq(3)
    expect(model.properties[0].display_name).to eq("Key 1")
    expect(model.properties[0].value).to eq("value1")
    expect(model.properties[1].display_name).to eq("Key 2")
    expect(model.properties[1].value).to eq("value2")
    expect(model.properties[2].display_name).to eq("Key 3 Secure")
    expect(model.properties[2].value).to eq("secure")
  end

  it "should create package view model from metadata" do
    model = PackageViewModel.new @metadata, PackageDefinition.new
    expect(model.name).to eq(nil)
    expect(model.properties.size).to eq(3)
    expect(model.properties[0].display_name).to eq("Key 1")
    expect(model.properties[0].value).to eq(nil)
    expect(model.properties[1].display_name).to eq("Key 2")
    expect(model.properties[1].value).to eq(nil)
    expect(model.properties[2].display_name).to eq("Key 3 Secure")
    expect(model.properties[2].value).to eq(nil)
  end

  it "should filter secure properties" do
    model = PackageViewModel.new @metadata, @package
    expect(model.name).to eq("package-name")
    expect(model.properties.size).to eq(3)
    model.filterSecureProperties!
    expect(model.properties.size).to eq(2)
    expect(model.properties[0].display_name).to eq("Key 1")
    expect(model.properties[0].value).to eq("value1")
    expect(model.properties[1].display_name).to eq("Key 2")
    expect(model.properties[1].value).to eq("value2")
  end

  it "should create empty package view model with just name if metadata is nil (plugin not found scenario)" do
    model = PackageViewModel.new nil, @package
    expect(model.name).to eq(@package.name)
    expect(model.properties.size).to eq(0)
  end
end


text:
/**
 * @file
 *
 * This file contains classes representing the connections between
 * particles.
 */
#ifndef CYCLONE_PLINKS_H
#define CYCLONE_PLINKS_H

#include "pcontacts.h"

namespace cyclone {

    /**
     * Links connect two particles together, generating a contact if
     * they violate the constraints of their link. It is used as a
     * base class for cables and rods, and could be used as a base
     * class for springs with a limit to their extension..
     */
    class ParticleLink : public ParticleContactGenerator
    {
    public:
        /**
         * Holds the pair of particles that are connected by this link.
         */
        Particle* particle[2];

    protected:
        /**
         * Returns the current length of the link.
         */
        real currentLength() const;

    public:
        /**
         * Geneates the contacts to keep this link from being
         * violated. This class can only ever generate a single
         * contact, so the pointer can be a pointer to a single
         * element, the limit parameter is assumed to be at least one
         * (zero isn't valid) and the return value is either 0, if the
         * cable wasn't over-extended, or one if a contact was needed.
         *
         * NB: This method is declared in the same way (as pure
         * virtual) in the parent class, but is replicated here for
         * documentation purposes.
         */
        virtual unsigned addContact(ParticleContact *contact,
                                    unsigned limit) const = 0;
    };

    /**
     * Cables link a pair of particles, generating a contact if they
     * stray too far apart.
     */
    class ParticleCable : public ParticleLink
    {
    public:
        /**
         * Holds the maximum length of the cable.
         */
        real maxLength;

        /**
         * Holds the restitution (bounciness) of the cable.
         */
        real restitution;

    public:
        /**
         * Fills the given contact structure with the contact needed
         * to keep the cable from over-extending.
         */
        virtual unsigned addContact(ParticleContact *contact,
                                    unsigned limit) const;
    };

    /**
     * Rods link a pair of particles, generating a contact if they
     * stray too far apart or too close.
     */
    class ParticleRod : public ParticleLink
    {
    public:
        /**
         * Holds the length of the rod.
         */
        real length;

    public:
        /**
         * Fills the given contact structure with the contact needed
         * to keep the rod from extending or compressing.
         */
        virtual unsigned addContact(ParticleContact *contact,
                                     unsigned limit) const;
    };

    /**
    * Constraints are just like links, except they connect a particle to
    * an immovable anchor point.
    */
    class ParticleConstraint : public ParticleContactGenerator
    {
    public:
        /**
        * Holds the particles connected by this constraint.
        */
        Particle* particle;

        /**
         * The point to which the particle is anchored.
         */
        Vector3 anchor;

    protected:
        /**
        * Returns the current length of the link.
        */
        real currentLength() const;

    public:
        /**
        * Geneates the contacts to keep this link from being
        * violated. This class can only ever generate a single
        * contact, so the pointer can be a pointer to a single
        * element, the limit parameter is assumed to be at least one
        * (zero isn't valid) and the return value is either 0, if the
        * cable wasn't over-extended, or one if a contact was needed.
        *
        * NB: This method is declared in the same way (as pure
        * virtual) in the parent class, but is replicated here for
        * documentation purposes.
        */
        virtual unsigned addContact(ParticleContact *contact,
            unsigned limit) const = 0;
    };

    /**
    * Cables link a particle to an anchor point, generating a contact if they
    * stray too far apart.
    */
    class ParticleCableConstraint : public ParticleConstraint
    {
    public:
        /**
        * Holds the maximum length of the cable.
        */
        real maxLength;

        /**
        * Holds the restitution (bounciness) of the cable.
        */
        real restitution;

    public:
        /**
        * Fills the given contact structure with the contact needed
        * to keep the cable from over-extending.
        */
        virtual unsigned addContact(ParticleContact *contact,
            unsigned limit) const;
    };

    /**
    * Rods link a particle to an anchor point, generating a contact if they
    * stray too far apart or too close.
    */
    class ParticleRodConstraint : public ParticleConstraint
    {
    public:
        /**
        * Holds the length of the rod.
        */
        real length;

    public:
        /**
        * Fills the given contact structure with the contact needed
        * to keep the rod from extending or compressing.
        */
        virtual unsigned addContact(ParticleContact *contact,
            unsigned limit) const;
    };
} // namespace cyclone

#endif // CYCLONE_CONTACTS_H


text:
package main

import (
	"github.com/hashicorp/terraform/plugin"
	"github.com/terraform-providers/terraform-provider-ignition/ignition"
)

func main() {
	plugin.Serve(&plugin.ServeOpts{
		ProviderFunc: ignition.Provider})
}


text:
<?php

namespace CakeManager\Model\Table;

use Cake\ORM\Table;
use Cake\Validation\Validator;

/**
 * Users Model
 *
 */
class UsersTable extends Table
{

    /**
     * Initialize method
     *
     * @param array $config The configuration for the Table.
     * @return void
     */
    public function initialize(array $config)
    {
        $this->table('users');
        $this->displayField('email');
        $this->primaryKey('id');
        $this->addBehavior('Timestamp');

        $this->belongsTo('Roles', [
            'className' => 'CakeManager.Roles',
            'foreignKey' => 'role_id',
            'propertyName' => 'role',
        ]);
    }

    /**
     * Default validation rules.
     *
     * @param \Cake\Validation\Validator $validator Validator.
     * @return \Cake\Validation\Validator
     */
    public function validationDefault(Validator $validator)
    {
        $validator
            ->add('id', 'valid', ['rule' => 'numeric'])
            ->allowEmpty('id', 'create')
            ->add('email', 'valid', ['rule' => 'email'])
            ->requirePresence('email', 'create')
            ->notEmpty('email')
            ->add('email', 'unique', ['rule' => 'validateUnique', 'provider' => 'table'])
            ->notEmpty('password');

        $validator->add('new_password', 'custom', [
            'rule' => function ($value, $context) {
                if ($value !== $context['data']['confirm_password']) {
                    return false;
                }
                return true;
            },
            'message' => __('Passwords are not equal!'),
        ]);

        $validator->add('confirm_password', 'custom', [
            'rule' => function ($value, $context) {
                if ($value !== $context['data']['new_password']) {
                    return false;
                }
                return true;
            },
            'message' => __('Passwords are not equal.'),
        ]);

        return $validator;
    }

    /**
     * beforeSave Callback
     *
     * @param \Cake\Event\Event $event Event.
     * @param \Cake\ORM\Entity $entity Current entity.
     * @param array $options Options.
     * @return void
     */
    public function beforeSave($event, $entity, $options)
    {
        if (!empty($entity->new_password)) {
            $entity->password = $entity->new_password; // set for password-changes
        }
    }

    /**
     * This method generates an activation key for a new user.
     * This key will be mailed at the user so he can activate it's account.
     * For activation is needed: e-mail and activation-key
     *
     * @return string
     */
    public function generateActivationKey()
    {
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $charactersLength = strlen($characters);
        $activationKey = '';
        for ($i = 0; $i < 40; $i++) {
            $activationKey .= $characters[rand(0, $charactersLength - 1)];
        }
        return $activationKey;
    }

    /**
     * Checks if an user is allowed to do an action with a required activation-key
     *
     * User-data: e-mailaddress
     *
     * @param string $email E-mailaddress of the user.
     * @param string $activationKey Activation key of the user.
     * @return bool
     */
    public function validateActivationKey($email, $activationKey)
    {
        $query = $this->findByEmailAndActivationKey($email, $activationKey);

        if ($query->Count() > 0) {
            return true;
        }

        return false;
    }

    /**
     * Activates an user
     *
     * @param string $email E-mailaddress of the user.
     * @param string $activationKey Activation key of the user.
     * @return bool
     */
    public function activateUser($email, $activationKey)
    {
        if ($this->validateActivationKey($email, $activationKey)) {
            $user = $this->findByEmailAndActivationKey($email, $activationKey)->first();

            if ($user->active == 0) {
                $user->active = 1;
                $user->activation_key = null;
                if ($this->save($user)) {
                    return true;
                }
            }
        }

        return false;
    }
}


text:
/**
@module ember
*/
import { precompileJSON } from '@glimmer/compiler';
import { SerializedTemplateWithLazyBlock, TemplateFactory } from '@glimmer/interfaces';
import { templateFactory } from '@glimmer/opcode-compiler';
import { compileOptions, EmberPrecompileOptions } from 'ember-template-compiler';

let templateId = 0;

/**
  Uses HTMLBars `compile` function to process a string into a compiled template.

  This is not present in production builds.

  @private
  @method compile
  @param {String} templateString This is the string to be compiled by HTMLBars.
  @param {Object} options This is an options hash to augment the compiler options.
*/
export default function compile(
  templateSource: string,
  options: Partial<EmberPrecompileOptions> = {},
  scopeValues: Record<string, unknown> = {}
): TemplateFactory {
  options.locals = options.locals ?? Object.keys(scopeValues ?? {});
  let [block, usedLocals] = precompileJSON(templateSource, compileOptions(options));
  let reifiedScopeValues = usedLocals.map((key) => scopeValues[key]);

  let templateBlock: SerializedTemplateWithLazyBlock = {
    id: String(templateId++),
    block: JSON.stringify(block),
    moduleName: options.moduleName ?? options.meta?.moduleName ?? '(unknown template module)',
    scope: reifiedScopeValues.length > 0 ? () => reifiedScopeValues : null,
    isStrictMode: options.strictMode ?? false,
  };

  return templateFactory(templateBlock);
}


text:
require 'test_helper'
require 'active_support/core_ext/hash/conversions'

class Model
  def to_json(options = {})
    { :a => 'b' }.to_json(options)
  end

  def to_xml(options = {})
    { :a => 'b' }.to_xml(options)
  end
end

class RenderersApiController < ActionController::API
  use ActionDispatch::ShowExceptions, Rails::API::PublicExceptions.new(Rails.public_path)

  def one
    render :json => Model.new
  end

  def two
    render :xml => Model.new
  end

  def boom
    raise "boom"
  end
end

class RenderersApiTest < ActionController::TestCase
  tests RenderersApiController

  def test_render_json
    get :one
    assert_response :success
    assert_equal({ :a => 'b' }.to_json, @response.body)
  end

  def test_render_xml
    get :two
    assert_response :success
    assert_equal({ :a => 'b' }.to_xml, @response.body)
  end
end

class RenderExceptionsTest < ActionDispatch::IntegrationTest
  def setup
    @app = RenderersApiController.action(:boom)
  end

  def test_render_json_exception
    get "/fake", {}, 'HTTP_ACCEPT' => 'application/json'
    assert_response :internal_server_error
    assert_equal 'application/json', response.content_type.to_s
    assert_equal({ :status => '500', :error => 'boom' }.to_json, response.body)
  end

  def test_render_xml_exception
    get "/fake", {}, 'HTTP_ACCEPT' => 'application/xml'
    assert_response :internal_server_error
    assert_equal 'application/xml', response.content_type.to_s
    assert_equal({ :status => '500', :error => 'boom' }.to_xml, response.body)
  end

  def test_render_fallback_exception
    get "/fake", {}, 'HTTP_ACCEPT' => 'text/csv'
    assert_response :internal_server_error
    assert_equal 'text/html', response.content_type.to_s
  end
end


text:
function [value,isterminal,direction] = event(~,y,params)
%EVENT Summary of this function goes here
%   Detailed explanation goes here
    isterminal = 1;
    direction = 0;
    if size(y,2) == 1
        y = y';
    end
    value = mod( y(:,1) - y(:,2) + pi, 2*pi) - pi - params.pinAngle;

end


text:
var fs = require('fs');
var b = require('bookmarkletify');
var browserstig = fs.readFileSync('browserstig.js').toString();
var example = fs.readFileSync('twitter-example.js').toString();
fs.writeFileSync('bookmarklet.js', b(browserstig + example));


text:
// ##### Part of the **[retold](https://stevenvelozo.github.io/retold/)** system
/**
* @license MIT
* @author <steven@velozo.com>
*/

const libFS = require('fs');

// File write functions
module.exports = (pState, pData, pPath, pFileName, fCallback) =>
{
	// Now write out the file
	pState.Libraries.DropBag.makeFolderRecursive(
		{
			File: pFileName,
			Path: pState.Behaviors.parseReportPath(pPath, pState),
			Data: pData,
			AutoCreateFolders: true,
		},
		(pCreateError) =>
		{
			// We shouldn't bail out because one template didn't load so don't alter the callback.
			if (pCreateError)
			{
				pState.Behaviors.stateLog(pState, 'Error making folder for report file stream: ' + pState.Behaviors.parseReportPath(pPath, pState) + ' -> ' + pFileName + ': ' + pCreateError, pCreateError);
			}

			const tmpReportFileStream = libFS.createWriteStream(pState.Behaviors.parseReportPath(pPath, pState) + pFileName);

			return fCallback(null, tmpReportFileStream);
		});
};


text:
import React from 'react';

import $ from 'jquery';
import { Foundation } from 'foundation-sites/js/foundation.core';
import { MediaQuery } from 'foundation-sites/js/foundation.util.mediaQuery';
import { ImageLoader } from 'foundation-sites/js/foundation.util.imageLoader';
import { Equalizer } from 'foundation-sites/js/foundation.equalizer';

class PortfolioAbout extends React.Component {
  constructor(props) {
    super(props);
    this.reInitEqualizer = this.reInitEqualizer.bind(this);
  }

  componentDidMount() {
    if (!$(document).foundation) {
      Foundation.addToJquery($);
    }
    new Equalizer($('#equalizer-portfolio-about'));
    addEventListener('resize', this.reInitEqualizer);
  }

  componentDidUpdate() {
    this.reInitEqualizer();
  }

  componentWillUnmount() {
    $('#equalizer-portfolio-about').foundation('destroy');
    removeEventListener('resize', this.reInitEqualizer);
  }

  reInitEqualizer() {
    Foundation.reInit($('#equalizer-portfolio-about'));
  }

  renderAboutSection(section) {
    const { title, description, image } = section;

    return(

{title}

            {description.map((item) =>
{item}
)}

    );
  }

  render() {
    const { aboutData } = this.props;

    return(

About hello world

            {aboutData['sections'].map((section) => this.renderAboutSection(section))}

    );
  }
}

export default PortfolioAbout;


text:
<?php

namespace Application\API\Repositories\Factories {

    use Zend\ServiceManager\FactoryInterface,
        Zend\ServiceManager\ServiceLocatorInterface,
        Application\API\Repositories\Implementations\ServicesEnquiryTypeRepository;

    class EnquiryTypeRepositoryFactory implements FactoryInterface {

        public function createService(ServiceLocatorInterface $serviceLocator) {
            return new ServicesEnquiryTypeRepository($serviceLocator->get('doctrine.entitymanager.orm_default'));
        }
    }
}


text:
"""
=============
Parsers Tests
=============

:Authors:
    Moritz Emanuel Beber
    Alexandra Mirela Grigore
    Nikolaus Sonnenschein
:Date:
    2011-04-10
:Copyright:
    Copyright(c) 2011 Jacobs University of Bremen. All rights reserved.
:File:
    test_parsers.py
"""

import os
import nose.tools as nt

from .. import networks


text:
using System.Windows.Controls;

namespace LaunchPad2.Controls
{
    public partial class NetworkPanel : UserControl
    {
        public NetworkPanel()
        {
            InitializeComponent();
        }
    }
}


text:
using namespace cv;
using namespace std;

namespace media {

PictureWatershedTransform::PictureWatershedTransform(ElementFactory *aFactory, const QString &aObjectName) :
    ElementBase(aFactory, aObjectName)
    {
    }

void PictureWatershedTransform::process()
    {
    vector<vector<Point> > contours;
    PictureRGBFrame srcFrame;
    foreach (const ElementBase *source, mSourceElementsReadySet)
        for (int i = 0; i < source->getFramesNo(); ++i)
            {
            const FrameBase *frame = source->getFrame(i);
            if (PointsFrame().isCopyable(*frame))
                {
                vector<Point> contour;
                contour.resize(frame->getDimensionT(PointsFrame::Index).mResolution);
                int point[PointsFrame::Dimensions] = {0, 0};
                for (point[PointsFrame::Index] = 0; point[PointsFrame::Index] < frame->getDimensionT(PointsFrame::Index).mResolution; ++point[PointsFrame::Index])
                    {
                    point[PointsFrame::Axis] = PointsFrame::XAxis;
                    contour[point[PointsFrame::Index]].x = frame->getSampleT(point);
                    point[PointsFrame::Axis] = PointsFrame::YAxis;
                    contour[point[PointsFrame::Index]].y = frame->getSampleT(point);
                    }
                contours.push_back(contour);
                }
            else if (srcFrame.isCopyable(*frame))
                {
                srcFrame.resizeAndCopyFrame(*frame);
                mPictureFrame.setSourceName(frame->getSourceName());
                }
            }

    IplImage *srcImg = (IplImage*)srcFrame;
    if (!srcImg || !contours.size())
        return;

    IplImage *markers = cvCreateImage(cvGetSize(srcImg), IPL_DEPTH_32S, 1);
    cvZero(markers);

    //draws contours on the markers image from CvSeq* contours
    for (size_t i = 0; i < contours.size(); ++i)
        drawContours(Mat(markers), contours, i, Scalar(i + 1, i + 1, i + 1), -1, 8, noArray(), -1);

    CvMat* color_tab = cvCreateMat(1, contours.size(), CV_8UC3);
    for (size_t i = 0; i < contours.size(); ++i)
        {
        uchar* ptr = color_tab->data.ptr + i*3;
        ptr[0] = (uchar)(theRNG()(180) + 50);
        ptr[1] = (uchar)(theRNG()(180) + 50);
        ptr[2] = (uchar)(theRNG()(180) + 50);
        }

    //segment the image using markers
    cvWatershed(srcImg, markers);

    IplImage *wshed = cvCloneImage(srcImg);
    cvZero(wshed);

    // paint the watershed image
    for (int i = 0; i < markers->height; ++i)
        for (int j = 0; j < markers->width; ++j)
        {
        int idx = CV_IMAGE_ELEM(markers, int, i, j);
        uchar* dst = &CV_IMAGE_ELEM(wshed, uchar, i, j*3);
        if (idx == -1)
            dst[0] = dst[1] = dst[2] = (uchar)255;
        else if (idx <= 0 || idx > (int)contours.size())
            dst[0] = dst[1] = dst[2] = (uchar)0; // should not get here
        else
            {
            uchar* ptr = color_tab->data.ptr + (idx-1)*3;
            dst[0] = ptr[0]; dst[1] = ptr[1]; dst[2] = ptr[2];
            }
        }

//    IplImage *img_gray = cvCloneImage(srcImg);
//    IplImage *img_bw = cvCreateImage(cvGetSize(srcImg), 8, 1);
//    cvCvtColor(img, img_bw, CV_BGR2GRAY);
//    cvCvtColor(img_bw, img_gray, CV_GRAY2BGR);
//    cvAddWeighted(wshed, 0.5, img_gray, 0.5, 0, wshed);
    mPictureFrame = *wshed;

    cvReleaseMat(&color_tab);
    cvReleaseImage(&wshed);
    cvReleaseImage(&markers);

    emit framesReady();
    }

} // namespace media


text:
touch ChangeLog
touch genfft/.depend

echo "PLEASE IGNORE WARNINGS AND ERRORS"

# paranoia: sometimes autoconf doesn't get things right the first time
rm -rf autom4te.cache
autoreconf --verbose --install --symlink --force
autoreconf --verbose --install --symlink --force
autoreconf --verbose --install --symlink --force

rm -f config.cache

# --enable-maintainer-mode enables build of genfft and automatic
# rebuild of codelets whenever genfft changes
(
    ./configure --disable-shared --enable-maintainer-mode --enable-threads $*
    (cd genfft; make depend)
)


text:
// Copyright (c) 2018 Google LLC.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.

using Google.Api.Gax.ResourceNames;
using Google.Cloud.Monitoring.V3;
using Google.Protobuf.WellKnownTypes;
using System;
using static Google.Cloud.Monitoring.V3.Aggregation.Types;
using static Google.Cloud.Monitoring.V3.AlertPolicy.Types;
using static Google.Cloud.Monitoring.V3.AlertPolicy.Types.Condition.Types;

/// <summary>
/// Creates an AlertPolicy and NotificationChannel for the duration
/// of the tests.
/// </summary>
public class AlertTestFixture : IDisposable
{
    public NotificationChannel CreateChannel()
    {
        var channel = new NotificationChannel()
        {
            Type = "email",
            DisplayName = "Email joe.",
            Description = "AlertTest.cs",
            Labels = { { "email_address", "joe@example.com" } },
            UserLabels =
                {
                    { "role", "operations" },
                    { "level", "5" },
                    { "office", "california_westcoast_usa" },
                    { "division", "fulfillment"}
                }
        };
        return NotificationChannelClient.CreateNotificationChannel(
            new ProjectName(ProjectId), channel);
    }

    public AlertTestFixture()
    {
        Channel = CreateChannel();
        string filter = @"metric.label.state=""blocked"" AND
            metric.type=""agent.googleapis.com/processes/count_by_state""
            AND resource.type=""gce_instance""";
        Alert = AlertPolicyClient.CreateAlertPolicy(
            new ProjectName(ProjectId), new AlertPolicy()
            {
                DisplayName = "AlertTest.cs",
                Enabled = false,
                Combiner = ConditionCombinerType.Or,
                Conditions =
            {
                    new AlertPolicy.Types.Condition()
                    {
                        ConditionThreshold = new MetricThreshold()
                        {
                            Filter = filter,
                            Aggregations = {
                                new Aggregation() {
                                    AlignmentPeriod = Duration.FromTimeSpan(
                                        TimeSpan.FromSeconds(60)),
                                    PerSeriesAligner = Aligner.AlignMean,
                                    CrossSeriesReducer = Reducer.ReduceMean,
                                    GroupByFields = {
                                        "project",
                                        "resource.label.instance_id",
                                        "resource.label.zone"
                                    }
                                }
                            },
                            DenominatorFilter = "",
                            DenominatorAggregations = {},
                            Comparison = ComparisonType.ComparisonGt,
                            ThresholdValue = 100.0,
                            Duration = Duration.FromTimeSpan(
                                TimeSpan.FromSeconds(900)),
                            Trigger = new Trigger() {
                                Count = 1,
                                Percent = 0.0,
                            }
                        },
                        DisplayName = "AlertTest.cs",
                    }
            },
            });
    }

    public NotificationChannel Channel { get; private set; }
    public AlertPolicy Alert { get; private set; }

    public string ProjectId { get; private set; } =
        Environment.GetEnvironmentVariable("GOOGLE_PROJECT_ID");

    public NotificationChannelServiceClient NotificationChannelClient
    { get; private set; } = NotificationChannelServiceClient.Create();

    public AlertPolicyServiceClient AlertPolicyClient
    { get; private set; } = AlertPolicyServiceClient.Create();

    public void Dispose()
    {
        NotificationChannelClient.DeleteNotificationChannel(
            NotificationChannelName.Parse(Channel.Name), true);
        AlertPolicyClient.DeleteAlertPolicy(
            AlertPolicyName.Parse(Alert.Name));
    }
}


text:
class OperatorGroupUtil:
    common_starts = ["layer_norm", "matmul_v2", "matmul"]

    @staticmethod
    def get_ranks(seq):
        """Get rank array of the given seq by doubled algorithm."""
        ordered_seq = sorted(list(set(seq)))
        item_to_rank = {item: idx for idx, item in enumerate(ordered_seq)}
        inter_ranks = [item_to_rank[item] for item in seq]

        length = len(inter_ranks)
        power = 0
        interval = 2**power
        while interval < length:
            for idx, item in enumerate(inter_ranks):
                if idx + interval >= length:
                    inter_ranks[idx] = [item, -1]
                else:
                    inter_ranks[idx] = [item, inter_ranks[idx + interval]]

            tmp = []
            for item in inter_ranks:
                if item not in tmp:
                    tmp.append(item)
            tmp.sort(key=lambda x: (x[0], x[1]))
            item_to_rank = {}
            for idx, val in enumerate(tmp):
                key = ",".join(str(item) for item in val)
                item_to_rank[key] = idx

            inter_ranks = [
                item_to_rank[",".join(str(val) for val in item)]
                for item in inter_ranks
            ]
            power += 1
            interval = 2**power

        return inter_ranks

    @staticmethod
    def get_suffixes(ranks):
        """Get suffix array by the given rank array."""
        suffixes = [0 for idx in range(len(ranks))]
        for idx, item in enumerate(ranks):
            suffixes[item] = idx
        return suffixes

    @staticmethod
    def get_heights(suffixes, seq):
        """Get height array by the suffix array and seq"""
        heights = [-1 for i in range(len(suffixes))]
        for i in range(1, len(seq)):
            x = seq[suffixes[i - 1] :]
            y = seq[suffixes[i] :]
            max_len = len(x) if len(x) > len(y) else len(y)
            same_count = 0
            for j in range(max_len):
                if j >= len(x) or j >= len(y):
                    break
                else:
                    if x[j] == y[j]:
                        same_count += 1
                    else:
                        break
            heights[i] = same_count

        return heights

    @staticmethod
    def get_longest_repeated_sub_seq(suffixes, heights, seq):
        """Get longest repeated sub sequence by suffix array algorithm."""
        length = len(seq)
        if length <= 1:
            return None
        k = length // 2
        height_groups = []
        longest_sub_seq = None
        longest_sub_seqs = []

        while k >= 2:
            height_group = []
            for i in range(1, len(heights)):
                if heights[i] >= k:
                    if i == 1:
                        height_group.append(0)
                    height_group.append(i)
                else:
                    if i == 1:
                        height_groups.append([0])
                        height_group = [i]
                    else:
                        height_groups.append(height_group)
                        height_group = [i]

            if height_group:
                height_groups.append(height_group)

            for height_group in height_groups:
                suffix_group = []
                index_group = []
                for idx in height_group:
                    suffix_group.append(idx)
                    index_group.append(suffixes[idx])

                max_index = max(index_group)
                min_index = min(index_group)
                if max_index - min_index >= k:
                    longest_sub_seq = seq[min_index : min_index + k]
                    if longest_sub_seq[0] in OperatorGroupUtil.common_starts:
                        return longest_sub_seq
            if longest_sub_seq is not None:
                return longest_sub_seq

            k -= 1
            height_groups = []

        return longest_sub_seq

    @staticmethod
    def get_decomposed_sub_seq(seq):
        """Get decomposed sub seq s by seq S such as s * R = S."""
        if not seq:
            return seq

        decomposed_sub_seq = seq
        seq_len = len(seq)
        if seq_len == 1:
            return decomposed_sub_seq
        else:
            for interval in range(2, seq_len + 1):
                if seq_len % interval == 0:
                    repeated_times = seq_len // interval
                    decomposed_sub_seq = seq[0:interval]
                    decomposed = True
                    for j in range(1, repeated_times + 1):
                        sub_seq = seq[interval * (j - 1) : interval * j]
                        if sub_seq != decomposed_sub_seq:
                            decomposed = False
                            break
                    if decomposed:
                        return decomposed_sub_seq

        return decomposed_sub_seq

    @staticmethod
    def replace_by_decomposed_seq(sub_seq, seq):
        """Replace seq by sub seq."""
        if not sub_seq:
            return seq

        result = []
        sub_seq_len = len(sub_seq)
        i = 0
        while i < len(seq):
            if seq[i : i + sub_seq_len] == sub_seq:
                result.append(seq[i : i + sub_seq_len])
                i += sub_seq_len
            else:
                result.append(seq[i])
                i += 1

        return result

    @staticmethod
    def stop_replace(seq):
        for item in seq:
            if not isinstance(item, list):
                return False
        return True

class RuleBasedTuner:
    def __init__(self, dist_context, mode="train"):
        self._dist_context = dist_context
        self._mode = mode

    def group_operators(self, ops):
        """
        Group operators to layers.

        Args:
            ops (list): A operator list.

        Returns:
            List: The list contains the list of operators which belong to the same layer.
        """
        seq = [op.type for op in ops]

        while not OperatorGroupUtil.stop_replace(seq):
            to_replace_seq = []
            to_replace_idxes = []
            has_append = False
            for idx, item in enumerate(seq):
                if not isinstance(item, list):
                    has_append = True
                    to_replace_seq.append(item)
                    to_replace_idxes.append(idx)
                elif isinstance(seq, list) and not has_append:
                    continue
                elif isinstance(seq, list) and has_append:
                    break

            ranks = OperatorGroupUtil.get_ranks(to_replace_seq)
            suffixes = OperatorGroupUtil.get_suffixes(ranks)
            heights = OperatorGroupUtil.get_heights(suffixes, to_replace_seq)
            longest_sub_seq = OperatorGroupUtil.get_longest_repeated_sub_seq(
                suffixes, heights, to_replace_seq
            )
            has_merged = False
            if longest_sub_seq is None:
                for i in range(to_replace_idxes[-1] + 1, len(seq)):
                    if isinstance(seq[i], list):
                        seq[i] = to_replace_seq + seq[i]
                        has_merged = True
                        break
                if not has_merged:
                    for i in range(to_replace_idxes[0] - 1, -1, -1):
                        if isinstance(seq[i], list):
                            seq[i].extend(to_replace_seq)
                            has_merged = True
                            break
                if not has_merged:
                    seq = [to_replace_seq]
                    break

            decomposed_sub_seq = OperatorGroupUtil.get_decomposed_sub_seq(
                longest_sub_seq
            )
            to_replace_seq = OperatorGroupUtil.replace_by_decomposed_seq(
                decomposed_sub_seq, to_replace_seq
            )
            result = seq[: to_replace_idxes[0]]
            if not has_merged:
                result.extend(to_replace_seq)
            result.extend(seq[to_replace_idxes[-1] + 1 :])
            seq = result

        layers = []
        idx = 0
        for groups in seq:
            layer = []
            for op in groups:
                layer.append(ops[idx])
                idx += 1
            layers.append(layer)

        return layers


text:
package edu.ncsu.monopoly;

import edu.ncsu.monopoly.gui.GoCellInfoFormatter;
import edu.ncsu.monopoly.gui.InfoFormatter;
import junit.framework.TestCase;

public class CellInfoFormatterTest extends TestCase {

    public void testGoCellTest() {
        GoCell cell = new GoCell();
        String goLabel = GoCellInfoFormatter.GO_CELL_LABEL;
        assertEquals(goLabel, InfoFormatter.cellInfo(cell));
    }

    public void testPropertyCellText() {
        String propertyName = "Blue 1";
        String propertyColor = "blue";
        String ownerName = "Owner1";
        int numHouses = 2;
        int propertyValue = 120;
        String propertyLabel = "" + propertyName + "
" +
				"$" + propertyValue +
				"
Owner: " + ownerName +
				"
* " + numHouses +
				"";
        PropertyCell cell = new PropertyCell();
        cell.setName(propertyName);
        cell.setPrice(propertyValue);
        cell.setColorGroup(propertyColor);
        Player p = new Player();
        p.setName(ownerName);
        cell.setOwner(p);
        cell.setNumHouses(numHouses);
        assertEquals(propertyLabel, InfoFormatter.cellInfo(cell));
    }
}


text:
package trustedresources

import "errors"

// ErrorResourceVerificationFailed is returned when trusted resources fails verification.
var ErrorResourceVerificationFailed = errors.New("resource verification failed")


text:
'use strict';

var should = require('should');
var util = require('util');
var _ = require('underscore');

var testUtils = require('../../../util/util');
var CLITest = require('../../../framework/arm-cli-test');
var NetworkTestUtil = require('../../../util/networkTestUtil');
var networkUtil = new NetworkTestUtil();

var testPrefix = 'arm-network-nsg-tests',
  groupName = 'xplat-test-nsg',
  location;

var nsgProp = {
  name: 'test-nsg',
  tags: networkUtil.tags,
  newTags: networkUtil.newTags
};

var requiredEnvironment = [{
  name: 'AZURE_VM_TEST_LOCATION',
  defaultValue: 'eastus'
}];

describe('arm', function () {
  describe('network', function () {
    var suite, retry = 5;
    var networkUtil = new NetworkTestUtil();

    before(function (done) {
      suite = new CLITest(this, testPrefix, requiredEnvironment);
      suite.setupSuite(function () {
        location = process.env.AZURE_VM_TEST_LOCATION;
        groupName = suite.isMocked ? groupName : suite.generateId(groupName, null);

        nsgProp.group = groupName;
        nsgProp.location = location;
        nsgProp.name = suite.isMocked ? nsgProp.name : suite.generateId(nsgProp.name, null);

        done();
      });
    });
    after(function (done) {
      networkUtil.deleteGroup(groupName, suite, function () {
        suite.teardownSuite(done);
      });
    });
    beforeEach(function (done) {
      suite.setupTest(done);
    });
    afterEach(function (done) {
      suite.teardownTest(done);
    });

    describe('nsg', function () {
      it('create should create nsg', function (done) {
        networkUtil.createGroup(groupName, location, suite, function () {
          var cmd = 'network nsg create -g {group} -n {name} -l {location} -t {tags} --json'.formatArgs(nsgProp);
          testUtils.executeCommand(suite, retry, cmd, function (result) {
            result.exitStatus.should.equal(0);
            var nsg = JSON.parse(result.text);
            nsg.name.should.equal(nsg.name);
            networkUtil.shouldHaveTags(nsg);
            networkUtil.shouldBeSucceeded(nsg);
            done();
          });
        });
      });
      it('set should modify nsg', function (done) {
        var cmd = 'network nsg set -g {group} -n {name} -t {newTags} --json'.formatArgs(nsgProp);
        testUtils.executeCommand(suite, retry, cmd, function (result) {
          result.exitStatus.should.equal(0);
          var nsg = JSON.parse(result.text);
          nsg.name.should.equal(nsg.name);
          networkUtil.shouldAppendTags(nsg);
          networkUtil.shouldBeSucceeded(nsg);
          done();
        });
      });
      it('show should display details about nsg', function (done) {
        var cmd = 'network nsg show -g {group} -n {name} --json'.formatArgs(nsgProp);
        testUtils.executeCommand(suite, retry, cmd, function (result) {
          result.exitStatus.should.equal(0);
          var nsg = JSON.parse(result.text);
          nsg.name.should.equal(nsg.name);
          done();
        });
      });
      it('list should display all nsg in resource group', function (done) {
        var cmd = 'network nsg list -g {group} --json'.formatArgs(nsgProp);
        testUtils.executeCommand(suite, retry, cmd, function (result) {
          result.exitStatus.should.equal(0);
          var nsgs = JSON.parse(result.text);
          _.some(nsgs, function (nsg) {
            return nsg.name === nsgProp.name;
          }).should.be.true;
          done();
        });
      });
      it('delete should delete nsg', function (done) {
        var cmd = 'network nsg delete -g {group} -n {name} --quiet --json'.formatArgs(nsgProp);
        testUtils.executeCommand(suite, retry, cmd, function (result) {
          result.exitStatus.should.equal(0);

          cmd = 'network nsg show -g {group} -n {name} --json'.formatArgs(nsgProp);
          testUtils.executeCommand(suite, retry, cmd, function (result) {
            result.exitStatus.should.equal(0);
            var nsg = JSON.parse(result.text);
            nsg.should.be.empty;
            done();
          });
        });
      });
    });
  });
});