text:
using System.Collections.Generic;
using Org.Xmlpull.V1;

namespace System.Xml.Linq
{
    /// <summary>
    /// XML element
    /// </summary>
	public class XElement : XContainer
    {
        internal XAttribute lastAttribute;
        internal XName name;

        /// <summary>
        /// Default ctor
        /// </summary>
        public XElement(XName name)
        {
            if (name == null)
                throw new ArgumentNullException("name");
            this.name = name;
        }

        /// <summary>
        /// Default ctor
        /// </summary>
        public XElement(XName name, object content)
            : this(name)
        {
            Add(content);
        }

        /// <summary>
        /// Default ctor
        /// </summary>
        public XElement(XName name, params object[] content)
            : this(name)
        {
            Add(content, false);
        }

        /// <summary>
        /// Copy ctor
        /// </summary>
        public XElement(XElement source)
            : base(source)
        {
            name = source.name;
            if (source.lastAttribute != null)
            {
                foreach (var attr in source.Attributes())
                {
                    Add(new XAttribute(attr), false);
                }
            }
        }

	    /// <summary>
	    /// Gets the type of this node.
	    /// </summary>
	    public override XmlNodeType NodeType
        {
            get { return XmlNodeType.Element; }
        }

        /// <summary>
        /// Gets/sets the name of this element.
        /// </summary>
        public XName Name
        {
            get { return name; }
            set
            {
                if (value == null)
                    throw new ArgumentNullException("value");
                var hasHandlers = NotifyChanging(this, XObjectChangeEventArgs.Name);
                name = value;
                if (hasHandlers)
                    NotifyChanged(this, XObjectChangeEventArgs.Name);
            }
        }

        /// <summary>
        /// Gets/sets the concatenated text content of this element.
        /// </summary>
        public string Value
        {
            get
            {
                if (content == null)
                {
                    return "";
                }
                var text = content as string;
                if (text != null)
                    return text;
                var buffer = new Java.Lang.StringBuffer();
                AppendTextTo(buffer);
                return buffer.ToString();
            }
            set
            {
                if (value == null)
                    throw new ArgumentNullException("value");
                RemoveNodes(true);
                Add(value, true);
            }
        }

        /// <summary>
        /// Does this element have at least one attribute?
        /// </summary>
        public bool HasAttributes
        {
            get { return (lastAttribute != null); }
        }

        /// <summary>
        /// Does this element have at least one child element?
        /// </summary>
        public bool HasElements
        {
            get
            {
                foreach (var node in Nodes())
                {
                    if (node is XElement)
                        return true;
                }
                return false;
            }
        }

        /// <summary>
        /// Does this element have no content?
        /// </summary>
        public bool IsEmpty
        {
            get { return (content == null); }
        }

        /// <summary>
        /// Gets all attributes.
        /// </summary>
        public IEnumerable<XAttribute> Attributes()
        {
            var x = lastAttribute;
            if (x != null)
            {
                do
                {
                    x = x.next;
                    yield return x;
                } while ((x.parent == this) && (lastAttribute != x));
            }
        }

        /// <summary>
        /// Gets all attributes with given name.
        /// </summary>
        public IEnumerable<XAttribute> Attributes(XName name)
        {
            if (name == null)
                yield break;
            if (lastAttribute != null)
            {
                foreach (var attr in Attributes())
                {
                    if (attr.name == name)
                        yield return attr;
                }
            }
        }

        /// <summary>
        /// Gets the first attribute with given name.
        /// </summary>
        public XAttribute Attribute(XName name)
        {
            if (lastAttribute != null)
            {
                foreach (var attr in Attributes())
                {
                    if (attr.name == name)
                        return attr;
                }
            }
            return null;
        }

        /// <summary>
        /// Add the given attribute
        /// </summary>
        internal override void Add(XAttribute attribute, bool notify)
        {
            if (Attribute(attribute.name) != null)
                throw new InvalidOperationException("Duplicate attribute");
            if (attribute.parent != null)
            {
                attribute = new XAttribute(attribute);
            }
            Append(attribute, notify);
        }

        /// <summary>
        /// Append the given attribute
        /// </summary>
        internal void Append(XAttribute attribute, bool notify)
        {
            if (attribute.parent != null)
                throw new InvalidOperationException("Invalid parent");
            var hasHandlers = notify && NotifyChanging(attribute, XObjectChangeEventArgs.Add);

            // Now append

            attribute.parent = this;
            if (lastAttribute == null)
            {
                attribute.next = attribute;
            }
            else
            {
                attribute.next = lastAttribute.next;
                lastAttribute.next = attribute;
            }
            lastAttribute = attribute;

            // Notify if needed
            if (hasHandlers) NotifyChanged(attribute, XObjectChangeEventArgs.Add);
        }

        /// <summary>
        /// Remove the given attribute from my list.
        /// </summary>
        internal void Remove(XAttribute attribute)
        {
            if (attribute.parent != this)
            {
                throw new InvalidOperationException("Invalid parent");
            }

            var hasHandlers = NotifyChanging(this, XObjectChangeEventArgs.Remove);

            var iterator = lastAttribute;
            if ((iterator == attribute) && (attribute.next == attribute))
            {
                // Last remaining attribute
                lastAttribute = null;
            }
            else
            {
                XAttribute next;
                while ((next = iterator.next) != attribute)
                {
                    iterator = next;
                }
                if (lastAttribute == attribute)
                {
                    lastAttribute = iterator;
                }
                iterator.next = attribute.next;
            }
            attribute.parent = null;
            attribute.next = null;

            if (hasHandlers)
            {
                NotifyChanged(this, XObjectChangeEventArgs.Remove);
            }
        }

        /// <summary>
        /// Returns a collection of elements that contain this element, and all descendant elements of this element, in document order.
        /// </summary>
        public IEnumerable<XElement> DescendantsAndSelf()
        {
            yield return this;

            foreach (var decendant in Descendants())
            {
                yield return decendant;
            }
        }

        /// <summary>
        /// Returns a collection of elements that contain this element, and all descendant elements of this element, in document order.
        /// </summary>
        public IEnumerable<XElement> DescendantsAndSelf(XName name)
        {
            if(Name == name) yield return this;

            foreach (var decendant in Descendants(name))
            {
                yield return decendant;
            }
        }

        /// <summary>
        /// Returns a collection of nodes that contain this element, and all descendant nodes of this element, in document order.
        /// </summary>
        public IEnumerable<XNode> DescendantNodesAndSelf()
        {
            yield return this;

            foreach (var decendantNode in DescendantNodes())
            {
                yield return decendantNode;
            }
        }

        /// <summary>
        /// Create a clone of this node.
        /// </summary>
        internal override XNode Clone()
        {
            return new XElement(this);
        }

        /// <summary>
        /// Serialize this object to the given serializer.
        /// </summary>
        public override void WriteTo(IXmlSerializer serializer)
        {
            serializer.StartTag(name.NamespaceName, name.LocalName);

            if (HasAttributes)
            {
                foreach (var attr in Attributes())
                {
                    attr.WriteTo(serializer);
                }
            }

            if (content is string)
            {
                serializer.Text((string) content);
            }
            else if (content is XNode)
            {
                foreach (var node in Nodes())
                {
                    node.WriteTo(serializer);
                }
            }

            serializer.EndTag(name.NamespaceName, name.LocalName);
        }
    }
}


text:
from cachel.base import BaseCache, SERIALIZERS
from cachel import compat

class Cache(BaseCache):
    def __init__(self):
        self.cache = {}

    def set(self, key, value, expire):
        self.cache[key] = value, expire

    def get(self, key):
        try:
            return self.cache[key][0]
        except KeyError:
            pass

    def delete(self, key):
        self.cache.pop(key, None)

if compat.ASYNC_AWAIT:
    from ._async_helpers import AsyncCache

redpajama_set_name: RedPajamaGithub


text:
module SyncsHelper
  module ClientActions
    MAX_ERRORS = 10

    private

    # run the complete download procedure, with batch support.
    # f is the log file handle
    def run_download(server_machine_id, f)
      count = begin
        do_get_server_data_count(address, server_machine_id)
      rescue Exception => e
        f.puts "#{log_timestamp} -- DOWNLOADED AND PROCESSED: 0 RECORDS"
        f.flush
        return ActsAsReplica::Structs::SyncPayload.build_empty
      end

      f.puts "#{log_timestamp} --- ESTIMATED TOTAL RECORDS TO DOWNLOAD: #{count.total}"
      f.flush
      total, total_errors = 0, 0
      while total_errors < SyncsHelper::ClientActions::MAX_ERRORS
        begin
          result_up = do_get_server_data(address, server_machine_id)
          if result_up.status == 200
            f.puts "#{log_timestamp} -- DOWNLOADED AND PROCESSED: #{total} RECORDS"
            f.flush
            result_up.total > 0 ? total += result_up.total : break
          elsif result_up.errors && result_up.errors.size > 0
            total_errors += 1 # avoid infinite loop
            f.puts "#{log_timestamp} --- WARNING FROM #{address}. ERROR: #{result_up.errors.join("\n")}"
            f.flush
          end
        rescue Exception => e
          total_errors += 1 # avoid infinite loop
          f.puts "#{log_timestamp} --- WARNING FROM #{address}. ERROR: #{e.inspect}"
          f.flush
        end
      end
      # only consider a Fatal Error if looped many times without results
      # this should flag the origin caller to stop the process and ask the user to retry
      if total_errors == SyncsHelper::ClientActions::MAX_ERRORS
        f.puts "#{log_timestamp} --- ERROR DOWNLOADING FROM #{address}. ERROR: SEE WARNINGS ABOVE"
        f.flush
      end
      total
    end

    # run the complete upload procedure, with batch support.
    # server_result is the last synced id got from the server in the handshake procedure
    # f is the log file handle
    def run_upload(server_result, server_machine_id, f)
      count = Replica.down(server_result, server_machine_id, :count => true)
      f.puts "#{log_timestamp} --- ESTIMATED TOTAL RECORDS TO UPLOAD: #{count.total}"
      f.flush
      total, total_errors = 0, 0
      while total_errors < SyncsHelper::ClientActions::MAX_ERRORS
        begin
          result_down = do_send_client_data(address, server_result, server_machine_id)
          server_result = result_down.last_synced_id if result_down.respond_to?(:last_synced_id)
          if result_down.total > 0
            total += result_down.total
            f.puts "#{log_timestamp} -- UPLOADED AND PROCESSED: #{total} RECORDS"
            f.flush
          else
            break
          end
        rescue Exception => e
          total_errors += 1 # avoid infinite loop
          f.puts "#{log_timestamp} --- ERROR: CANNOT UPLOAD AT #{address}. ERROR: #{e.inspect}"
          f.flush
        end
      end
      total
    end

    def run_sync(manual_server_package = nil)
      @config = $SYNC_CONFIG
      total_down, total_up = 0, 0
      File.open(SyncsHelper::ReplicatorRunner.log_file, 'a') do |f|
        start_time = Time.now
        f.puts "#{log_timestamp} --- REPLICATION STARTED."
        f.flush
        begin
          server_package = manual_server_package || handshake_authenticate(address)
          if server_package
            logger.info "-- HANDSHAKE FINAL PACKAGE: #{server_package.to_yaml}"
            server_result = server_package[:last_synced]
            server_machine_id = server_package[:server_machine_id]
            total_up = run_upload( server_result, server_machine_id, f )
            total_down = run_download( server_machine_id, f )
          else
            f.puts "#{log_timestamp} --- ERROR: PROBLEMS AUTHENTICATION. WRONG USERNAME?"
            f.flush
          end
        rescue Exception => e
          f.puts "#{log_timestamp} --- ERROR: CANNOT REACH SERVER AT #{address}. ERROR: #{e.inspect}"
          f.flush
        end
        end_time = Time.now
        total_time = log_fmt_timestamp(end_time - start_time)
        f.puts "#{log_timestamp} --- REPLICATION FINISHED IN #{total_time} HOURS. #{total_down} RECORDS DOWNLOADED. #{total_up} RECORDS UPLOADED."
        f.flush
      end
    end

    def run_dump(manual_server_package = nil, tables_list = [])
      @config = $SYNC_CONFIG
      total_tables = 0
      File.open(SyncsHelper::ReplicatorRunner.log_file, 'a') do |f|
        start_time = Time.now
        f.puts "#{log_timestamp} --- DUMP STARTED."
        f.flush
        begin
          server_package = manual_server_package || handshake_authenticate(address)
          if server_package
            logger.info "-- HANDSHAKE FINAL PACKAGE: #{server_package.to_yaml}"
            tables_list.each do |table_name|
              result_dump = do_get_server_dump(address, table_name)
              if result_dump.errors && result_dump.errors.size > 0
                f.puts "#{log_timestamp} --- ERROR DOWNLOADING FROM #{address}. ERROR: #{result_dump.errors.join("\n")}"
                f.flush
              end
            end
          else
            f.puts "#{log_timestamp} --- ERROR: PROBLEMS AUTHENTICATION. WRONG USERNAME?"
            f.flush
          end
        rescue Exception => e
          f.puts "#{log_timestamp} --- ERROR: CANNOT REACH SERVER AT #{address}. ERROR: #{e.inspect}"
          f.flush
        end
        end_time = Time.now
        total_time = log_fmt_timestamp(end_time - start_time)
        f.puts "#{log_timestamp} --- DUMP FINISHED IN #{total_time} HOURS. #{total_tables} TABLES DOWNLOADED"
        f.flush
      end
    end
  end
end


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

using System;
using System.ComponentModel;

namespace DocumentFormat.OpenXml.Office2016.Drawing.ChartDrawing
{
    /// <summary>
    /// <para>Defines the IdxXsdunsignedInt Class.</para>
    /// <para>This class is available in Office 2016 and above.</para>
    /// <para>When the object is serialized out as xml, it's qualified name is cx:idx.</para>
    /// </summary>
    [Obsolete("Please use UnsignedIntegerType as this type will be removed in a future version")]
    [EditorBrowsable(EditorBrowsableState.Never)]
    public partial class IdxXsdunsignedInt : OpenXmlLeafTextElement
    {
        /// <summary>
        /// Initializes a new instance of the IdxXsdunsignedInt class.
        /// </summary>
        public IdxXsdunsignedInt()
            : base()
        {
        }

        /// <summary>
        /// Initializes a new instance of the IdxXsdunsignedInt class with the specified text content.
        /// </summary>
        /// <param name="text">Specifies the text content of the element.</param>
        public IdxXsdunsignedInt(string text)
            : base(text)
        {
        }

        internal override OpenXmlSimpleType InnerTextToValue(string text)
        {
            return new UInt32Value { InnerText = text };
        }

        /// <inheritdoc/>
        public override OpenXmlElement CloneNode(bool deep) => CloneImp<IdxXsdunsignedInt>(deep);
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<DeploymentSettings>
  <DeploymentProfile>
    <InstanceID>0</InstanceID>
    <Name>Default Profile</Name>
    <WebUrl>http://localhost/scada</WebUrl>
    <ConnectionSettings>
      <Host>localhost</Host>
      <Port>10002</Port>
      <Username>ScadaAdmin</Username>
      <Password>672C3165774A308878A00927A987C759</Password>
      <ScadaInstance>Default</ScadaInstance>
      <SecretKey>5ABF5A7FD01752A2F1DFD21370B96EA462B0AE5C66A64F8901C9E1E2A06E40F1</SecretKey>
    </ConnectionSettings>
    <DownloadSettings>
      <IncludeBase>true</IncludeBase>
      <IncludeInterface>true</IncludeInterface>
      <IncludeServer>true</IncludeServer>
      <IncludeComm>true</IncludeComm>
      <IncludeWeb>true</IncludeWeb>
      <IgnoreRegKeys>false</IgnoreRegKeys>
      <IgnoreWebStorage>true</IgnoreWebStorage>
    </DownloadSettings>
    <UploadSettings>
      <IncludeBase>true</IncludeBase>
      <IncludeInterface>true</IncludeInterface>
      <IncludeServer>true</IncludeServer>
      <IncludeComm>true</IncludeComm>
      <IncludeWeb>true</IncludeWeb>
      <IgnoreRegKeys>false</IgnoreRegKeys>
      <IgnoreWebStorage>true</IgnoreWebStorage>
      <RestartServer>true</RestartServer>
      <RestartComm>true</RestartComm>
      <ObjNums />
    </UploadSettings>
  </DeploymentProfile>
</DeploymentSettings>


text:
PAWS
====

A utility for automatically pausing music when some other audio starts playing
and resuming the music afterwards.

Building instructions
---------------------
Install gcc, make, pkg-config and pulseaudio if necessary and then run

    $ make

in the directory to which paws has been downloaded.

Usage
-----

    $ paws [-v] [-p pause-cmd] [-r resume-cmd] [-i ignore-client]

### `-v`

Verbose. Print stuff when things happen.

### `-p pause-cmd`

Run `pause-cmd` when another application appears to have started playing audio.

### `-r resume-cmd`

Run `resume-cmd` when the applications that made us pause have stopped.

### `-i ignore-client`

Ignore any events that stem from a Pulseaudio client named `ignore-client`.
This will typically be the client name of your music player.

Example
-------

For Clementine, use the following flags:

    $ paws -p "clementine -u" -r "clementine -p" -i Clementine

To find out what client name to ignore for your music player, run:

    $ paws -v

If you fire up your music player and start playing some music at this point,
paws should print e.g.:

    Client 225 (Clementine) added its first input sink (# active clients = 1)

The text in parentheses is the name that you want to ignore.

Implementation notes
--------------------

The utility is written in C and uses Pulseaudio's asynchronous API. It listens
to certain Pulseaudio events, but will be idle for the most part.

The events that it listens to are those to do with clients (i.e. applications
that connect to the Pulseaudio server) and their input sinks, which are what
clients use to play audio.

The utility keeps track of any new input sinks and will run the pause command
when one appears. When the sinks that it keeps track of have been removed, it
will run the resume command.

It should be evident that the method used to determine if there is anything
playing may not always be accurate, but it seems to work pretty well.

Contact
-------
Olle Fredriksson - https://github.com/ollef


text:
module.exports = function(io, nox){

  io.configure('development', function(){

    io.set('log level', 1);

  });

  io.sockets.on('connection', function (socket) {

    nox.on('requestError', function(error){
      socket.emit('requestError', error);
    });

    nox.on('newRequest', function(partial){
      socket.emit('newRequest', partial);
    });

  });

}


text:
package trash.objects;

public abstract class AirGoon extends Goon{
    public static final int INTERSECT_MARGIN = 10;

    protected double targetY;

	public AirGoon(Player play)
    {
		super(play);
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
	<uses-sdk android:minSdkVersion="16" android:targetSdkVersion="17" />
	<application android:label="MobileTest.Android"></application>
</manifest>


text:
/*	$NetBSD: uipc_proto.c,v 1.23 2014/05/18 14:46:15 rmind Exp $	*/

/*-
 * Copyright (c) 1982, 1986, 1993
 *	The Regents of the University of California.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 *	@(#)uipc_proto.c	8.2 (Berkeley) 2/14/95
 */

#include <sys/cdefs.h>
__KERNEL_RCSID(0, "$NetBSD: uipc_proto.c,v 1.23 2014/05/18 14:46:15 rmind Exp $");

#include <sys/param.h>
#include <sys/socket.h>
#include <sys/protosw.h>
#include <sys/domain.h>
#include <sys/mbuf.h>
#include <sys/un.h>
#include <sys/socketvar.h>

#include <net/if.h>
#include <net/raw_cb.h>

/*
 * Definitions of protocols supported in the UNIX domain.
 */

DOMAIN_DEFINE(unixdomain);	/* forward define and add to link set */

const struct protosw unixsw[] = {
	{
		.pr_type = SOCK_STREAM,
		.pr_domain = &unixdomain,
		.pr_flags = PR_CONNREQUIRED|PR_WANTRCVD|PR_RIGHTS|PR_LISTEN,
		.pr_ctloutput = uipc_ctloutput,
		.pr_usrreqs = &unp_usrreqs,
	},
	{
		.pr_type = SOCK_DGRAM,
		.pr_domain = &unixdomain,
		.pr_flags = PR_ATOMIC|PR_ADDR|PR_RIGHTS,
		.pr_ctloutput = uipc_ctloutput,
		.pr_usrreqs = &unp_usrreqs,
	},
	{
		.pr_type = SOCK_SEQPACKET,
		.pr_domain = &unixdomain,
		.pr_flags = PR_CONNREQUIRED|PR_WANTRCVD|PR_RIGHTS|PR_LISTEN|
			    PR_ATOMIC,
		.pr_ctloutput = uipc_ctloutput,
		.pr_usrreqs = &unp_usrreqs,
	}
};

struct domain unixdomain = {
	.dom_family = AF_LOCAL,
	.dom_init = uipc_init,
	.dom_name = "unix",
	.dom_externalize = unp_externalize,
	.dom_dispose = unp_dispose,
	.dom_protosw = unixsw,
	.dom_protoswNPROTOSW = &unixsw[__arraycount(unixsw)],
};


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.mogsev.currencyconvertor">

    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/currency"
        android:label="@string/app_name"
        android:theme="@style/AppTheme.NoActionBar">
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name">

            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>

        </activity>

    </application>

</manifest>


text:
from unittest.mock import Mock, patch

from file_transfer.send_file import send_file

@patch("socket.socket")
@patch("builtins.open")
def test_send_file_running_as_expected(file, sock):
    # ===== initialization =====
    conn = Mock()
    sock.return_value.accept.return_value = conn, Mock()
    f = iter([1, None])
    file.return_value.__enter__.return_value.read.side_effect = lambda _: next(f)

    # ===== invoke =====
    send_file(filename="mytext.txt", testing=True)

    # ===== ensurance =====
    sock.assert_called_once()
    sock.return_value.bind.assert_called_once()
    sock.return_value.listen.assert_called_once()
    sock.return_value.accept.assert_called_once()
    conn.recv.assert_called_once()

    file.return_value.__enter__.assert_called_once()
    file.return_value.__enter__.return_value.read.assert_called()

    conn.send.assert_called_once()
    conn.close.assert_called_once()
    sock.return_value.shutdown.assert_called_once()
    sock.return_value.close.assert_called_once()


text:
namespace chromeos {

class CountingNewWindowClient : public ash::mojom::NewWindowClient {
 public:
  CountingNewWindowClient() {}
  ~CountingNewWindowClient() override {}

  int new_tab_action_count() const { return new_tab_action_count_; }

  // ash::mojom::NewWindowClient:
  void NewTab() override { new_tab_action_count_++; }
  void NewWindow(bool incognito) override {}
  void OpenFileManager() override {}
  void OpenCrosh() override {}
  void OpenGetHelp() override {}
  void RestoreTab() override {}
  void ShowKeyboardOverlay() override {}
  void ShowTaskManager() override {}
  void OpenFeedbackPage() override {}

 private:
  int new_tab_action_count_ = 0;

  DISALLOW_COPY_AND_ASSIGN(CountingNewWindowClient);
};

class StickyKeysBrowserTest : public InProcessBrowserTest {
 public:
  void SetUpOnMainThread() override {
    content::BrowserTestBase::SetUpOnMainThread();
    event_generator_.reset(
        new ui::test::EventGenerator(browser()->window()->GetNativeWindow()));

    new_window_client_ = new CountingNewWindowClient;
    ash::WmShellTestApi().SetNewWindowClient(
        base::WrapUnique(new_window_client_));
  }

 protected:
  StickyKeysBrowserTest() {}
  ~StickyKeysBrowserTest() override {}

  void EnableStickyKeys() {
    AccessibilityManager::Get()->EnableStickyKeys(true);
  }

  void DisableStickyKeys() {
    AccessibilityManager::Get()->EnableStickyKeys(false);
  }

  ash::SystemTray* GetSystemTray() {
    return ash::Shell::GetInstance()->GetPrimarySystemTray();
  }

  void SendKeyPress(ui::KeyboardCode key) {
    event_generator_->PressKey(key, ui::EF_NONE);
    event_generator_->ReleaseKey(key, ui::EF_NONE);
  }

  content::NotificationRegistrar registrar_;
  std::unique_ptr<ui::test::EventGenerator> event_generator_;
  CountingNewWindowClient* new_window_client_;

  DISALLOW_COPY_AND_ASSIGN(StickyKeysBrowserTest);
};

IN_PROC_BROWSER_TEST_F(StickyKeysBrowserTest, OpenTrayMenu) {
  EnableStickyKeys();

  // Open system tray bubble with shortcut.
  SendKeyPress(ui::VKEY_MENU); // alt key.
  SendKeyPress(ui::VKEY_SHIFT);
  SendKeyPress(ui::VKEY_S);
  EXPECT_TRUE(GetSystemTray()->HasSystemBubble());

  // Hide system bubble.
  GetSystemTray()->CloseSystemBubble();
  EXPECT_FALSE(GetSystemTray()->HasSystemBubble());

  // Pressing S again should not reopen the bubble.
  SendKeyPress(ui::VKEY_S);
  EXPECT_FALSE(GetSystemTray()->HasSystemBubble());

  // With sticky keys disabled, we will fail to perform the shortcut.
  DisableStickyKeys();
  SendKeyPress(ui::VKEY_MENU); // alt key.
  SendKeyPress(ui::VKEY_SHIFT);
  SendKeyPress(ui::VKEY_S);
  EXPECT_FALSE(GetSystemTray()->HasSystemBubble());
}

IN_PROC_BROWSER_TEST_F(StickyKeysBrowserTest, OpenNewTabs) {
  // Lock the modifier key.
  EnableStickyKeys();
  SendKeyPress(ui::VKEY_CONTROL);
  SendKeyPress(ui::VKEY_CONTROL);

  // In the locked state, pressing 't' should open a new tab each time.
  int tab_count = 0;
  for (; tab_count < 4; ++tab_count) {
    EXPECT_EQ(tab_count, new_window_client_->new_tab_action_count());
    SendKeyPress(ui::VKEY_T);
  }

  // Unlock the modifier key and shortcut should no longer activate.
  SendKeyPress(ui::VKEY_CONTROL);
  SendKeyPress(ui::VKEY_T);
  EXPECT_EQ(tab_count, new_window_client_->new_tab_action_count());

  // Shortcut should not work after disabling sticky keys.
  DisableStickyKeys();
  SendKeyPress(ui::VKEY_CONTROL);
  SendKeyPress(ui::VKEY_CONTROL);
  SendKeyPress(ui::VKEY_T);
  EXPECT_EQ(tab_count, new_window_client_->new_tab_action_count());
}

IN_PROC_BROWSER_TEST_F(StickyKeysBrowserTest, CtrlClickHomeButton) {
  // Show home page button.
  browser()->profile()->GetPrefs()->SetBoolean(prefs::kShowHomeButton, true);
  TabStripModel* tab_strip_model = browser()->tab_strip_model();
  int tab_count = 1;
  EXPECT_EQ(tab_count, tab_strip_model->count());

  // Test sticky keys with modified mouse click action.
  EnableStickyKeys();
  SendKeyPress(ui::VKEY_CONTROL);
  ui_test_utils::ClickOnView(browser(), VIEW_ID_HOME_BUTTON);
  EXPECT_EQ(++tab_count, tab_strip_model->count());
  ui_test_utils::ClickOnView(browser(), VIEW_ID_HOME_BUTTON);
  EXPECT_EQ(tab_count, tab_strip_model->count());

  // Test locked modifier key with mouse click.
  SendKeyPress(ui::VKEY_CONTROL);
  SendKeyPress(ui::VKEY_CONTROL);
  for (; tab_count < 5; ++tab_count) {
    EXPECT_EQ(tab_count, tab_strip_model->count());
    ui_test_utils::ClickOnView(browser(), VIEW_ID_HOME_BUTTON);
  }
  SendKeyPress(ui::VKEY_CONTROL);
  ui_test_utils::ClickOnView(browser(), VIEW_ID_HOME_BUTTON);
  EXPECT_EQ(tab_count, tab_strip_model->count());

  // Test disabling sticky keys prevent modified mouse click.
  DisableStickyKeys();
  SendKeyPress(ui::VKEY_CONTROL);
  ui_test_utils::ClickOnView(browser(), VIEW_ID_HOME_BUTTON);
  EXPECT_EQ(tab_count, tab_strip_model->count());
}

IN_PROC_BROWSER_TEST_F(StickyKeysBrowserTest, SearchLeftOmnibox) {
  EnableStickyKeys();

  OmniboxView* omnibox =
      browser()->window()->GetLocationBar()->GetOmniboxView();

  // Give the omnibox focus.
  omnibox->SetFocus();

  // Make sure that the AppList is not erroneously displayed and the omnibox
  // doesn't lose focus.
  EXPECT_FALSE(ash::WmShell::Get()->GetAppListTargetVisibility());
  EXPECT_TRUE(omnibox->GetNativeView()->HasFocus());

  // Type 'foo'.
  SendKeyPress(ui::VKEY_F);
  SendKeyPress(ui::VKEY_O);
  SendKeyPress(ui::VKEY_O);

  // Verify the location of the caret.
  size_t start, end;
  omnibox->GetSelectionBounds(&start, &end);
  ASSERT_EQ(3U, start);
  ASSERT_EQ(3U, end);

  EXPECT_FALSE(ash::WmShell::Get()->GetAppListTargetVisibility());
  EXPECT_TRUE(omnibox->GetNativeView()->HasFocus());

  // Hit Home by sequencing Search (left Windows) and Left (arrow).
  SendKeyPress(ui::VKEY_LWIN);
  SendKeyPress(ui::VKEY_LEFT);

  EXPECT_FALSE(ash::WmShell::Get()->GetAppListTargetVisibility());
  EXPECT_TRUE(omnibox->GetNativeView()->HasFocus());

  // Verify caret moved to the beginning.
  omnibox->GetSelectionBounds(&start, &end);
  ASSERT_EQ(0U, start);
  ASSERT_EQ(0U, end);
}

IN_PROC_BROWSER_TEST_F(StickyKeysBrowserTest, OverlayShown) {
  const ui::KeyboardCode modifier_keys[] = { ui::VKEY_CONTROL,
                                             ui::VKEY_SHIFT,
                                             ui::VKEY_MENU,
                                             ui::VKEY_COMMAND };

  // Overlay should not be visible if sticky keys is not enabled.
  ash::StickyKeysController* controller =
      ash::Shell::GetInstance()->sticky_keys_controller();
  EXPECT_FALSE(controller->GetOverlayForTest());
  for (auto key_code : modifier_keys) {
    SendKeyPress(key_code);
    EXPECT_FALSE(controller->GetOverlayForTest());
  }

  // Cycle through the modifier keys and make sure each gets shown.
  EnableStickyKeys();
  ash::StickyKeysOverlay* sticky_keys_overlay = controller->GetOverlayForTest();
  for (auto key_code : modifier_keys) {
    SendKeyPress(key_code);
    EXPECT_TRUE(sticky_keys_overlay->is_visible());
    SendKeyPress(key_code);
    EXPECT_TRUE(sticky_keys_overlay->is_visible());
    SendKeyPress(key_code);
    EXPECT_FALSE(sticky_keys_overlay->is_visible());
  }

  // Disabling sticky keys should hide the overlay.
  SendKeyPress(ui::VKEY_CONTROL);
  EXPECT_TRUE(sticky_keys_overlay->is_visible());
  DisableStickyKeys();
  EXPECT_FALSE(controller->GetOverlayForTest());
  for (auto key_code : modifier_keys) {
    SendKeyPress(key_code);
    EXPECT_FALSE(controller->GetOverlayForTest());
  }
}

}  // namespace chromeos


text:
import Provider from '../openCageProvider';

test.skip('Can fetch results with OpenCage', async () => {
  const provider = new Provider({
    params: {
      key: process.env.OPENCAGE_API_KEY,
    },
  });

  const results = await provider.search({ query: 'Madurodam' });
  const result = results[0];

  t.truthy(result.label);
  t.true(result.x > 5 && result.x < 6);
  t.true(result.y > 50 && result.y < 55);
  expect(result.bounds).toBeValidBounds();
});

test.skip('Can get localized results', async () => {
  const provider = new Provider({
    params: {
      key: process.env.OPENCAGE_API_KEY,
      'accept-language': 'nl',
    },
  });

  const results = await provider.search({ query: 'Madurodam' });
  t.is(results[0].label, 'Madurodam');
});


text:
package wrightstuff.wowscrubber.ui.guild;

import android.content.Context;

import wrightstuff.wowscrubber.model.guild.GuildNews;
import wrightstuff.wowscrubber.model.guild.News;
import wrightstuff.wowscrubber.ui.base.BasePresenter;
import wrightstuff.wowscrubber.ui.base.BaseView;

/**
 * Created by michaelwright on 01/08/2017.
 */

public interface GuildContract {

    interface View extends BaseView {
        void setDataToAdapter(GuildNews data);

        void enableFab(boolean visibility);
    }

    interface Presenter extends BasePresenter<View> {
        void updateGuildNews();

        void sendNewsItemMessage(final Context context, News userNews);
    }
}


text:
    <meta charset="utf-8">

<?php
$bdd = new PDO("mysql:host=localhost;dbname=pizzaten;charset=utf8","root",""); //Variable de connexion a la BDD pizzaten

//Fonction inscription client a la BDD
function inscription($bdd){
  if(isset($_POST['validerInscription']))
  {
    $nomC = $_POST['nomInscription'];
    $prenomC = $_POST['prenomInscription'];
    $birthC = $_POST['birthInscription'];
    $emailC = $_POST['emailInscription'];
    $mdpC = $_POST['mdpInscription'];

    echo "

"."Vous venez de vous inscrire !"."

";
    $sql = "INSERT INTO utilisateur (nom, prenom, birth, email, mdp, type)
            VALUES ('$nomC', '$prenomC', '$birthC', '$emailC', '$mdpC', 'client')";
    $bdd->exec($sql);
    echo "Veuillez vous connecter pour accéder à vos commandes";
  }
}

//Fonction connexion utilisateur(client/admin) a la BDD
function connexion($bdd){
  if(isset($_POST['seconnecterUser'])){
    $mail = $_POST['emailUser'];
    $mdp = $_POST['mdpUser'];

    $sqlUser = $bdd->query("SELECT * FROM utilisateur WHERE email = '$mail' AND mdp = '$mdp'");
    $resultat = $sqlUser->fetch();

    if($resultat != false){
      if($_SESSION['type'] == 'admin'){
        echo "Vous etes connecter en tant qu'administrateur : ";
      }else{
        echo "Vous etes connecter en tant que client : ";
      }
      echo "
";
      echo $_SESSION['nom'];
      echo " ";
      echo $_SESSION['prenom'];
      echo "

";
      // echo $_SESSION['email'];
      // echo "
";
      // echo $_SESSION['type'];
    }else{
      echo "Veuillez entrer des identifiants correct ou bien vous inscrire en cliquant ici

";
    }
  }
}

//Fonction connexion utilisateur(client/admin) a la BDD
function connexionUser($bdd){
  if(isset($_POST['seconnecterUser'])){
    $mail = $_POST['emailUser'];
    $mdp = $_POST['mdpUser'];

    $sqlUser = $bdd->query("SELECT * FROM utilisateur WHERE email = '$mail' AND mdp = '$mdp'");
    $resultat = $sqlUser->fetch();

    if($resultat != false){
      $_SESSION['idUtilisateur'] = $resultat['idUtilisateur'];
      $_SESSION['nom'] = $resultat['nom'];
      $_SESSION['prenom'] = $resultat['prenom'];
      $_SESSION['birth'] = $resultat['birth'];
      $_SESSION['adresse'] = $resultat['adresse'];
      $_SESSION['cp'] = $resultat['cp'];
      $_SESSION['ville'] = $resultat['ville'];
      $_SESSION['tel'] = $resultat['tel'];
      $_SESSION['email'] = $resultat['email'];
      $_SESSION['mdp'] = $resultat['mdp'];
      $_SESSION['type'] = $resultat['type'];
    }
  }
}

//Fonction selectionProduit qui selectionne tout les produits
function selectionProduit($bdd){
    $sqlProduit = $bdd->query("SELECT * FROM produit");
    while($unProduit = $sqlProduit->fetch()){
?>

        <img class="card-img-top" src="<?php echo $unProduit['urlPhoto']; ?>" alt="">

            <?php echo $unProduit['nomProduit']; ?>

<?php echo $unProduit['prixProduit']."€"; ?>

<?php echo $unProduit['descriptionProduit']; ?>

          ★ ★ ★ ★ ☆

  <?php
    }
}

//Fonction selectionP qui selectionne les produits en fonction du produit desirer $produit
function selectionP($bdd, $produit){
    $sqlProduit = $bdd->query("SELECT * FROM produit WHERE categorie = '$produit'");
    while($unProduit = $sqlProduit->fetch()){
?>

        <img class="card-img-top" src="<?php echo $unProduit['urlPhoto']; ?>" alt="">

          <?php echo $unProduit['nomProduit']; ?>

<?php echo $unProduit['prixProduit']."€"; ?>

<?php echo $unProduit['descriptionProduit']; ?>

      <form method="GET" action="#">

          <input type="hidden" name="nomP" value="<?php echo $unProduit['nomProduit']; ?>">
          <?php
            if(isset($_SESSION['type']) && $_SESSION['type'] == 'client'){ // Si l'on se connecte en tant que client
          ?>
              Quantité : <input type="number" name="quantityProduit" min="0" max="50">
              <button type="submit" name="validerCommande" onclick="popUpPayer()">Valider la commande</button>

              <input type="submit" name="validerPanier" value="Mettre dans le panier">
          <?php
        }elseif(isset($_SESSION['type']) && $_SESSION['type'] == 'admin'){ // Si l'on se connecte en tant qu'admin
          ?>
              <?php echo $unProduit['nomProduit']; echo ' : '.$unProduit['nbrProduit'].' produits
';?>
              Modifier le nombre de produits : <input type="number" name="nombreProduit" min="0" max="10000">
              <input type="submit" name="insertProduit" value="Valider">
          <?php
            }
          ?>

      </form>

  <?php
    }
}

//Fonction updateProduit qui modifie le nombre de produits dans la BDD (gere le stock)
function updateProduit($bdd, $produit){
  if(isset($_GET['nombreProduit']))
  {
    $nombreProduit = $_GET['nombreProduit'];
    $nomP = $_GET['nomP'];

    $sqlAddProduit = "UPDATE produit SET nbrProduit = '$nombreProduit' WHERE nomProduit = '$nomP' "; //Modifie le nombre  de desserts dns la BDD
    $bdd->exec($sqlAddProduit);
    echo "Vous venez d'ajouter ".$nombreProduit." ".$produit." de ".$nomP;
  }
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

//Fonction calculePrix qui calcule le nombre de produits et le multiplie par le prix dans la BDD (gere le stock)
function calculePrix($bdd){
  if(isset($_GET['quantityProduit']) && isset($_GET['validerCommande']))
  {
    $quantityProduit = $_GET['quantityProduit'];
    $nomP = $_GET['nomP'];

    $sqlProduit = $bdd->query("SELECT prixProduit FROM produit WHERE nomProduit = '$nomP'");
    $resultat = $sqlProduit->fetch();
    $prixUnite = $resultat['prixProduit'];
    $total = $prixUnite * $quantityProduit;

    echo "Felicitation ! Votre commande vous sera livré dans quelques minutes, pour un montant total de ".$total."€";

    ?>

    <?php
  }
}
?>


text:
namespace ConsoleApplication3.Models.Providers
{
    using System;
    using Contracts;

    public class ConsoleWriterProvider : IWriter
    {
        public void Write(string text)
        {
            Console.Write(text);
        }

        public void WriteLine(string text)
        {
            Console.WriteLine(text);
        }
    }
}


text:
require 'spec_helper'

describe file('/etc/murmur/murmur.ini') do
  its(:content) { should match(/^welcometext=.*Welcome to this server/) }
  its(:content) do
    should include '[-=\\\\w\\\\[\\\\]\\\\{\\\\}\\\\(\\\\)\\\\@\\\\|\\\\.]+'
  end
end


text:
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "txXSLTNumber.h"
#include "nsReadableUtils.h"
#include "txCore.h"

class txDecimalCounter : public txFormattedCounter {
public:
    txDecimalCounter() : mMinLength(1), mGroupSize(50)
    {
    }

    txDecimalCounter(int32_t aMinLength, int32_t aGroupSize,
                     const nsAString& mGroupSeparator);

    virtual void appendNumber(int32_t aNumber, nsAString& aDest);

private:
    int32_t mMinLength;
    int32_t mGroupSize;
    nsString mGroupSeparator;
};

class txAlphaCounter : public txFormattedCounter {
public:
    txAlphaCounter(PRUnichar aOffset) : mOffset(aOffset)
    {
    }

    virtual void appendNumber(int32_t aNumber, nsAString& aDest);

private:
    PRUnichar mOffset;
};

class txRomanCounter : public txFormattedCounter {
public:
    txRomanCounter(bool aUpper) : mTableOffset(aUpper ? 30 : 0)
    {
    }

    void appendNumber(int32_t aNumber, nsAString& aDest);

private:
    int32_t mTableOffset;
};

nsresult
txFormattedCounter::getCounterFor(const nsAFlatString& aToken,
                                  int32_t aGroupSize,
                                  const nsAString& aGroupSeparator,
                                  txFormattedCounter*& aCounter)
{
    int32_t length = aToken.Length();
    NS_ASSERTION(length, "getting counter for empty token");
    aCounter = 0;

    if (length == 1) {
        PRUnichar ch = aToken.CharAt(0);
        switch (ch) {

            case 'i':
            case 'I':
                aCounter = new txRomanCounter(ch == 'I');
                break;

            case 'a':
            case 'A':
                aCounter = new txAlphaCounter(ch);
                break;

            case '1':
            default:
                // if we don't recognize the token then use "1"
                aCounter = new txDecimalCounter(1, aGroupSize,
                                                aGroupSeparator);
                break;
        }
        return aCounter ? NS_OK : NS_ERROR_OUT_OF_MEMORY;
    }

    // for now, the only multi-char token we support are decimals
    int32_t i;
    for (i = 0; i < length-1; ++i) {
        if (aToken.CharAt(i) != '0')
            break;
    }
    if (i == length-1 && aToken.CharAt(i) == '1') {
        aCounter = new txDecimalCounter(length, aGroupSize, aGroupSeparator);
    }
    else {
        // if we don't recognize the token then use '1'
        aCounter = new txDecimalCounter(1, aGroupSize, aGroupSeparator);
    }

    return aCounter ? NS_OK : NS_ERROR_OUT_OF_MEMORY;
}

txDecimalCounter::txDecimalCounter(int32_t aMinLength, int32_t aGroupSize,
                                   const nsAString& aGroupSeparator)
    : mMinLength(aMinLength), mGroupSize(aGroupSize),
      mGroupSeparator(aGroupSeparator)
{
    if (mGroupSize <= 0) {
        mGroupSize = aMinLength + 10;
    }
}

void txDecimalCounter::appendNumber(int32_t aNumber, nsAString& aDest)
{
    const int32_t bufsize = 10; //must be able to fit an int32_t
    PRUnichar buf[bufsize];
    int32_t pos = bufsize;
    while (aNumber > 0) {
        int32_t ch = aNumber % 10;
        aNumber /= 10;
        buf[--pos] = ch + '0';
    }

    // in case we didn't get a long enough string
    int32_t end  = (bufsize > mMinLength) ? bufsize - mMinLength : 0;
    while (pos > end) {
        buf[--pos] = '0';
    }

    // in case we *still* didn't get a long enough string.
    // this should be very rare since it only happens if mMinLength is bigger
    // then the length of any int32_t.
    // pos will always be zero
    int32_t extraPos = mMinLength;
    while (extraPos > bufsize) {
        aDest.Append(PRUnichar('0'));
        --extraPos;
        if (extraPos % mGroupSize == 0) {
            aDest.Append(mGroupSeparator);
        }
    }

    // copy string to buffer
    if (mGroupSize >= bufsize - pos) {
        // no grouping will occur
        aDest.Append(buf + pos, (uint32_t)(bufsize - pos));
    }
    else {
        // append chars up to first grouping separator
        int32_t len = ((bufsize - pos - 1) % mGroupSize) + 1;
        aDest.Append(buf + pos, len);
        pos += len;
        while (bufsize - pos > 0) {
            aDest.Append(mGroupSeparator);
            aDest.Append(buf + pos, mGroupSize);
            pos += mGroupSize;
        }
        NS_ASSERTION(bufsize == pos, "error while grouping");
    }
}

void txAlphaCounter::appendNumber(int32_t aNumber, nsAString& aDest)
{
    PRUnichar buf[12];
    buf[11] = 0;
    int32_t pos = 11;
    while (aNumber > 0) {
        --aNumber;
        int32_t ch = aNumber % 26;
        aNumber /= 26;
        buf[--pos] = ch + mOffset;
    }

    aDest.Append(buf + pos, (uint32_t)(11 - pos));
}

const char* const kTxRomanNumbers[] =
    {"", "c", "cc", "ccc", "cd", "d", "dc", "dcc", "dccc", "cm",
     "", "x", "xx", "xxx", "xl", "l", "lx", "lxx", "lxxx", "xc",
     "", "i", "ii", "iii", "iv", "v", "vi", "vii", "viii", "ix",
     "", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM",
     "", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC",
     "", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"};

void txRomanCounter::appendNumber(int32_t aNumber, nsAString& aDest)
{
    // Numbers bigger then 3999 and negative numbers can't be done in roman
    if (uint32_t(aNumber) >= 4000) {
        txDecimalCounter().appendNumber(aNumber, aDest);
        return;
    }

    while (aNumber >= 1000) {
        aDest.Append(!mTableOffset ? PRUnichar('m') : PRUnichar('M'));
        aNumber -= 1000;
    }

    int32_t posValue;

    // Hundreds
    posValue = aNumber / 100;
    aNumber %= 100;
    AppendASCIItoUTF16(kTxRomanNumbers[posValue + mTableOffset], aDest);
    // Tens
    posValue = aNumber / 10;
    aNumber %= 10;
    AppendASCIItoUTF16(kTxRomanNumbers[10 + posValue + mTableOffset], aDest);
    // Ones
    AppendASCIItoUTF16(kTxRomanNumbers[20 + aNumber + mTableOffset], aDest);
}


text:
var React = require('react/addons');

<div {...getProps()}>
  foo
</div>;


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using MvcHaack.Ajax;

namespace NuGetGallery.Controllers
{
  public class InternalController : JsonController
  {
    private readonly IPackageService _packageService;

    public InternalController(IPackageService packageService)
    {
      _packageService = packageService;
    }

    public IEnumerable<object> Packages(bool includePrerelease = false)
    {
      return _packageService
        .GetPackagesForListing(includePrerelease)
        .Select(_ => new
        {
          _.PackageRegistration.Id,
          _.Title,
          _.Description,
          Owners = _.PackageRegistration.Owners.Select(__ => __.Username),
          Dependencies = _.Dependencies.Select(__ => new { product = __.Id, version = __.VersionSpec }),
          _.Tags,
          _.LastUpdated,
          _.Version,
          _.PackageRegistration.DownloadCount,
          _.ProjectUrl,
          _.LicenseUrl,
          _.IconUrl
        })
        .AsEnumerable()
        .Select(_ => new
        {
          Name = string.IsNullOrEmpty(_.Title) ? _.Id : _.Title,
          Description = _.Description,
          Owners = _.Owners.Select(__ => new { owner = __, url = Url.RouteUrl(MVC.Users.Profiles(__).GetRouteValueDictionary()) }),
          Compatible_versions = _.Dependencies,
          Tags = (_.Tags ?? "").Trim().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).Select(__ => new { tag = __ }),
          Last_update = _.LastUpdated,
          Last_version = _.Version,
          Downloads = _.DownloadCount,
          URLs = new { project = _.ProjectUrl, license = _.LicenseUrl, contact = Url.RouteUrl(MVC.Packages.ContactOwners(_.Id).GetRouteValueDictionary()) },
          Logo = _.IconUrl
        });
    }
  }
}


text:
package uk.co.steffandroid.parking.ui;

import android.Manifest;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;

import com.tbruyelle.rxpermissions.RxPermissions;
import com.trello.rxlifecycle.components.support.RxAppCompatActivity;

import javax.inject.Inject;

import butterknife.Bind;
import butterknife.ButterKnife;
import pl.charmas.android.reactivelocation.ReactiveLocationProvider;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import uk.co.steffandroid.parking.ParkingApp;
import uk.co.steffandroid.parking.R;
import uk.co.steffandroid.parking.data.DataManager;

public class MainActivity extends RxAppCompatActivity {
    @Inject
    DataManager dataManager;

    @Bind(R.id.toolbar)
    Toolbar toolbar;
    @Bind(R.id.car_park_refresh_layout)
    SwipeRefreshLayout refreshLayout;
    @Bind(R.id.car_park_list)
    RecyclerView carParkList;
    @Bind(R.id.error)
    View error;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);

        ((ParkingApp) getApplication()).component().inject(this);

        setSupportActionBar(toolbar);

        CarParkAdapter adapter = new CarParkAdapter(this, carPark -> {
            Uri gmmIntentUri = Uri.parse("google.navigation:q=" + carPark.name());
            Intent mapIntent = new Intent(Intent.ACTION_VIEW, gmmIntentUri);
            mapIntent.setPackage("com.google.android.apps.maps");
            startActivity(mapIntent);
        });
        carParkList.setAdapter(adapter);
        carParkList.setLayoutManager(new LinearLayoutManager(this));

        refreshLayout.setOnRefreshListener(dataManager::refresh);

        showProgress(true);
        RxPermissions.getInstance(this)
                .request(Manifest.permission.ACCESS_FINE_LOCATION)
                .filter(granted -> granted)
                .flatMap(granted -> new ReactiveLocationProvider(this).getLastKnownLocation())
                .firstOrDefault(null)
                .flatMap(dataManager::getCarParks)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(bindToLifecycle())
                .subscribe(carParks -> {
                    showProgress(false);
                    adapter.addAll(carParks);
                }, throwable -> {
                    showError();
                });
    }

    private void showProgress(boolean isLoading) {
        carParkList.setVisibility(isLoading ? View.GONE : View.VISIBLE);
        error.setVisibility(View.GONE);
        refreshLayout.post(() -> refreshLayout.setRefreshing(isLoading));
    }

    private void showError() {
        carParkList.setVisibility(View.GONE);
        error.setVisibility(View.VISIBLE);
        refreshLayout.setRefreshing(false);
    }
}


text:
    <title>GDG VIT Vellore | Home</title>
    <meta charset="utf-8">
    <meta name="language" content="en-us"/>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
    <meta name="description" content="GDG VIT Vellore comprehends a diverse group of technology enthusiasts who are passionate about google products and its developer technologies." />
    <meta name="keywords" content="Google Developers Group, VIT, Vellore, GDG, Technology, Beta Testing, Designing, App Development, GDG India, Quadocopters, Web Designing" />
    <meta name="distribution" content="Global" />
    <meta name="robots" content="index, follow" />
    <meta name="revisit-after" content="1 days"/>
    <meta name="publisher" content="GDG VIT Vellore, gdgvitvellore@gmail.com," />
    <meta name="author" content="Anurag Tiwari, tiwari.anurag126@gmail.com, Shubhodeep Mukherjee, shubhodeep9@gmail.com, Amit Srivastava"/>
    <meta name="copyright" content="GDG VIT Vellore"/>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
    <link type="text/css" rel="stylesheet" href="css/materialize.min.css"  media="screen,projection"/>
    <link type="text/css" rel="stylesheet" href="css/mainstyle.css"/>
    <link rel="shortcut icon" href="images/favicon.png" />
    <link href="https://plus.google.com/106628518438662355516" rel="publisher">

{{name.name}}

{{name.name}}

GDG VIT

We Create The Future

ABOUT US

5

PROJECTS

7

ONGOING

60

MEMBERS

WHAT WE DO

                      Tech Talks

                   Google talks are a grassroots-style series of presentation given by various technical experts spanning a wide spectrum of topics in technology and related areas.

                      DEV Fests

                   GDG Dev Fests are large scale, community-run events that offer speaker sessions across multiple product areas, hackathons, code labs and many more.

                      Code School

                   Google code school teaches web technologies in the comfort of your browser through video lessons, coding challenges and screencasts.

                      Beta Testing

                   Beta Testing is the essence of developing a software. We test every aspect of our product before releasing it for the real-world exposure.

Our Works

We have successfully completed a wide pool of projects and are always working towards building the next big thing.

Our Photos

Our gdg photos from google plus

               <input type="text" placeholder="Search by Events" ng-model="search" style="color:#ee6373;overflow:-moz-scrollbars-none;">

Our News

Our gdg news from google plus

                                {{n.title}}

Our Team

Rajatnoor Singh

Co-Founder

Madhav Menon

Co-Founder

Prerit Kimtani

President

Sarthak Saxena

Vice-President(Technical)

Shamvil Raza

Vice-President

Sahil Narula

Co-Vice President(Technical)

Maria Yusuf

Executive Head and WTM Lead

Sauraj Babu

Senior Designer

Tetali Chaitanya

Secretary

Piyush Shukla

Project Lead

Sourabh Parmar

Mentor Lead

STAY CONNECTED

                <form class="col s11 m11 l10">

                         <input id="full_name" type="text" class="validate" required>
                         Full name

                         <input id="email" type="email" class="validate" required>
                         Email

                         <input id="subject" type="email" class="validate">
                         Subject

                         <textarea id="textarea1" class="materialize-textarea" required></textarea>
                         Message

                      <button class="btn waves-effect waves-light" type="submit" name="action">Submit

                      </button>

                </form>


text:
/* 7zItem.c */

#include "7zItem.h"
#include "7zAlloc.h"

void SzCoderInfoInit(CCoderInfo *coder)
{
  SzByteBufferInit(&coder->Properties);
}

void SzCoderInfoFree(CCoderInfo *coder, void (*freeFunc)(void *p))
{
  SzByteBufferFree(&coder->Properties, freeFunc);
  SzCoderInfoInit(coder);
}

void SzFolderInit(CFolder *folder)
{
  folder->NumCoders = 0;
  folder->Coders = 0;
  folder->NumBindPairs = 0;
  folder->BindPairs = 0;
  folder->NumPackStreams = 0;
  folder->PackStreams = 0;
  folder->UnPackSizes = 0;
  folder->UnPackCRCDefined = 0;
  folder->UnPackCRC = 0;
  folder->NumUnPackStreams = 0;
}

void SzFolderFree(CFolder *folder, void (*freeFunc)(void *p))
{
  UInt32 i;
  for (i = 0; i < folder->NumCoders; i++)
    SzCoderInfoFree(&folder->Coders[i], freeFunc);
  freeFunc(folder->Coders);
  freeFunc(folder->BindPairs);
  freeFunc(folder->PackStreams);
  freeFunc(folder->UnPackSizes);
  SzFolderInit(folder);
}

UInt32 SzFolderGetNumOutStreams(CFolder *folder)
{
  UInt32 result = 0;
  UInt32 i;
  for (i = 0; i < folder->NumCoders; i++)
    result += folder->Coders[i].NumOutStreams;
  return result;
}

int SzFolderFindBindPairForInStream(CFolder *folder, UInt32 inStreamIndex)
{
  UInt32 i;
  for(i = 0; i < folder->NumBindPairs; i++)
    if (folder->BindPairs[i].InIndex == inStreamIndex)
      return i;
  return -1;
}

int SzFolderFindBindPairForOutStream(CFolder *folder, UInt32 outStreamIndex)
{
  UInt32 i;
  for(i = 0; i < folder->NumBindPairs; i++)
    if (folder->BindPairs[i].OutIndex == outStreamIndex)
      return i;
  return -1;
}

CFileSize SzFolderGetUnPackSize(CFolder *folder)
{
  int i = (int)SzFolderGetNumOutStreams(folder);
  if (i == 0)
    return 0;
  for (i--; i >= 0; i--)
    if (SzFolderFindBindPairForOutStream(folder, i) < 0)
      return folder->UnPackSizes[i];
  /* throw 1; */
  return 0;
}

/*
int FindPackStreamArrayIndex(int inStreamIndex) const
{
  for(int i = 0; i < PackStreams.Size(); i++)
  if (PackStreams[i] == inStreamIndex)
    return i;
  return -1;
}
*/

void SzFileInit(CFileItem *fileItem)
{
  fileItem->IsFileCRCDefined = 0;
  fileItem->HasStream = 1;
  fileItem->IsDirectory = 0;
  fileItem->IsAnti = 0;
  fileItem->IsLastWriteTimeDefined = 0;
  fileItem->Name = 0;
}

void SzFileFree(CFileItem *fileItem, void (*freeFunc)(void *p))
{
  freeFunc(fileItem->Name);
  SzFileInit(fileItem);
}

void SzArchiveDatabaseInit(CArchiveDatabase *db)
{
  db->NumPackStreams = 0;
  db->PackSizes = 0;
  db->PackCRCsDefined = 0;
  db->PackCRCs = 0;
  db->NumFolders = 0;
  db->Folders = 0;
  db->NumFiles = 0;
  db->Files = 0;
}

void SzArchiveDatabaseFree(CArchiveDatabase *db, void (*freeFunc)(void *))
{
  UInt32 i;
  for (i = 0; i < db->NumFolders; i++)
    SzFolderFree(&db->Folders[i], freeFunc);
  for (i = 0; i < db->NumFiles; i++)
    SzFileFree(&db->Files[i], freeFunc);
  freeFunc(db->PackSizes);
  freeFunc(db->PackCRCsDefined);
  freeFunc(db->PackCRCs);
  freeFunc(db->Folders);
  freeFunc(db->Files);
  SzArchiveDatabaseInit(db);
}


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Polymer Site</title>
    <meta name="viewport" content="width=device-width, minimum-scale=1.0, initial-scale=1.0, user-scalable=yes">

    <link rel="stylesheet" href="./styles/main.css"/>

    <link rel="import" href="elements/elements.html">

    <template is="dom-bind" id="app">
        <template is="dom-if" if="[[authenticated]]">
            <paper-drawer-panel id="app-holder" responsive-width="3000px">
                <paper-header-panel drawer>
                    <paper-toolbar>
                        <paper-icon-button icon="menu" paper-drawer-toggle></paper-icon-button>

App Name

                    </paper-toolbar>
                    <app-menu route="{{route}}"></app-menu>
                </paper-header-panel>

            </paper-drawer-panel>
        </template>
        <template is="dom-if" if="[[!authenticated]]">
            <login-page></login-page>
        </template>
    </template>


text:
VoteSquared
===================

The rails repository for Vote Squared's platform ( VoteSquared.org ).

Requirements
------------
Platforms:
- CentOS

Database:
- MongoDb

App Server:
- Web Brick for localhost and single threading
- Passenger + nginx for multi-threading

Installation Steps
------------------
1. Clone the repository
2. Run update.sh to install the required gems
3. You will need devise.rb in config/initializers .  To create it, comment out devise code and run 'rails generate devise:install'.  Restore devise code to prevent crashes.
4. Create /congig/initializers/admins.yml .  Add the ids for your admins to this file.
5. Create /congig/initializers/secrets.yml and place your SMTP settings for the environment configurations.

License & Authors
-----------------
- Author:: Forest Handford (forest.handford+VS@gmail.com)

```text
Copyright 2014, Vote Squared

Licensed under the MIT License;
You may not use this file except in compliance with the License.


text:
import requests
from threading import Timer, Lock
import datetime
import pandas as pd
import logging
import os

dir = os.path.dirname(__file__)

logging.basicConfig(
    filename=os.path.join(dir, "./log/events.log"),
    level=logging.INFO,
    format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s'
)

class WebsiteHandler(object):
    """ Every website entry will have a corresponding WebsiteHandler instance.

    This class will monitor a website using HEAD requests, log the results into a Pandas dataframe, and compute
    statistics and metrics.

    When an instance is created, a timed thread is started to ping the website at periodic intervals.
    """

    # This value is the value for which a website is considered as timing out.
    timeout = 4

    def __init__(self, name, url, interval, parent):
        # Info about the website
        self.name = name
        self.url = url
        self.interval = int(interval)

        self.parent = parent

        # The lock prevent adding an entry to df_history while the statistics are being computed.
        self.lock = Lock()

        self._timer = None  # This attribute will hold the thread
        self.is_running = False
        self.start()

        # This dataframe will hold the historical results of the requests to compute statistics.
        self.df_history = pd.DataFrame()

        self.convert = {"* All": None,
                        "* 2 minutes": datetime.timedelta(minutes=2),
                        "* 10 minutes": datetime.timedelta(minutes=10),
                        "* 1 hour": datetime.timedelta(hours=1),
                        "* 24 hours": datetime.timedelta(days=1)}

        # In case of connection error, no entry is added to df_history.
        # The last connection error is stored in that dict.
        self.connection_error = {'connection error': False,
                                 'name': None,
                                 'details': None,
                                 'last check': None}

        self.on_alert = False
        self.availability = float('nan')
        self.last_header = None
        self.hourly_stats = ['No data', 'No data']

    def has_no_data(self):
        """True if there is no record."""
        return self.df_history.empty

    def _run(self):
        """Thread setup"""
        self.is_running = False
        self.start()
        self.ping_website()

    def start(self):
        """Starts the timed thread."""
        if not self.is_running:
            self._timer = Timer(self.interval, self._run)
            self._timer.setDaemon(True)
            self._timer.start()
            self.is_running = True

    def stop(self):
        """Stops the thread."""
        self._timer.cancel()
        self.is_running = False

    def ping_website(self):
        """ This is the method called at regular intervals.

        The method ping the website by performing a HEAD request. I have decided to use a HEAD request rather than a GET
        one to avoid downloading the whole webpage. If an abnormal time is taken during the downloading part, the HEAD
        request won't return a timeout. So the choice between the two is not obvious, but I have decided to stick with the
        HEAD request. I have been testing it with real websites that were down, and it was working well.
        It is easy to modify, just change requests.head to requests.get, and everything will work the same.
        (Change also RunServers.)

        If everything is ok:
         - add to df_history the date, the time elapsed for the request, the status code, and a flag to say it went fine
        If timeout:
         - append a similar line to the dataframe, but with the timeout status and the flag set to False
        If ConnectionError:
         - the df_history dataframe stays the same, and only the connection_error dict is updated.

         At the end of the method, an alert is raised if the availability has gone below 80, or if it has recovered from
         an alert.

        """
        now = datetime.datetime.now()
        try:
            response = requests.head(self.url, timeout=self.__class__.timeout)
        except requests.Timeout:
            self.connection_error['connection error'] = False
            with self.lock:
                self.df_history = self.df_history.append({'date': now,
                                                          'status code': 'Timeout',
                                                          'elapsed': None,
                                                          'OK': False}, ignore_index=True)
        except requests.RequestException as e:
            with self.lock:
                self.connection_error['connection error'] = True
                self.connection_error['name'] = type(e).__name__
                self.connection_error['details'] = type(e).__doc__
                self.connection_error['last check'] = now
                logging.debug('{} -- {}'.format(self.url, e.__doc__))
        else:
            with self.lock:
                self.connection_error['connection error'] = False
                self.df_history = self.df_history.append({'date': now,
                                                          'status code': str(response.status_code),
                                                          'elapsed': response.elapsed,
                                                          'OK': True}, ignore_index=True)

                # Store the last header for the detailed stats.
                self.last_header = response.headers

        # Check for alerts
        if self.on_alert:
            self.recover_alert_check()
        else:
            self.trigger_alert_check()

    def get_info_for_grid(self, small_update):
        """ Compute the metrics for the grid and return the values.

        small_update:
            False - all the grid is updated
            True - all, except the hourly stats

        Returns: All the info to fill the grid:
                ['Website', 'Interval Check', 'Last Check', 'Last Status', 'Last Resp. Time', 'availability (2 min)',
                           'MAX (10 min)', 'AVG (10 min)', 'MAX (1 hour)', 'AVG (1 hour)']
        """

        info = [self.name, self.interval]

        with self.lock:
            if self.has_no_data():
                if self.connection_error['connection error']:
                    info += [self.connection_error['last check'].strftime('%H:%M:%S.%f')[:-3],  # Last check
                             self.connection_error['name']]  # Last status
                    info += [None] * 6
                else:
                    info += [None] * 8
            else:
                tail = self.df_history.tail(n=1).values
                if not self.connection_error['connection error']:
                    info += [tail[0, 1].strftime('%H:%M:%S.%f')[:-3],  # Last check
                             tail[0, 3],  # Last status
                             self.elapsed_to_string(tail[0, 2])]  # Last Resp. Time
                else:
                    info += [self.connection_error['last check'].strftime('%H:%M:%S.%f')[:-3],  # Last check
                             self.connection_error['name'],  # Last status
                             None]  # Last Resp. Time

                df_OK = self.df_history['OK'] == 1
                now = datetime.datetime.now()
                mask_10min = (self.df_history['date'] > (now - datetime.timedelta(minutes=10))) & df_OK

                if not small_update:
                    mask_1hour = (self.df_history['date'] > (now - datetime.timedelta(hours=1))) & df_OK

                    info += [self.elapsed_to_string(self.df_history.loc[mask_10min]['elapsed'].max()),
                             self.elapsed_to_string(self.df_history.loc[mask_10min]['elapsed'].mean()),
                             self.elapsed_to_string(self.df_history.loc[mask_1hour]['elapsed'].max()),
                             self.elapsed_to_string(self.df_history.loc[mask_1hour]['elapsed'].mean()),
                             self.availability_to_string(self.availability)]

                    self.hourly_stats = [info[7], info[8]]

                else:
                    info += [self.elapsed_to_string(self.df_history.loc[mask_10min]['elapsed'].max()),
                             self.elapsed_to_string(self.df_history.loc[mask_10min]['elapsed'].mean()),
                             self.hourly_stats[0],
                             self.hourly_stats[1],
                             self.availability_to_string(self.availability)]

        return info

    def availability_to_string(self, availability):
        """Format for the availability fields."""
        # Check if availability == NaN (pandas returns NaN if there was no value to compute the metric)
        if availability == availability:
            return '{:.2f} %'.format(availability * 100)
        else:
            return 'No data'

    def elapsed_to_string(self, time_elapsed):
        """Format for time elapsed fields."""
        if time_elapsed == time_elapsed and time_elapsed is not None:
            return '{}.{:03d}s'.format(time_elapsed.seconds, time_elapsed.microseconds // 1000)
        else:
            return 'No data'

    def get_detailed_stats_fixed(self):
        """Return the time independent information about the website for the detailed info frame."""
        return [['Website', self.name], ['URL', self.url], ['Interval', self.interval]]

    def get_detailed_stats_dynamic(self, str_time_scale):
        """Returns the time dependent information about the website for the detailed info frame.

        The string str_time_scale comes from the detailed website info form, and is converted into datetime.timedelta
        using the convert dict.

        """
        converted = self.convert[str_time_scale]
        assert not self.has_no_data()
        with self.lock:
            if converted is None:
                status = self.df_history.groupby(by=['status code']).size().index.tolist()
                counts = self.df_history.groupby(by=['status code']).size().tolist()
                availability = self.availability_to_string(self.df_history['OK'].mean())
                mini = self.df_history.loc[self.df_history['OK'] == 1]['elapsed'].min()
                avg = self.df_history.loc[self.df_history['OK'] == 1]['elapsed'].mean()
                maxi = self.df_history.loc[self.df_history['OK'] == 1]['elapsed'].max()
            else:
                mask = self.df_history['date'] > (datetime.datetime.now() - converted)
                status = self.df_history.loc[mask].groupby(by=['status code']).size().index.tolist()
                counts = self.df_history.loc[mask].groupby(by=['status code']).size().tolist()
                availability = self.availability_to_string(self.df_history.loc[mask]['OK'].mean())
                mini = self.df_history.loc[mask & self.df_history['OK'] == 1]['elapsed'].min()
                avg = self.df_history.loc[mask & self.df_history['OK'] == 1]['elapsed'].mean()
                maxi = self.df_history.loc[mask & self.df_history['OK'] == 1]['elapsed'].max()

            elapsed_info = [[text, self.elapsed_to_string(time)] for text, time in
                            zip(['Min', 'Average', 'Max'], [mini, avg, maxi])]
            status_info = [[stat, count] for stat, count in zip(status, counts)]

            if self.last_header is not None:
                last_header = [[key, value] for key, value in self.last_header.items()]
            else:
                last_header = [['No header']]

        return availability, status_info, elapsed_info, last_header

    def trigger_alert_check(self):
        """Triggers an alert if the website's availability goes below 80% for the last 2 minutes."""
        if not self.has_no_data():
            now = datetime.datetime.now()
            mask = self.df_history['date'] > (now - datetime.timedelta(minutes=2))
            self.availability = self.df_history[mask]['OK'].mean()
            if self.availability < 0.8:
                self.parent.trigger_alert(self.url, self.name, self.availability, now)
                self.on_alert = True

    def recover_alert_check(self):
        """Check if the website has recovered from the previous alert."""
        now = datetime.datetime.now()
        mask = self.df_history['date'] > (now - datetime.timedelta(minutes=2))
        self.availability = self.df_history[mask]['OK'].mean()
        if self.availability > 0.8:
            self.parent.recover_alert(self.url, self.name, self.availability, now)
            self.on_alert = False

class WebsitesContainer(object):
    """The different WebsiteHandlers are stored in a WebsiteContainer instance."""

    def __init__(self):
        self.website_handlers = []
        self.wg_alert_box = None

        # The lock prevents alerts from being written at the same time in the wg_alert_box widget.
        self.lock = Lock()

    def get_website_handler(self, index):
        """Returns the index_th website handler."""
        return self.website_handlers[index]

    def add(self, website):
        """Adds a website to monitor."""
        self.website_handlers.append(WebsiteHandler(*website, self))

    def get_detailed_stats_fixed(self, index):
        """Returns the time independent info of the index_th website."""
        return self.website_handlers[index].get_detailed_stats_fixed()

    def get_detailed_stats_dynamic(self, index, str_time_scale):
        """Returns the time dependent info of the index_th website."""
        return self.website_handlers[index].get_detailed_stats_dynamic(str_time_scale)

    def list_all_websites(self, small_update):
        """Returns the info to fill the grid."""
        grid_info = []
        for website_handler in self.website_handlers:
            grid_info.append(website_handler.get_info_for_grid(small_update=small_update))
        return grid_info

    def stop_all_checks(self):
        """Stops all threads. Called before exiting."""
        for website_handler in self.website_handlers:
            website_handler.stop()

    def set_alert_box(self, wgAlertBox):
        self.wg_alert_box = wgAlertBox

    def trigger_alert(self, url, name, availability, now):
        """Triggers an alert: writes it in the alert box, and logs it."""
        with self.lock:
            assert self.wg_alert_box is not None
            self.wg_alert_box.add_line(
                ["Website {} is down. availability={:.2f}, time={}".format(name, availability,
                                                                           now.strftime('%H:%M:%S.%f')[:-3])])
            logging.info("Website {} is down. availability={:.2f}".format(url, availability,
                                                                          now.strftime('%H:%M:%S.%f')[:-3]))

    def recover_alert(self, url, name, availability, now):
        """Recovers from an alert: writes it in the alert box, and logs it."""
        with self.lock:
            assert self.wg_alert_box is not None
            self.wg_alert_box.add_line(
                ["Website {} recovered. availability={:.2f}, time={}".format(name, availability,
                                                                             now.strftime('%H:%M:%S.%f')[:-3])])
            logging.info("Website {} recovered. availability={:.2f}".format(url, availability,
                                                                            now.strftime('%H:%M:%S.%f')[:-3]))

class GridUpdater(object):
    """This class is used to update the grid."""

    def __init__(self, interval, wgWebsiteGrid, main_form):
        self._timer = None
        self.interval = interval
        self.wgWebsiteGrid = wgWebsiteGrid
        self.main_form = main_form
        self.is_running = False
        # Keep track for updates on a different timescale
        self.counter = 0
        self.start()

    def updater(self):
        """
        Updates the grid. It ils fully updated every 60 seconds, and every 10 seconds, everything except the
        hourly stats.
        """
        full_update = (self.counter % 6 == 0)
        self.wgWebsiteGrid.values = self.main_form.parentApp.websitesContainer.list_all_websites(not full_update)
        self.counter += 1
        if self.main_form.parentApp.getHistory()[-1] == 'MAIN':
            self.wgWebsiteGrid.display()

    def _run(self):
        self.is_running = False
        self.start()
        self.updater()

    def start(self):
        if not self.is_running:
            self._timer = Timer(self.interval, self._run)
            self._timer.setDaemon(True)
            self._timer.start()
            self.is_running = True

    def stop(self):
        self._timer.cancel()
        self.is_running = False


text:
View
----

.. automodule:: casingSimulations.view
    :show-inheritance:
    :members:
    :undoc-members:


text:
'use strict';

var models = require('./index');

var util = require('util');

/**
 * @class
 * Initializes a new instance of the HiveJobProperties class.
 * @constructor
 * @member {array} [statementInfo] the statement information for each
 * statement in the script
 *
 * @member {string} [logsLocation] the Hive logs location
 *
 * @member {string} [warehouseLocation] the location of the Hive warehouse
 *
 * @member {number} [statementCount] the number of statements that will be run
 * based on the script
 *
 * @member {number} [executedStatementCount] the number of statements that
 * have been run based on the script
 *
 */
function HiveJobProperties() {
  HiveJobProperties['super_'].call(this);
}

util.inherits(HiveJobProperties, models['JobProperties']);

/**
 * Defines the metadata of HiveJobProperties
 *
 * @returns {object} metadata of HiveJobProperties
 *
 */
HiveJobProperties.prototype.mapper = function () {
  return {
    required: false,
    serializedName: 'Hive',
    type: {
      name: 'Composite',
      className: 'HiveJobProperties',
      modelProperties: {
        runtimeVersion: {
          required: false,
          serializedName: 'runtimeVersion',
          type: {
            name: 'String'
          }
        },
        script: {
          required: true,
          serializedName: 'script',
          type: {
            name: 'String'
          }
        },
        type: {
          required: true,
          serializedName: 'type',
          type: {
            name: 'String'
          }
        },
        statementInfo: {
          required: false,
          serializedName: 'statementInfo',
          type: {
            name: 'Sequence',
            element: {
                required: false,
                serializedName: 'HiveJobStatementInfoElementType',
                type: {
                  name: 'Composite',
                  className: 'HiveJobStatementInfo'
                }
            }
          }
        },
        logsLocation: {
          required: false,
          serializedName: 'logsLocation',
          type: {
            name: 'String'
          }
        },
        warehouseLocation: {
          required: false,
          serializedName: 'warehouseLocation',
          type: {
            name: 'String'
          }
        },
        statementCount: {
          required: false,
          serializedName: 'statementCount',
          type: {
            name: 'Number'
          }
        },
        executedStatementCount: {
          required: false,
          serializedName: 'executedStatementCount',
          type: {
            name: 'Number'
          }
        }
      }
    }
  };
};

module.exports = HiveJobProperties;


text:
var express = require('express'),
    app = express(),
    server = require('http').createServer(app),
    io = require('socket.io').listen(server),
    swig = require('swig'),
    routes = require('./routes');

app.engine('html', swig.renderFile);

app.set('view engine', 'html');
app.set('views', __dirname + '/views');
app.set('view cache', false);
// app.use(logger());
app.use(express.static(__dirname + '/public'));
swig.setDefaults({
    cache: false
});

app.get('/:class', routes.episode);
app.get('/', routes.main);

server.listen(20081);
console.log('Server is listen to port 20081');


text:
/**
 *
 */
package sample.layout;

import org.testng.annotations.Test;

import util.testng.GalenBaseTest;

/**
 * @author mreinhardt
 *
 */
public class HomeLayoutTest extends GalenBaseTest {

	@Test(dataProvider = "devices")
	public void testHomePage(final TestDevice device) throws Exception {
		verifyPage("/", device, "/specs/homePageLayout.spec");
	}

}


text:
package com.itheima.c_hbm;

import org.hibernate.Transaction;
import org.junit.Test;

import com.itheima.a_hello.User;
import com.itheima.utils.HibernateUtils;
public class session_test {
	@Test
	//演示dynamic-insert
	public void fun1(){
		org.hibernate.Session session = HibernateUtils.openSession();
		Transaction ts = session.beginTransaction();

		User u = new User();
		u.setName("zhangsan");
		//调用Session的save方法保存对象到数据库中
		session.save(u);

		ts.commit();
		//关闭资源
		session.close();
	}
	@Test
	//演示dynamic-update
	public void fun2(){
		org.hibernate.Session session = HibernateUtils.openSession();

		Transaction ts = session.beginTransaction();

		User u = (User) session.get(User.class, 1);

		u.setName("jerry");

		session.update(u);

		ts.commit();
		//关闭资源
		session.close();
	}
}


text:
<!DOCTYPE html>

    <title>Composite Radial Progress Demo</title>

	  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">

Composite Radial Progress Demo

          <input type="text" id="dial" class="dial" data-min="0" data-max="360" data-readOnly="true" data-displayInput="false" value="0">

          <button class="btn btn-default" data-bind="click: addItem"> Add Item</button>

          <button class="btn btn-default" data-bind="click: pauseAll"> All</button>
          <button class="btn btn-default" data-bind="click: unpauseAll"> All</button>

            <button class="btn btn-default" data-bind="click: pause, visible: !paused()"></button>
            <button class="btn btn-default" data-bind="click: unpause, visible: paused"></button>
            <button class="btn btn-default" data-bind="click: slowDown"></button>
            <button class="btn btn-default" data-bind="click: speedUp"></button>
            <button class="btn btn-default" data-bind="click: finish"></button>


text:
module RuboCop
  module Cop
    module Performance
      # This cop identifies places where a case-insensitive string comparison
      # can better be implemented using `casecmp`.
      #
      # @example
      #   @bad
      #   str.downcase == 'abc'
      #   str.upcase.eql? 'ABC'
      #   'abc' == str.downcase
      #   'ABC'.eql? str.upcase
      #   str.downcase == str.downcase
      #
      #   @good
      #   str.casecmp('ABC').zero?
      #   'abc'.casecmp(str).zero?
      class Casecmp < Cop
        MSG = 'Use `casecmp` instead of `%s %s`.'.freeze
        CASE_METHODS = [:downcase, :upcase].freeze

        def_node_matcher :downcase_eq, <<-END
          (send
            $(send _ ${:downcase :upcase})
            ${:== :eql? :!=}
            ${str (send _ {:downcase :upcase} ...) (begin str)})
        END

        def_node_matcher :eq_downcase, <<-END
          (send
            {str (send _ {:downcase :upcase} ...) (begin str)}
            ${:== :eql? :!=}
            $(send _ ${:downcase :upcase}))
        END

        def on_send(node)
          return if part_of_ignored_node?(node)

          downcase_eq(node) do |send_downcase, case_method, eq_method, other|
            *_, method = *other
            if CASE_METHODS.include?(method)
              range = node.loc.expression
              ignore_node(node)
            else
              range = node.loc.selector.join(send_downcase.loc.selector)
            end

            add_offense(node, range, format(MSG, case_method, eq_method))
            return
          end

          eq_downcase(node) do |eq_method, send_downcase, case_method|
            range = node.loc.selector.join(send_downcase.loc.selector)
            add_offense(node, range, format(MSG, eq_method, case_method))
          end
        end

        def autocorrect(node)
          downcase_eq(node) do
            receiver, method, arg = *node
            variable, = *receiver
            return correction(node, receiver, method, arg, variable)
          end

          eq_downcase(node) do
            arg, method, receiver = *node
            variable, = *receiver
            return correction(node, receiver, method, arg, variable)
          end
        end

        private

        def correction(node, _receiver, method, arg, variable)
          lambda do |corrector|
            corrector.insert_before(node.loc.expression, '!') if method == :!=

            # we want resulting call to be parenthesized
            # if arg already includes one or more sets of parens, don't add more
            # or if method call already used parens, again, don't add more
            replacement = if arg.send_type? || !parentheses?(arg)
                            "#{variable.source}.casecmp(#{arg.source}).zero?"
                          else
                            "#{variable.source}.casecmp#{arg.source}.zero?"
                          end

            corrector.replace(node.loc.expression, replacement)
          end
        end
      end
    end
  end
end


text:
!function(global) {
    function definition($) {
        $.fn.measure = function(fn) {
            var clone = $(this).clone(), result;

            clone.css({
                visibility: 'hidden',
                position: 'absolute'
            });
            clone.appendTo(document.body);

            if (typeof fn == 'function') {
                result = fn.apply(clone);
            }
            clone.remove();

            return result;
        };
    }

    if (typeof define === 'function' && define.amd) {
        define(['jquery'], definition);
    } else {
        definition(global.jQuery);
    }
}(this);


text:
<?php namespace Fungku\NetSuite\Classes;

class Rate {
	public $value;
	public $priceLevel;
	static $paramtypesmap = array(
		"value" => "float",
		"priceLevel" => "RecordRef",
	);
}