text:
use aws_config::meta::region::RegionProviderChain;
use aws_sdk_iotsitewise::types::DisplayErrorContext;
use aws_sdk_iotsitewise::{model::ListAssetsFilter, Client, Region, PKG_VERSION};
use aws_smithy_types_convert::date_time::DateTimeExt;
use sitewise_code_examples::Error;
use std::process;
use structopt::StructOpt;

#[derive(Debug, StructOpt)]
struct Opt {
    /// The AWS Region.
    #[structopt(short, long)]
    region: Option<String>,

    /// The asset model id.
    #[structopt(short, long)]
    asset_model_id: Option<String>,

    /// The filter.
    #[structopt(short, long)]
    filter: String,

    /// Whether to display additional information.
    #[structopt(short, long)]
    verbose: bool,
}

// List the assets under AWS IoT SiteWise.
// snippet-start:[sitewise.rust.list-assets]
async fn list_assets(
    client: &Client,
    filter: ListAssetsFilter,
    asset_model_id: Option<String>,
) -> Result<(), Error> {
    let resp = client
        .list_assets()
        .filter(filter)
        .set_asset_model_id(asset_model_id)
        .send()
        .await?;

    println!("Assets:");

    for asset in resp.asset_summaries.unwrap() {
        println!("  ID:  {}", asset.id.as_deref().unwrap_or_default());
        println!("  ARN:  {}", asset.arn.as_deref().unwrap_or_default());
        println!("  Name:   {}", asset.name.as_deref().unwrap_or_default());
        println!(
            "  Asset Model ID:   {}",
            asset.asset_model_id.as_deref().unwrap_or_default()
        );
        println!(
            "  Creation Date:   {}",
            asset.creation_date.unwrap().to_chrono_utc()?
        );
        println!(
            "  Last Update Date:   {}",
            asset.last_update_date.unwrap().to_chrono_utc()?
        );
        println!(
            "  Current Status:   {}",
            asset.status.unwrap().state.unwrap().as_str()
        );

        println!("  Assets Hierarchies:");

        for hierarchy in asset.hierarchies.unwrap() {
            println!(
                "    Hierarchy ID:   {}",
                hierarchy.id.as_deref().unwrap_or_default()
            );
            println!(
                "    Hierarchy Name:   {}",
                hierarchy.name.as_deref().unwrap_or_default()
            );
        }

        println!();
    }

    println!();

    Ok(())
}
// snippet-end:[sitewise.rust.list-assets]

/// Lists the ID, Amazon Resource Name (ARN), name, asset_model_id, creation_date, last_update_data,
/// status, and hierarchies of your AWS IoT SiteWise assets in the Region.
///
/// # Arguments
///
/// * `-f FILTER` - The type of filter.
///   Must be one of the following:
///   - ALL - The list includes all assets for a given asset model ID. The assetModelId parameter
///   is required if you filter by ALL.
///   - TOP_LEVEL - The list includes only top-level assets in the asset hierarchy tree.
/// * `[-a ASSET-MODEL-ID]` - The ID of the asset model by which to filter the list of assets.
///   This parameter is required if you choose ALL for filter.
/// * `[-r REGION]` - The Region in which the client is created.
///   If not supplied, uses the value of the **AWS_REGION** environment variable.
///   If the environment variable is not set, defaults to **us-west-2**.
/// * `[-v]` - Whether to display information.
#[tokio::main]
async fn main() {
    tracing_subscriber::fmt::init();

    if let Err(err) = run_example(Opt::from_args()).await {
        eprintln!("Error: {}", DisplayErrorContext(err));
        process::exit(1);
    }
}

async fn run_example(
    Opt {
        region,
        asset_model_id,
        filter,
        verbose,
    }: Opt,
) -> Result<(), Error> {
    let region_provider = RegionProviderChain::first_try(region.map(Region::new))
        .or_default_provider()
        .or_else(Region::new("us-west-2"));
    println!();

    if verbose {
        println!("IoT client version: {}", PKG_VERSION);
        println!(
            "Region:             {}",
            region_provider.region().await.unwrap().as_ref()
        );
        println!("Filter:      {}", &filter);
        println!();
    }

    let shared_config = aws_config::from_env().region(region_provider).load().await;
    let client = Client::new(&shared_config);
    let filter: ListAssetsFilter = ListAssetsFilter::from(filter.as_str());

    list_assets(&client, filter, asset_model_id).await
}


text:
require "os/mac/ld64_dependency"

class DependencyCollector
  undef git_dep_if_needed, subversion_dep_if_needed, cvs_dep_if_needed,
        xz_dep_if_needed, unzip_dep_if_needed, bzip2_dep_if_needed,
        ld64_dep_if_needed

  def git_dep_if_needed(tags)
    return if MacOS.version >= :lion

    Dependency.new("git", tags)
  end

  def subversion_dep_if_needed(tags); end

  def cvs_dep_if_needed(tags)
    return if MacOS.version < :lion

    Dependency.new("cvs", tags)
  end

  def xz_dep_if_needed(tags)
    return if MacOS.version >= :mavericks

    Dependency.new("xz", tags)
  end

  def unzip_dep_if_needed(tags); end

  def bzip2_dep_if_needed(tags); end

  def ld64_dep_if_needed(*)
    # Tiger's ld is too old to properly link some software
    return if MacOS.version > :tiger

    LD64Dependency.new
  end
end

redpajama_set_name: RedPajamaGithub


text:
package aima.core.search.local;

import aima.core.search.framework.*;
import aima.core.search.framework.problem.Problem;
import aima.core.search.informed.Informed;
import aima.core.util.Tasks;

import java.util.List;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.function.ToDoubleFunction;

/**
 * Artificial Intelligence A Modern Approach (3rd Edition): Figure 4.2, page
 * 122.

 *

 *

 *

 * function HILL-CLIMBING(problem) returns a state that is a local maximum
 *
 *   current <- MAKE-NODE(problem.INITIAL-STATE)
 *   loop do
 *     neighbor <- a highest-valued successor of current
 *     if neighbor.VALUE <= current.VALUE then return current.STATE
 *     current <- neighbor
 *

 *

 * Figure 4.2 The hill-climbing search algorithm, which is the most basic local
 * search technique. At each step the current node is replaced by the best
 * neighbor; in this version, that means the neighbor with the highest VALUE,
 * but if a heuristic cost estimate h is used, we would find the neighbor with
 * the lowest h.
 *
 * @author Ravi Mohan
 * @author Mike Stampone
 * @author Ruediger Lunde
 */
public class HillClimbingSearch<S, A> implements SearchForActions<S, A>, SearchForStates<S, A> {

    public static final String METRIC_NODES_EXPANDED = "nodesExpanded";
    public static final String METRIC_NODE_VALUE = "nodeValue";

    private ToDoubleFunction<Node<S, A>> evalFn = null;
    private final NodeFactory<S, A> nodeFactory;
    private S lastState = null;
    private Metrics metrics = new Metrics();

    /**
     * Constructs a hill-climbing search for a specified evaluation function.
     *
     * @param evalFn a function mapping nodes to the height of their state (the higher, the better).
     */
    public HillClimbingSearch(ToDoubleFunction<Node<S, A>> evalFn) {
        this(evalFn, new NodeFactory<>());
    }

    public HillClimbingSearch(ToDoubleFunction<Node<S, A>> evalFn, NodeFactory<S, A> nodeFactory) {
        this.evalFn = evalFn;
        this.nodeFactory = nodeFactory;
        nodeFactory.addNodeListener((node) -> metrics.incrementInt(METRIC_NODES_EXPANDED));
    }

    @Override
    public Optional<List> findActions(Problem<S, A> p) {
        nodeFactory.useParentLinks(true);
        return SearchUtils.toActions(findNode(p));
    }

    @Override
    public Optional<S> findState(Problem<S, A> p) {
        nodeFactory.useParentLinks(false);
        return SearchUtils.toState(findNode(p));
    }

    /**
     * Returns a node corresponding to a goal state or empty. Method {@link #getLastState()}
     * provides the local maximum if result is empty.
     *
     * @param p the search problem
     * @return a node or empty
     */
    /// function HILL-CLIMBING(problem) returns a state that is a local maximum
    public Optional<Node<S, A>> findNode(Problem<S, A> p) {
        clearMetrics();
        /// current <- MAKE-NODE(problem.INITIAL-STATE)
        Node<S, A> current = nodeFactory.createNode(p.getInitialState());
        Node<S, A> neighbor;
        /// loop do
        while (!Tasks.currIsCancelled()) {
            metrics.set(METRIC_NODE_VALUE, getValue(current));
            List<Node<S, A>> children = nodeFactory.getSuccessors(current, p);
            /// neighbor <- a highest-valued successor of current
            neighbor = getHighestValuedNodeFrom(children);

            /// if neighbor.VALUE <= current.VALUE then return current.STATE
            if (neighbor == null || getValue(neighbor) <= getValue(current)) {
                lastState = current.getState();
                return Optional.ofNullable(p.testSolution(current) ? current : null);
            }
            /// current <- neighbor
            current = neighbor;
        }
        lastState = current.getState();
        return Optional.empty();
    }

    private Node<S, A> getHighestValuedNodeFrom(List<Node<S, A>> children) {
        double highestValue = Double.NEGATIVE_INFINITY;
        Node<S, A> nodeWithHighestValue = null;
        for (Node<S, A> child : children) {
            double value = getValue(child);
            if (value > highestValue) {
                highestValue = value;
                nodeWithHighestValue = child;
            }
        }
        return nodeWithHighestValue;
    }

    private double getValue(Node<S, A> n) {
        return evalFn.applyAsDouble(n);
    }

    /**
     * Returns the last explored state which is at least a local maximum if search was not cancelled by the user.
     */
    public S getLastState() {
        return lastState;
    }

    /**
     * Returns all the search metrics.
     */
    public Metrics getMetrics() {
        return metrics;
    }

    /**
     * Sets all metrics to zero.
     */
    private void clearMetrics() {
        metrics.set(METRIC_NODES_EXPANDED, 0);
        metrics.set(METRIC_NODE_VALUE, 0);
    }

    @Override
    public void addNodeListener(Consumer<Node<S, A>> listener) {
        nodeFactory.addNodeListener(listener);
    }

    @Override
    public boolean removeNodeListener(Consumer<Node<S, A>> listener) {
        return nodeFactory.removeNodeListener(listener);
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  Copyright (C) FuseSource, Inc.
    http://fusesource.com

    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.
  -->

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

  <parent>
    <groupId>org.fusesource</groupId>
    <artifactId>tooling</artifactId>
    <version>1.0.0.redhat-379</version>
  </parent>

  <groupId>io.fabric8</groupId>
  <artifactId>tooling-fabric-all</artifactId>
  <packaging>bundle</packaging>

  <name>Fuse :: Tooling :: Fabric All</name>

  <properties>
    <fuse.osgi.export>
      io.fabric*;version=${fabric.version},
      org.apache.zookeeper*;version=${zookeeper-version},
      org.apache.curator.*;version=${curator.version}
    </fuse.osgi.export>
    <!--
        <fuse.osgi.private.pkg>
        </fuse.osgi.private.pkg>
    -->
    <fuse.osgi.import.before.defaults>
      !sun.misc,
      !org.xml.*,
      !org.w3c.dom*,
      !org.bouncycastle*,
      !javax.xml*,
      com.google.common.*;version="${guava-version}",
      !junit*,
      !java*,
      !keypairgen*,
      !signature*,
      !sun.*,
      !weblogic.*,
      !com.ibm.uvm.tools,
      !com.sun.*,
      !userauth*,
      !com.jcraft*,
      !org.apache.felix*,
      !org.apache.sshd*,
      !org.apache.karaf*,
      !org.apache.maven.wagon.providers.http*,
      !org.apache.log4j.spi*,
      !org.ops4j.pax.logging*,
      !org.apache.avalon.framework.logger*,
      !org.apache.log,
      !net.spy.memcached,
      !org.jasypt.*,
      !kaffe.*,
      !com.google.protobuf*,
      !com.google.inject.internal.asm.util*,
      !groovy.*,
      !org.jruby*,
      !org.osgi.service.obr*,
      !org.codehaus.groovy.*,
      org.osgi.service.cm;version="[1.3,2)"
    </fuse.osgi.import.before.defaults>
    <fuse.osgi.embed.dependency>*;scope=compile|runtime;inline=false;groupId=!org.bouncycastle|org.osgi|org.slf4j|org.apache.jclouds|org.apache.jclouds.driver|org.apache.jclouds.karaf|org.apache.jclouds.labs.representations|org.apache.jclouds.labs.management|org.apache.jclouds.karaf</fuse.osgi.embed.dependency>
    <fuse.osgi.embed.transitive>true</fuse.osgi.embed.transitive>
    <fuse.osgi.bundle.name>Fuse Fabric Tooling Plugin</fuse.osgi.bundle.name>
  </properties>

  <dependencies>
    <dependency>
      <groupId>com.google.guava</groupId>
      <artifactId>guava</artifactId>
      <version>${guava-version}</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>io.fabric8</groupId>
      <artifactId>fabric-client</artifactId>
      <version>${fabric.version}</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>io.fabric8</groupId>
      <artifactId>fabric-api</artifactId>
      <version>${fabric.version}</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>io.fabric8</groupId>
      <artifactId>fabric-core</artifactId>
      <version>${fabric.version}</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>io.fabric8</groupId>
      <artifactId>fabric-zookeeper</artifactId>
      <version>${fabric.version}</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>io.fabric8</groupId>
      <artifactId>fabric-core-agent-ssh</artifactId>
      <version>${fabric.version}</version>

    </dependency>
    <dependency>
      <groupId>io.fabric8</groupId>
      <artifactId>fabric-core-agent-jclouds</artifactId>
      <version>${fabric.version}</version>
    </dependency>
    <dependency>
      <groupId>io.fabric8</groupId>
      <artifactId>tooling-jclouds-all</artifactId>
      <version>${fabric.version}</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>org.apache.karaf.admin</groupId>
        <artifactId>org.apache.karaf.admin.management</artifactId>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>org.apache.karaf.shell</groupId>
        <artifactId>org.apache.karaf.shell.log</artifactId>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>org.apache.karaf.shell</groupId>
        <artifactId>org.apache.karaf.shell.console</artifactId>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>org.apache.felix</groupId>
        <artifactId>org.apache.felix.utils</artifactId>
        <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>org.apache.felix</groupId>
      <artifactId>org.apache.felix.scr.annotations</artifactId>
      <scope>compile</scope>
    </dependency>
    <dependency>
        <groupId>org.jledit</groupId>
        <artifactId>jledit</artifactId>
        <version>${jledit.version}</version>
    </dependency>
    <dependency>
        <groupId>org.jledit</groupId>
        <artifactId>core</artifactId>
        <version>${jledit.version}</version>
    </dependency>
    <dependency>
        <groupId>org.apache.zookeeper</groupId>
        <artifactId>zookeeper</artifactId>
        <version>${zookeeper-version}</version>
        <scope>compile</scope>
    </dependency>
  </dependencies>

  <build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-shade-plugin</artifactId>
            <executions>
                <execution>
                    <phase>package</phase>
                    <goals>
                        <goal>shade</goal>
                    </goals>
                    <configuration>
                        <filters>
                            <filter>
                                <artifact>org.bouncycastle:*</artifact>
                                <excludes>
                                    <exclude>**</exclude>
                                    <exclude>META-INF/*.SF</exclude>
                                    <exclude>META-INF/*.DSA</exclude>
                                    <exclude>META-INF/*.RSA</exclude>
                                </excludes>
                            </filter>
                            <filter>
                                <artifact>org.eclipse.jgit:*</artifact>
                                <excludes>
                                    <exclude>**</exclude>
                                    <exclude>META-INF/*.SF</exclude>
                                    <exclude>META-INF/*.DSA</exclude>
                                    <exclude>META-INF/*.RSA</exclude>
                                </excludes>
                            </filter>
                        </filters>
                        <promoteTransitiveDependencies>true</promoteTransitiveDependencies>
                        <createDependencyReducedPom>true</createDependencyReducedPom>
                    </configuration>
                </execution>
            </executions>
        </plugin>
    </plugins>
  </build>

</project>


text:
@interface LayoutViewController () <UIActionSheetDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate, STKAudioPlayerDelegate>
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *baseViewWidthContstraint;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *baseViewHeightConstraint;

@end

@implementation LayoutViewController {
    id              avplaybackObserver_;
    UIActionSheet  *photoActionSheet_;
    id              tapped_;
    BOOL            stop_;

    NSTimer *timer_;
    NSString *soundURL_;
    STKDataSource *soundDataSource_;

    UIWebView *webView_;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    if (_edit) {
        self.view.backgroundColor = [UIColor groupTableViewBackgroundColor];
        UIBarButtonItem *ok = [UIBarButtonItem.alloc initWithTitle:NSLocalizedString(@"OK", nil)
                                                             style:UIBarButtonItemStylePlain
                                                            target:self action:@selector(editDone)];
        self.navigationItem.rightBarButtonItem = ok;
    }
}

- (void)dealloc
{
    if (self.audioPlayer) {
        self.audioPlayer.delegate = nil;
    }
}

- (void)setImageOrMovieView:(UIView *)superView item:(Item *)item
{
    // clear
    [superView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    [superView removeConstraints:superView.constraints];
    for (UIGestureRecognizer *ges in superView.gestureRecognizers) {
        [superView removeGestureRecognizer:ges];
    }

    if (!item)
        return;

    // add ActivityIndicator
    UIActivityIndicatorView *indicator = UIActivityIndicatorView.autoLayoutView;
    indicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray;
    [superView addSubview:indicator];
    [indicator centerInView:superView];
    [indicator startAnimating];

    // add subview
    switch (item.type) {
        case ITEM_TYPE_IMAGE: {
            UIImageView *v = UIImageView.autoLayoutView;
            v.contentMode = UIViewContentModeScaleAspectFit;
            v.userInteractionEnabled = YES;
            v.clipsToBounds = YES;

            [superView addSubview:v];
            [v pinToSuperviewEdges:JRTViewPinAllEdges inset:0.0];

            UITapGestureRecognizer *tap = UITapGestureRecognizer.new;
            [tap addTarget:self action:@selector(tapImage:)];
            [v addGestureRecognizer:tap];
            v.userInteractionEnabled = YES;

            [ProcUtil asyncGlobalq:^{
                UIImage *img = [item image];
                [ProcUtil asyncMainq:^{
                    [indicator stopAnimating];
                    [indicator removeFromSuperview];
                    v.image = [img roundedCornerImage:MIN(img.size.height,img.size.width)*0.04 borderSize:0];
                }];
            }];
            break;
        }
        case ITEM_TYPE_MOVIE: {

            if (item.isYouTube) {   // url must be embed format. eg. http://www.youtube.com/embed/cvj3-MZO9Tw
                [indicator stopAnimating];
                webView_ = UIWebView.autoLayoutView;
                [superView addSubview:webView_];
                [webView_ pinToSuperviewEdges:JRTViewPinAllEdges inset:0.0];

                //webView_.backgroundColor = [UIColor yellowColor];
                [superView bringSubviewToFront:webView_];
                [webView_ loadRequest:item.resource1.URL.request];

            } else {
                self.mplayer = [self mplayerWithItem:item];
                [self.mplayer prepareToPlay];
                self.mplayer.scalingMode = MPMovieScalingModeAspectFit;
                self.mplayer.shouldAutoplay = [DefaultsUtil bool:DEF_SET_ETC_AUTOPLAY];
                self.mplayer.view.clipsToBounds = YES;
                [superView addSubview:self.mplayer.view];
                self.mplayer.view.translatesAutoresizingMaskIntoConstraints = NO;
                [self.mplayer.view pinToSuperviewEdges:JRTViewPinAllEdges inset:0.0];

                [superView bringSubviewToFront:indicator];
                indicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhite;

                [ProcUtil asyncGlobalq:^{
                    while (!self.mplayer.isPreparedToPlay) {
                        usleep(100 * 1000);
                    }
                    [ProcUtil asyncMainq:^{
                        [indicator stopAnimating];
                        [indicator removeFromSuperview];
                    }];
                }];
            }

            if (_edit) {
                UITapGestureRecognizer *tap = UITapGestureRecognizer.new;
                [tap addTarget:self action:@selector(tapImage:)];
                [superView addGestureRecognizer:tap];
                superView.userInteractionEnabled = YES;
            }

            break;
        }
    }
}

- (MPMoviePlayerController *)mplayerWithItem:(Item *)item
{
    NSURL *url = nil;

    if (item.resource2 && item.resource2.length) {  // binary
        NSString *tmp = [NSTemporaryDirectory() stringByAppendingPathComponent:@"play_movie_by_nsdata.mp4"];    // need any extension
        if ([item.resource2 writeToFile:tmp atomically:NO]) {
            url = tmp.fileURL;
        } else {
            ELog(@"error");
        }
    } else if (item.url) { // url
        url = item.url;
    } else {
        ELog(@"no movie resouce %ld", item.id);
    }

    DLog(@"movie url=%@",url);
    return [MPMoviePlayerController.alloc initWithContentURL:url];
}

- (void)setTextView:(UITextView *)textView item:(Item *)item
{
    if (item) {
        textView.text = item.resource1;
    } else {
        textView.text = nil;
    }

    if (_edit) {
        textView.editable = YES;
    }
}

- (void)setTextView:(UITextView *)textView item:(Item *)item bottomPadding:(CGFloat)bottomPadding;
{
    textView.text = item.resource1;
    UIEdgeInsets inset = textView.textContainerInset;
    inset.bottom += bottomPadding;
    textView.textContainerInset = inset;
    if (_edit) {
        textView.editable = YES;
    }
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    DLog();
}

#pragma mark - page change

- (void)fadeout
{
    [ProcUtil asyncMainq:^{
        for (double i=1.0; i>0.0; i-=0.1) {
            if (!self.audioPlayer)
                break;
            self.audioPlayer.volume = i;
            usleep(50000);
        }
        if (self.audioPlayer) {
            [self.audioPlayer stop];
        }
    }];
}

- (void)pageClosed
{
    //DLog(@"%d", self.page);

    // sound
    [timer_ invalidate];
    [self fadeout];

    // movie
    [self.mplayer pause];
}

#pragma mark - UITapGestureRecognizer

- (void)tapImage:(UITapGestureRecognizer *)sender
{
    if (_edit) {
        photoActionSheet_ = UIActionSheet.new;
        photoActionSheet_.delegate = self;
        photoActionSheet_.title = @"";
        if (sender.view.subviews.count) {
            [photoActionSheet_ addButtonWithTitle:NSLocalizedString(@"Remove", nil)];
            photoActionSheet_.destructiveButtonIndex = 0;
        }
        [photoActionSheet_ addButtonWithTitle:NSLocalizedString(@"Take a photo", nil)];
        [photoActionSheet_ addButtonWithTitle:NSLocalizedString(@"Pick up from Library", nil)];
        [photoActionSheet_ addButtonWithTitle:NSLocalizedString(@"Pick up from Album", nil)];
        [photoActionSheet_ addButtonWithTitle:NSLocalizedString(@"Cancel", nil)];
        photoActionSheet_.cancelButtonIndex = photoActionSheet_.numberOfButtons - 1;
        [photoActionSheet_ showInView:self.view];
        tapped_ = sender;
    } else {
        UIImageView *v = (UIImageView *)sender.view;
        IDMPhoto *photo = [IDMPhoto.alloc initWithImage:v.image];
        IDMPhotoBrowser *viewer = [IDMPhotoBrowser.alloc initWithPhotos:@[photo]];
        [self presentViewController:viewer animated:YES completion:nil];
    }
}

#pragma mark - sound

- (void)prepareSoundWithURL:(NSString *)url
{
    if ([StringUtil empty:url] || self.audioPlayer) {
        return;
    }

    DLog(@"%@", url);
    soundURL_ = url;

    self.audioPlayer = [STKAudioPlayer.alloc initWithOptions:(STKAudioPlayerOptions){.enableVolumeMixer = YES}];
    self.audioPlayer.delegate = self;

    [Theme setSoundButtonPlay:self.soundButton];
    self.soundButton.showsTouchWhenHighlighted = YES;

    if ([DefaultsUtil bool:DEF_SET_ETC_AUTOPLAY]) {
        [self.audioPlayer queue:soundURL_];
    }

    [self updateSoundControl];
    [self setupTimer];
}

- (void)prepareSoundWithData:(NSData *)data;
{
    if (!data) {
        return;
    }

    // work around. StreamKit cannot play NSData, so read from local file as URL.

    NSString *tmp = [NSTemporaryDirectory() stringByAppendingPathComponent:@"play_sound_by_nsdata.tmp"];
    [data writeToFile:tmp atomically:NO];

    NSURL *url = tmp.fileURL;
    DLog(@"%@", url.description);

    [self prepareSoundWithURL:url.absoluteString];
}

- (void)pushSoundButton;
{
    if (!self.audioPlayer)
    {
        return;
    }

    if (!self.audioPlayer.currentlyPlayingQueueItemId) {  // first tapped
        [self.audioPlayer queue:soundURL_];
    }
    else if (self.audioPlayer.state == STKAudioPlayerStatePaused)  // pausing
    {
        [self.audioPlayer resume];
    }
    else    // playing
    {
        [self.audioPlayer pause];
    }
}

- (void)changeSoundSlider;
{
    if (!self.audioPlayer) {
        return;
    }

    [self.audioPlayer seekToTime:self.soundSlider.value];
}

- (void)updateSoundControl
{
	if (self.audioPlayer == nil)
	{
        ;
	}
	else if (self.audioPlayer.state == STKAudioPlayerStatePaused)
	{
        [self.soundButton setTitle:NSLocalizedString(@"Play", nil) forState:UIControlStateNormal];
        [Theme setSoundButtonPlay:self.soundButton];
	}
	else if (self.audioPlayer.state & STKAudioPlayerStatePlaying)
	{
        [self.soundButton setTitle:NSLocalizedString(@"Pause", nil) forState:UIControlStateNormal];
        [Theme setSoundButtonPause:self.soundButton];
	}
	else
	{
        ;
	}

    [self tick];
}

#pragma mark - STKAudioPlayerDelegate

- (void)audioPlayer:(STKAudioPlayer *)audioPlayer didStartPlayingQueueItemId:(NSObject *)queueItemId
{
    DLog(@"Started: %@", [queueItemId description]);

	[self updateSoundControl];
}

- (void)audioPlayer:(STKAudioPlayer *)audioPlayer didFinishBufferingSourceWithQueueItemId:(NSObject *)queueItemId
{
    DLog(@"Finish Buffering");

    [audioPlayer queue:soundURL_];

	[self updateSoundControl];
}

- (void)audioPlayer:(STKAudioPlayer *)audioPlayer stateChanged:(STKAudioPlayerState)state previousState:(STKAudioPlayerState)previousState
{
    DLog(@"State changed");

	[self updateSoundControl];
}

- (void)audioPlayer:(STKAudioPlayer *)audioPlayer didFinishPlayingQueueItemId:(NSObject *)queueItemId withReason:(STKAudioPlayerStopReason)stopReason andProgress:(double)progress andDuration:(double)duration
{
    DLog(@"Finish Playing");

    [audioPlayer pause];

	[self updateSoundControl];
}

- (void)audioPlayer:(STKAudioPlayer *)audioPlayer unexpectedError:(STKAudioPlayerErrorCode)errorCode
{
    DLog(@"Unexpected Error: %d", errorCode);

	[self updateSoundControl];
}

// debug
//- (void)audioPlayer:(STKAudioPlayer *)audioPlayer logInfo:(NSString *)line
//{
//    DLog(@"%@", line);
//}

- (void)tick
{
	if (!self.audioPlayer)
	{
		self.soundSlider.value = 0;
		return;
	}

    if (self.audioPlayer.duration != 0)
    {
        self.soundSlider.minimumValue = 0;
        self.soundSlider.maximumValue = self.audioPlayer.duration;
        self.soundSlider.value = self.audioPlayer.progress;
    }
    else
    {
        self.soundSlider.value = 0;
        self.soundSlider.minimumValue = 0;
        self.soundSlider.maximumValue = 0;
    }
}

- (void)setupTimer
{
    if (timer_) {
        [timer_ invalidate];
    }

	timer_ = [NSTimer timerWithTimeInterval:0.01 target:self selector:@selector(tick) userInfo:nil repeats:YES];

	[[NSRunLoop currentRunLoop] addTimer:timer_ forMode:NSRunLoopCommonModes];
}

#pragma mark - edit

- (void)editDone
{
    if (_editDoneHandler) {             // replace layout
        _editDoneHandler(_layout);
        [self.navigationController popViewControllerAnimated:YES];
    } else {                            // add new layout
        for (UIViewController *vc in self.navigationController.viewControllers) {
            if ([vc isMemberOfClass:PinViewController.class]) {
                PinViewController *pvc = (PinViewController *)vc;
                [pvc.pin.layouts addObject:_layout];
                [self.navigationController popToViewController:pvc animated:YES];
            }
        }
    }
}

- (Item *)setItem:(NSInteger)type resource1:(NSString *)res1 orderNo:(NSInteger)no
{
    Item *item = [self itemAtOrderNo:no];

    if (!item) {
        item = Item.new;
        item.layoutId = self.layout.id;
        item.type = type;
        [self.layout.items addObject:item];
    }
    item.orderNo = no;
    item.resource1 = res1;

    return item;
}

- (Item *)setItemWithMediaInfo:(NSDictionary *)info orderNo:(NSInteger)no
{
    NSString *mediaType = info[UIImagePickerControllerMediaType];
    NSInteger type = 0;

    if (CFStringCompare((CFStringRef)mediaType, kUTTypeImage, 0) == kCFCompareEqualTo) {
        type = ITEM_TYPE_IMAGE;
    } else if (CFStringCompare((CFStringRef)mediaType, kUTTypeMovie, 0) == kCFCompareEqualTo) {
        type = ITEM_TYPE_MOVIE;
    } else {
        [self removeImageOrMovie:tapped_];
        return nil;
    }

    Item *item = [self setItem:type resource1:nil orderNo:no];
    item.localUrl = info[UIImagePickerControllerReferenceURL];

    return item;
}

- (Item *)itemAtOrderNo:(NSInteger)no
{
    for (Item *item in self.layout.items) {
        if (item.orderNo == no)
            return item;
    }
    return nil;
}

- (void)removeItemsAtOrderNo:(NSInteger)no
{
    for (Item *item in self.layout.items) {
        if (item.orderNo == no)
            [self.layout.items removeObject:item];
    }
}

- (void)removeImageOrMovie:(id)sender
{
    ELog(@"must be override");
}

- (void)setImageOrMovie:(id)sender info:(NSDictionary *)info;
{
    ELog(@"must be override");
}

#pragma mark - UIActionSheet delegate

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (actionSheet == photoActionSheet_) {
        if (photoActionSheet_.numberOfButtons > 3)
            ++buttonIndex;
        switch (buttonIndex) {
            case 0:
                [self removeImageOrMovie:tapped_];
                break;
            case 1:
                [self pushImagePicker:UIImagePickerControllerSourceTypeCamera];
                break;
            case 2:
                [self pushImagePicker:UIImagePickerControllerSourceTypePhotoLibrary];
                break;
            case 3:
                [self pushImagePicker:UIImagePickerControllerSourceTypeSavedPhotosAlbum];
                break;
        }
    }
}

- (void)pushImagePicker:(UIImagePickerControllerSourceType)type
{
    if (![UIImagePickerController isSourceTypeAvailable:type]) {
        Alert(nil, NSLocalizedString(@"device not supported", nil));
        return;
    }
    UIImagePickerController *picker = UIImagePickerController.new;
    picker.sourceType = type;
    picker.delegate = self;
    picker.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:type];

    // TODO what will output, when camera..
    for (NSString *t in picker.mediaTypes) {
        DLog(@"%@", t);
    }
    [self presentViewController:picker animated:YES completion:nil];
}

#pragma mark - UIImagePickerControllerDelegate

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [self dismissViewControllerAnimated:YES completion:nil];

    [self setImageOrMovie:tapped_ info:info];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController*)picker
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

@end


text:
namespace Owin.Scim.Tests.Integration.Users.Update.add
{
    using System.Linq;
    using System.Net;
    using System.Net.Http;
    using System.Text;

    using Machine.Specifications;

    using Model.Users;

    using v2.Model;

    /// <summary>
    /// Try assigning subattribute to a null complex attribute
    /// </summary>
    public class with_path_direct_subattribute_null_parent : when_updating_a_user
    {
        Establish context = () =>
        {
            UserToUpdate = new ScimUser2
            {
                UserName = UserNameUtility.GenerateUserName(),
                DisplayName = "Danny",
                PhoneNumbers = new []
                {
                    new PhoneNumber {Value = "8009991234", Type = "old"}
                }
            };

            PatchContent = new StringContent(
                @"
                        {
                            ""schemas"": [""urn:ietf:params:scim:api:messages:2.0:PatchOp""],
                            ""Operations"": [{
                                ""op"":""add"",
                                ""path"": ""name.givenName"",
                                ""value"": ""Daniel""
                            }]
                        }",
                Encoding.UTF8,
                "application/json");
        };

        It should_return_ok = () => PatchResponse.StatusCode.ShouldEqual(HttpStatusCode.OK);

        It should_update_version = () => UpdatedUser.Meta.Version.ShouldNotEqual(UserToUpdate.Meta.Version);

        It should_update_last_modified = () => UpdatedUser.Meta.LastModified.ShouldBeGreaterThan(UserToUpdate.Meta.LastModified);

        It should_replace_complex_attribute = () =>
        {
            UpdatedUser.Name.ShouldNotBeNull();
            UpdatedUser.Name.GivenName.ShouldEqual("Daniel");
        };
    }
}


text:
package main

import (
	"io"
	"net/http"

	"code.google.com/p/go.net/websocket"
	"github.com/gorilla/mux"
)

func WebsocketHandler(ws *websocket.Conn) {
	io.Copy(ws, ws)
}

func main() {
	router := mux.NewRouter()
	router.Handle("/ws", websocket.Handler(WebsocketHandler))
	staticHandler := http.FileServer(http.Dir("."))
	router.PathPrefix("/").Handler(staticHandler)
	http.ListenAndServe("localhost:1234", router)
}


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.InheritanceMargin;

namespace Microsoft.CodeAnalysis.Remote
{
    internal sealed class RemoteInheritanceMarginService : BrokeredServiceBase, IRemoteInheritanceMarginService
    {
        internal sealed class Factory : FactoryBase<IRemoteInheritanceMarginService>
        {
            protected override IRemoteInheritanceMarginService CreateService(in ServiceConstructionArguments arguments)
            {
                return new RemoteInheritanceMarginService(arguments);
            }
        }

        public RemoteInheritanceMarginService(in ServiceConstructionArguments arguments) : base(in arguments)
        {
        }

        public ValueTask<ImmutableArray<SerializableInheritanceMarginItem>> GetInheritanceMarginItemsAsync(
            PinnedSolutionInfo pinnedSolutionInfo,
            ProjectId projectId,
            ImmutableArray<(SymbolKey symbolKey, int lineNumber)> symbolKeyAndLineNumbers,
            CancellationToken cancellationToken)
            => RunServiceAsync(async cancellationToken =>
            {
                var solution = await GetSolutionAsync(pinnedSolutionInfo, cancellationToken).ConfigureAwait(false);
                return await InheritanceMarginServiceHelper
                    .GetInheritanceMemberItemAsync(solution, projectId, symbolKeyAndLineNumbers, cancellationToken)
                    .ConfigureAwait(false);
            }, cancellationToken);
    }
}


text:
"""Tests for archivebot.py/Timestripper."""
#
# (C) Pywikibot team, 2014
#
# Distributed under the terms of the MIT license.
#
from __future__ import unicode_literals

__version__ = '$Id$'

import datetime

from pywikibot.textlib import TimeStripper, tzoneFixedOffset
from tests.aspects import unittest, TestCase

class TestTimeStripperWithNoDigitsAsMonths(TestCase):

    """Test cases for TimeStripper methods."""

    family = 'wikipedia'
    code = 'fr'

    cached = True

    def setUp(self):
        """Set up test cases."""
        super(TestTimeStripperWithNoDigitsAsMonths, self).setUp()
        self.ts = TimeStripper(self.get_site())

    def test_findmarker(self):
        """Test that string which is not part of text is found."""
        txt = u'this is a string with a maker is @@@@already present'
        self.assertEqual(self.ts.findmarker(txt, base=u'@@', delta='@@'),
                         '@@@@@@')

    def test_last_match_and_replace(self):
        """Test that pattern matches and removes items correctly."""
        txtWithOneMatch = u'this string has 3000, 1999 and 3000 in it'
        txtWithTwoMatch = u'this string has 1998, 1999 and 3000 in it'
        txtWithNoMatch = u'this string has no match'
        pat = self.ts.pyearR

        self.assertEqual(self.ts.last_match_and_replace(txtWithOneMatch, pat),
                         (u'this string has 3000, @@ and 3000 in it',
                          {'year': u'1999'})
                         )
        self.assertEqual(self.ts.last_match_and_replace(txtWithTwoMatch, pat),
                         (u'this string has @@, @@ and 3000 in it',
                          {'year': u'1999'})
                         )
        self.assertEqual(self.ts.last_match_and_replace(txtWithNoMatch, pat),
                         (txtWithNoMatch,
                          None)
                         )

        txtWithOneMatch = u'this string has XXX, YYY and février in it'
        txtWithTwoMatch = u'this string has XXX, mars and février in it'
        txtWithThreeMatch = u'this string has avr, mars and février in it'
        txtWithNoMatch = u'this string has no match'
        pat = self.ts.pmonthR

        self.assertEqual(self.ts.last_match_and_replace(txtWithOneMatch, pat),
                         (u'this string has XXX, YYY and @@ in it',
                          {'month': u'février'})
                         )
        self.assertEqual(self.ts.last_match_and_replace(txtWithTwoMatch, pat),
                         (u'this string has XXX, @@ and @@ in it',
                          {'month': u'février'})
                         )
        self.assertEqual(self.ts.last_match_and_replace(txtWithThreeMatch, pat),
                         (u'this string has @@, @@ and @@ in it',
                          {'month': u'février'})
                         )
        self.assertEqual(self.ts.last_match_and_replace(txtWithNoMatch, pat),
                         (txtWithNoMatch,
                          None)
                         )

    def test_hour(self):
        """Test that correct hour is matched."""
        txtHourInRange = u'7 février 2010 à 23:00 (CET)'
        txtHourOutOfRange = u'7 février 2010 à 24:00 (CET)'

        self.assertNotEqual(self.ts.timestripper(txtHourInRange), None)
        self.assertEqual(self.ts.timestripper(txtHourOutOfRange), None)

class TestTimeStripperWithDigitsAsMonths(TestCase):

    """Test cases for TimeStripper methods."""

    family = 'wikipedia'
    code = 'cs'

    cached = True

    def setUp(self):
        """Setup a timestripper for the configured site."""
        super(TestTimeStripperWithDigitsAsMonths, self).setUp()
        self.ts = TimeStripper(self.get_site())

    def test_last_match_and_replace(self):
        """Test that pattern matches and removes items correctly."""
        txtWithOneMatch = u'this string has XX. YY. 12. in it'
        txtWithTwoMatch = u'this string has XX. 1. 12. in it'
        txtWithThreeMatch = u'this string has 1. 1. 12. in it'
        txtWithNoMatch = u'this string has no match'
        pat = self.ts.pmonthR

        self.assertEqual(self.ts.last_match_and_replace(txtWithOneMatch, pat),
                         (u'this string has XX. YY. 12. in it',
                          {'month': u'12.'})
                         )
        self.assertEqual(self.ts.last_match_and_replace(txtWithTwoMatch, pat),
                         (u'this string has XX. 1. 12. in it',
                          {'month': u'12.'})
                         )
        self.assertEqual(self.ts.last_match_and_replace(txtWithThreeMatch, pat),
                         (u'this string has @@ 1. 12. in it',
                          {'month': u'12.'})
                         )
        self.assertEqual(self.ts.last_match_and_replace(txtWithNoMatch, pat),
                         (txtWithNoMatch,
                          None)
                         )

class TestTimeStripperLanguage(TestCase):

    """Test cases for English language."""

    sites = {
        'cswiki': {
            'family': 'wikipedia',
            'code': 'cs',
            'match': u'3. 2. 2010, 19:48 (UTC) 7. 2. 2010 19:48 (UTC)',
        },
        'enwiki': {
            'family': 'wikipedia',
            'code': 'en',
            'match': u'3 February 2010 19:48 (UTC) 7 February 2010 19:48 (UTC)',
            'nomatch': u'3. 2. 2010, 19:48 (UTC) 7. 2. 2010 19:48 (UTC)',
        },
        'fawiki': {
            'family': 'wikipedia',
            'code': 'fa',
            'match': u'۳ فوریهٔ  ۲۰۱۰، ساعت ۱۹:۴۸ (UTC) ۷ فوریهٔ  ۲۰۱۰، ساعت ۱۹:۴۸ (UTC)',
            'nomatch': u'۳ ۲ ۲۰۱۴ ۱۹:۴۸ (UTC) ۷ ۲ ۲۰۱۰ ۱۹:۴۸ (UTC)',
        },
        'frwiki': {
            'family': 'wikipedia',
            'code': 'fr',
            'match': u'3 février 2010 à 19:48 (CET) 7 février 2010 à 19:48 (CET)',
            'nomatch': u'3 March 2010 19:48 (CET) 7 March 2010 19:48 (CET)',
        },
        'kowiki': {
            'family': 'wikipedia',
            'code': 'ko',
            'match': u'2010년 2월 3일 (수) 19:48 (KST) 2010년 2월 7일 (수) 19:48 (KST)',
        },
        'nowiki': {
            'family': 'wikipedia',
            'code': 'no',
            'match': u'3. feb 2010 kl. 19:48 (CET) 7. feb 2010 kl. 19:48 (UTC)',
        },
        'ptwiki': {
            'family': 'wikipedia',
            'code': 'pt',
            'match': u'19h48min de 3 de fevereiro de 2010 (UTC) 19h48min de 7 de fevereiro de 2010 (UTC)',
        },
        'viwiki': {
            'family': 'wikipedia',
            'code': 'vi',
            'match': u'19:48, ngày 15 tháng 9 năm 2008 (UTC) 19:48, ngày 7 tháng 2 năm 2010 (UTC)',
            'match2': u'16:41, ngày 15 tháng 9 năm 2008 (UTC) 16:41, ngày 12 tháng 9 năm 2008 (UTC)',
            'match3':  u'21:18, ngày 13 tháng 8 năm 2014 (UTC) 21:18, ngày 14 tháng 8 năm 2014 (UTC)',
            'nomatch1': u'21:18, ngày 13 March 8 năm 2014 (UTC) 21:18, ngày 14 March 8 năm 2014 (UTC)',
        },
    }

    cached = True

    def test_timestripper_match(self, key):
        """Test that correct date is matched."""
        self.ts = TimeStripper(self.get_site(key))

        tzone = tzoneFixedOffset(self.ts.site.siteinfo['timeoffset'],
                                 self.ts.site.siteinfo['timezone'])

        txtMatch = self.sites[key]['match']

        res = datetime.datetime(2010, 2, 7, 19, 48, tzinfo=tzone)

        self.assertEqual(self.ts.timestripper(txtMatch), res)

        if 'match2' not in self.sites[key]:
            return

        txtMatch = self.sites[key]['match2']

        res = datetime.datetime(2008, 9, 12, 16, 41, tzinfo=tzone)

        self.assertEqual(self.ts.timestripper(txtMatch), res)

        if 'match3' not in self.sites[key]:
            return

        txtMatch = self.sites[key]['match3']

        res = datetime.datetime(2014, 8, 14, 21, 18, tzinfo=tzone)

        self.assertEqual(self.ts.timestripper(txtMatch), res)

    def test_timestripper_nomatch(self, key):
        """Test that correct date is not matched."""
        self.ts = TimeStripper(self.get_site(key))

        if 'nomatch' in self.sites[key]:
            txtNoMatch = self.sites[key]['nomatch']
        else:
            txtNoMatch = u'3 March 2010 19:48 (UTC) 7 March 2010 19:48 (UTC)'

        self.assertEqual(self.ts.timestripper(txtNoMatch), None)

        if 'nomatch1' not in self.sites[key]:
            return

        txtNoMatch = self.sites[key]['nomatch1']
        self.assertEqual(self.ts.timestripper(txtNoMatch), None)

class TestTimeStripperDoNotArchiveUntil(TestCase):

    """Test cases for Do Not Archive Until templates.

    See https://commons.wikimedia.org/wiki/Template:DNAU and
    https://en.wikipedia.org/wiki/Template:Do_not_archive_until.
    """

    family = 'wikisource'
    code = 'en'

    cached = True

    username = '[[User:DoNotArchiveUntil]]'
    date = '06:57 06 June 2015 (UTC)'
    user_and_date = username + ' ' + date
    tzone = tzoneFixedOffset(0, 'UTC')

    def test_timestripper_match(self):
        """Test that dates in comments  are correctly recognised."""
        ts = TimeStripper(self.get_site())

        txt_match = '<!-- [[User:Do___ArchiveUntil]] ' + self.date + ' -->'
        res = datetime.datetime(2015, 6, 6, 6, 57, tzinfo=self.tzone)
        self.assertEqual(ts.timestripper(txt_match), res)

        txt_match = '<!-- --> <!-- ' + self.user_and_date + ' <!-- -->'
        res = datetime.datetime(2015, 6, 6, 6, 57, tzinfo=self.tzone)
        self.assertEqual(ts.timestripper(txt_match), res)

        txt_match = '<!-- ' + self.user_and_date + ' -->'
        res = datetime.datetime(2015, 6, 6, 6, 57, tzinfo=self.tzone)
        self.assertEqual(ts.timestripper(txt_match), res)

    def test_timestripper_match_only(self):
        """Test that latest date is used instead of other dates."""
        ts = TimeStripper(self.get_site())

        later_date = '10:57 06 June 2015 (UTC)'
        txt_match = '<!-- --> ' + self.user_and_date + ' <!-- -->' + later_date
        res = datetime.datetime(2015, 6, 6, 10, 57, tzinfo=self.tzone)
        self.assertEqual(ts.timestripper(txt_match), res)

        earlier_date = '02:57 06 June 2015 (UTC)'
        txt_match = '<!-- ' + self.user_and_date + ' --> ' + earlier_date
        res = datetime.datetime(2015, 6, 6, 6, 57, tzinfo=self.tzone)
        self.assertEqual(ts.timestripper(txt_match), res)

if __name__ == '__main__':
    try:
        unittest.main()
    except SystemExit:
        pass


text:
#ifndef __ARCH_ARM_SRC_SAM34_CHIP_SAM_MEMORYMAP_H
#define __ARCH_ARM_SRC_SAM34_CHIP_SAM_MEMORYMAP_H

/************************************************************************************
 * Included Files
 ************************************************************************************/

#include <nuttx/config.h>
#include <arch/sam34/chip.h>

#if defined(CONFIG_ARCH_CHIP_SAM3U)
#  include "chip/sam3u_memorymap.h"
#elif defined(CONFIG_ARCH_CHIP_SAM4L)
#  include "chip/sam4l_memorymap.h"
#elif defined(CONFIG_ARCH_CHIP_SAM4S)
#  include "chip/sam4s_memorymap.h"
#else
#  error Unrecognized SAM architecture
#endif

#endif /* __ARCH_ARM_SRC_SAM34_CHIP_SAM_MEMORYMAP_H */


text:
package org.javers.organization.structure.domain;

import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import java.io.Serializable;
import java.util.List;

@Entity
@Table
public class Hierarchy implements Serializable{

    @Id
    private String name;

    @OneToMany(mappedBy = "hierarchy", fetch = FetchType.EAGER)
    private List<HierarchyEmployees> hierarchyEmployees;

    public Hierarchy() {
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<HierarchyEmployees> getHierarchyEmployees() {
        return hierarchyEmployees;
    }

    public void setHierarchyEmployees(List<HierarchyEmployees> hierarchyEmployees) {
        this.hierarchyEmployees = hierarchyEmployees;
    }
}


text:
//
//  PhysicsEngineComponent.hpp
//  NicoEngine
//
//  Created by Hsieh Yu Hua on 12/7/15.
//  Copyright © 2015 Heish Yu Hua. All rights reserved.
//

#ifndef PhysicsEngineComponent_hpp
#define PhysicsEngineComponent_hpp
#include "Component.hpp"
#include "PhysicsEngine.hpp"
#include <memory>
namespace nico {
    class PhysicsEngineComponent : public Component{
    public:
        PhysicsEngineComponent(PhysicsEngine* physics_engine):
        m_physics_engine(physics_engine){}

        virtual void update(Duration delta) override{
            m_physics_engine->update(delta);
            m_physics_engine->process_collision();
        };

        inline const auto& get_physical_engine(){
            return m_physics_engine;
        }

    private:
        PhysicsEngine* m_physics_engine;
    };
}//end class nico
#endif /* PhysicsEngineComponent_hpp */


text:
@interface SKPostsViewController : ICTableViewController

@end


text:
require 'spec_helper'

describe DocCollections::Find do
  describe 'filtering by docs' do
    it 'works as expected' do
      doc_1, doc_2, doc_3 = create_list(:doc, 3)
      doc_collection_1 = create(:doc_collection, docs: [doc_1, doc_2, doc_3])
      doc_collection_2 = create(:doc_collection, docs: [doc_1, doc_2])
      doc_collection_3 = create(:doc_collection, docs: [doc_2, doc_3])
      doc_collections = DocCollections::Find.call(docs: [doc_1, doc_2])
      expect(doc_collections).to eq([doc_collection_2])
    end
  end
end


text:
typedef enum {
    KATSocketStateOffline,       // no network, set via reachability callbacks
    KATSocketStateConnecting,
    KATSocketStateConnected,
    KATSocketStateDisconnected
} KATSocketState;

typedef enum {
    KATSocketConnectConditionAlways,
    KATSocketConnectConditionWLAN
} KATSocketConnectCondition;

NSString *NSStringFromSocketState(KATSocketState state);

static  NSString    *const     KATGameServiceConnectionErrorNotification  =   @"KATGameServiceConnectionErrorNotification";

static  NSString    *const     KATGameServiceConnectionErrorReasonKey         =   @"KATGameServiceConnectionErrorReasonKey";
static  NSString    *const     KATGameServiceConnectionErrorReasonOffline     =   @"KATGameServiceConnectionErrorReasonOffline";
static  NSString    *const     KATGameServiceConnectionErrorReasonServerDown  =   @"KATGameServiceConnectionErrorReasonServerDown";
static  NSString    *const     KATGameServiceConnectionErrorReasonTimeout     =   @"KATGameServiceConnectionErrorReasonTimeout";
static  NSString    *const     KATGameServiceConnectionErrorReasonGeneric     =   @"KATGameServiceConnectionErrorReasonGeneric";

static  NSString    *const     KATGameServiceSocketErrorKey                   =   @"KATGameServiceSocketErrorKey";

@protocol KATSocketShuttleDelegate;

@interface KATSocketShuttle : NSObject

-(id)initWithRequest:(NSURLRequest *)request delegate:(id<KATSocketShuttleDelegate>) delegate connectConditions:(KATSocketConnectCondition)connectConditions;
-(id)initWithRequest:(NSURLRequest *)request delegate:(id<KATSocketShuttleDelegate>)delegate;
-(id)initWithServerURL:(NSURL *)serverURL delegate:(id<KATSocketShuttleDelegate>)delegate;

-(void)send:(NSString *)message;
-(void)disconnect;
-(void)ensureConnected;

@property (nonatomic, readonly) KATSocketState socketState;
@property (nonatomic, assign) id <KATSocketShuttleDelegate> delegate;
@property (nonatomic)   NSTimeInterval  timeoutInterval; // defaults to 30 seconds
@property (nonatomic, readonly) NSURL *serverURL;
@property (nonatomic, strong) NSURLRequest *request;
@property (nonatomic, readonly) KATSocketConnectCondition connectConditions;

@end

@protocol KATSocketShuttleDelegate <NSObject>

// message will either be an NSString if the server is using text
// or NSData if the server is using binary

@required
- (void)socket:(KATSocketShuttle *)socket didReceiveMessage:(id)message;

@optional
- (void)socketDidOpen:(KATSocketShuttle *)socket;
- (void)socket:(KATSocketShuttle *)socket didFailWithError:(NSError *)error;
- (void)socket:(KATSocketShuttle *)socket didCloseWithCode:(NSInteger)code reason:(NSString *)reason wasClean:(BOOL)wasClean;

@end


text:
class BookmarkBubbleSignInDelegateTest : public BrowserWithTestWindowTest {
 public:
  BookmarkBubbleSignInDelegateTest() {}

 protected:
  class Window : public TestBrowserWindow {
   public:
    Window() : show_count_(0) {}

    int show_count() { return show_count_; }

   private:
    // TestBrowserWindow:
    virtual void Show() OVERRIDE {
      ++show_count_;
    }

    // Number of times that the Show() method has been called.
    int show_count_;

    DISALLOW_COPY_AND_ASSIGN(Window);
  };

  virtual BrowserWindow* CreateBrowserWindow() OVERRIDE {
    return new Window();
  }

 private:
  DISALLOW_COPY_AND_ASSIGN(BookmarkBubbleSignInDelegateTest);
};

TEST_F(BookmarkBubbleSignInDelegateTest, OnSignInLinkClicked) {
  int starting_tab_count = browser()->tab_strip_model()->count();

  scoped_ptr<BookmarkBubbleDelegate> delegate;
  delegate.reset(new BookmarkBubbleSignInDelegate(browser()));

  delegate->OnSignInLinkClicked();

  // A new tab should have been opened and the browser should be visible.
  int tab_count = browser()->tab_strip_model()->count();
  EXPECT_EQ(starting_tab_count + 1, tab_count);
  EXPECT_EQ(1,
            static_cast<BookmarkBubbleSignInDelegateTest::Window*>(
                browser()->window())->show_count());
}

TEST_F(BookmarkBubbleSignInDelegateTest, OnSignInLinkClickedIncognito) {
  // Create an incognito browser.
  TestingProfile::Builder incognito_profile_builder;
  incognito_profile_builder.SetIncognito();
  scoped_ptr<TestingProfile> incognito_profile =
      incognito_profile_builder.Build();
  incognito_profile->SetOriginalProfile(profile());
  profile()->SetOffTheRecordProfile(incognito_profile.PassAs<Profile>());

  scoped_ptr<BrowserWindow> incognito_window;
  incognito_window.reset(CreateBrowserWindow());
  Browser::CreateParams params(browser()->profile()->GetOffTheRecordProfile(),
                               browser()->host_desktop_type());
  params.window = incognito_window.get();
  scoped_ptr<Browser> incognito_browser;
  incognito_browser.reset(new Browser(params));

  int starting_tab_count_normal = browser()->tab_strip_model()->count();
  int starting_tab_count_incognito =
      incognito_browser.get()->tab_strip_model()->count();

  scoped_ptr<BookmarkBubbleDelegate> delegate;
  delegate.reset(new BookmarkBubbleSignInDelegate(incognito_browser.get()));

  delegate->OnSignInLinkClicked();

  // A new tab should have been opened in the normal browser, which should be
  // visible.
  int tab_count_normal = browser()->tab_strip_model()->count();
  EXPECT_EQ(starting_tab_count_normal + 1, tab_count_normal);
  EXPECT_EQ(1,
            static_cast<BookmarkBubbleSignInDelegateTest::Window*>(
                browser()->window())->show_count());

  // No effect is expected on the incognito browser.
  int tab_count_incognito = incognito_browser->tab_strip_model()->count();
  EXPECT_EQ(starting_tab_count_incognito, tab_count_incognito);
  EXPECT_EQ(0,
            static_cast<BookmarkBubbleSignInDelegateTest::Window*>(
                incognito_window.get())->show_count());
}

// Verifies that the sign in page can be loaded in a different browser
// if the provided browser is invalidated.
TEST_F(BookmarkBubbleSignInDelegateTest, BrowserRemoved) {
  // Create an extra browser.
  scoped_ptr<BrowserWindow> extra_window;
  extra_window.reset(CreateBrowserWindow());

  Browser::CreateParams params(browser()->profile(),
                               browser()->host_desktop_type());
  params.window = extra_window.get();
  scoped_ptr<Browser> extra_browser;
  extra_browser.reset(new Browser(params));

  int starting_tab_count = extra_browser->tab_strip_model()->count();

  scoped_ptr<BookmarkBubbleDelegate> delegate;
  delegate.reset(new BookmarkBubbleSignInDelegate(browser()));

  BrowserList::SetLastActive(extra_browser.get());

  browser()->tab_strip_model()->CloseAllTabs();
  set_browser(NULL);

  delegate->OnSignInLinkClicked();

  // A new tab should have been opened in the extra browser, which should be
  // visible.
  int tab_count = extra_browser->tab_strip_model()->count();
  EXPECT_EQ(starting_tab_count + 1, tab_count);
  EXPECT_EQ(1,
            static_cast<BookmarkBubbleSignInDelegateTest::Window*>(
                extra_window.get())->show_count());

  // Required to avoid a crash when the browser is deleted.
  extra_browser->tab_strip_model()->CloseAllTabs();
}


text:
namespace content {

class ShellRenderProcessObserver : public RenderProcessObserver {
 public:
  ShellRenderProcessObserver();
   ~ShellRenderProcessObserver() final;

  // RenderProcessObserver implementation.
   bool OnControlMessageReceived(const IPC::Message& message) override;
   void OnRenderProcessWillShutdown() override;
   void WebKitInitialized() override;
 private:
  void OnOpen(const std::string& path);
  void OnReopen();
  void OnClearCache();

  bool webkit_initialized_;

  DISALLOW_COPY_AND_ASSIGN(ShellRenderProcessObserver);
};

}  // namespace content

#endif  // CONTENT_NW_SRC_RENDERER_SHELL_RENDER_PROCESS_OBSERVER_H_


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LockTest.Synchronization
{
    public class ObjectLock : IDisposable
    {
        static ObjectLock()
        {
            stateLock = new SimpleSpinLock();
            objectToLockMap = new Dictionary<object, ObjectLock>();
        }

        public static ObjectLock Lock(object syncObject)
        {
            ObjectLock resultLock;

            using (AutoLock.Lock(stateLock))
            {
                if (!objectToLockMap.TryGetValue(syncObject, out resultLock))
                {
                    resultLock = new ObjectLock(syncObject);

                    objectToLockMap.Add(syncObject, resultLock);
                }

                resultLock.referenceCount++;
            }

            resultLock.instanceLock.Lock();

            return resultLock;
        }

        #region IDisposable Members

        public void Dispose()
        {
            Unlock();
        }

        #endregion

        void Unlock()
        {
            using (AutoLock.Lock(stateLock))
            {
                referenceCount--;

                if (referenceCount < 0)
                {
                    throw new ArgumentException(string.Format("Internal synchronization error -- negative reference count: {0}", referenceCount));
                }

                if (0 == referenceCount)
                {
                    if (! objectToLockMap.Remove(syncObject))
                    {
                        throw new SynchronizationException("Internal synchronization error -- failed to remove object lock");
                    }
                }
            }

            instanceLock.Unlock();
        }

        ObjectLock(object syncObject)
        {
            this.syncObject = syncObject;
            instanceLock = new SimpleSpinLock();
        }

        int referenceCount = 0;
        SimpleSpinLock instanceLock;
        object syncObject;

        static ISyncLock stateLock;
        static Dictionary<object, ObjectLock> objectToLockMap;
    }
}


text:
/**
 * 参考 express官方例子: https://github.com/visionmedia/express/blob/master/examples/auth
 * 详细例子可查看 check out https://github.com/visionmedia/node-pwd
 */

'use strict';

/**
 * Module dependencies.
 */

var crypto = require('crypto');

/**
 * Bytesize.
 */

var len = 128;

/**
 * Iterations. ~300ms
 */

var iterations = 12000;

/**
 * 如果没有传入可选项 salt 表示加密
 * 传入salt 表示返回加密后的密码
 * Hashes a password with optional `salt`, otherwise
 * generate a salt for `password` and invoke `fn(err, salt, hash)`.
 *
 * @param {String} password to hash 要加密或解密的密码
 * @param {String} optional salt 密钥
 * @param {Function} callback
 * @api public
 */

exports.hash = function (password, salt, fn) {
  if (3 === arguments.length) {
    if(password === undefined || salt === undefined){
      return fn(new  Error('password or salt is not defined'));
    }
    crypto.pbkdf2(password, salt, iterations, len, function (err, hash) {
      fn(err, hash.toString('base64'));
    });
  } else {
    fn = salt;
    crypto.randomBytes(len, function (err, salt) {
      if (err) {
        return fn(err);
      }
      salt = salt.toString('base64');
      crypto.pbkdf2(password, salt, iterations, len, function (err, hash) {
        if (err) {
          return fn(err);
        }
        fn(null, salt, hash.toString('base64'));
      });
    });
  }
};

exports.encryption = {
  /**
   * 加密
   * @param key
   * @param str
   * @returns {*}
   */
  encrypt: function (key, str) {
    var cipher = crypto.createCipher('aes-256-cbc',key);
    var enc = cipher.update(str,'utf8','hex');
    enc += cipher.final('hex');
    return enc;
  },
  /**
   * 解密
   * @param key
   * @param str
   * @returns {*}
   */
  decrypt: function (key, str) {
    var dec = '';
    try{
      var decipher = crypto.createDecipher('aes-256-cbc', key);
      dec = decipher.update(str, 'hex', 'utf8');
      dec += decipher.final('utf8');
    }catch(e){
      console.error('解密出错:' + e.message);
      throw new Error('解密出错');
    }
    return dec;
  },
  getKey: function () {
    var key = crypto.createDiffieHellman(256).getPrime('base64');
    return key;
  }
};


text:
"""Tests for kw_only_dataclasses."""

import dataclasses
import inspect
from absl.testing import absltest

from flax.linen import kw_only_dataclasses

class KwOnlyDataclassesTest(absltest.TestCase):

  def test_kwonly_args_moved_to_end(self):

    @kw_only_dataclasses.dataclass
    class TestClass:
      a: int = 1
      b: int = kw_only_dataclasses.field(default=2, kw_only=True)
      c: int = 3

    params = inspect.signature(TestClass.__init__).parameters
    self.assertEqual(list(params), ['self', 'a', 'c', 'b'])
    self.assertEqual(params['a'].default, 1)
    self.assertEqual(params['b'].default, 2)
    self.assertEqual(params['c'].default, 3)

    v1 = TestClass()
    self.assertDictEqual(dataclasses.asdict(v1), dict(a=1, b=2, c=3))

    v2 = TestClass(b=20)
    self.assertDictEqual(dataclasses.asdict(v2), dict(a=1, b=20, c=3))

    v3 = TestClass(1, 30)
    self.assertDictEqual(dataclasses.asdict(v3), dict(a=1, b=2, c=30))

  def test_base_optional_subclass_required(self):

    @kw_only_dataclasses.dataclass
    class Parent:
      a: int = kw_only_dataclasses.field(default=2, kw_only=True)

    @kw_only_dataclasses.dataclass
    class Child(Parent):
      b: int

    child_params = inspect.signature(Child.__init__).parameters
    self.assertEqual(list(child_params), ['self', 'b', 'a'])
    self.assertEqual(child_params['a'].default, 2)
    self.assertEqual(child_params['b'].default, inspect.Parameter.empty)

    v1 = Child(4)
    self.assertDictEqual(dataclasses.asdict(v1), dict(a=2, b=4))

    v2 = Child(4, 5)  # pylint: disable=too-many-function-args
    self.assertDictEqual(dataclasses.asdict(v2), dict(a=5, b=4))

  def test_subclass_overrides_base(self):
    # Note: if a base class declares a field as keyword-only, then
    # subclasses don't need to also declare it as keyword-only.

    @kw_only_dataclasses.dataclass
    class A:
      x: int = kw_only_dataclasses.field(default=1, kw_only=True)

    @kw_only_dataclasses.dataclass
    class B(A):
      size: float
      y: int = kw_only_dataclasses.field(default=3, kw_only=True)
      x: int = 2

    @kw_only_dataclasses.dataclass
    class C(B):
      name: str

    a_params = inspect.signature(A.__init__).parameters
    b_params = inspect.signature(B.__init__).parameters
    c_params = inspect.signature(C.__init__).parameters

    self.assertEqual(list(a_params), ['self', 'x'])
    self.assertEqual(list(b_params), ['self', 'size', 'x', 'y'])
    self.assertEqual(list(c_params), ['self', 'size', 'name', 'x', 'y'])

    self.assertEqual(a_params['x'].default, 1)
    self.assertEqual(b_params['x'].default, 2)
    self.assertEqual(b_params['y'].default, 3)
    self.assertEqual(b_params['size'].default, inspect.Parameter.empty)
    self.assertEqual(c_params['x'].default, 2)
    self.assertEqual(c_params['y'].default, 3)
    self.assertEqual(c_params['name'].default, inspect.Parameter.empty)
    self.assertEqual(c_params['size'].default, inspect.Parameter.empty)

    value = C(4, 'foo')  # pylint: disable=too-many-function-args
    self.assertDictEqual(
        dataclasses.asdict(value), dict(name='foo', size=4, x=2, y=3))

  def test_kwonly_marker(self):

    @kw_only_dataclasses.dataclass
    class A:
      x: float
      _: kw_only_dataclasses.KW_ONLY
      a: int = 5
      b: int = kw_only_dataclasses.field(default=2)
      c: int = kw_only_dataclasses.field(default=2, kw_only=True)

    @kw_only_dataclasses.dataclass
    class B(A):
      z: str

    a_params = inspect.signature(A.__init__).parameters
    b_params = inspect.signature(B.__init__).parameters
    self.assertEqual(list(a_params), ['self', 'x', 'a', 'b', 'c'])
    self.assertEqual(list(b_params), ['self', 'x', 'z', 'a', 'b', 'c'])

if __name__ == '__main__':
  absltest.main()


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.haox</groupId>
        <artifactId>haox-kerb</artifactId>
        <version>1.0-SNAPSHOT</version>
    </parent>

    <artifactId>kerb-core</artifactId>

    <name>Haox-kerb core</name>
    <description>Haox-kerb core facilities</description>

    <dependencies>
        <dependency>
            <groupId>org.haox</groupId>
            <artifactId>haox-asn1</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>

    </dependencies>
</project>


text:
package org.apache.tez.history.parser.datamodel;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.tez.common.counters.CounterGroup;
import org.apache.tez.common.counters.TezCounter;
import org.apache.tez.common.counters.TezCounters;
import org.apache.tez.history.parser.utils.Utils;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;

import java.util.Iterator;
import java.util.List;
import java.util.Map;

import static org.apache.hadoop.classification.InterfaceAudience.Public;
import static org.apache.hadoop.classification.InterfaceStability.Evolving;

@Public
@Evolving
public abstract class BaseInfo {

  protected TezCounters tezCounters;
  protected List<Event> eventList;

  BaseInfo(JSONObject jsonObject) throws JSONException {
    final JSONObject otherInfoNode = jsonObject.getJSONObject(Constants.OTHER_INFO);
    //parse tez counters
    tezCounters = Utils.parseTezCountersFromJSON(
        otherInfoNode.optJSONObject(Constants.COUNTERS));

    //parse events
    eventList = Lists.newArrayList();
    Utils.parseEvents(jsonObject.optJSONArray(Constants.EVENTS), eventList);
  }

  public TezCounters getTezCounters() {
    return tezCounters;
  }

  /**
   * Get start time w.r.t DAG
   *
   * @return long
   */
  public abstract long getStartTime();

  /**
   * Get finish time w.r.t DAG
   *
   * @return long
   */
  public abstract long getFinishTime();

  /**
   * Get absolute start time
   *
   * @return long
   */
  public abstract long getAbsStartTime();

  /**
   * Get absolute finish time
   *
   * @return long
   */
  public abstract long getAbsFinishTime();

  public abstract String getDiagnostics();

  public List<Event> getEvents() {
    return eventList;
  }

  /**
   * Get counter for a specific counter group name.
   * If counterGroupName is not mentioned, it would end up returning counter found in all
   * groups
   *
   * @param counterGroupName
   * @param counter
   * @return Map<String, TezCounter> tez counter at every counter group level
   */
  public Map<String, TezCounter> getCounter(String counterGroupName, String counter) {
    //TODO: FS, TaskCounters are directly getting added as TezCounters always pass those.  Need a
    // way to get rid of these.
    Map<String, TezCounter> result = Maps.newHashMap();
    Iterator<String> iterator = tezCounters.getGroupNames().iterator();
    boolean found = false;
    while (iterator.hasNext()) {
      CounterGroup counterGroup = tezCounters.getGroup(iterator.next());
      if (counterGroupName != null) {
        String groupName = counterGroup.getName();
        if (groupName.equals(counterGroupName)) {
          found = true;
        }
      }

      //Explicitly mention that no need to create the counter if not present
      TezCounter tezCounter = counterGroup.getUnderlyingGroup().findCounter(counter, false);
      if (tezCounter != null) {
        result.put(counterGroup.getName(), tezCounter);
      }

      if (found) {
        //Retrieved counter specific to a counter group. Safe to exit.
        break;
      }

    }
    return result;
  }

  /**
   * Find a counter in all counter groups
   *
   * @param counter
   * @return Map of countergroup to TezCounter mapping
   */
  public Map<String, TezCounter> getCounter(String counter) {
    return getCounter(null, counter);
  }

}


text:
i_want_pets = ["I", "want", 3, "pets", "but", "only", "have", 2]
my_family_pets_ages = {"Evi" => 6, "Ditto" => 3, "Hoobie" => 3, "George" => 12, "Bogart" => 4, "Poly" => 4, "Annabelle" => 0}

# Person 1's solution (Zach Barton) - Find Matching Data
def my_array_finding_method(source, thing_to_find)
  new_array = []
  source.each do |word|
    if word.to_s.include? thing_to_find.to_s
      new_array << word
    else
    end
  end
  return new_array
end

def my_hash_finding_method(source, thing_to_find)
  new_array = []
  source.each do |key, value|
    if value == thing_to_find
      new_array << key.to_s
    else
    end
  end
  return new_array
end

puts my_hash_finding_method(my_family_pets_ages, 3)

# Identify and describe the Ruby method(s) you implemented.

# I used the each method in both examples to iterate over an array and a hash. The difference
# between iterating over an array and a hash is that the do loop for a hash requires two arguments
# so that both the key and the values can be accessed.
#
# To check if a string contains a certain letter or other substring, I used the .include? method
# to check if each string in the array contains the thing_to_find argument. The include method syntax
# looks like this: string.include? "substring" and will return true if the string contains the substring.
#
# Finally, I used the .to_s method to explicitly change the variables into strings before returning
# them out of the method.
#
# For searching through the ruby documentation, I just looked for the page corresponding to the class
# I wanted to apply a method to (string, hash, array, etc.) and searched the page for a method that
# sounded similar to function I wanted to perform.

# Person 2 (Michael Wang) - Modify Existing Data
def my_array_modification_method!(source, thing_to_modify)
  source.map! do |element|
    if element.is_a? Integer
      element + thing_to_modify
    else
      element
    end
  end
  return source
end

def my_hash_modification_method!(source, thing_to_modify)
  source.each { |k, v| source[k] = v + thing_to_modify}
  return source
end

# Identify and describe the Ruby method(s) you implemented.
# => map! to replace the element in the array with the value returned by the block; this let's you change the input array directly
# => is_a? to determine if element in array is an integer. This makes sure that you are only modifying the integers in the array.
# => each to modify each value of the hash, since all the values in the hash are already integers, you don't need the is_a? method

# Person 3 (Bobby Reith)- Sort Data
def my_array_sorting_method(i_want_pets)
	i_want_pets.sort { |a, b| a.to_s <=> b.to_s }
end

def my_hash_sorting_method (my_family_pets_ages)
	my_family_pets_ages.sort_by { |name,age| age }
end

# Identify and describe the Ruby method(s) you implemented.
# For the array the .sort method was used adding a block which compared each value to one another.
# Within the block the .to_s method was used so when the values were compared, it was comparing a
# string to a string. The sort method returns an array.
#
# For the hash the .sort_by method was used adding a block which took the key(name) and value(age) as
# the arguments and sorted by the value(age). The sort_by method returns an array.
#
# The research was fairly straight forward for the sort methods. Once I reviewed the challenge, I was
# able to go into the Ruby Docs and find the methods needed in the array and hash sections. After looking
# over what each method did in detail, I was able to implement them in the challenge successfully.

# Person 4 (Bethelhem Assefa) - Delete Matching Data
def my_array_deletion_method!(i_want_pets, letter)
  i_want_pets.delete_if { |item| item.to_s.include?(letter) }
end
my_array_deletion_method!(i_want_pets,"a")
p i_want_pets

def my_hash_deletion_method!(my_family_pets_ages, name)
  my_family_pets_ages.delete_if { |pet,age| pet.include?(name) }
end
my_hash_deletion_method!(my_family_pets_ages, "George")
p my_family_pets_ages

# Identify and describe the Ruby method(s) you implemented.
# I used a delete_if method because it deletes every element of self for which block evaluates to true. Meaning that
# for my_array_deletion_method! it deletes all the string that contains the letter provided and
# for my_hash_deletion_method! it deletes the item that is equal to the name argument.

# Teach your accountability group how to use the methods
# The method is pretty forward to use. there are 3 options to use a delete-method in an array.
#  .delete : which deletes all items from the array that are equal to obj.
#      forexample : array=["a","b","c"] and if we use array.delete("b") the method will remove "b" from the array.
#  .delete_at : in this one we need to provide the index number where we want to delete item. so it will go ahead and remove it from the array.
#     using the previous example delete_at(1) removes "b" since it is located on index 1
#  .delete_if is the third option and which i used for this exercise. since our i_want_pets array contains numbers, make sure to change the item.to_s other wise, you will encounter an error message.

# Person 5 (Mauve Tierney) - Split Data

def my_array_splitting_method(i_want_pets)
  first_array=[]
  second_array=[]

  first_array = i_want_pets.select{ |x| x.is_a? Integer}

  second_array = i_want_pets.select{ |x| x.is_a? String}

  return Array[first_array, second_array]

end

def my_hash_splitting_method(my_family_pets_ages, age)
  young_dogs = {}
  old_dogs = {}

  young_dogs = my_family_pets_ages.select{ |name, age| age <= 4 }

  old_dogs = my_family_pets_ages.select{ |name, age| age > 4 }

  return dogs = [young_dogs.to_a, old_dogs.to_a]

end

# Then create a my_hash_splitting_method that will separate the
# hash into two arrays based on the value. It should return two arrays,
#  the first which includes all pets who are four years of age or younger
#  and the second that includes all other pets. This should not alter
#  the original data structure.
# my_family_pets_ages = {"Evi" => 6, "Hoobie" => 3, "George" => 12,
# "Bogart" => 4, "Poly" => 4, "Annabelle" => 0, "Ditto" => 3}

# Release 3: Reflect!
# What did you learn about researching and explaining your research to others?
# => Through teaching my group members about the methods I used, I was able to get a better understanding of them myself.
# => I had to make sure I truly understood the methods before I was able to offer any explanations.
# => It was also interesting to see how my group members approached their problems to see which new methods they used.
#


text:
using System;
using System.Collections.Generic;
using System.Linq;
using Moq;
using Xunit;
using System.Diagnostics.CodeAnalysis;

namespace RaptoRCon.Games.Dice.Tests
{
    [ExcludeFromCodeCoverage]
    public class DicePacketTest
    {
        private readonly Mock<IDicePacketSequence> packetSequenceMock;
        private readonly List<IDiceWord> wordsMock;

        public DicePacketTest()
        {
            packetSequenceMock = new Mock<IDicePacketSequence>();
            wordsMock = new List<IDiceWord>();
        }

        #region ctor

        [Fact]
        public void ctor_SequenceNull_ThrowsArgumentNullException()
        {
            Assert.Throws<ArgumentNullException>(() => new DicePacket(null, new List<IDiceWord>{new DiceWord("Test")}));
        }

        [Fact]
        public void ctor_WordsNull_ThrowsArgumentNullException()
        {
            Assert.Throws<ArgumentNullException>(
                () => new DicePacket(new DicePacketSequence(123u, PacketType.Request, Origin.Client), null));
        }

        [Fact]
        public void ctor_ImplementsIPacket()
        {
            var instance = new DicePacket(packetSequenceMock.Object, wordsMock);
            Assert.IsAssignableFrom<IDicePacket>(instance);
        }

        [Fact]
        public void ctor_WithWords_WordsReturnsValue()
        {
            var instance = new DicePacket(packetSequenceMock.Object, wordsMock);
            Assert.Equal(wordsMock, instance.Words);
        }

        [Fact]
        public void ctor_WithOneWords_NumWords1()
        {
            wordsMock.Add(new DiceWord("myWord"));
            var instance = new DicePacket(packetSequenceMock.Object, wordsMock);
            Assert.Equal((uint)1, instance.NumWords);
        }

        [Fact]
        public void ctor_With3Words_NumWords3()
        {
            wordsMock.Add(new DiceWord("myWord"));
            wordsMock.Add(new DiceWord("myWord"));
            wordsMock.Add(new DiceWord("myWord"));
            var instance = new DicePacket(packetSequenceMock.Object, wordsMock);
            Assert.Equal((uint)3, instance.NumWords);
        }

        [Fact]
        public void ctor_With1WordTest_Size17()
        {
            wordsMock.Add(new DiceWord("Test"));
            var instance = new DicePacket(packetSequenceMock.Object, wordsMock);
            Assert.Equal((uint) 21, instance.Size);
        }

        [Fact]
        public void ctor_With2WordsTestTest_Size22()
        {
            wordsMock.Add(new DiceWord("Test"));
            wordsMock.Add(new DiceWord("Test"));
            var instance = new DicePacket(packetSequenceMock.Object, wordsMock);
            Assert.Equal((uint)30, instance.Size);
        }

        #endregion

        #region ToBytes()

        [Fact]
        public void ToBytes_Packet458RequestServerListPlayersAll_BytesEqual()
        {
            var packetSequence = new DicePacketSequence((uint)458, PacketType.Request, Origin.Client);
            var words = new List<IDiceWord>() {new DiceWord("listPlayers"), new DiceWord("all")};
            var packet = new DicePacket(packetSequence, words);

            var expectedBytes = Convert.FromBase64String("ygEAgCQAAAACAAAACwAAAGxpc3RQbGF5ZXJzAAMAAABhbGwA");
            Assert.Equal(expectedBytes, packet.ToBytes());
        }

        #endregion

        #region ToString()

        [Fact]
        public void ToString_123ClientRequestServerInfo_123ClientRequestServerInfoSize()
        {
            var packet = new DicePacket(new DicePacketSequence(123, PacketType.Request, Origin.Client),
                                    new List<IDiceWord>() {new DiceWord("serverInfo")});
            var actual = packet.ToString();
            Assert.Equal("{[Id: 123] [Client] [Request] [Size: 27] [1: serverInfo]}", actual);
        }

        [Fact]
        public void ToString_123ClientRequestListPlayersAll_123ClientRequestListPlayersAllSize()
        {
            var packet = new DicePacket(new DicePacketSequence(123, PacketType.Request, Origin.Client),
                                    new List<IDiceWord>() { new DiceWord("listPlayers"), new DiceWord("all") });
            var actual = packet.ToString();
            Assert.Equal("{[Id: 123] [Client] [Request] [Size: 36] [1: listPlayers] [2: all]}", actual);
        }

        #endregion

        #region Equals()

        [Fact]
        public void Equals_PacketSequenceMockTest_True()
        {
            var packet = new DicePacket(packetSequenceMock.Object, new List<IDiceWord>() {new DiceWord("Test")});
            var packet2 = new DicePacket(packetSequenceMock.Object, new List<IDiceWord>() { new DiceWord("Test") });
            Assert.Equal(packet, packet2);
        }

        [Fact]
        public void Equals_WithString_False()
        {
            var packet = new DicePacket(packetSequenceMock.Object, new List<IDiceWord>() { new DiceWord("Test") });

            Assert.False(packet.Equals("A String"));
        }

        [Fact]
        public void Equals_Null_False()
        {
            var packet = new DicePacket(packetSequenceMock.Object, new List<IDiceWord>() { new DiceWord("Test") });

            Assert.False(packet.Equals(null));
        }

        [Fact]
        public void Equals_SameInstance_True()
        {
            var packet = new DicePacket(packetSequenceMock.Object, new List<IDiceWord>() { new DiceWord("Test") });

            Assert.True(packet.Equals(packet));
        }

        [Fact]
        public void Equals_AnotherPacket_True()
        {
            var packet = new DicePacket(packetSequenceMock.Object, new List<IDiceWord>() { new DiceWord("Test") });
            var packet2 = new DicePacket(new DicePacketSequence(123, PacketType.Request, Origin.Client), new List<IDiceWord>() { new DiceWord("Test2") });
            Assert.False(packet.Equals(packet2));
        }

        #endregion

        #region GetHashCode()

        [Fact]
        public void GetHashCode_PacketSequenceMockTest_True()
        {
            var packet = new DicePacket(packetSequenceMock.Object, new List<IDiceWord>() { new DiceWord("Test") });
            Assert.Equal(packet.GetHashCode(), packet.GetHashCode());
        }

        #endregion
    }
}


text:
/*
 * DO NOT EDIT.  THIS FILE IS GENERATED FROM /builds/slave/rel-m-rel-xr-osx64-bld/build/toolkit/components/passwordmgr/nsILoginManager.idl
 */

#ifndef __gen_nsILoginManager_h__
#define __gen_nsILoginManager_h__

#ifndef __gen_nsISupports_h__
#include "nsISupports.h"
#endif

/* For IDL files that don't want to include root IDL files. */
#ifndef NS_NO_VTABLE
#define NS_NO_VTABLE
#endif
class nsIURI; /* forward declaration */

class nsILoginInfo; /* forward declaration */

class nsIAutoCompleteResult; /* forward declaration */

class nsIDOMHTMLInputElement; /* forward declaration */

class nsIDOMHTMLFormElement; /* forward declaration */

class nsIPropertyBag; /* forward declaration */

/* starting interface:    nsILoginManager */
#define NS_ILOGINMANAGER_IID_STR "1f02142f-7e3f-4d02-b3e0-495c5f83ad7d"

#define NS_ILOGINMANAGER_IID \
  {0x1f02142f, 0x7e3f, 0x4d02, \
    { 0xb3, 0xe0, 0x49, 0x5c, 0x5f, 0x83, 0xad, 0x7d }}

class NS_NO_VTABLE NS_SCRIPTABLE nsILoginManager : public nsISupports {
 public:

  NS_DECLARE_STATIC_IID_ACCESSOR(NS_ILOGINMANAGER_IID)

  /* void addLogin (in nsILoginInfo aLogin); */
  NS_SCRIPTABLE NS_IMETHOD AddLogin(nsILoginInfo *aLogin) = 0;

  /* void removeLogin (in nsILoginInfo aLogin); */
  NS_SCRIPTABLE NS_IMETHOD RemoveLogin(nsILoginInfo *aLogin) = 0;

  /* void modifyLogin (in nsILoginInfo oldLogin, in nsISupports newLoginData); */
  NS_SCRIPTABLE NS_IMETHOD ModifyLogin(nsILoginInfo *oldLogin, nsISupports *newLoginData) = 0;

  /* void removeAllLogins (); */
  NS_SCRIPTABLE NS_IMETHOD RemoveAllLogins(void) = 0;

  /* void getAllLogins ([optional] out unsigned long count, [array, size_is (count), retval] out nsILoginInfo logins); */
  NS_SCRIPTABLE NS_IMETHOD GetAllLogins(PRUint32 *count NS_OUTPARAM, nsILoginInfo * **logins NS_OUTPARAM) = 0;

  /* void getAllDisabledHosts ([optional] out unsigned long count, [array, size_is (count), retval] out wstring hostnames); */
  NS_SCRIPTABLE NS_IMETHOD GetAllDisabledHosts(PRUint32 *count NS_OUTPARAM, PRUnichar * **hostnames NS_OUTPARAM) = 0;

  /* boolean getLoginSavingEnabled (in AString aHost); */
  NS_SCRIPTABLE NS_IMETHOD GetLoginSavingEnabled(const nsAString & aHost, PRBool *_retval NS_OUTPARAM) = 0;

  /* void setLoginSavingEnabled (in AString aHost, in boolean isEnabled); */
  NS_SCRIPTABLE NS_IMETHOD SetLoginSavingEnabled(const nsAString & aHost, PRBool isEnabled) = 0;

  /* void findLogins (out unsigned long count, in AString aHostname, in AString aActionURL, in AString aHttpRealm, [array, size_is (count), retval] out nsILoginInfo logins); */
  NS_SCRIPTABLE NS_IMETHOD FindLogins(PRUint32 *count NS_OUTPARAM, const nsAString & aHostname, const nsAString & aActionURL, const nsAString & aHttpRealm, nsILoginInfo * **logins NS_OUTPARAM) = 0;

  /* unsigned long countLogins (in AString aHostname, in AString aActionURL, in AString aHttpRealm); */
  NS_SCRIPTABLE NS_IMETHOD CountLogins(const nsAString & aHostname, const nsAString & aActionURL, const nsAString & aHttpRealm, PRUint32 *_retval NS_OUTPARAM) = 0;

  /* nsIAutoCompleteResult autoCompleteSearch (in AString aSearchString, in nsIAutoCompleteResult aPreviousResult, in nsIDOMHTMLInputElement aElement); */
  NS_SCRIPTABLE NS_IMETHOD AutoCompleteSearch(const nsAString & aSearchString, nsIAutoCompleteResult *aPreviousResult, nsIDOMHTMLInputElement *aElement, nsIAutoCompleteResult * *_retval NS_OUTPARAM) = 0;

  /* boolean fillForm (in nsIDOMHTMLFormElement aForm); */
  NS_SCRIPTABLE NS_IMETHOD FillForm(nsIDOMHTMLFormElement *aForm, PRBool *_retval NS_OUTPARAM) = 0;

  /* void searchLogins (out unsigned long count, in nsIPropertyBag matchData, [array, size_is (count), retval] out nsILoginInfo logins); */
  NS_SCRIPTABLE NS_IMETHOD SearchLogins(PRUint32 *count NS_OUTPARAM, nsIPropertyBag *matchData, nsILoginInfo * **logins NS_OUTPARAM) = 0;

  /* readonly attribute boolean uiBusy; */
  NS_SCRIPTABLE NS_IMETHOD GetUiBusy(PRBool *aUiBusy) = 0;

};

  NS_DEFINE_STATIC_IID_ACCESSOR(nsILoginManager, NS_ILOGINMANAGER_IID)

/* Use this macro when declaring classes that implement this interface. */
#define NS_DECL_NSILOGINMANAGER \
  NS_SCRIPTABLE NS_IMETHOD AddLogin(nsILoginInfo *aLogin); \
  NS_SCRIPTABLE NS_IMETHOD RemoveLogin(nsILoginInfo *aLogin); \
  NS_SCRIPTABLE NS_IMETHOD ModifyLogin(nsILoginInfo *oldLogin, nsISupports *newLoginData); \
  NS_SCRIPTABLE NS_IMETHOD RemoveAllLogins(void); \
  NS_SCRIPTABLE NS_IMETHOD GetAllLogins(PRUint32 *count NS_OUTPARAM, nsILoginInfo * **logins NS_OUTPARAM); \
  NS_SCRIPTABLE NS_IMETHOD GetAllDisabledHosts(PRUint32 *count NS_OUTPARAM, PRUnichar * **hostnames NS_OUTPARAM); \
  NS_SCRIPTABLE NS_IMETHOD GetLoginSavingEnabled(const nsAString & aHost, PRBool *_retval NS_OUTPARAM); \
  NS_SCRIPTABLE NS_IMETHOD SetLoginSavingEnabled(const nsAString & aHost, PRBool isEnabled); \
  NS_SCRIPTABLE NS_IMETHOD FindLogins(PRUint32 *count NS_OUTPARAM, const nsAString & aHostname, const nsAString & aActionURL, const nsAString & aHttpRealm, nsILoginInfo * **logins NS_OUTPARAM); \
  NS_SCRIPTABLE NS_IMETHOD CountLogins(const nsAString & aHostname, const nsAString & aActionURL, const nsAString & aHttpRealm, PRUint32 *_retval NS_OUTPARAM); \
  NS_SCRIPTABLE NS_IMETHOD AutoCompleteSearch(const nsAString & aSearchString, nsIAutoCompleteResult *aPreviousResult, nsIDOMHTMLInputElement *aElement, nsIAutoCompleteResult * *_retval NS_OUTPARAM); \
  NS_SCRIPTABLE NS_IMETHOD FillForm(nsIDOMHTMLFormElement *aForm, PRBool *_retval NS_OUTPARAM); \
  NS_SCRIPTABLE NS_IMETHOD SearchLogins(PRUint32 *count NS_OUTPARAM, nsIPropertyBag *matchData, nsILoginInfo * **logins NS_OUTPARAM); \
  NS_SCRIPTABLE NS_IMETHOD GetUiBusy(PRBool *aUiBusy);

/* Use this macro to declare functions that forward the behavior of this interface to another object. */
#define NS_FORWARD_NSILOGINMANAGER(_to) \
  NS_SCRIPTABLE NS_IMETHOD AddLogin(nsILoginInfo *aLogin) { return _to AddLogin(aLogin); } \
  NS_SCRIPTABLE NS_IMETHOD RemoveLogin(nsILoginInfo *aLogin) { return _to RemoveLogin(aLogin); } \
  NS_SCRIPTABLE NS_IMETHOD ModifyLogin(nsILoginInfo *oldLogin, nsISupports *newLoginData) { return _to ModifyLogin(oldLogin, newLoginData); } \
  NS_SCRIPTABLE NS_IMETHOD RemoveAllLogins(void) { return _to RemoveAllLogins(); } \
  NS_SCRIPTABLE NS_IMETHOD GetAllLogins(PRUint32 *count NS_OUTPARAM, nsILoginInfo * **logins NS_OUTPARAM) { return _to GetAllLogins(count, logins); } \
  NS_SCRIPTABLE NS_IMETHOD GetAllDisabledHosts(PRUint32 *count NS_OUTPARAM, PRUnichar * **hostnames NS_OUTPARAM) { return _to GetAllDisabledHosts(count, hostnames); } \
  NS_SCRIPTABLE NS_IMETHOD GetLoginSavingEnabled(const nsAString & aHost, PRBool *_retval NS_OUTPARAM) { return _to GetLoginSavingEnabled(aHost, _retval); } \
  NS_SCRIPTABLE NS_IMETHOD SetLoginSavingEnabled(const nsAString & aHost, PRBool isEnabled) { return _to SetLoginSavingEnabled(aHost, isEnabled); } \
  NS_SCRIPTABLE NS_IMETHOD FindLogins(PRUint32 *count NS_OUTPARAM, const nsAString & aHostname, const nsAString & aActionURL, const nsAString & aHttpRealm, nsILoginInfo * **logins NS_OUTPARAM) { return _to FindLogins(count, aHostname, aActionURL, aHttpRealm, logins); } \
  NS_SCRIPTABLE NS_IMETHOD CountLogins(const nsAString & aHostname, const nsAString & aActionURL, const nsAString & aHttpRealm, PRUint32 *_retval NS_OUTPARAM) { return _to CountLogins(aHostname, aActionURL, aHttpRealm, _retval); } \
  NS_SCRIPTABLE NS_IMETHOD AutoCompleteSearch(const nsAString & aSearchString, nsIAutoCompleteResult *aPreviousResult, nsIDOMHTMLInputElement *aElement, nsIAutoCompleteResult * *_retval NS_OUTPARAM) { return _to AutoCompleteSearch(aSearchString, aPreviousResult, aElement, _retval); } \
  NS_SCRIPTABLE NS_IMETHOD FillForm(nsIDOMHTMLFormElement *aForm, PRBool *_retval NS_OUTPARAM) { return _to FillForm(aForm, _retval); } \
  NS_SCRIPTABLE NS_IMETHOD SearchLogins(PRUint32 *count NS_OUTPARAM, nsIPropertyBag *matchData, nsILoginInfo * **logins NS_OUTPARAM) { return _to SearchLogins(count, matchData, logins); } \
  NS_SCRIPTABLE NS_IMETHOD GetUiBusy(PRBool *aUiBusy) { return _to GetUiBusy(aUiBusy); }

/* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */
#define NS_FORWARD_SAFE_NSILOGINMANAGER(_to) \
  NS_SCRIPTABLE NS_IMETHOD AddLogin(nsILoginInfo *aLogin) { return !_to ? NS_ERROR_NULL_POINTER : _to->AddLogin(aLogin); } \
  NS_SCRIPTABLE NS_IMETHOD RemoveLogin(nsILoginInfo *aLogin) { return !_to ? NS_ERROR_NULL_POINTER : _to->RemoveLogin(aLogin); } \
  NS_SCRIPTABLE NS_IMETHOD ModifyLogin(nsILoginInfo *oldLogin, nsISupports *newLoginData) { return !_to ? NS_ERROR_NULL_POINTER : _to->ModifyLogin(oldLogin, newLoginData); } \
  NS_SCRIPTABLE NS_IMETHOD RemoveAllLogins(void) { return !_to ? NS_ERROR_NULL_POINTER : _to->RemoveAllLogins(); } \
  NS_SCRIPTABLE NS_IMETHOD GetAllLogins(PRUint32 *count NS_OUTPARAM, nsILoginInfo * **logins NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetAllLogins(count, logins); } \
  NS_SCRIPTABLE NS_IMETHOD GetAllDisabledHosts(PRUint32 *count NS_OUTPARAM, PRUnichar * **hostnames NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetAllDisabledHosts(count, hostnames); } \
  NS_SCRIPTABLE NS_IMETHOD GetLoginSavingEnabled(const nsAString & aHost, PRBool *_retval NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetLoginSavingEnabled(aHost, _retval); } \
  NS_SCRIPTABLE NS_IMETHOD SetLoginSavingEnabled(const nsAString & aHost, PRBool isEnabled) { return !_to ? NS_ERROR_NULL_POINTER : _to->SetLoginSavingEnabled(aHost, isEnabled); } \
  NS_SCRIPTABLE NS_IMETHOD FindLogins(PRUint32 *count NS_OUTPARAM, const nsAString & aHostname, const nsAString & aActionURL, const nsAString & aHttpRealm, nsILoginInfo * **logins NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->FindLogins(count, aHostname, aActionURL, aHttpRealm, logins); } \
  NS_SCRIPTABLE NS_IMETHOD CountLogins(const nsAString & aHostname, const nsAString & aActionURL, const nsAString & aHttpRealm, PRUint32 *_retval NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->CountLogins(aHostname, aActionURL, aHttpRealm, _retval); } \
  NS_SCRIPTABLE NS_IMETHOD AutoCompleteSearch(const nsAString & aSearchString, nsIAutoCompleteResult *aPreviousResult, nsIDOMHTMLInputElement *aElement, nsIAutoCompleteResult * *_retval NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->AutoCompleteSearch(aSearchString, aPreviousResult, aElement, _retval); } \
  NS_SCRIPTABLE NS_IMETHOD FillForm(nsIDOMHTMLFormElement *aForm, PRBool *_retval NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->FillForm(aForm, _retval); } \
  NS_SCRIPTABLE NS_IMETHOD SearchLogins(PRUint32 *count NS_OUTPARAM, nsIPropertyBag *matchData, nsILoginInfo * **logins NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->SearchLogins(count, matchData, logins); } \
  NS_SCRIPTABLE NS_IMETHOD GetUiBusy(PRBool *aUiBusy) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetUiBusy(aUiBusy); }

#if 0
/* Use the code below as a template for the implementation class for this interface. */

/* Header file */
class nsLoginManager : public nsILoginManager
{
public:
  NS_DECL_ISUPPORTS
  NS_DECL_NSILOGINMANAGER

  nsLoginManager();

private:
  ~nsLoginManager();

protected:
  /* additional members */
};

/* Implementation file */
NS_IMPL_ISUPPORTS1(nsLoginManager, nsILoginManager)

nsLoginManager::nsLoginManager()
{
  /* member initializers and constructor code */
}

nsLoginManager::~nsLoginManager()
{
  /* destructor code */
}

/* void addLogin (in nsILoginInfo aLogin); */
NS_IMETHODIMP nsLoginManager::AddLogin(nsILoginInfo *aLogin)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* void removeLogin (in nsILoginInfo aLogin); */
NS_IMETHODIMP nsLoginManager::RemoveLogin(nsILoginInfo *aLogin)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* void modifyLogin (in nsILoginInfo oldLogin, in nsISupports newLoginData); */
NS_IMETHODIMP nsLoginManager::ModifyLogin(nsILoginInfo *oldLogin, nsISupports *newLoginData)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* void removeAllLogins (); */
NS_IMETHODIMP nsLoginManager::RemoveAllLogins()
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* void getAllLogins ([optional] out unsigned long count, [array, size_is (count), retval] out nsILoginInfo logins); */
NS_IMETHODIMP nsLoginManager::GetAllLogins(PRUint32 *count NS_OUTPARAM, nsILoginInfo * **logins NS_OUTPARAM)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* void getAllDisabledHosts ([optional] out unsigned long count, [array, size_is (count), retval] out wstring hostnames); */
NS_IMETHODIMP nsLoginManager::GetAllDisabledHosts(PRUint32 *count NS_OUTPARAM, PRUnichar * **hostnames NS_OUTPARAM)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* boolean getLoginSavingEnabled (in AString aHost); */
NS_IMETHODIMP nsLoginManager::GetLoginSavingEnabled(const nsAString & aHost, PRBool *_retval NS_OUTPARAM)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* void setLoginSavingEnabled (in AString aHost, in boolean isEnabled); */
NS_IMETHODIMP nsLoginManager::SetLoginSavingEnabled(const nsAString & aHost, PRBool isEnabled)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* void findLogins (out unsigned long count, in AString aHostname, in AString aActionURL, in AString aHttpRealm, [array, size_is (count), retval] out nsILoginInfo logins); */
NS_IMETHODIMP nsLoginManager::FindLogins(PRUint32 *count NS_OUTPARAM, const nsAString & aHostname, const nsAString & aActionURL, const nsAString & aHttpRealm, nsILoginInfo * **logins NS_OUTPARAM)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* unsigned long countLogins (in AString aHostname, in AString aActionURL, in AString aHttpRealm); */
NS_IMETHODIMP nsLoginManager::CountLogins(const nsAString & aHostname, const nsAString & aActionURL, const nsAString & aHttpRealm, PRUint32 *_retval NS_OUTPARAM)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* nsIAutoCompleteResult autoCompleteSearch (in AString aSearchString, in nsIAutoCompleteResult aPreviousResult, in nsIDOMHTMLInputElement aElement); */
NS_IMETHODIMP nsLoginManager::AutoCompleteSearch(const nsAString & aSearchString, nsIAutoCompleteResult *aPreviousResult, nsIDOMHTMLInputElement *aElement, nsIAutoCompleteResult * *_retval NS_OUTPARAM)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* boolean fillForm (in nsIDOMHTMLFormElement aForm); */
NS_IMETHODIMP nsLoginManager::FillForm(nsIDOMHTMLFormElement *aForm, PRBool *_retval NS_OUTPARAM)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* void searchLogins (out unsigned long count, in nsIPropertyBag matchData, [array, size_is (count), retval] out nsILoginInfo logins); */
NS_IMETHODIMP nsLoginManager::SearchLogins(PRUint32 *count NS_OUTPARAM, nsIPropertyBag *matchData, nsILoginInfo * **logins NS_OUTPARAM)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* readonly attribute boolean uiBusy; */
NS_IMETHODIMP nsLoginManager::GetUiBusy(PRBool *aUiBusy)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* End of implementation class template. */
#endif

#define NS_LOGINMANAGER_CONTRACTID "@mozilla.org/login-manager;1"

#endif /* __gen_nsILoginManager_h__ */