text:
"""This script runs an automated Cronet performance benchmark.

This script:
1. Sets up "USB reverse tethering" which allow network traffic to flow from
   an Android device connected to the host machine via a USB cable.
2. Starts HTTP and QUIC servers on the host machine.
3. Installs an Android app on the attached Android device and runs it.
4. Collects the results from the app.

Prerequisites:
1. A rooted (i.e. "adb root" succeeds) Android device connected via a USB cable
   to the host machine (i.e. the computer running this script).
2. quic_server has been built for the host machine, e.g. via:
     gn gen out/Release --args="is_debug=false"
     ninja -C out/Release quic_server
3. cronet_perf_test_apk has been built for the Android device, e.g. via:
     ./components/cronet/tools/cr_cronet.py gn -r
     ninja -C out/Release cronet_perf_test_apk
4. If "sudo ufw status" doesn't say "Status: inactive", run "sudo ufw disable".
5. sudo apt-get install lighttpd
6. If the usb0 interface on the host keeps losing it's IPv4 address
   (WaitFor(HasHostAddress) will keep failing), NetworkManager may need to be
   told to leave usb0 alone with these commands:
     sudo bash -c "printf \"\\n[keyfile]\
         \\nunmanaged-devices=interface-name:usb0\\n\" \
         >> /etc/NetworkManager/NetworkManager.conf"
     sudo service network-manager restart

Invocation:
./run.py

Output:
Benchmark timings are output by telemetry to stdout and written to
./results.html

"""

import json
import optparse
import os
import shutil
import sys
import tempfile
import time
import six.moves.urllib_parse # pylint: disable=import-error

REPOSITORY_ROOT = os.path.abspath(os.path.join(
    os.path.dirname(__file__), '..', '..', '..', '..', '..'))

sys.path.append(os.path.join(REPOSITORY_ROOT, 'tools', 'perf'))
sys.path.append(os.path.join(REPOSITORY_ROOT, 'build', 'android'))
sys.path.append(os.path.join(REPOSITORY_ROOT, 'components'))

# pylint: disable=wrong-import-position
from chrome_telemetry_build import chromium_config
from devil.android import device_utils
from devil.android.sdk import intent
from core import benchmark_runner
from cronet.tools import android_rndis_forwarder
from cronet.tools import perf_test_utils
import lighttpd_server
from pylib import constants
from telemetry import android
from telemetry import benchmark
from telemetry import story as story_module
from telemetry.web_perf import timeline_based_measurement
# pylint: enable=wrong-import-position

def GetDevice():
  devices = device_utils.DeviceUtils.HealthyDevices()
  assert len(devices) == 1
  return devices[0]

class CronetPerfTestAndroidStory(android.AndroidStory):
  # Android AppStory implementation wrapping CronetPerfTest app.
  # Launches Cronet perf test app and waits for execution to complete
  # by waiting for presence of DONE_FILE.

  def __init__(self, device):
    self._device = device
    config = perf_test_utils.GetConfig(device)
    device.RemovePath(config['DONE_FILE'], force=True)
    self.url ='http://dummy/?' + six.moves.urllib_parse.urlencode(config)
    start_intent = intent.Intent(
        package=perf_test_utils.APP_PACKAGE,
        activity=perf_test_utils.APP_ACTIVITY,
        action=perf_test_utils.APP_ACTION,
        # |config| maps from configuration value names to the configured values.
        # |config| is encoded as URL parameter names and values and passed to
        # the Cronet perf test app via the Intent data field.
        data=self.url,
        extras=None,
        category=None)
    super(CronetPerfTestAndroidStory, self).__init__(
        start_intent, name='CronetPerfTest',
        # No reason to wait for app; Run() will wait for results.  By default
        # StartActivity will timeout waiting for CronetPerfTest, so override
        # |is_app_ready_predicate| to not wait.
        is_app_ready_predicate=lambda app: True)

  def Run(self, shared_user_story_state):
    while not self._device.FileExists(
        perf_test_utils.GetConfig(self._device)['DONE_FILE']):
      time.sleep(1.0)

class CronetPerfTestStorySet(story_module.StorySet):

  def __init__(self, device):
    super(CronetPerfTestStorySet, self).__init__()
    # Create and add Cronet perf test AndroidStory.
    self.AddStory(CronetPerfTestAndroidStory(device))

class CronetPerfTestMeasurement(
    timeline_based_measurement.TimelineBasedMeasurement):
  # For now AndroidStory's SharedAppState works only with
  # TimelineBasedMeasurements, so implement one that just forwards results from
  # Cronet perf test app.

  def __init__(self, device, options):
    super(CronetPerfTestMeasurement, self).__init__(options)
    self._device = device

  def WillRunStory(self, platform, story=None):
    # Skip parent implementation which doesn't apply to Cronet perf test app as
    # it is not a browser with a timeline interface.
    pass

  def Measure(self, platform, results):
    # Reads results from |RESULTS_FILE| on target and adds to |results|.
    jsonResults = json.loads(self._device.ReadFile(
        perf_test_utils.GetConfig(self._device)['RESULTS_FILE']))
    for test in jsonResults:
      results.AddMeasurement(test, 'ms', jsonResults[test])

  def DidRunStory(self, platform, results):
    # Skip parent implementation which calls into tracing_controller which this
    # doesn't have.
    pass

class CronetPerfTestBenchmark(benchmark.Benchmark):
  # Benchmark implementation spawning off Cronet perf test measurement and
  # StorySet.
  SUPPORTED_PLATFORMS = [story_module.expectations.ALL_ANDROID]

  def __init__(self, max_failures=None):
    super(CronetPerfTestBenchmark, self).__init__(max_failures)
    self._device = GetDevice()

  def CreatePageTest(self, options):
    return CronetPerfTestMeasurement(self._device, options)

  def CreateStorySet(self, options):
    return CronetPerfTestStorySet(self._device)

def main():
  parser = optparse.OptionParser()
  parser.add_option('--output-format', default='html',
                   help='The output format of the results file.')
  parser.add_option('--output-dir', default=None,
                   help='The directory for the output file. Default value is '
                        'the base directory of this script.')
  options, _ = parser.parse_args()
  constants.SetBuildType(perf_test_utils.BUILD_TYPE)
  # Install APK
  device = GetDevice()
  device.EnableRoot()
  device.Install(perf_test_utils.APP_APK)
  # Start USB reverse tethering.
  android_rndis_forwarder.AndroidRndisForwarder(device,
      perf_test_utils.GetAndroidRndisConfig(device))
  # Start HTTP server.
  http_server_doc_root = perf_test_utils.GenerateHttpTestResources()
  config_file = tempfile.NamedTemporaryFile()
  http_server = lighttpd_server.LighttpdServer(http_server_doc_root,
      port=perf_test_utils.HTTP_PORT,
      base_config_path=config_file.name)
  perf_test_utils.GenerateLighttpdConfig(config_file, http_server_doc_root,
                                         http_server)
  assert http_server.StartupHttpServer()
  config_file.close()
  # Start QUIC server.
  quic_server_doc_root = perf_test_utils.GenerateQuicTestResources(device)
  quic_server = perf_test_utils.QuicServer(quic_server_doc_root)
  quic_server.StartupQuicServer(device)
  # Launch Telemetry's benchmark_runner on CronetPerfTestBenchmark.
  # By specifying this file's directory as the benchmark directory, it will
  # allow benchmark_runner to in turn open this file up and find the
  # CronetPerfTestBenchmark class to run the benchmark.
  top_level_dir = os.path.dirname(os.path.realpath(__file__))
  expectations_files = [os.path.join(top_level_dir, 'expectations.config')]
  runner_config = chromium_config.ChromiumConfig(
      top_level_dir=top_level_dir,
      benchmark_dirs=[top_level_dir],
      expectations_files=expectations_files)
  sys.argv.insert(1, 'run')
  sys.argv.insert(2, 'run.CronetPerfTestBenchmark')
  sys.argv.insert(3, '--browser=android-system-chrome')
  sys.argv.insert(4, '--output-format=' + options.output_format)
  if options.output_dir:
    sys.argv.insert(5, '--output-dir=' + options.output_dir)
  benchmark_runner.main(runner_config)
  # Shutdown.
  quic_server.ShutdownQuicServer()
  shutil.rmtree(quic_server_doc_root)
  http_server.ShutdownHttpServer()
  shutil.rmtree(http_server_doc_root)

if __name__ == '__main__':
  main()


text:
export class Texture {
    width: number = 1;
    height: number = 1;
    tex_id: WebGLTexture;
}

export class Pixels {
    width: number = 1;
    raw: Uint32Array = new Uint32Array(0);
}

export function texRepeat(gl: WebGLRenderingContext, tex_id: WebGLTexture) {
    gl.bindTexture(gl.TEXTURE_2D, tex_id);
    gl.texParameteri(
        gl.TEXTURE_2D,
        gl.TEXTURE_WRAP_S,
        gl.REPEAT
    );
    gl.texParameteri(
        gl.TEXTURE_2D,
        gl.TEXTURE_WRAP_T,
        gl.REPEAT
    );
    gl.texParameteri(
        gl.TEXTURE_2D,
        gl.TEXTURE_MIN_FILTER,
        gl.NEAREST
    );
    gl.texParameteri(
        gl.TEXTURE_2D,
        gl.TEXTURE_MAG_FILTER,
        gl.NEAREST
    );
}

export function updateTextureFromPixels(
    gl: WebGLRenderingContext,
    tex: Texture,
    pixels: Pixels
): void {
    tex.width = pixels.width;
    tex.height = pixels.raw.length / pixels.width;
    gl.bindTexture(gl.TEXTURE_2D, tex.tex_id);
    gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, tex.width, tex.height,
        0, gl.RGBA,
        gl.UNSIGNED_BYTE, new Uint8Array(pixels.raw.buffer));
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
}

export class TextureLoader {

    private cache: { [path: string]: {
        cbs: Array<(tex: Texture) => void>,
        tex?: Texture
    }} = {};

    constructor(private gl: WebGLRenderingContext) {}

    loadSingleColorTexture(color: Uint8Array, cb: (tex: Texture) => void) {
        let gl = this.gl;
        let tex_id = gl.createTexture();
        gl.bindTexture(gl.TEXTURE_2D, tex_id);
        gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA,
            gl.UNSIGNED_BYTE, color);
        let tex = new Texture();
        // TODO: Remove cast and handle the error somehow.
        tex.tex_id = tex_id as WebGLTexture;
        tex.width = 1;
        tex.height = 1;
        cb(tex);
    }

    loadTextureFromPixels(pixels: Pixels, cb: (tex: Texture) => void) {
        let gl = this.gl;
        let tex_id = gl.createTexture();
        let tex = new Texture();
        // TODO: Remove cast and handle the error somehow.
        tex.tex_id = tex_id as WebGLTexture;
        updateTextureFromPixels(gl, tex, pixels);
        cb(tex);
    }

    loadTexture(path: string, cb: (tex: Texture) => void) {

        if (!(path in this.cache)) {

            // Prepare the texture fetch
            let img = new Image();
            let gl = this.gl;
            let tex_id = gl.createTexture();
            gl.bindTexture(gl.TEXTURE_2D, tex_id);
            // Fill the texture with a 1x1 blue pixel.
            gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE,
                          new Uint8Array([0, 0, 255, 255]));
            img.src = path;

            let isPowerOf2 = (value: number) => (value & (value - 1)) === 0;

            img.onload = () => {
                gl.bindTexture(gl.TEXTURE_2D, tex_id);
                gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA,
                    gl.UNSIGNED_BYTE, img);
                if (isPowerOf2(img.width) && isPowerOf2(img.height)) {
                    gl.generateMipmap(gl.TEXTURE_2D);
                    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST_MIPMAP_NEAREST);
                    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST_MIPMAP_NEAREST);
                } else {
                    // Check that:
                    // No, it's not a power of 2. Turn off mips and set wrapping to clamp to edge
                    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
                    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
                    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
                    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
                }
                let tex = new Texture();
                // TODO: Remove cast and handle the error somehow.
                tex.tex_id = tex_id as WebGLTexture;
                tex.width = img.width;
                tex.height = img.height;

                this.cache[path].tex = tex;

                for (let callback of this.cache[path].cbs) {
                    callback(tex);
                }
            };

            // Add to the cache our request:
            this.cache[path] = {
                cbs: [cb],
                tex: undefined
            };

        } else {
            let tex = this.cache[path].tex;
            if (tex) {
                cb(tex);
            } else {
                this.cache[path].cbs.push(cb);
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
'use strict';

module.exports = function(Basicuser) {

  Basicuser.createUser = function(userDetails,cb){
    var i = userDetails[0];
    var first_name = i['first_name'];
    var last_name = i['last_name'];
    var phone_number = i['phone_number'];
    Basicuser.create({"first_name":first_name,"last_name":last_name,"phone_number":phone_number},function(err,response){
      if(err!=null){
        cb(null,err);
      }else{
        cb(null,"User "+response.first_name+" "+response.last_name+" id created with id "+response.id);
      }
    });
  }

  Basicuser.remoteMethod("createUser",{
    accepts:{arg:"userDetails",type:"array",required:true},
    returns:{arg:"returnMessage",type:"string"},
    http:{path:"/newUser",verb:"post"}
  })
  // Basicuser.disableRemoteMethodByName("create",false);
  // Basicuser.disableRemoteMethodByName("find",false);
  // Basicuser.disableRemoteMethodByName("upsert",false);
  // Basicuser.disableRemoteMethodByName("update",false);
  // Basicuser.disableRemoteMethodByName("count",false);
  // Basicuser.disableRemoteMethodByName("createChangeStream",false);
  // Basicuser.disableRemoteMethodByName("findOne",false);
  // Basicuser.disableRemoteMethodByName("count",false);
  // Basicuser.disableRemoteMethodByName("replaceOrCreate",false);
  // Basicuser.disableRemoteMethodByName("upsertWithWhere",false);
  // Basicuser.disableRemoteMethodByName("upsertById",false);

};


text:
function nntpchan_apicall(url, handler, err_handler, method, data) {
  var ajax = new XMLHttpRequest();
  ajax.onreadystatechange = function() {
    if (ajax.readyState == XMLHttpRequest.DONE ) {
      var status = ajax.status;
      var j = null;
      if (status == 200 || status == 201) {
        // found
        try {
          j = JSON.parse(ajax.responseText);
        } catch (e) {} // ignore parse error
      } else if (status == 410) {
        if (err_handler) {err_handler("cannot fetch post: api disabled");}
        return;
      }
      handler(j);
    }
  };
  var meth = method || "GET";
  ajax.open(meth, url);
  if(data)
    ajax.send(data);
  else
    ajax.send();
}

// build post from json
// inject into parent
// if j is null then inject "not found" post
function nntpchan_buildpost(parent, j) {
  var post = document.createElement("div");
  if (j) {
    // huehuehue
    post.innerHTML = j.PostMarkup;
    inject_hover_for_element(post);
  } else {
    post.setAttribute("class", "notfound post");
    post.appendChild(document.createTextNode("post not found"));
  }
  parent.appendChild(post);
}


text:
package org.apache.sis.io;

import java.io.IOException;

/**
 * Delegates calls to {@code append(CharSequence, int, int)} to a sequence of calls
 * to {@code append(char)}. This is used in order to explore more code paths in
 * {@link Appender} implementations.
 *
 * @author  Martin Desruisseaux (Geomatys)
 * @version 0.3
 * @since   0.3
 * @module
 */
final class SingleCharAppendable extends Appender {
    /**
     * Constructs a {@code SingleCharAppendable} object delegating to the given {@code Appendable}.
     *
     * @param  out  the underlying stream or buffer.
     */
    public SingleCharAppendable(final Appendable out) {
        super(out);
    }

    /**
     * Forwards to {@link #out}.
     */
    @Override
    public Appendable append(final char c) throws IOException {
        out.append(c);
        return this;
    }

    /**
     * Writes a portion of a character sequence.
     *
     * @param  sequence  the character sequence to be written.
     * @param  start     index from which to start reading characters.
     * @param  end       index of the character following the last character to read.
     * @throws IOException if an I/O error occurs.
     */
    @Override
    public Appendable append(final CharSequence sequence, int start, final int end) throws IOException {
        while (start < end) {
            out.append(sequence.charAt(start++));
        }
        return this;
    }
}


text:
/*
 * $Id$
 */

/*

Copyright (c) 2000-2003 Board of Trustees of Leland Stanford Jr. University,
all rights reserved.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
STANFORD UNIVERSITY BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Except as contained in this notice, the name of Stanford University shall not
be used in advertising or otherwise to promote the sale, use or other dealings
in this Software without prior written authorization from Stanford University.

*/

package org.lockss.util;
import java.io.*;

/**
 * CharRing with some additions used by the filtering code
 */

public class FilterCharRing extends CharRing {
  private static Logger logger = Logger.getLogger("FilterCharRing");

  char[] preBuffer;

  public FilterCharRing(int capacity) {
    super(capacity);
    preBuffer = new char[capacity];
  }

  /**
   * @return true if the two chars are equal ignoring case
   */
  public static boolean charEqualsIgnoreCase(char kar1, char kar2) {
    return (Character.toUpperCase(kar1) == Character.toUpperCase(kar2));
  }

  /**
   * @param tag tag to check
   * @return true if the char buffer begins with this tag, false otherwise
   * @throws RuntimeException if tag.length() > size() of charBuffer
   */
  public boolean startsWith(String tag) {
    return startsWith(0, tag, false);
  }

  /**
   * @param idx index at which to begin checking the char buffer
   * @param tag tag to check
   * @param ignoreCase whether to ignore case
   * @return true if the char buffer contains the tag beginning at index idx
   * @throws RuntimeException if idx + tag.length() > size() of charBuffer
   */
  public boolean startsWith(int idx, String tag, boolean ignoreCase) {
    //XXX reimplement with DNA searching algorithm
    int taglen = tag.length();
    int ringsize = size();
    if ((idx + taglen) > ringsize) {
      throw new RuntimeException("idx("+idx+") plus the length of the tag("
				 +tag+") is greater than the remaining size "
				 +"of the charBuffer("+ringsize+")");
    }

    if (logger.isDebug3()) {
      logger.debug3("checking if \""+this+"\" has \"" +tag+"\" at index "+idx);
    }
    //less common case than first char not match, but we have to check for
    //size before that anyway
    if (ringsize < taglen + idx) {
      return false;
    }

    for (int ix=0; ix < taglen && ix + idx < ringsize; ix ++) {
      char curChar = get(ix + idx);
      if (ignoreCase) {
	if (!charEqualsIgnoreCase(curChar, tag.charAt(ix))) {
	  logger.debug3("It doesn't");
	  return false;
	}
      } else {
	if (curChar != tag.charAt(ix)) {
	  logger.debug3("It doesn't");
	  return false;
	}
      }
    }
    logger.debug3("It does");
    return true;
  }

  /**
   * Refill the buffer from the specified reader
   * @param reader reader from which to refill the charBuffer
   * @return true if we've read through the reader, false otherwise
   * @throws IllegalArgumentException if called with a null reader
   */
  public boolean refillBuffer(Reader reader)
      throws IOException {
    if (reader == null) {
      throw new IllegalArgumentException("Called with null reader");
    }
    logger.debug3("Refilling buffer");
    int curKar;

    int charsNeeded = capacity() - size();
    while (charsNeeded > 0) {
      int charsRead = reader.read(preBuffer, 0, charsNeeded);
      if (charsRead == -1) {
	return true;
      }
      try{
	add(preBuffer, 0, charsRead);
      } catch (CharRing.RingFullException e) {
	logger.error("Overfilled a CharRing", e);
	throw new IOException("Overfilled a CharRing");
      }
      charsNeeded = capacity() - size();
    }
    return false;
  }
}


text:
                <button type="button" class="close" data-dismiss="modal">×</button>

Item Details

                            Account Code
                            Serial #
                            Official Receipt #
                            Description
                            Usage
                            Distribution Date
                            Received By
                            Unit Cost


text:
/**
 * A directive to hide the tags input when the max tags limit is reached.
 * Works with github.com/mbenford/ngTagsInput
 */
app.directive( 'restrictToMaxTags', function () {
    var KEY_BACKSPACE =  8;
        KEY_TAB = 9;

    return {
        require: 'ngModel',
        priority: -10,
        link: function ( $scope, $element, $attrs, ngModelController ) {
            var tagsInputScope = $element.isolateScope(),
                maxTags,
                getTags,
                checkTags,
                maxTagsReached,
                input = $element.find( 'input' ),
                placeholder;

            $attrs.$observe( 'maxTags', function ( _maxTags ) {
                maxTags = _maxTags;
            });

            getTags = function () {
                return ngModelController.$modelValue;
            };

            checkTags = function () {
                var tags = getTags();
                if ( tags && tags.length && tags.length >= maxTags ) {
                    if ( !maxTagsReached ) {
                        // trigger the autocomplete to hide
                        tagsInputScope.events.trigger( 'input-blur' );
                        placeholder = input.attr( 'placeholder' );
                        input.attr( 'placeholder', '' );
                        // use max-width to avoid conflicts with the tiAutosize
                        // directive that ngTagsInput uses
                        // input.css( 'max-width', '0' );
                        $scope.maxTags = true;
                        maxTagsReached = true;
                    }
                } else if ( maxTagsReached ) {
                    input.attr( 'placeholder', placeholder );
                    // input.css( 'max-width', '' );
                    $scope.maxTags = false;
                    maxTagsReached = false;
                }
            };

            $scope.$watchCollection( getTags, checkTags );

            // prevent any keys from being entered into
            // the input when max tags is reached
            input.on( 'keydown', function ( event ) {
                if ( maxTagsReached && event.keyCode !== KEY_BACKSPACE && event.keyCode !== KEY_TAB ) {
                    event.stopImmediatePropagation();
                    event.preventDefault();
                }
            });

            // prevent the autocomplete from being triggered
            input.on( 'focus', function ( event ) {
                checkTags();
                if ( maxTagsReached ) {
                    tagsInputScope.hasFocus = true;
                    event.stopImmediatePropagation();
                }
            });
        }
    };
});


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

namespace App\Repository;

use App\Entity\Client;

/**
 * @method Client|null find($id, $lockMode = null, $lockVersion = null)
 * @method Client|null findOneBy(array $criteria, array $orderBy = null)
 * @method Client[]    findAll()
 * @method Client[]    findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
 */
interface ClientRepository
{
    public function refresh(Client $client): void;

    public function save(Client $client): void;

    public function findOneByName(string $value): Client;

    public function findOneByEmail(string $value): Client;
}


text:
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.extensions.impl;

import com.intellij.openapi.extensions.ExtensionPoint;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.util.containers.CollectionFactory;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.AbstractMap.SimpleImmutableEntry;
import java.util.*;
import java.util.concurrent.ConcurrentMap;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;

// Separate class to keep ExtensionPointImpl class implementation clear and readable,
// such simple util code better to keep separately.

// getThreadSafeAdapterList can be opened to used here directly to avoid using of iterator, but it doesn't make sense
// - if there is already cached extension list, it will be used instead of custom iterator.
// It is not only about performance and common sense, but also supporting ability to mock extension list in tests (custom list is set).
@ApiStatus.Internal
public final class ExtensionProcessingHelper {
  public static <T> void forEachExtensionSafe(@NotNull Iterable<? extends T> iterable, @NotNull Consumer<? super T> extensionConsumer) {
    for (T t : iterable) {
      if (t == null) {
        break;
      }

      try {
        extensionConsumer.accept(t);
      }
      catch (ProcessCanceledException e) {
        throw e;
      }
      catch (Throwable e) {
        ExtensionPointImpl.LOG.error(e);
      }
    }
  }

  public static @Nullable <T> T findFirstSafe(@NotNull Predicate<? super T> predicate, @NotNull Iterable<? extends T> iterable) {
    return computeSafeIfAny(o -> predicate.test(o) ? o : null, iterable);
  }

  public static @Nullable <T, R> R computeSafeIfAny(@NotNull Function<? super T, ? extends R> processor, @NotNull Iterable<? extends T> iterable) {
    for (T t : iterable) {
      if (t == null) {
        return null;
      }

      try {
        R result = processor.apply(t);
        if (result != null) {
          return result;
        }
      }
      catch (ProcessCanceledException e) {
        throw e;
      }
      catch (Exception e) {
        ExtensionPointImpl.LOG.error(e);
      }
    }

    return null;
  }

  /**
   * See {@link com.intellij.openapi.extensions.ExtensionPointName#getByGroupingKey}.
   */
  public static <@NotNull K, @NotNull T> @NotNull List<T> getByGroupingKey(@NotNull ExtensionPointImpl<T> point,
                                                                           @NotNull Class<?> cacheId,
                                                                           @NotNull K key,
                                                                           @NotNull Function<? super @NotNull T, ? extends @Nullable K> keyMapper) {
    ConcurrentMap<Class<?>, Map<K, List<T>>> keyMapperToCache = point.getCacheMap();
    Map<K, List<T>> cache = keyMapperToCache.get(cacheId);
    if (cache == null) {
      cache = buildCacheForGroupingKeyMapper(keyMapper, point);
      Map<K, List<T>> prev = keyMapperToCache.putIfAbsent(cacheId, cache);
      if (prev != null) {
        cache = prev;
      }
    }

    List<T> result = cache.get(key);
    return result == null ? Collections.emptyList() : result;
  }

  /**
   * See {@link com.intellij.openapi.extensions.ExtensionPointName#getByKey}.
   */
  @ApiStatus.Internal
  public static <@NotNull K, @NotNull T, @NotNull V> @Nullable V getByKey(@NotNull ExtensionPointImpl<T> point,
                                                                          @NotNull K key,
                                                                          @NotNull Class<?> cacheId,
                                                                          @NotNull Function<? super @NotNull T, ? extends @Nullable K> keyMapper,
                                                                          @NotNull Function<? super @NotNull T, ? extends @Nullable V> valueMapper) {
    return doGetByKey(point, cacheId, key, keyMapper, valueMapper, point.getCacheMap());
  }

  /**
   * See {@link com.intellij.openapi.extensions.ExtensionPointName#getByKey}.
   */
  @ApiStatus.Internal
  public static <@NotNull K, @NotNull T> @Nullable T getByKey(@NotNull ExtensionPointImpl<T> point,
                                                              @NotNull K key,
                                                              @NotNull Class<?> cacheId,
                                                              @NotNull Function<? super @NotNull T, ? extends @Nullable K> keyMapper) {
    return doGetByKey(point, cacheId, key, keyMapper, Function.identity(), point.getCacheMap());
  }

  /**
   * See {@link com.intellij.openapi.extensions.ExtensionPointName#getByKey}.
   */
  @ApiStatus.Internal
  public static <@NotNull K, @NotNull T, @NotNull V> @NotNull V computeIfAbsent(@NotNull ExtensionPointImpl<T> point,
                                                                                @NotNull K key,
                                                                                @NotNull Class<?> cacheId,
                                                                                @NotNull Function<? super K, ? extends V> valueProducer) {
    // Or to have double look-up (map for valueProducer, map for key), or using of composite key. Java GC is quite good, so, composite key.
    ConcurrentMap<SimpleImmutableEntry<K, Class<?>>, V> cache = point.getCacheMap();
    return cache.computeIfAbsent(new SimpleImmutableEntry<>(key, cacheId), entry -> valueProducer.apply(entry.getKey()));
  }

  @ApiStatus.Internal
  public static <@NotNull T, @NotNull V> @NotNull V computeIfAbsent(@NotNull ExtensionPointImpl<T> point,
                                                                    @NotNull Class<?> cacheId,
                                                                    @NotNull Supplier<? extends V> valueProducer) {
    ConcurrentMap<Class<?>, V> cache = point.getCacheMap();
    return cache.computeIfAbsent(cacheId, __ -> valueProducer.get());
  }

  private static <CACHE_KEY, K, T, V> @Nullable V doGetByKey(@NotNull ExtensionPoint<T> point,
                                                             @NotNull CACHE_KEY cacheId,
                                                             @NotNull K key,
                                                             @NotNull Function<? super T, ? extends K> keyMapper,
                                                             @NotNull Function<? super @NotNull T, ? extends @Nullable V> valueMapper,
                                                             @NotNull ConcurrentMap<CACHE_KEY, Map<K, V>> keyMapperToCache) {
    Map<K, V> cache = keyMapperToCache.get(cacheId);
    if (cache == null) {
      cache = buildCacheForKeyMapper(keyMapper, valueMapper, point);
      Map<K, V> prev = keyMapperToCache.putIfAbsent(cacheId, cache);
      if (prev != null) {
        cache = prev;
      }
    }
    return cache.get(key);
  }

  private static <K, T> @NotNull Map<K, List<T>> buildCacheForGroupingKeyMapper(@NotNull Function<? super T, ? extends K> keyMapper,
                                                                                @NotNull ExtensionPoint<T> point) {
    // use HashMap instead of THashMap - a lot of keys not expected, nowadays HashMap is a more optimized (e.g. computeIfAbsent implemented in an efficient manner)
    Map<K, List<T>> cache = new HashMap<>();
    for (T extension : point.getExtensionList()) {
      K key = keyMapper.apply(extension);
      if (key != null) {
        // SmartList is not used - expected that list size will be > 1
        cache.computeIfAbsent(key, k -> new ArrayList<>()).add(extension);
      }
    }
    return cache;
  }

  private static @NotNull <K, T, V> Map<K, V> buildCacheForKeyMapper(@NotNull Function<? super T, ? extends K> keyMapper,
                                                                     @NotNull Function<? super @NotNull T, ? extends @Nullable V> valueMapper,
                                                                     @NotNull ExtensionPoint<T> point) {
    List<T> extensions = point.getExtensionList();
    Map<K, V> cache = CollectionFactory.createSmallMemoryFootprintMap(extensions.size());
    for (T extension : extensions) {
      K key = keyMapper.apply(extension);
      if (key == null) {
        continue;
      }

      V value = valueMapper.apply(extension);
      if (value == null) {
        continue;
      }
      cache.put(key, value);
    }
    return cache;
  }
}


text:
using UnityEngine;

namespace DFVolume
{
    public class VolumeData : ScriptableObject
    {
        #region Exposed attributes

        [SerializeField] Texture3D _texture;

        public Texture3D texture {
            get { return _texture; }
        }

        #endregion

        #if UNITY_EDITOR

        #region Editor functions

        public void Initialize(VolumeSampler sampler)
        {
            var dim = sampler.resolution;
            _texture = new Texture3D(dim, dim, dim, TextureFormat.RGBAHalf, true);

            _texture.name = "Distance Field Texture";
            _texture.filterMode = FilterMode.Bilinear;
            _texture.wrapMode = TextureWrapMode.Clamp;
            _texture.SetPixels(sampler.GenerateBitmap());
            _texture.Apply();
        }

        #endregion

        #endif
    }
}


text:
from wtforms import validators, fields
from wtforms.form import Form, FormMeta

class DocumentFieldConverter(object):
    """
    Convert the given ``document_class`` into WTForm fields.

    :param document_class:
        The Mongoengine document to convert.

    :param fields:
        A ``tuple`` of fields to include (optional).

    :param exclude:
        A ``tuple`` of fields to exclude (optional).

    .. note::
        When both using ``fields`` and ``exclude``, ``fields`` will be used.

    """

    def __init__(self, document_class, fields=None, exclude=None):
        self.document_class = document_class
        self.only_fields = fields
        self.exclude_fields = exclude

    @property
    def fields(self):
        """
        Return a ``dict`` containing the WTForms fields.

        :return:
            A ``dict`` with the following as key / value:

            key
                The (internal) field name.

            value
                An object representing the WTForms field.

        """
        field_dict = {}
        field_names = self.document_class._fields.keys()

        if self.only_fields:
            field_names = (f for f in field_names if f in self.only_fields)
        elif self.exclude_fields:
            field_names = (
                f for f in field_names if f not in self.exclude_fields)

        for field_name in field_names:
            model_field = self.document_class._fields[field_name]
            wtf_field = self.convert(model_field)
            if wtf_field:
                field_dict[field_name] = wtf_field

        return field_dict

    def convert(self, document_field):
        """
        Convert ``document_field`` into a WTForms field.

        :param document_field:
            Instance of a Mongoengine field class.

        :return:
            Instance of a WTForms instance.

        """
        kwargs = {
            'label': document_field.verbose_name or document_field.name,
            'description': document_field.help_text or '',
            'validators': [],
            'default': document_field.default,
        }

        if document_field.required:
            kwargs['validators'].append(validators.Required())

        if document_field.choices:
            kwargs['choices'] = document_field.choices
            return fields.SelectField(**kwargs)

        document_field_type = type(document_field).__name__

        convert_method_name = 'from_{0}'.format(document_field_type.lower())

        if hasattr(self, convert_method_name):
            return getattr(self, convert_method_name)(document_field, **kwargs)
        else:
            return None

    def set_common_string_kwargs(self, document_field, kwargs):
        """
        Set common string arguments.

        :param document_field:
            Instance of Mongoengine field.

        :param kwargs:
            A ``dict`` that needs to be updated with the new arguments.

        """
        if document_field.max_length or document_field.min_length:
            kwargs['validators'].append(
                validators.Length(
                    max=document_field.max_length or -1,
                    min=document_field.min_length or -1
                )
            )

        if document_field.regex:
            kwargs['validators'].append(
                validators.Regexp(regex=document_field.regex)
            )

    def set_common_number_kwargs(self, document_field, kwargs):
        """
        Set common number arguments.

        :param document_field:
            Instance of Mongoengine field.

        :param kwargs:
            A ``dict`` that needs to be updated with the new arguments.

        """
        if document_field.max_value or document_field.min_value:
            kwargs['validators'].append(
                validators.NumberRange(
                    max=document_field.max_value,
                    min=document_field.min_value
                )
            )

    def from_stringfield(self, document_field, **kwargs):
        """
        Convert ``document_field`` into a ``TextField``.

        :param document_field:
            Instance of Mongoengine field.

        :return:
            Instance of :py:class:`!wtforms.fields.TextField`.

        """
        self.set_common_string_kwargs(document_field, kwargs)
        return fields.TextField(**kwargs)

    def from_urlfield(self, document_field, **kwargs):
        """
        Convert ``document_field`` into a ``TextField`` with URL validation.

        :param document_field:
            Instance of Mongoengine field.

        :return:
            Instance of :py:class:`!wtforms.fields.TextField`.

        """
        kwargs['validators'].append(validators.URL())
        # TODO: cleanyp set_common_string_kwargs?
        self.set_common_string_kwargs(document_field, kwargs)
        return fields.TextField(**kwargs)

    def from_emailfield(self, document_field, **kwargs):
        """
        Convert ``document_field`` into a ``TextField`` with e-mail validation.

        :param document_field:
            Instance of Mongoengine field.

        :return:
            Instance of :py:class:`!wtforms.fields.TextField`.

        """
        kwargs['validators'].append(validators.Email())
        self.set_common_string_kwargs(document_field, kwargs)
        return fields.TextField(**kwargs)

    def from_intfield(self, document_field, **kwargs):
        """
        Convert ``document_field`` into a ``IntegerField``.

        :param document_field:
            Instance of Mongoengine field.

        :return:
            Instance of :py:class:`!wtforms.fields.IntegerField`.

        """
        self.set_common_number_kwargs(document_field, kwargs)
        return fields.IntegerField(**kwargs)

    def from_floatfield(self, document_field, **kwargs):
        """
        Convert ``document_field`` into a ``FloatField``.

        :param document_field:
            Instance of Mongoengine field.

        :return:
            Instance of :py:class:`!wtforms.fields.FloatField`.

        """
        self.set_common_number_kwargs(document_field, kwargs)
        return fields.FloatField(**kwargs)

    def from_decimalfield(self, document_field, **kwargs):
        """
        Convert ``document_field`` into a ``DecimalField``.

        :param document_field:
            Instance of Mongoengine field.

        :return:
            Instance of :py:class:`!wtforms.fields.DecimalField`.

        """
        self.set_common_number_kwargs(document_field, kwargs)
        return fields.DecimalField(**kwargs)

    def from_datetimefield(self, document_field, **kwargs):
        """
        Convert ``document_field`` into a ``DateTimeField``.

        :param document_field:

        :return:
            Instance of :py:class:`!wtforms.fields.DateTimeField`.

        """
        return fields.DateTimeField(**kwargs)

    def from_complexdatetimefield(self, document_field, **kwargs):
        raise NotImplementedError('ComplexDateTimeField not implemented.')

    def from_listfield(self, document_field, **kwargs):
        raise NotImplementedError('ListField not implemented.')

    def from_sortedlistfield(self, document_field, **kwargs):
        raise NotImplementedError('SortedListField not implemented.')

    def from_dictfield(self, document_field, **kwargs):
        raise NotImplementedError('DictField not implemented.')

    def from_mapfield(self, document_field, **kwargs):
        raise NotImplementedError('MapField not implemented.')

    def from_objectidfield(self, document_field, **kwargs):
        return None

    def from_referencefield(self, document_field, **kwargs):
        raise NotImplementedError('ReferenceField not implemented.')

    def from_genericreferencefield(self, document_field, **kwargs):
        raise NotImplementedError('GenericReferenceField not implemented.')

    def from_embeddeddocumentfield(self, document_field, **kwargs):
        raise NotImplementedError('EmbeddedDocumentField not implemented.')

    def from_genericembeddeddocumentfield(self, document_field, **kwargs):
        raise NotImplementedError(
            'GenericEmbeddedDocumentField not implemented.')

    def from_booleanfield(self, document_field, **kwargs):
        """
        Convert ``document_field`` into a ``BooleanField``.

        :param document_field:
            Instance of Mongoengine field.

        :return:
            Instance of :py:class:`!wtforms.fields.BooleanField`.

        """
        return fields.BooleanField(**kwargs)

    def from_filefield(self, document_field, **kwargs):
        raise NotImplementedError('FileField not implemented.')

    def from_binaryfield(self, document_field, **kwargs):
        raise NotImplementedError('BinaryField not implemented.')

    def from_geopointfield(self, document_field, **kwargs):
        raise NotImplementedError('GeoPointField not implemented.')

    def from_sequencefield(self, document_field, **kwargs):
        raise NotImplementedError('SequenceField not implemented.')

class DocumentFormMetaClassBase(type):
    """
    Meta-class for generating the actual WTForms class.
    """
    def __new__(cls, name, bases, attrs):
        if 'Meta' in attrs:
            document_class = attrs['Meta'].document_class
            fields = getattr(attrs['Meta'], 'fields', None)
            exclude = getattr(attrs['Meta'], 'exclude', None)

            converter = DocumentFieldConverter(document_class, fields, exclude)
            attrs = converter.fields

        return super(
            DocumentFormMetaClassBase, cls).__new__(cls, name, bases, attrs)

class DocumentFormMetaClass(DocumentFormMetaClassBase, FormMeta):
    # This object, combining the two meta classes, is needed to avoid conflicts
    pass

class DocumentForm(Form):
    """
    Baseclass for constructing a WTF form from a Mongoengine Document class.

    Usage example::

        from mongoengine import document, fields
        from wtfmongoengine.forms import DocumentForm

        class User(document.Document):
            first_name = fields.StringField(
                verbose_name='First name',
                max_length=50,
                required=True,
            )
            last_name = fields.StringField(
                verbose_name='Last name',
                max_length=50,
                required=False,
            )
            email = fields.EmailField(
                verbose_name='E-mail address',
                required=True,
            )

        class UserForm(DocumentForm):
            class Meta:
                document_class = User

                # In case you only want to include ``first_name`` in the form
                # fields = ('first_name',)

                # In case you want to exclude ``email`` from the form
                # exclude = ('email',)

    .. note::
        When using both ``fields`` and ``exclude``, only ``fields`` will
        be used.

    """
    __metaclass__ = DocumentFormMetaClass


text:
package ee.pri.bcup.common.message.server;

import lombok.Data;
import lombok.EqualsAndHashCode;

@Data
@EqualsAndHashCode(callSuper = false)
public class ServerPartRoomMessage extends ServerMessage {
	private Long playerId;

	public ServerPartRoomMessage() {}

	public ServerPartRoomMessage(Long playerId) {
		this.playerId = playerId;
	}

}


text:
require 'net/http'
require 'rexml/document'

class ResponseData

  include WiziqApiConstants::ResponseNodes

  attr_reader :doc_root,:api_method,:api_msg,:api_code,:api_status
  attr_accessor :optional_params
  def initialize(response_xml)

    @optional_params = []
    res_doc = REXML::Document.new(response_xml,{:compress_whitespace => :all})
    @doc_root = res_doc.root
    raise 'Invalid api response' if @doc_root.blank?
    @api_status = @doc_root.attributes["status"]
    @api_method = @doc_root.elements["method/text()"]
    @api_msg = @doc_root.elements["error/@msg"]
    @api_code = @doc_root.elements["error/@code"]
    Rails::logger.debug " api method is  #{ @api_method }"

  end

  # parse response based upon api_method

  def parse_schedule_class_response

    hash = Hash.new

    class_id = @doc_root.elements["//"+Schedule::CLASS_ID].text
    hash.store(Schedule::CLASS_ID,class_id)
    recording_url = @doc_root.elements["//" + Schedule::RECORDING_URL].text
    hash.store(Schedule::RECORDING_URL,recording_url)
    presenters = []
    @doc_root.elements["//" + Schedule::PRESENTER].each do |presenter|

      next if presenter.type == REXML::Text
      presenters << Hash[
        Schedule::PRESENTER_URL, presenter.elements["//" + Schedule::PRESENTER_URL].text,
        Schedule::PRESENTER_ID, presenter.elements["//" + Schedule::PRESENTER_ID].text
      ]

    end
    hash.store("presenters",presenters)
    hash
  end

  def parse_add_attendee_response

    hash = Hash.new
    class_id = @doc_root.elements["//" + AddAttendee::CLASS_ID].text
    hash.store(AddAttendee::CLASS_ID,class_id)
    hash.store(AddAttendee::ATTENDEE_ID, @doc_root.elements["//" + AddAttendee::ATTENDEE_ID].text)
    hash.store(AddAttendee::ATTENDEE_URL, @doc_root.elements["//" + AddAttendee::ATTENDEE_URL].text)
    hash.store(AddAttendee::LANGUAGE , @doc_root.elements["//" + AddAttendee::LANGUAGE].text)
    hash

  end

  def parse_class_info

    hash = Hash.new
    Rails::logger.debug " each debug s  "
    begin
      @optional_params.each do |node|

        Rails::logger.debug " each debug stub  #{ node.type  }  "
        next if node.type == REXML::Text

        hash.store(node,@doc_root.elements["//#{ node }"].text)
        Rails::logger.debug " parsing class launch node =>  #{ node }, value => #{ @doc_root.elements["//#{ node }"].text  if !@doc_root.elements["//#{ node }"].blank?  }  "

      end
    rescue
      false
    end
    hash
  end

end


text:
import os
import sys
import django

from django.conf import settings
from django.core.management import call_command

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

settings.configure(DEBUG=True,
                   INSTALLED_APPS=(
                       'django.contrib.admin',
                       'django.contrib.auth',
                       'django.contrib.contenttypes',
                       'django.contrib.sessions',
                       'django.contrib.messages',
                       'django.contrib.staticfiles',
                       'rest_framework',
                       'rest_framework.authtoken',
                       'slothauth',
                       'test_mocks',
                   ),
                   DATABASES={
                       'default': {
                           'ENGINE': 'django.db.backends.sqlite3',
                            'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
                       }
                   },
                   ROOT_URLCONF='slothauth.urls',
                   MIDDLEWARE=[
                       'django.middleware.security.SecurityMiddleware',
                       'django.contrib.sessions.middleware.SessionMiddleware',
                       'django.middleware.common.CommonMiddleware',
                       'django.middleware.csrf.CsrfViewMiddleware',
                       'slothauth.middleware.PasswordlessUserMiddleware',
                       'slothauth.middleware.OneTimeAuthenticationKeyMiddleware',
                       'django.contrib.auth.middleware.AuthenticationMiddleware',
                       'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
                       'django.contrib.messages.middleware.MessageMiddleware',
                       'django.middleware.clickjacking.XFrameOptionsMiddleware',
                   ],
                   AUTH_USER_MODEL='test_mocks.Account',
                   AUTHENTICATION_BACKENDS=[
                       'slothauth.backends.PasswordlessAuthentication',
                   ],
                   ACCOUNT_FORM='slothauth.forms.AccountForm',
                   TEMPLATES=[{
                       'BACKEND': 'django.template.backends.django.DjangoTemplates',
                       'DIRS': [],
                       'OPTIONS': {
                           'context_processors': [
                               'django.template.context_processors.debug',
                               'django.template.context_processors.media',
                               'django.template.context_processors.request',
                               'django.contrib.auth.context_processors.auth',
                               'django.contrib.messages.context_processors.messages',
                           ],
                           'loaders': [
                               'django.template.loaders.filesystem.Loader',
                               'django.template.loaders.app_directories.Loader',
                           ]
                       },
                   }, ], )

django.setup()
call_command('test', 'slothauth')


text:
title: Яндекс заменяет тИЦ на ИКС — индекс качества сайта
date: 2018-08-22 14:13:00 Z
categories:
- useful
tags:
- Яндекс
- тИЦ
- ИКС
- индекс качества сайта
- тематический индекс цитирования
header: ИКС — новый показатель качества сайта от Яндекс
description: Яндекс отменяет тИЦ навсегда! На следующей неделе в Яндексе перестанет
  отображаться тИЦ на всех наших ресурсах. Ему на смену придёт ИКС — индекс качества
  сайта.
---

На следующей неделе в Яндексе перестанет отображаться тИЦ на всех наших ресурсах. Ему на смену придёт **ИКС — индекс качества сайта**. Он будет использоваться вместо старого показателя.

Тематический индекс цитирования, или тИЦ, Яндекс представил в 1999 году. Этот показатель служил для определения авторитетности сайта на основании количества и качества других сайтов, которые на него ссылаются. С тех пор прошло почти 20 лет, и за это время интернет сильно изменился: развились соцсети, выросло количество мобильных сайтов и пользователей, прошла эпоха SEO-ссылок… Алгоритмы ранжирования сайтов тоже сильно изменились: современные поисковые системы учитывают при формировании выдачи сотни различных сигналов. Сейчас ссылки — далеко не единственный показатель качества, на который стоит ориентироваться владельцам сайтов.

Таким образом, стала очевидна необходимость метрики, учитывающей помимо ссылок и другие аспекты качества сайта, известные Яндексу. В Яндексе решили назвать её **ИКС — индекс качества сайта**. Под **ИКС**, то есть под качеством сайта, Яндекс понимает в первую очередь востребованность сайта аудиторией. Чем больше пользователей смогли с помощью сайта удовлетворить свои потребности, чем больше задач они решили, тем он полезней. При этом важно не просто количество пользователей, но и степень их удовлетворённости, общий уровень доверия к сайту. Похожие принципы используются нами для нашей основной метрики качества поиска.

**ИКС полностью заменит тИЦ**. Тематический индекс цитирования больше не будет рассчитываться и отображаться. Любой пользователь или владелец сайта сможет узнать индекс качества своего и других сайтов в Яндекс.Вебмастере уже на следующей неделе.

![indeks kachestva saita iks yandex.png](/uploads/indeks%20kachestva%20saita%20iks%20yandex.png){:alt="ИКС заменит тИЦ Яндекс"}

При расчёте **ИКС** в компании Яндекс намерены использовать всевозможные имеющиеся у поисковика данные как о сайте, так и о стоящем за ним бизнесе. Эти данные могут быть получены как из Поиска, так и из любых других сервисов Яндекса: например, Метрики, Карт, Дзена и так далее. По мере учёта этих данных алгоритм расчета ИКС будет меняться. Поэтому сейчас мы получим его пока в виде беты.


text:
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.python.codeInsight.intentions;

import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.util.IncorrectOperationException;
import com.jetbrains.python.PyPsiBundle;
import com.jetbrains.python.codeInsight.ConditionUtil;
import com.jetbrains.python.psi.PyBinaryExpression;
import com.jetbrains.python.psi.PyFile;
import kotlin.Pair;
import org.jetbrains.annotations.NotNull;

/**
 * Author: Alexey.Ivanov
 */
public class PyNegateComparisonIntention extends PyBaseIntentionAction {

  @Override
  @NotNull
  public String getFamilyName() {
    return PyPsiBundle.message("INTN.NAME.negate.comparison");
  }

  @Override
  public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) {
    if (!(file instanceof PyFile)) {
      return false;
    }

    PsiElement element = file.findElementAt(editor.getCaretModel().getOffset());
    PyBinaryExpression binaryExpression = PsiTreeUtil.getParentOfType(element, PyBinaryExpression.class, false);
    Pair<String, String> negation = ConditionUtil.findComparisonNegationOperators(binaryExpression);
    if (negation != null) {
      setText(PyPsiBundle.message("INTN.negate.comparison", negation.component1(), negation.component2()));
      return true;
    }
    return false;
  }

  @Override
  public void doInvoke(@NotNull Project project, Editor editor, PsiFile file) throws IncorrectOperationException {
    PsiElement element = file.findElementAt(editor.getCaretModel().getOffset());
    PyBinaryExpression binaryExpression = PsiTreeUtil.getParentOfType(element, PyBinaryExpression.class, false);
    ConditionUtil.negateComparisonExpression(project, file, binaryExpression);
  }
}


text:
Alloy.CFG.HTTP_TIMEOUT_SECONDS = 7;
Alloy.CFG.BACKEND_ROOT_URL     = 'http://sinatra-api-demo.herokuapp.com';

// Lister for internet connection
var NETWORK_ONLINE = 'event_network_online';
var NETWORK_OFFLINE = 'event_network_offline';
Titanium.Network.addEventListener('change', function(e) {
  if(e.online) {
    Ti.App.fireEvent(NETWORK_ONLINE);
  }
  else {
    Ti.App.fireEvent(NETWORK_OFFLINE);
  }
});


text:
@implementation FlipsideViewController

@synthesize delegate;
@synthesize portsTextField = _portsTextField;

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor viewFlipsideBackgroundColor];
}

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

    [[self portsTextField] setText:[[NSUserDefaults standardUserDefaults] valueForKey:@"kMongoosePorts"]];
}

- (IBAction)done
{
    [[NSUserDefaults standardUserDefaults] setValue:[[self portsTextField] text] forKey:@"kMongoosePorts"];

	[[self delegate] flipsideViewControllerDidFinish:self];
}

- (void)dealloc {
    [_portsTextField release];
    [super dealloc];
}

@end


text:
0.0.0.5
=========
* Added labels for metrics
* Added graphite area overload option

0.0.0.4
=========
* Removed metric_prefix from config
* Added metric prefix to macro templates
* Added metric to macro templates

0.0.0.3
=========
* Removed .value from Grapher.php and added to the macro templates, the default templates respect this change.

0.0.0.2
=========
* Changed defaults for service_name_template and host_name_template to align with the example configuration.


text:
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/**
 * @fileoverview 'cr-lottie' is a wrapper around the player for lottie
 * animations. Since the player runs on a worker thread, 'cr-lottie' requires
 * the document CSP to be set to "worker-src blob: 'self';".
 * Fires a 'cr-lottie-initialized' event when the animation was successfully
 * initialized.
 * Fires a 'cr-lottie-playing' event when the animation starts playing.
 * Fires a 'cr-lottie-paused' event when the animation has paused.
 * Fires a 'cr-lottie-stopped' event when animation has stopped.
 * Fires a 'cr-lottie-resized' event when the canvas the animation is being
 * drawn on is resized.
 */

import {PolymerElement} from '//resources/polymer/v3_0/polymer/polymer_bundled.min.js';

import {assert, assertNotReached} from '../../js/assert_ts.js';
import {getTrustedScriptURL} from '../../js/static_types.js';

import {getTemplate} from './cr_lottie.html.js';

let workerLoaderPolicy: TrustedTypePolicy|null = null;

function getLottieWorkerURL(): TrustedScriptURL {
  if (workerLoaderPolicy === null) {
    workerLoaderPolicy =
        window.trustedTypes!.createPolicy('lottie-worker-script-loader', {
          createScriptURL: (_ignore: string) => {
            const workerUrl =
                getTrustedScriptURL`chrome://resources/lottie/lottie_worker.min.js`;
            // Need to add a try-catch clause because in tests the parent
            // element can be removed from the DOM before the importScripts()
            // call  has finished loading, resulting in test errors.
            const script = `try{ importScripts('${
                workerUrl}'); } catch(e) { console.warn(e); };`;
            // CORS blocks loading worker script from a different origin, even
            // if chrome://resources/ is added in the 'worker-src' CSP header.
            // (see https://crbug.com/1385477). Loading scripts as blob and then
            // instantiating it as web worker is possible.
            const blob = new Blob([script], {type: 'text/javascript'});
            return URL.createObjectURL(blob);
          },
          createHTML: () => assertNotReached(),
          createScript: () => assertNotReached(),
        });
  }

  return workerLoaderPolicy.createScriptURL('');
}

interface OffscreenCanvas {
  width: number;
  height: number;
}

interface MessageData {
  animationData: object|null|string;
  drawSize: {width: number, height: number};
  params: {loop: boolean, autoplay: boolean};
  canvas?: OffscreenCanvas;
}

interface CanvasElementWithOffscreen extends HTMLCanvasElement {
  transferControlToOffscreen: () => OffscreenCanvas;
}

export interface CrLottieElement {
  $: {
    canvas: CanvasElementWithOffscreen,
  };
}

export class CrLottieElement extends PolymerElement {
  static get is() {
    return 'cr-lottie';
  }

  static get template() {
    return getTemplate();
  }

  static get properties() {
    return {
      animationUrl: {
        type: String,
        value: '',
        observer: 'animationUrlChanged_',
      },

      autoplay: {
        type: Boolean,
        value: false,
      },

      hidden: {
        type: Boolean,
        value: false,
      },

      singleLoop: {
        type: Boolean,
        value: false,
      },
    };
  }

  animationUrl: string;
  autoplay: boolean;
  override hidden: boolean;
  singleLoop: boolean;

  private canvasElement_: CanvasElementWithOffscreen|null = null;
  private isAnimationLoaded_: boolean = false;
  private offscreenCanvas_: OffscreenCanvas|null = null;

  /** Whether the canvas has been transferred to the worker thread. */
  private hasTransferredCanvas_: boolean = false;

  private resizeObserver_: ResizeObserver|null = null;

  /**
   * The last state that was explicitly set via setPlay.
   * In case setPlay() is invoked before the animation is initialized, the
   * state is stored in this variable. Once the animation initializes, the
   * state is sent to the worker.
   */
  private playState_: boolean = false;

  /**
   * Whether the Worker needs to receive new size
   * information about the canvas. This is necessary for the corner case
   * when the size information is received when the animation is still being
   * loaded into the worker.
   */
  private workerNeedsSizeUpdate_: boolean = false;

  /**
   * Whether the Worker needs to receive new control
   * information about its desired state. This is necessary for the corner
   * case when the control information is received when the animation is still
   * being loaded into the worker.
   */
  private workerNeedsPlayControlUpdate_: boolean = false;

  private worker_: Worker|null = null;

  /** The current in-flight request. */
  private xhr_: XMLHttpRequest|null = null;

  override connectedCallback() {
    super.connectedCallback();

    this.worker_ = new Worker(getLottieWorkerURL() as unknown as URL);
    this.worker_.onmessage = this.onMessage_.bind(this);
    this.initialize_();
  }

  override disconnectedCallback() {
    super.disconnectedCallback();
    if (this.resizeObserver_) {
      this.resizeObserver_.disconnect();
    }
    if (this.worker_) {
      this.worker_.terminate();
      this.worker_ = null;
    }
    if (this.xhr_) {
      this.xhr_.abort();
      this.xhr_ = null;
    }
  }

  /**
   * Controls the animation based on the value of |shouldPlay|. If the
   * animation is being loaded into the worker when this method is invoked,
   * the action will be postponed to when the animation is fully loaded.
   * @param shouldPlay True for play, false for pause.
   */
  setPlay(shouldPlay: boolean) {
    this.playState_ = shouldPlay;
    if (this.isAnimationLoaded_) {
      this.sendPlayControlInformationToWorker_();
    } else {
      this.workerNeedsPlayControlUpdate_ = true;
    }
  }

  /**
   * Sends control (play/pause) information to the worker.
   */
  private sendPlayControlInformationToWorker_() {
    assert(this.worker_);
    this.worker_.postMessage({control: {play: this.playState_}});
  }

  /**
   * Initializes all the members of this polymer element.
   */
  private initialize_() {
    // Generate an offscreen canvas.
    this.canvasElement_ = this.$.canvas;
    this.offscreenCanvas_ = this.canvasElement_.transferControlToOffscreen();

    this.resizeObserver_ =
        new ResizeObserver(this.onCanvasElementResized_.bind(this));
    this.resizeObserver_.observe(this.canvasElement_);

    if (this.isAnimationLoaded_) {
      return;
    }

    // Open animation file and start playing the animation.
    this.sendXmlHttpRequest_(
        this.animationUrl, 'json', this.initAnimation_.bind(this));
  }

  /**
   * Updates the animation that is being displayed.
   */
  private animationUrlChanged_() {
    if (!this.worker_) {
      // The worker hasn't loaded yet. We will load the new animation once the
      // worker loads.
      return;
    }
    if (this.xhr_) {
      // There is an in-flight request to load the previous animation. Abort it
      // before loading a new image.
      this.xhr_.abort();
      this.xhr_ = null;
    }
    if (this.isAnimationLoaded_) {
      this.worker_.postMessage({control: {stop: true}});
      this.isAnimationLoaded_ = false;
    }
    this.sendXmlHttpRequest_(
        this.animationUrl, 'json', this.initAnimation_.bind(this));
  }

  /**
   * Computes the draw buffer size for the canvas. This ensures that the
   * rasterization is crisp and sharp rather than blurry.
   * @return Size of the canvas draw buffer
   */
  private getCanvasDrawBufferSize_(): {width: number, height: number} {
    const canvasElement = this.$.canvas;
    const devicePixelRatio = window.devicePixelRatio;
    const clientRect = canvasElement.getBoundingClientRect();
    const drawSize = {
      width: clientRect.width * devicePixelRatio,
      height: clientRect.height * devicePixelRatio,
    };
    return drawSize;
  }

  /**
   * Returns true if the |maybeValidUrl| provided is safe to use in an
   * XMLHTTPRequest.
   * @param maybeValidUrl The url string to check for validity.
   */
  private isValidUrl_(maybeValidUrl: string): boolean {
    const url = new URL(maybeValidUrl, document.location.href);
    return url.protocol === 'chrome:' ||
        (url.protocol === 'data:' &&
         url.pathname.startsWith('application/json;'));
  }

  /**
   * Sends an XMLHTTPRequest to load a resource and runs the callback on
   * getting a successful response.
   * @param url The URL to load the resource.
   * @param responseType The type of response the request would
   *     give on success.
   * @param successCallback The callback to run
   *     when a successful response is received.
   */
  private sendXmlHttpRequest_(
      url: string, responseType: XMLHttpRequestResponseType,
      successCallback: (p: object|null|Blob|MediaSource) => void) {
    assert(this.isValidUrl_(url), 'Invalid scheme or data url used.');
    assert(!this.xhr_);

    this.xhr_ = new XMLHttpRequest();
    this.xhr_!.open('GET', url, true);
    this.xhr_!.responseType = responseType;
    this.xhr_!.send();
    this.xhr_!.onreadystatechange = () => {
      assert(this.xhr_);
      if (this.xhr_.readyState === 4 && this.xhr_.status === 200) {
        // |successCallback| might trigger another xhr, so we set to null before
        // calling it.
        const response = this.xhr_.response;
        this.xhr_ = null;
        successCallback(response);
      }
    };
  }

  /**
   * Handles the canvas element resize event. If the animation isn't fully
   * loaded, the canvas size is sent later, once the loading is done.
   */
  private onCanvasElementResized_() {
    if (this.isAnimationLoaded_) {
      this.sendCanvasSizeToWorker_();
    } else {
      // Mark a size update as necessary once the animation is loaded.
      this.workerNeedsSizeUpdate_ = true;
    }
  }

  /**
   * This informs the offscreen canvas worker of the current canvas size.
   */
  private sendCanvasSizeToWorker_() {
    assert(this.worker_);
    this.worker_.postMessage({drawSize: this.getCanvasDrawBufferSize_()});
  }

  /**
   * Initializes the the animation on the web worker with the data provided.
   * @param animationData The animation that will be played.
   */
  private initAnimation_(animationData: object|null|string) {
    const message: MessageData = {
      animationData,
      drawSize: this.getCanvasDrawBufferSize_(),
      params: {loop: !this.singleLoop, autoplay: this.autoplay},
    };
    assert(this.worker_);
    if (!this.hasTransferredCanvas_) {
      message.canvas = this.offscreenCanvas_!;
      this.hasTransferredCanvas_ = true;
      this.worker_.postMessage(
          message, [this.offscreenCanvas_! as unknown as Transferable]);
    } else {
      this.worker_.postMessage(message);
    }
  }

  private fire_(eventName: string, eventData?: number) {
    this.dispatchEvent(new CustomEvent(
        eventName, {bubbles: true, composed: true, detail: eventData}));
  }

  /**
   * Handles the messages sent from the web worker to its parent thread.
   * @param event Event sent by the web worker.
   */
  private onMessage_(event: MessageEvent) {
    if (event.data.name === 'initialized' && event.data.success) {
      this.isAnimationLoaded_ = true;
      this.sendPendingInfo_();
      this.fire_('cr-lottie-initialized');
    } else if (event.data.name === 'playing') {
      this.fire_('cr-lottie-playing');
    } else if (event.data.name === 'paused') {
      this.fire_('cr-lottie-paused');
    } else if (event.data.name === 'stopped') {
      this.fire_('cr-lottie-stopped');
    } else if (event.data.name === 'resized') {
      this.fire_('cr-lottie-resized', event.data.size);
    }
  }

  /**
   * Called once the animation is fully loaded into the worker. Sends any
   * size or control information that may have arrived while the animation
   * was not yet fully loaded.
   */
  private sendPendingInfo_() {
    if (this.workerNeedsSizeUpdate_) {
      this.workerNeedsSizeUpdate_ = false;
      this.sendCanvasSizeToWorker_();
    }
    if (this.workerNeedsPlayControlUpdate_) {
      this.workerNeedsPlayControlUpdate_ = false;
      this.sendPlayControlInformationToWorker_();
    }
  }
}

declare global {
  interface HTMLElementTagNameMap {
    'cr-lottie': CrLottieElement;
  }
}

customElements.define(CrLottieElement.is, CrLottieElement);


text:
This guide describes **Angular Universal**, a technology that renders Angular applications on the server.

A normal Angular application executes in the _browser_, rendering pages in the DOM in response to user actions.
Angular Universal executes on the _server_, generating _static_ application pages that later get bootstrapped on
the client. This means that the application generally renders more quickly, giving users a chance to view the application
layout before it becomes fully interactive.

For a more detailed look at different techniques and concepts surrounding SSR, please check out this
[article](https://developers.google.com/web/updates/2019/02/rendering-on-the-web).

You can easily prepare an app for server-side rendering using the [Angular CLI](guide/glossary#cli).
The CLI schematic `@nguniversal/express-engine` performs the required steps, as described below.

  **Note:** [Download the finished sample code](generated/zips/universal/universal.zip),
  which runs in a [Node.js® Express](https://expressjs.com/) server.

{@a the-example}
## Universal tutorial

The [Tour of Heroes tutorial](tutorial) is the foundation for this walkthrough.

In this example, the Angular CLI compiles and bundles the Universal version of the app with the
[Ahead-of-Time (AoT) compiler](guide/aot-compiler).
A Node Express web server compiles HTML pages with Universal based on client requests.

To create the server-side app module, `app.server.module.ts`, run the following CLI command.

ng add @nguniversal/express-engine

The command creates the following folder structure.

src/
  index.html                 app web page
  main.ts                    bootstrapper for client app
  main.server.ts             * bootstrapper for server app
  style.css                  styles for the app
  app/ ...                   application code
    app.server.module.ts     * server-side application module
server.ts                    * express web server
tsconfig.json                TypeScript client configuration
tsconfig.app.json            TypeScript client configuration
tsconfig.server.json         * TypeScript server configuration
tsconfig.spec.json           TypeScript spec configuration
package.json                 npm configuration

The files marked with `*` are new and not in the original tutorial sample.

### Universal in action

To start rendering your app with Universal on your local system, use the following command.

npm run build:ssr && npm run serve:ssr

Open a browser and navigate to http://localhost:4000/.
You should see the familiar Tour of Heroes dashboard page.

Navigation via `routerLinks` works correctly because they use the native anchor (`<a>`) tags.
You can go from the Dashboard to the Heroes page and back.
You can click a hero on the Dashboard page to display its Details page.

If you throttle your network speed so that the client-side scripts take longer to download (instructions below),
you'll notice:
* Clicking a hero on the Heroes page does nothing.
* You can't add or delete a hero.
* The search box on the Dashboard page is ignored.
* The *Back* and *Save* buttons on the Details page don't work.

User events other than `routerLink` clicks aren't supported.
You must wait for the full client app to bootstrap and run, or buffer the events using libraries like
[preboot](https://github.com/angular/preboot), which allow you to replay these events once the client-side scripts load.

The transition from the server-rendered app to the client app happens quickly on a development machine, but you should
always test your apps in real-world scenarios.

You can simulate a slower network to see the transition more clearly as follows:

1. Open the Chrome Dev Tools and go to the Network tab.
1. Find the [Network Throttling](https://developers.google.com/web/tools/chrome-devtools/network-performance/reference#throttling)
dropdown on the far right of the menu bar.
1. Try one of the "3G" speeds.

The server-rendered app still launches quickly but the full client app may take seconds to load.

{@a why-do-it}
## Why use server-side rendering?

There are three main reasons to create a Universal version of your app.

1. Facilitate web crawlers through [search engine optimization (SEO)](https://static.googleusercontent.com/media/www.google.com/en//webmasters/docs/search-engine-optimization-starter-guide.pdf)
1. Improve performance on mobile and low-powered devices
1. Show the first page quickly with a [first-contentful paint (FCP)](https://developers.google.com/web/tools/lighthouse/audits/first-contentful-paint)

{@a seo}
{@a web-crawlers}
### Facilitate web crawlers (SEO)

Google, Bing, Facebook, Twitter, and other social media sites rely on web crawlers to index your application content and
make that content searchable on the web.
These web crawlers may be unable to navigate and index your highly interactive Angular application as a human user could do.

Angular Universal can generate a static version of your app that is easily searchable, linkable, and navigable without JavaScript.
Universal also makes a site preview available since each URL returns a fully rendered page.

{@a no-javascript}
### Improve performance on mobile and low-powered devices

Some devices don't support JavaScript or execute JavaScript so poorly that the user experience is unacceptable.
For these cases, you may require a server-rendered, no-JavaScript version of the app.
This version, however limited, may be the only practical alternative for
people who otherwise couldn't use the app at all.

{@a startup-performance}
### Show the first page quickly

Displaying the first page quickly can be critical for user engagement.
[53 percent of mobile site visits are abandoned](https://www.thinkwithgoogle.com/marketing-resources/data-measurement/mobile-page-speed-new-industry-benchmarks/)
if pages take longer than 3 seconds to load.
Your app may have to launch faster to engage these users before they decide to do something else.

With Angular Universal, you can generate landing pages for the app that look like the complete app.
The pages are pure HTML, and can display even if JavaScript is disabled.
The pages don't handle browser events, but they _do_ support navigation through the site using [`routerLink`](guide/router#router-link).

In practice, you'll serve a static version of the landing page to hold the user's attention.
At the same time, you'll load the full Angular app behind it.
The user perceives near-instant performance from the landing page
and gets the full interactive experience after the full app loads.

{@a how-does-it-work}
## Universal web servers

A Universal web server responds to application page requests with static HTML rendered by the [Universal template engine](#universal-engine).
The server receives and responds to HTTP requests from clients (usually browsers), and serves static assets such as scripts, CSS, and images.
It may respond to data requests, either directly or as a proxy to a separate data server.

The sample web server for this guide is based on the popular [Express](https://expressjs.com/) framework.

  **Note:** _Any_ web server technology can serve a Universal app as long as it can call Universal's `renderModule()` function.
  The principles and decision points discussed here apply to any web server technology.

Universal applications use the Angular `platform-server` package (as opposed to `platform-browser`), which provides
server implementations of the DOM, `XMLHttpRequest`, and other low-level features that don't rely on a browser.

The server ([Node Express](https://expressjs.com/) in this guide's example)
passes client requests for application pages to the NgUniversal `ngExpressEngine`. Under the hood, this
calls Universal's `renderModule()` function, while providing caching and other helpful utilities.

The `renderModule()` function takes as inputs a *template* HTML page (usually `index.html`),
an Angular *module* containing components,
and a *route* that determines which components to display.
The route comes from the client's request to the server.

Each request results in the appropriate view for the requested route.
The `renderModule()` function renders the view within the `<app>` tag of the template,
creating a finished HTML page for the client.

Finally, the server returns the rendered page to the client.

### Working around the browser APIs

Because a Universal app doesn't execute in the browser, some of the browser APIs and capabilities may be missing on the server.

For example, server-side applications can't reference browser-only global objects such as `window`, `document`, `navigator`, or `location`.

Angular provides some injectable abstractions over these objects, such as [`Location`](api/common/Location)
or [`DOCUMENT`](api/common/DOCUMENT); it may substitute adequately for these APIs.
If Angular doesn't provide it, it's possible to write new abstractions that delegate to the browser APIs while in the browser
and to an alternative implementation while on the server (aka shimming).

Similarly, without mouse or keyboard events, a server-side app can't rely on a user clicking a button to show a component.
The app must determine what to render based solely on the incoming client request.
This is a good argument for making the app [routable](guide/router).

{@a http-urls}
### Using absolute URLs for server requests

The tutorial's `HeroService` and `HeroSearchService` delegate to the Angular `HttpClient` module to fetch application data.
These services send requests to _relative_ URLs such as `api/heroes`.
In a Universal app, HTTP URLs must be _absolute_ (for example, `https://my-server.com/api/heroes`).
This means you need to change your services to make requests with absolute URLs when running on the server and with relative
URLs when running in the browser.

One solution is to provide the full URL to your application on the server, and write an interceptor that can retrieve this
value and prepend it to the request URL. If you're using the `ngExpressEngine`, as shown in the example in this guide, half
the work is already done. We'll assume this is the case, but it's trivial to provide the same functionality.

Start by creating an [HttpInterceptor](api/common/http/HttpInterceptor).

import {Injectable, Inject, Optional} from '@angular/core';
import {HttpInterceptor, HttpHandler, HttpRequest, HttpHeaders} from '@angular/common/http';
import {Request} from 'express';
import {REQUEST} from '@nguniversal/express-engine/tokens';

@Injectable()
export class UniversalInterceptor implements HttpInterceptor {

  constructor(@Optional() @Inject(REQUEST) protected request: Request) {}

  intercept(req: HttpRequest<any>, next: HttpHandler) {
    let serverReq: HttpRequest<any> = req;
    if (this.request) {
      let newUrl = `${this.request.protocol}://${this.request.get('host')}`;
      if (!req.url.startsWith('/')) {
        newUrl += '/';
      }
      newUrl += req.url;
      serverReq = req.clone({url: newUrl});
    }
    return next.handle(serverReq);
  }
}

Next, provide the interceptor in the providers for the server `AppModule`.

import {HTTP_INTERCEPTORS} from '@angular/common/http';
import {UniversalInterceptor} from './universal-interceptor';

@NgModule({
  ...
  providers: [{
    provide: HTTP_INTERCEPTORS,
    useClass: UniversalInterceptor,
    multi: true
  }],
})
export class AppServerModule {}

Now, on every HTTP request made on the server, this interceptor will fire and replace the request URL with the absolute
URL provided in the Express `Request` object.

{@a universal-engine}
### Universal template engine

The important bit in the `server.ts` file is the `ngExpressEngine()` function.

The `ngExpressEngine()` function is a wrapper around Universal's `renderModule()` function which turns a client's
requests into server-rendered HTML pages.

* The first parameter is `AppServerModule`.
It's the bridge between the Universal server-side renderer and the Angular application.

* The second parameter, `extraProviders`, is optional. It lets you specify dependency providers that apply only when
running on this server.
You can do this when your app needs information that can only be determined by the currently running server instance.
One example could be the running server's *origin*, which could be used to [calculate absolute HTTP URLs](#http-urls) if
not using the `Request` token as shown above.

The `ngExpressEngine()` function returns a `Promise` callback that resolves to the rendered page.
It's up to the engine to decide what to do with that page.
This engine's `Promise` callback returns the rendered page to the web server,
which then forwards it to the client in the HTTP response.

  **Note:**  These wrappers help hide the complexity of the `renderModule()` function. There are more wrappers
  for different backend technologies at the [Universal repository](https://github.com/angular/universal).

### Filtering request URLs

NOTE: the basic behavior described below is handled automatically when using the NgUniversal Express schematic, this
is helpful when trying to understand the underlying behavior or replicate it without using the schematic.

The web server must distinguish _app page requests_ from other kinds of requests.

It's not as simple as intercepting a request to the root address `/`.
The browser could ask for one of the application routes such as `/dashboard`, `/heroes`, or `/detail:12`.
In fact, if the app were only rendered by the server, _every_ app link clicked would arrive at the server
as a navigation URL intended for the router.

Fortunately, application routes have something in common: their URLs lack file extensions.
(Data requests also lack extensions but they're easy to recognize because they always begin with `/api`.)
All static asset requests have a file extension (such as `main.js` or `/node_modules/zone.js/dist/zone.js`).

Because we use routing, we can easily recognize the three types of requests and handle them differently.

1. **Data request**: request URL that begins `/api`.
1. **App navigation**: request URL with no file extension.
1. **Static asset**: all other requests.

A Node Express server is a pipeline of middleware that filters and processes requests one after the other.
You configure the Node Express server pipeline with calls to `app.get()` like this one for data requests.

  **Note:** This sample server doesn't handle data requests.

  The tutorial's "in-memory web API" module, a demo and development tool, intercepts all HTTP calls and
  simulates the behavior of a remote data server.
  In practice, you would remove that module and register your web API middleware on the server here.

The following code filters for request URLs with no extensions and treats them as navigation requests.

### Serving static files safely

A single `app.use()` treats all other URLs as requests for static assets
such as JavaScript, image, and style files.

To ensure that clients can only download the files that they are permitted to see, put all client-facing asset files in
the `/dist` folder and only honor requests for files from the `/dist` folder.

The following Node Express code routes all remaining requests to `/dist`, and returns a `404 - NOT FOUND` error if the
file isn't found.


text:
package gnu.gcj.convert;

/**
 * Convert Unicode to SJIS (Shift JIS, used on Japanese MS-Windows).
 * @author Per Bothner <bothner@cygnus.com>
 * @date April 1999.
 */

public class Output_SJIS extends UnicodeToBytes
{
  public String getName() { return "SJIS"; }

  public native int write (char[] inbuffer, int inpos, int inlength);

  public native int write (String str, int inpos, int inlength, char[] work);

  public boolean havePendingBytes()
  {
    return pending >= 0;
  }

  int pending = -1;
}


text:
from robot.utils import JYTHON

from .argumentmapper import DefaultValue
from .argumentparser import (PythonArgumentParser, UserKeywordArgumentParser,
                             DynamicArgumentParser, JavaArgumentParser)
from .argumentspec import ArgumentSpec
from .embedded import EmbeddedArguments
if JYTHON:
    from .javaargumentcoercer import JavaArgumentCoercer
else:
    JavaArgumentCoercer = None


text:
Welcome to |project| documentation!
===================================

.. toctree::
   :maxdepth: 1

   history
   irc

.. tidelift-referral-banner::

.. include:: ../README.rst

Indices and tables
==================

* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`


text:
import template from './poster.html';
import styles from './poster.scss';

export default {
  template,
  bindings: {
    toplink: '<',
    toptitle: '<',
    topdata: '<',
  },
  controller: ['$scope', controller],
};

function controller() {
  this.styles = styles;

}


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

@ECHO OFF

IF "%PROFILE%" == "MSVC2012" (
  CALL "C:\Program Files (x86)\Microsoft Visual Studio 11.0\VC\vcvarsall.bat" %PLATFORM%
) ELSE IF "%PROFILE%" == "MSVC2013" (
  CALL "C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\vcvarsall.bat" %PLATFORM%
) ELSE IF "%PROFILE%" == "MSVC2015" (
  CALL "C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\vcvarsall.bat" %PLATFORM%
) ELSE IF "%PROFILE%" == "MSVC2017" (
  CALL :SETUPNEWERMSVC    || EXIT /B
) ELSE IF "%PROFILE%" == "MINGW" (
  REM Supported, nothing special to do here.
) ELSE IF "%PROFILE%" == "CYGWIN" (
  REM Supported, nothing special to do here.
) ELSE (
  ECHO Unsupported PROFILE=%PROFILE% or PLATFORM=%PLATFORM%
  EXIT /B 1
)

CALL cl_setcompiler.bat   || EXIT /B
CALL cl_setgenerator.bat  || EXIT /B

SET APPVEYOR_SCRIPTS=%APPVEYOR_BUILD_FOLDER%\build\appveyor
SET BUILDDIR=%APPVEYOR_BUILD_FOLDER%\..\build\%PROFILE%\%PLATFORM%
SET INSTDIR=%APPVEYOR_BUILD_FOLDER%\..\build\%PROFILE%\%PLATFORM%
SET SRCDIR=%APPVEYOR_BUILD_FOLDER%

:: PLATFORM is x64 or x86
:: NORM_PLATFORM is 64 or 32
SET NORM_PLATFORM=%PLATFORM:~-2,2%
IF "%NORM_PLATFORM%" == "86" (SET NORM_PLATFORM=32)

IF "%PROFILE:~0,4%" == "MSVC" (

  :: FindBoost needs forward slashes so cmake doesn't see something as an escaped character
  SET BOOST_ROOT=C:/Libraries/boost_%BOOST_VERSION:.=_%
  SET BOOST_LIBRARYDIR=!BOOST_ROOT!/lib%NORM_PLATFORM%-msvc-%COMPILER:~-3,2%.%COMPILER:~-1,1%
  SET OPENSSL_ROOT=C:\OpenSSL-Win%NORM_PLATFORM%
  SET WIN3P=%APPVEYOR_BUILD_FOLDER%\thirdparty

  SET THREADMODEL=STD

  IF "%PYTHON_VERSION%" == "" (
    SET WITH_PYTHON=OFF
  ) ELSE (
    SET WITH_PYTHON=ON
    IF /i "%PLATFORM%" == "x64" SET PTEXT=-x64
    SET PATH=C:\Python%PYTHON_VERSION:.=%!PTEXT!\scripts;C:\Python%PYTHON_VERSION:.=%!PTEXT!;!PATH!
  )
  IF "%CONFIGURATION%" == "Debug" (SET ZLIB_LIB_SUFFIX=d)

  IF NOT "%QT_VERSION%" == "" (
    IF /i "%PLATFORM%" == "x64" SET QTEXT=_64
    SET PATH=C:\Qt\%QT_VERSION%\%PROFILE%!QTEXT!\bin;!PATH!
  )

) ELSE IF "%PROFILE:~0,4%" == "MING" (

  :: PLATFORM = x86 means MINGWPLAT i686
  :: PLATFORM = x64 means MINGWPLAT x86_64
  SET MINGWPLAT=x86_64
  IF "%PLATFORM%" == "x86" (SET MINGWPLAT=i686)

  SET BASH=C:\msys64\usr\bin\bash.exe
  !BASH! -lc "sed -i '/export PATH=\/mingw32\/bin/d' ~/.bash_profile && sed -i '/export PATH=\/mingw64\/bin/d' ~/.bash_profile && echo 'export PATH=/mingw%NORM_PLATFORM%/bin:$PATH' >> ~/.bash_profile" || EXIT /B

  SET BUILDDIR=%BUILDDIR:\=/%
  SET BUILDDIR=/c!BUILDDIR:~2!
  SET INSTDIR=%INSTDIR:\=/%
  SET INSTDIR=/c!INSTDIR:~2!
  SET SRCDIR=%SRCDIR:\=/%
  SET SRCDIR=/c!SRCDIR:~2!

) ELSE IF "%PROFILE:~0,4%" == "CYGW" (

  SET CYGWINROOT=C:\cygwin
  IF "%PLATFORM%" == "x64" (SET CYGWINROOT=!CYGWINROOT!64)

  SET BASH=!CYGWINROOT!\bin\bash.exe
  SET SETUP=!CYGWINROOT!\setup-x86
  IF "%PLATFORM%" == "x64" (SET SETUP=!SETUP!_64)
  SET SETUP=!SETUP!.exe

  SET BUILDDIR=%BUILDDIR:\=/%
  SET BUILDDIR=/cygdrive/c!BUILDDIR:~2!
  SET INSTDIR=%INSTDIR:\=/%
  SET INSTDIR_CYG=/cygdrive/c!INSTDIR:~2!
  SET SRCDIR=%SRCDIR:\=/%
  SET SRCDIR=/cygdrive/c!SRCDIR:~2!

)

GOTO :EOF

:SETUPNEWERMSVC
  :: If VsDevCmd.bat has already executed, as is the case in the
  :: msvc2017 docker container, skip this...
  IF NOT DEFINED VSCMD_VER (
    FOR /F "USEBACKQ TOKENS=*" %%i IN (`call "%ProgramFiles(x86)%\Microsoft Visual Studio\Installer\vswhere.exe" -version "[15.0,16.0)" -property installationPath`) DO (
      IF "%MSVCROOT%" == "" (SET MSVCROOT=%%i)
    )
    SET MSVCPLAT=x86
    IF "%PLATFORM%" == "x64" (SET MSVCPLAT=amd64)

    SET CURRENTDIR=%CD%
    CALL "!MSVCROOT!\Common7\Tools\VsDevCmd.bat" -arch=!MSVCPLAT! || EXIT /B
    CD %CURRENTDIR%
    EXIT /B
  )
:EOF


text:
$(document).ready(function() {
  checkoutLogin();
  checkoutSignup();
})

function checkoutLogin(){
  $("#checkout-login-but").on("click", function(e){

    event.preventDefault();

    $(".checkout-signup-atts").css("display", "none");
     $(".checkout-login-form").css("display", "block");
  })
}

function checkoutSignup(){
  $("#checkout-signup-but").on("click", function(e){
    event.preventDefault();
     $(".checkout-login-form").css("display", "none");
    $(".checkout-signup-atts").css("display", "block");
  })
}


text:
_author__ = "Dilipbobby"

"""Note:The Fibonacci sequence specifies a series of numbers where the next number is found by adding up the two numbers just before it."""

#take user i/p
nterms = int(input("How many terms you want? "))
# first two terms
frs = 0
sec = 1
count = 2
# check if the number of terms is valid
if nterms <= 0:
   print("Plese enter a positive integer")
elif nterms == 1:
   print("Fibonacci sequence:")
   print(frs)
else:
   print("Fibonacci sequence:")
   print(frs,",",sec,end=', ')
#using while condition
   while count < nterms:
       nth = frs + sec
       print(nth,end=' , ')
       # update values
       frs = sec
       sec = nth
       count += 1


text:
#ifndef LUA_UCL_H_
#define LUA_UCL_H_

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>
#include "ucl.h"

/**
 * Closure structure for lua function storing inside UCL
 */
struct ucl_lua_funcdata {
	lua_State *L;
	int idx;
	char *ret;
};

/**
 * Initialize lua UCL API
 */
UCL_EXTERN int luaopen_ucl (lua_State *L);

/**
 * Import UCL object from lua state
 * @param L lua state
 * @param idx index of object at the lua stack to convert to UCL
 * @return new UCL object or NULL, the caller should unref object after using
 */
UCL_EXTERN ucl_object_t* ucl_object_lua_import (lua_State *L, int idx);

/**
 * Import UCL object from lua state, escaping JSON strings
 * @param L lua state
 * @param idx index of object at the lua stack to convert to UCL
 * @return new UCL object or NULL, the caller should unref object after using
 */
UCL_EXTERN ucl_object_t* ucl_object_lua_import_escape (lua_State *L, int idx);

/**
 * Push an object to lua
 * @param L lua state
 * @param obj object to push
 * @param allow_array traverse over implicit arrays
 */
UCL_EXTERN int ucl_object_push_lua (lua_State *L,
		const ucl_object_t *obj, bool allow_array);
/**
 * Push an object to lua replacing all ucl.null with `false`
 * @param L lua state
 * @param obj object to push
 * @param allow_array traverse over implicit arrays
 */
UCL_EXTERN int ucl_object_push_lua_filter_nil (lua_State *L,
											   const ucl_object_t *obj,
											   bool allow_array);

UCL_EXTERN struct ucl_lua_funcdata* ucl_object_toclosure (const ucl_object_t *obj);

#endif /* LUA_UCL_H_ */


text:
package com.getcapacitor.plugin.camera;

public enum CameraSource {
    PROMPT("PROMPT"),
    CAMERA("CAMERA"),
    PHOTOS("PHOTOS");

    private String source;

    CameraSource(String source) {
        this.source = source;
    }

    public String getSource() {
        return this.source;
    }
}


text:
package search;

import static com.google.common.truth.Truth.assertThat;
import static search.SearchWithFacetSpec.searchResponse;

import com.google.cloud.ServiceOptions;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.concurrent.ExecutionException;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

@RunWith(JUnit4.class)
public class SearchWithFacetSpecTest {
  private ByteArrayOutputStream bout;
  private PrintStream originalPrintStream;

  @Before
  public void setUp() throws IOException, InterruptedException, ExecutionException {
    final String projectId = ServiceOptions.getDefaultProjectId();
    final String defaultCatalogName =
        String.format("projects/%s/locations/global/catalogs/default_catalog", projectId);
    final String defaultSearchPlacementName = defaultCatalogName + "/placements/default_search";
    bout = new ByteArrayOutputStream();
    PrintStream out = new PrintStream(bout);
    originalPrintStream = System.out;
    System.setOut(out);

    searchResponse(defaultSearchPlacementName);
  }

  @Test
  public void testOutput() {
    String outputResult = bout.toString();

    assertThat(outputResult).contains("Search request");
    assertThat(outputResult).contains("Search response");
  }

  @After
  public void tearDown() {
    System.out.flush();
    System.setOut(originalPrintStream);
  }
}


text:
package com.wellfactored.playbindings

import org.scalatest.{EitherValues, FlatSpec, Matchers, OptionValues}
import play.api.mvc.QueryStringBindable

class ValueClassQueryStringBindableTest
  extends FlatSpec
    with Matchers
    with OptionValues
    with EitherValues
    with ValueClassQueryStringBindable
    with TestWrappers {

  val goodLongValue = Map("a" -> Seq("1"))
  val badLongValue = Map("a" -> Seq("-1"))

  "bind" should "implicitly summon a binder for Test" in {
    val b = implicitly[QueryStringBindable[LongWrapper]]

    b.bind("a", goodLongValue).value.right.value shouldBe LongWrapper(1)
  }

  "unbind" should "extract the wrapped value and convert it to a String" in {
    val b: QueryStringBindable[LongWrapper] = implicitly[QueryStringBindable[LongWrapper]]
    val lw = LongWrapper(1337)

    b.unbind("key", lw) shouldBe "key=1337"
  }

}


text:
package Moose::Meta::Method::Accessor::Native::Array::uniq;
BEGIN {
  $Moose::Meta::Method::Accessor::Native::Array::uniq::AUTHORITY = 'cpan:STEVAN';
}
{
  $Moose::Meta::Method::Accessor::Native::Array::uniq::VERSION = '2.0602';
}

use strict;
use warnings;

use List::MoreUtils ();

use Moose::Role;

with 'Moose::Meta::Method::Accessor::Native::Reader' =>
    { -excludes => ['_maximum_arguments'] };

sub _maximum_arguments { 0 }

sub _return_value {
    my $self = shift;
    my ($slot_access) = @_;

    return 'List::MoreUtils::uniq @{ (' . $slot_access . ') }';
}

no Moose::Role;

1;