text:
import template from './createEdit.html';
import controller from './createEdit.controller';

let createComponent = function () {
  return {
    restrict: 'E',
    scope: {},
    template,
    controller,
    controllerAs: 'createEditCtrl',
    bindToController: true
  };
};

export default createComponent;


text:
class CreatePlayers < ActiveRecord::Migration[5.1]
  def change
    create_table :players do |t|
      t.string :name
      t.string :color
      t.timestamps
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
    <input type="text" ng-model="defaultValue" class="form-control ng-pristine ng-invalid-required ng-invalid final" required="" readonly>

    <textarea class="form-control ng-pristine ng-invalid-required ng-invalid final" required="" rows="3" ng-bind-html="defaultValue" readonly></textarea>

    <multiple-choice
        multi-select="question.type === 'multiselect'"
        question="question"
        choices="choices"
        ng-required="isRequired === 'true'"
        ng-model="defaultValue"
        ng-disabled="isDisabled === 'true'"
        preview="preview">
    </multiple-choice>

        <button type="button" class="btn btn-default SurveyMaker-previewPasswordButton" id="{{ question.variable + '_show_input_button' }}" aw-tool-tip="Toggle the display of plaintext." aw-tip-placement="top" ng-click="toggleInput('#' + question.variable)" data-container="#survey-modal-dialog" data-original-title="" title="">SHOW</button>

    <input id="{{question.variable}}" type="password" name="" class="form-control ng-pristine ng-valid-api-error ng-invalid" autocomplete="false" ng-model="defaultValue" readonly>

    <input type="number" class="final form-control" name="" min="question.min" max="question.max" ng-value="defaultValue" readonly>

    <input type="number" class="final form-control" name="" min="question.min" max="question.max" ng-value="defaultValue" readonly>


text:
Pretty progress bars are easy to construct.

    require 'ansi/progressbar'

    pbar = ANSI::Progressbar.new("Test Bar", 100)

Running the bar simply requires calling the #inc method during
a loop and calling `#finish` when done.

    100.times do |i|
      sleep 0.01
      pbar.inc
    end
    pbar.finish

We will use this same rountine in all the examples below, so lets
make a quick macro for it. Notice we have to use `#reset` first
before reusing the same progress bar.

    def run(pbar)
      pbar.reset
      100.times do |i|
        sleep 0.01
        pbar.inc
      end
      pbar.finish
      puts
    end

The progress bar can be stylized in almost any way.
The `#format` setter provides control over the parts
that appear on the line. For example, by default the
format is:

    pbar.format("%-14s %3d%% %s %s", :title, :percentage, :bar, :stat)

So lets vary it up to demonstrate the case.

    pbar.format("%-14s %3d%% %s %s", :title, :percentage, :stat, :bar)
    run(pbar)

The progress bar has an extra build in format intended for use with
file downloads called `#transer_mode`.

    pbar.transfer_mode
    run(pbar)

Calling this methods is the same as calling:

    pbar.format("%-14s %3d%% %s %s",:title, :percentage, :bar, :stat_for_file_transfer)
    run(pbar)

The `#style` setter allows each part of the line be modified with ANSI codes.
And the `#bar_mark` writer can be used to change the character used to make the bar.

    pbar.standard_mode
    pbar.style(:title => [:red], :bar=>[:blue])
    pbar.bar_mark = "="
    run(pbar)


text:
package org.drools.core.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.DatagramSocket;
import java.net.ServerSocket;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.function.Predicate;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

public class IoUtils {

    public static final Charset UTF8_CHARSET = Charset.forName("UTF-8");

    public static int findPort() {
        for( int i = 1024; i < 65535; i++) {
            if ( validPort( i ) ) {
                return i;
            }
        }
        throw new RuntimeException( "No valid port could be found" );
    }

    public static boolean validPort(int port) {

        ServerSocket ss = null;
        DatagramSocket ds = null;
        try {
            ss = new ServerSocket(port);
            ss.setReuseAddress(true);
            ds = new DatagramSocket(port);
            ds.setReuseAddress(true);
            return true;
        } catch (IOException e) {
        } finally {
            if (ds != null) {
                ds.close();
            }

            if (ss != null) {
                try {
                    ss.close();
                } catch (IOException e) {
                    /* should not be thrown */
                }
            }
        }

        return false;
    }

    public static String readFileAsString(File file) {
        StringBuffer sb = new StringBuffer();
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), UTF8_CHARSET));
            for (String line = reader.readLine(); line != null; line = reader.readLine()) {
                sb.append(line).append("\n");
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) { }
            }
        }
        return sb.toString();
    }

    public static void copyFile(File sourceFile, File destFile) {
        destFile.getParentFile().mkdirs();
        if(!destFile.exists()) {
            try {
                destFile.createNewFile();
            } catch (IOException ioe) {
                throw new RuntimeException("Unable to create file " + destFile.getAbsolutePath(), ioe);
            }
        }

        FileChannel source = null;
        FileChannel destination = null;

        try {
            source = new FileInputStream(sourceFile).getChannel();
            destination = new FileOutputStream(destFile).getChannel();
            destination.transferFrom(source, 0, source.size());
        } catch (IOException ioe) {
            throw new RuntimeException("Unable to copy " + sourceFile.getAbsolutePath() + " to " + destFile.getAbsolutePath(), ioe);
        } finally {
            if(source != null) {
                try {
                    source.close();
                } catch (IOException e) { }
            }
            if(destination != null) {
                try {
                    destination.close();
                } catch (IOException e) { }
            }
        }
    }

    public static long copy( InputStream input, OutputStream output ) throws IOException {
        byte[] buffer = createBytesBuffer( input );
        long count = 0;
        int n = 0;
        while ((n = input.read(buffer)) != -1) {
            output.write(buffer, 0, n);
            count += n;
        }
        return count;
    }

    public static File copyInTempFile( InputStream input, String fileExtension ) throws IOException {
        File tempFile = File.createTempFile( UUID.randomUUID().toString(), "." + fileExtension );
        tempFile.deleteOnExit();
        copy(input, new FileOutputStream(tempFile));
        return tempFile;
    }

    public static List<String> recursiveListFile(File folder) {
        return recursiveListFile( folder, "", f -> true );
    }

    public static List<String> recursiveListFile(File folder, String prefix, Predicate<File> filter) {
        List<String> files = new ArrayList<String>();
        for (File child : safeListFiles(folder)) {
            filesInFolder(files, child, prefix, filter);
        }
        return files;
    }

    private static void filesInFolder(List<String> files, File file, String relativePath, Predicate<File> filter) {
        if (file.isDirectory()) {
            relativePath += file.getName() + "/";
            for (File child : safeListFiles(file)) {
                filesInFolder(files, child, relativePath, filter);
            }
        } else {
            if (filter.test(file)) {
                files.add(relativePath + file.getName());
            }
        }
    }

    /**
     * Returns {@link File#listFiles()} on a given file, avoids returning null when an IO error occurs.
     *
     * @param file directory whose files will be returned
     * @return {@link File#listFiles()}
     * @throws IllegalArgumentException when the file is a directory or cannot be accessed
     */
    private static File[] safeListFiles(final File file) {
        final File[] children = file.listFiles();
        if (children != null) {
            return children;
        } else {
            throw new IllegalArgumentException(String.format("Unable to retrieve contents of directory '%s'.",
                                                             file.getAbsolutePath()));
        }
    }

    public static byte[] readBytesFromInputStream(InputStream input) throws IOException {
        return readBytesFromInputStream( input, true );
    }

    public static byte[] readBytesFromInputStream(InputStream input, boolean closeInput) throws IOException {
        try {
            byte[] buffer = createBytesBuffer( input );
            ByteArrayOutputStream output = new ByteArrayOutputStream( buffer.length );

            int n = 0;
            while ( -1 != ( n = input.read( buffer ) ) ) {
                output.write( buffer, 0, n );
            }
            return output.toByteArray();
        } finally {
            try {
                if ( closeInput ) {
                    input.close();
                }
            } catch (Exception e) {
                // ignore
            }
        }
    }

    private static byte[] createBytesBuffer( InputStream input ) throws IOException {
        return new byte[Math.max(input.available(), 8192)];
    }

    public static byte[] readBytesFromZipEntry(File file, ZipEntry entry) throws IOException {
        if ( entry == null ) {
            return null;
        }

        ZipFile zipFile = null;
        byte[] bytes = null;
        try {
            zipFile = new ZipFile( file );
            bytes = IoUtils.readBytesFromInputStream(  zipFile.getInputStream( entry ), true );
        } finally {
            if ( zipFile != null ) {
                zipFile.close();
            }
        }
        return bytes;

    }

    public static byte[] readBytes(File f) throws IOException {
        byte[] buf = new byte[1024];

        BufferedInputStream bais = null;
        ByteArrayOutputStream baos = null;
        try {
            bais = new BufferedInputStream( new FileInputStream( f ) );
            baos = new ByteArrayOutputStream();
            int len;
            while ( (len = bais.read( buf )) > 0 ) {
                baos.write( buf, 0, len );
            }
        } finally {
            if (  baos != null ) {
                baos.close();
            }
            if ( bais != null ) {
                bais.close();
            }
        }

        return baos.toByteArray();
    }

    public static void write(File f,
                             byte[] data) throws IOException {
        if ( f.exists() ) {
            // we want to make sure there is a time difference for lastModified and lastRead checks as Linux and http often round to seconds
            // http://saloon.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=get_topic&f=1&t=019789
            try {
                Thread.sleep( 1000 );
            } catch ( Exception e ) {
                throw new RuntimeException( "Unable to sleep" );
            }
        }

        // Attempt to write the file
        writeBytes(f, data );

        // Now check the file was written and re-attempt if it was not
        // Need to do this for testing, to ensure the texts are read the same way, otherwise sometimes you get tail \n sometimes you don't
        int count = 0;
        while ( !areByteArraysEqual(data, readBytes( f ) ) && count < 5 ) {
            // The file failed to write, try 5 times, calling GC and sleep between each iteration
            // Sometimes windows takes a while to release a lock on a file
            System.gc();
            try {
                Thread.sleep( 250 );
            } catch ( InterruptedException e ) {
                throw new RuntimeException( "This should never happen" );
            }
            writeBytes(f, data );
            count++;
        }

        //areByteArraysEqual

        if ( count == 5 ) {
            throw new IOException( "Unable to write to file:" + f.getCanonicalPath() );
        }
    }

    public static void writeBytes(File f, byte[] data) throws IOException {
        byte[] buf = new byte[1024];

        BufferedOutputStream bos = null;
        ByteArrayInputStream bais = null;

        try {
            bos = new BufferedOutputStream( new FileOutputStream(f) );
            bais = new ByteArrayInputStream( data );
            int len;
            while ( (len = bais.read( buf )) > 0 ) {
                bos.write( buf, 0, len );
            }
        } finally {
            if (  bos != null ) {
                bos.close();
            }
            if ( bais != null ) {
                bais.close();
            }
        }
    }

    public static boolean areByteArraysEqual(byte[] b1,
                                             byte[] b2) {

        if ( b1.length != b2.length ) {
            return false;
        }

        for ( int i = 0, length = b1.length; i < length; i++ ) {
            if ( b1[i] != b2[i] ) {
                return false;
            }
        }

        return true;
    }

    public static String asSystemSpecificPath(String urlPath, int colonIndex) {
        String ic = urlPath.substring( Math.max( 0, colonIndex - 2 ), colonIndex + 1 );
        if  ( ic.matches( "\\/[a-zA-Z]:" ) ) {
            return urlPath.substring( colonIndex - 2 );
        } else if  ( ic.matches( "[a-zA-Z]:" ) ) {
            return urlPath.substring( colonIndex - 1 );
        } else {
            return urlPath.substring( colonIndex + 1 );
        }
    }
}


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

using System.IO;
using System.Xml.Linq;

namespace DataAccess.PSP {
  public class DataHelper {
    const string xml_header = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n";

    static string current_WeekDataFile = string.Empty;
    /// <summary>
    /// 当前打开的周数据文件名. Readonly.
    /// </summary>
    public static string CurrentWeekDataFile {
      get {
        return current_WeekDataFile;
      }
    }

    /// <summary>
    /// 第几周
    /// </summary>
    public static int WeekNumber { get; set; }

    static List<PSPModule> psp_modules = null;
    public static List<PSPModule> PSP_Modules {
      get {
        if ( psp_modules == null )
          psp_modules = LoadModules( Configuration.PSP_Data_Path );
        return psp_modules;
      }
      set {
        psp_modules = value;
      }
    }

    static List<TagReference> psp_tags = null;
    public static List<TagReference> PSP_Tags {
      get {
        if ( psp_tags == null )
          psp_tags = LoadTags( Configuration.PSP_Data_Path );
        return psp_tags;
      }
      set {
        psp_tags = value;
      }
    }

    static PSPWeek psp_week = null;
    public static PSPWeek PSP_Week {
      get {
        if ( psp_week == null )
          psp_week = LoadThisWeekData( Configuration.PSP_Data_Path );
        return psp_week;
      }
      set {
        psp_week = value;
      }
    }

    #region Module

    public static List<PSPModule> LoadModules( string pspDataPath ) {
      if ( !File.Exists( pspDataPath + "\\" + Configuration.PSP_Modules_File ) ) {
        return new List<PSPModule>();
      }

      List<PSPModule> modules = new List<PSPModule>();
      string xml = File.ReadAllText( pspDataPath + "\\" + Configuration.PSP_Modules_File, Encoding.UTF8 );
      try {
        XElement xroot = XElement.Parse( xml );
        if ( xroot == null )
          return null;
        foreach ( XElement xe in xroot.Elements( "module" ) ) {
          PSPModule pm = PSPModule.Parse( xe );
          if ( pm != null )
            modules.Add( pm );
        }

      }
      catch ( Exception ex ) {
        return null;
      }

      return modules;
    }

    public static List<PSPModule> LoadModules2( string fileName ) {
      if ( !File.Exists( fileName ) ) {
        return new List<PSPModule>();
      }

      List<PSPModule> modules = new List<PSPModule>();
      string xml = File.ReadAllText( fileName, Encoding.UTF8 );
      try {
        XElement xroot = XElement.Parse( xml );
        if ( xroot == null )
          return null;
        foreach ( XElement xe in xroot.Elements( "module" ) ) {
          PSPModule pm = PSPModule.Parse( xe );
          if ( pm != null )
            modules.Add( pm );
        }

      } catch ( Exception ex ) {
        return null;
      }

      return modules;
    }

    public static PSPModule GetModule( Guid guid ) {
      if ( Guid.Equals( guid, Guid.Empty ) )
        return null;
      foreach ( PSPModule m in PSP_Modules )
        if ( Guid.Equals( m.guid, guid ) )
          return m;
      return null;
    }

    public static int GetModuleIndex( Guid guid ) {
      int index = -1;
      if ( Guid.Equals( guid, Guid.Empty ) )
        return index;
      int count = PSP_Modules.Count;
      for ( int i = 0; i < count; i++ ) {
        if ( Guid.Equals( psp_modules[i].guid, guid ) ) {
          index = i;
          break;
        }
      }
      return index;
    }

    /// <summary>
    /// 可以是新创建,也可以使更新
    /// </summary>
    /// <param name="pm"></param>
    public static void SaveModule( PSPModule pm ) {
      if ( pm == null )
        return;
      int index = -1;
      for ( int i = 0; i < PSP_Modules.Count; i++ ) {
        if ( Guid.Equals( pm.guid, PSP_Modules[i].guid ) ) {
          index = i;
          break;
        }
      }
      if ( index >= 0 )
        PSP_Modules[index] = pm;
      else
        PSP_Modules.Add( pm );
      // save
      SaveModules( Configuration.PSP_Data_Path, PSP_Modules );
    }

    public static void DeleteModule( PSPModule pm ) {
      if ( pm == null )
        return;
      int index = -1;
      int count = PSP_Modules.Count;
      for ( int i = 0; i < count; i++ ) {
        if ( index < 0 && Guid.Equals( pm.guid, psp_modules[i].guid ) ) {
          index = i;
          break;
        }
      }
      if ( index < 0 )
        return;

      for ( int i = 0; i < count; i++ ) {
        // 删除将pm作为parent module的链接
        if ( Guid.Equals( pm.guid, psp_modules[i].parent_module ) ) {
          psp_modules[i].parent_module = Guid.Empty;
        }
        // 删除将pm作为child module的链接
        psp_modules[i].RemoveChild( pm.guid );

      }

      // remove
      psp_modules.RemoveAt( index );
      // save
      SaveModules( Configuration.PSP_Data_Path, psp_modules );
    }

    public static bool SaveModules( string pspDataPath, List<PSPModule> modules ) {
      if ( pspDataPath == null || pspDataPath.Length < 0 )
        return false;
      XElement xroot = new XElement( "psp_modules" );
      foreach ( PSPModule pm in modules ) {
        XElement xe = pm.ToXElement();
        if ( xe != null )
          xroot.Add( xe );
      }
      try {
        File.WriteAllText( pspDataPath + "\\" + Configuration.PSP_Modules_File, xml_header + xroot.ToString(), System.Text.Encoding.UTF8 );
      }
      catch ( Exception ex ) {
        return false;
      }

      // reload
      psp_modules = LoadModules( pspDataPath );

      return true;
    }

    /// <summary>
    /// 将从外界导入的模块数据,追加到当前的数据中
    /// </summary>
    /// <param name="importedModules"></param>
    /// <returns></returns>
    public static bool AppendModules( List<PSPModule> importedModules ) {
      if ( importedModules == null ) return true;
      foreach ( PSPModule pm in importedModules ) {
        int index = GetModuleIndex( pm.guid );
        if ( index < 0 )
          psp_modules.Add( pm );
      }
      // save
      return SaveModules( Configuration.PSP_Data_Path, PSP_Modules );
    }

    ///// <summary>
    ///// 2009.9.21
    ///// </summary>
    //public static void Update() {
    //  var vm = PSP_Modules;
    //  var vt = PSP_Tags;
    //  var vw = PSP_Week;
    //}

    #endregion Module

    #region Tag

    public static List<TagReference> LoadTags( string pspDataPath ) {
      if ( !File.Exists( pspDataPath + "\\" + Configuration.PSP_Tags_File ) ) {
        return new List<TagReference>();
      }

      List<TagReference> tags = new List<TagReference>();
      string xml = File.ReadAllText( pspDataPath + "\\" + Configuration.PSP_Tags_File, Encoding.UTF8 );
      try {
        XElement xroot = XElement.Parse( xml );
        if ( xroot == null )
          return null;
        foreach ( XElement xe in xroot.Elements( "tag" ) ) {
          TagReference tr = TagReference.ParseSingle( xe );
          if ( tr != null )
            tags.Add( tr );
        }

      }
      catch ( Exception ex ) {
        return null;
      }

      return tags;
    }

    public static int GetTagIndex( string name, Guid guid ) {
      int count = PSP_Tags.Count;
      for ( int i = 0; i < count; i++ ) {
        TagReference tr = psp_tags[i];
        if ( Guid.Equals( tr.guid, guid ) && string.Equals( tr.name, name ) )
          return i;
      }
      return -1;
    }

    /// <summary>
    /// 可以是新创建,也可以使更新
    /// </summary>
    /// <param name="pm"></param>
    public static void SaveTag( TagReference pm ) {
      if ( pm == null )
        return;
      int index = GetTagIndex( pm.name, pm.guid );
      if ( index >= 0 )
        PSP_Tags[index] = pm;
      else
        PSP_Tags.Add( pm );
      // save
      SaveTags( Configuration.PSP_Data_Path, PSP_Tags );
    }

    public static void DeleteTag( TagReference tag ) {
      if ( tag == null )
        return;
      int index = GetTagIndex( tag.name, tag.guid );
      if ( index >= 0 ) {
        // remove
        PSP_Tags.RemoveAt( index );
        // save
        SaveTags( Configuration.PSP_Data_Path, PSP_Tags );
      }
    }

    public static bool SaveTags( string pspDataPath, List<TagReference> tags ) {
      if ( pspDataPath == null || pspDataPath.Length < 0 )
        return false;
      XElement xroot = new XElement( "psp_tags" );
      foreach ( TagReference pm in tags ) {
        XElement xe = pm.ToXElement( "tag" );
        if ( xe != null )
          xroot.Add( xe );
      }
      try {
        File.WriteAllText( pspDataPath + "\\" + Configuration.PSP_Tags_File, xml_header + xroot.ToString(), System.Text.Encoding.UTF8 );
      }
      catch ( Exception ex ) {
        return false;
      }

      // reload
      psp_tags = LoadTags( pspDataPath );

      return true;
    }

    #endregion Tag

    #region Week

    /// <summary>
    /// 取某个日期所在的指定周的PSP数据,若不存在,创建
    /// </summary>
    /// <param name="pspDataPath"></param>
    /// <param name="dtTheDay"></param>
    /// <returns></returns>
    public static PSPWeek LoadWeekData( string pspDataPath, DateTime dtTheDay ) {
      DateTime monday = GetMondayDate( dtTheDay );
      current_WeekDataFile = Configuration.PSP_WeekFile + monday.ToString( "yyyy-MM-dd" ) + ".psp";
      string fileName = pspDataPath + "\\" + current_WeekDataFile;

      // 不存在 本周 的PSP数据,新建
      if ( !File.Exists( fileName ) ) {
        // 计算已经存在了多少个PSP周数据文件
        string[] weekFiles = Directory.GetFiles( pspDataPath, Configuration.PSP_WeekFile + "*.psp" );
        if ( weekFiles == null )
          WeekNumber = 0;
        else
          WeekNumber = weekFiles.Length;

        WeekNumber++;
        psp_week = new PSPWeek( WeekNumber, monday );
        return psp_week;
      }
      // 存在 本周 的PSP数据,导入
      string xml = File.ReadAllText( fileName, Encoding.UTF8 );
      try {
        XElement xroot = XElement.Parse( xml );
        if ( xroot == null )
          return null;
        psp_week = PSPWeek.Parse( xroot );
      }
      catch ( Exception ex ) {
        return null;
      }

      return psp_week;
    }

    /// <summary>
    /// 取某个日期所在的指定周的PSP数据,若不存在,不创建,返回null
    /// </summary>
    /// <param name="pspDataPath"></param>
    /// <param name="dtTheDay"></param>
    /// <returns></returns>
    public static PSPWeek LoadWeekData2( string pspDataPath, DateTime dtTheDay ) {
      DateTime monday = GetMondayDate( dtTheDay );
      current_WeekDataFile = Configuration.PSP_WeekFile + monday.ToString( "yyyy-MM-dd" ) + ".psp";
      string fileName = pspDataPath + "\\" + current_WeekDataFile;

      // 不存在 本周 的PSP数据,新建
      if ( !File.Exists( fileName ) ) {
        return null;
      }
      // 存在 本周 的PSP数据,导入
      string xml = File.ReadAllText( fileName, Encoding.UTF8 );
      try {
        XElement xroot = XElement.Parse( xml );
        if ( xroot == null )
          return null;
        psp_week = PSPWeek.Parse( xroot );
      } catch ( Exception ex ) {
        return null;
      }

      return psp_week;
    }

    /// <summary>
    /// 获取 本周 的PSP数据
    /// </summary>
    /// <returns></returns>
    public static PSPWeek LoadThisWeekData( string pspDataPath ) {
      return LoadWeekData( pspDataPath, DateTime.Today );
    }

    /// <summary>
    /// 保存当前打开的 周数据 到文件系统
    /// </summary>
    /// <param name="pspDataPath"></param>
    /// <returns></returns>
    public static bool SaveWeekData( string pspDataPath ) {
      if ( pspDataPath == null || pspDataPath.Length < 0 || psp_week == null )
        return false;
      XElement xroot = psp_week.ToXElement();
      try {
        File.WriteAllText( pspDataPath + "\\" + CurrentWeekDataFile, xml_header + xroot.ToString(), System.Text.Encoding.UTF8 );
      }
      catch ( Exception ex ) {
        return false;
      }

      // reload
      DateTime dt = psp_week.DateOfMonday;
      psp_week = LoadWeekData( pspDataPath, dt.Date );

      return true;
    }

    /// <summary>
    /// 从周数据中,获取某天的PSP数据
    /// --如果查询日期不属于本周数据,会重新载入符合查询日期的周数据
    /// </summary>
    /// <param name="dt"></param>
    public static PSPDay GetDayData( DateTime dt ) {
      if( psp_week == null)
        psp_week = LoadWeekData( Configuration.PSP_Data_Path, dt.Date );

      PSPDay pday = psp_week.Get_PSPDay( dt );
      // 如果所查询的日期不在 本周的PSP数据中
      if ( pday == null && !psp_week.DateOfMonday.Date.Equals( GetMondayDate( dt.Date ).Date ) ) {
        psp_week = LoadWeekData( Configuration.PSP_Data_Path, dt.Date );
        pday = psp_week.Get_PSPDay( dt );
      }

      return pday;
    }
    /// <summary>
    /// 从周数据中,获取某天的PSP数据的索引
    /// --如果查询日期不属于本周数据,会重新载入符合查询日期的周数据
    /// </summary>
    /// <param name="dt"></param>
    /// <returns></returns>
    public static int GetDayData_Index( DateTime dt ) {
      if ( psp_week == null )
        psp_week = LoadWeekData( Configuration.PSP_Data_Path, dt.Date );

      int index = psp_week.Get_PSPDay_Index( dt );
      // 如果所查询的日期不在 本周的PSP数据中
      if ( index == 0 && !psp_week.DateOfMonday.Date.Equals( GetMondayDate( dt.Date ).Date ) ) {
        psp_week = LoadWeekData( Configuration.PSP_Data_Path, dt.Date );
        index = GetDayData_Index2( dt.Date );
      }

      return index;
    }
    /// <summary>
    /// 从周数据中,获取某天的PSP数据
    /// --如果查询日期不属于本周数据,不会 重新载入符合查询日期的周数据
    /// </summary>
    /// <param name="dt"></param>
    public static PSPDay GetDayData2( DateTime dt ) {
      if ( psp_week == null )
        psp_week = LoadWeekData( Configuration.PSP_Data_Path, dt.Date );

      return psp_week.Get_PSPDay( dt );
    }
    /// <summary>
    /// 从周数据中,获取某天的PSP数据的索引
    /// --如果查询日期不属于本周数据,不会 重新载入符合查询日期的周数据
    /// </summary>
    /// <param name="dt"></param>
    /// <returns></returns>
    public static int GetDayData_Index2( DateTime dt ) {
      if ( psp_week == null )
        psp_week = LoadWeekData( Configuration.PSP_Data_Path, dt.Date );

      return psp_week.Get_PSPDay_Index( dt );
    }

    public static bool AddPSPEvent( PSPEvent pevent, DateTime dt ) {
      if ( pevent == null )
        return false;

      int index = GetDayData_Index( dt.Date );
      PSPDay pday = null;
      if ( index < 0 ) {
        pday = new PSPDay();
        pday.Date = dt;
      }
      else
        pday = psp_week.PSP_Week_Days[index];

      pday.AddEvent( pevent );
      // 模块
      if ( pevent.module != null ) {
        PSPModule pm = GetModule( pevent.module.guid );
        // 统计+1
        pm.referenced_times++;
        SaveModule( pm );
      }
      // 标签
      if ( pevent.tags != null && pevent.tags.Count > 0 ) {
        foreach ( TagReference tr in pevent.tags ) {
          int tagIndex = GetTagIndex( tr.name, tr.guid );
          if ( tagIndex < 0 ) {
            tr.referenced_times = 1;
            psp_tags.Add( tr );
          }
          else {
            // 统计+1
            tr.referenced_times = psp_tags[tagIndex].referenced_times + 1;
            psp_tags[tagIndex] = tr;
          }
        }
        // 保存标签
        SaveTags( Configuration.PSP_Data_Path, psp_tags );
      }

      //// 保存标签
      //if ( pevent.tags != null ) {
      //  bool toSave = false;
      //  foreach ( TagReference tr in pevent.tags ) {
      //    int tagIndex = GetTagIndex( tr.name, tr.guid );
      //    if ( tagIndex < 0 ) {
      //      PSP_Tags.Add( tr );
      //      toSave = true;
      //    }
      //  }
      //  // save
      //  if ( toSave )
      //    SaveTags( Configuration.PSP_Data_Path, psp_tags );
      //}

      // save
      return UpdateDayData( pday, index );
    }

    public static bool RemovePSPEvent( PSPEvent pevent ) {
      if ( pevent == null )
        return false;

      int index = GetDayData_Index( pevent.date.Date );
      if ( index < 0 ) {
        return false;
      }
      PSPDay pday = psp_week.PSP_Week_Days[index];
      pday.RemoveEvent( pevent );
      psp_week.PSP_Week_Days[index] = pday;
      // save to datastore
      return SaveWeekData( Configuration.PSP_Data_Path );
    }

    /// <summary>
    /// 更新某一天的PSP数据
    /// </summary>
    /// <param name="pday"></param>
    /// <returns></returns>
    public static bool UpdateDayData( PSPDay pday ) {
      if ( pday == null )
        return false;

      int index = GetDayData_Index( pday.Date.Date );
      return UpdateDayData( pday, index );
    }
    public static bool UpdateDayData( PSPDay pday, int index ) {
      if ( pday == null )
        return false;

      if ( index < 0 )
        psp_week.PSP_Week_Days.Add( pday );
      else
        psp_week.PSP_Week_Days[index] = pday;

      // save to datastore
      return SaveWeekData( Configuration.PSP_Data_Path );
    }

    /// <summary>
    /// 获取某周的PSP数据备份的数目
    /// </summary>
    /// <param name="dt"></param>
    /// <returns></returns>
    public static int BackupFilesCount( DateTime dt ) {
      int count = 0;
      DateTime monday = GetMondayDate( dt );
      string fileNamePrefix = Configuration.PSP_WeekFile + monday.ToString( "yyyy-MM-dd" ) + "_at";
      string bakPath = Configuration.PSP_Data_Path + "\\" + Configuration.PSP_Data_BackupFolder;
      if ( System.IO.Directory.Exists( bakPath ) ) {
        string[] files = Directory.GetFiles( bakPath, fileNamePrefix + "*.psp" );
        if ( files == null )
          count = 0;
        else
          count = files.Length;
      }
      else {
        System.IO.Directory.CreateDirectory( bakPath );
      }

      return count;
    }

    /// <summary>
    /// 备份某周的PSP数据至[PSP_Data]/bak
    /// </summary>
    /// <param name="dt"></param>
    /// <returns></returns>
    public static bool BackupWeekData( DateTime dt ) {
      bool result = true;
      DateTime monday = GetMondayDate( dt );
      string bakPath = Configuration.PSP_Data_Path + "\\" + Configuration.PSP_Data_BackupFolder;
      string fileNamePrefix = Configuration.PSP_WeekFile + monday.ToString( "yyyy-MM-dd" );
      string bakFilePath = bakPath + "\\" + fileNamePrefix + "_at" + DateTime.Now.ToString( "HHmmss" ) + ".psp",
        srcFilePath = Configuration.PSP_Data_Path + "\\" + fileNamePrefix + ".psp";

      try {
        System.IO.File.Copy( srcFilePath, bakFilePath );
      }
      catch ( Exception ex ) {
        result = false;
      }

      return result;
    }

    #endregion Week

    #region DateTime

    /// <summary>
    /// 根据指定日期,返回该周的周一所在日期
    /// </summary>
    /// <param name="dtTheDay"></param>
    /// <returns></returns>
    public static DateTime GetMondayDate( DateTime dtTheDay ) {
      DateTime dateOfMonday = dtTheDay;
      DayOfWeek dow = dtTheDay.DayOfWeek;
      switch ( dow ) {
        case DayOfWeek.Monday:
          break;
        case DayOfWeek.Tuesday:
          dateOfMonday = dateOfMonday.AddDays( -1 );
          break;
        case DayOfWeek.Wednesday:
          dateOfMonday = dateOfMonday.AddDays( -2 );
          break;
        case DayOfWeek.Thursday:
          dateOfMonday = dateOfMonday.AddDays( -3 );
          break;
        case DayOfWeek.Friday:
          dateOfMonday = dateOfMonday.AddDays( -4 );
          break;
        case DayOfWeek.Saturday:
          dateOfMonday = dateOfMonday.AddDays( -5 );
          break;
        case DayOfWeek.Sunday:
          dateOfMonday = dateOfMonday.AddDays( -6 );
          break;
      }
      return dateOfMonday.Date;
    }

    #endregion DateTime

    #region Statistics

    /// <summary>
    /// 获取指定日期的某模块的最近四周(不包括本周)的统计数据
    /// </summary>
    /// <returns></returns>
    public static List<StatisticsItem> Statistics_RecentFourWeeks( DateTime dt, string moduleName, Guid gModule ) {
      // Monday
      DateTime dtThisWeek = GetMondayDate( dt );
      DateTime dtWeekAgo1 = dtThisWeek.AddDays( -7 ),
        dtWeekAgo2 = dtThisWeek.AddDays( -14 ),
        dtWeekAgo3 = dtThisWeek.AddDays( -21 ),
        dtWeekAgo4 = dtThisWeek.AddDays( -28 );
      // Get week data
      PSPWeek weekData0 = LoadWeekData2( Configuration.PSP_Data_Path, dtThisWeek ),
        weekData1 = LoadWeekData2( Configuration.PSP_Data_Path, dtWeekAgo1 ),
        weekData2 = LoadWeekData2( Configuration.PSP_Data_Path, dtWeekAgo2 ),
        weekData3 = LoadWeekData2( Configuration.PSP_Data_Path, dtWeekAgo3 ),
        weekData4 = LoadWeekData2( Configuration.PSP_Data_Path, dtWeekAgo4 );

      List<StatisticsItem> results = new List<StatisticsItem>();
      if ( weekData0 != null ) {
        StatisticsItem si = new StatisticsItem();
        si.name = weekData0.DateOfMonday.ToString( "yy-MM-dd" );
        si.date = weekData0.DateOfMonday;
        si.guid = gModule;
        si.total_time = weekData0.GetWeekStatisticsOfModule2( moduleName, gModule );
        results.Add( si );
      }
      if ( weekData1 != null ) {
        StatisticsItem si = new StatisticsItem();
        si.name = weekData1.DateOfMonday.ToString( "yy-MM-dd" );
        si.date = weekData1.DateOfMonday;
        si.guid = gModule;
        si.total_time = weekData1.GetWeekStatisticsOfModule2( moduleName, gModule );
        results.Add( si );
      }
      if ( weekData2 != null ) {
        StatisticsItem si = new StatisticsItem();
        si.name = weekData2.DateOfMonday.ToString( "yy-MM-dd" );
        si.date = weekData2.DateOfMonday;
        si.guid = gModule;
        si.total_time = weekData2.GetWeekStatisticsOfModule2( moduleName, gModule );
        results.Add( si );
      }
      if ( weekData3 != null ) {
        StatisticsItem si = new StatisticsItem();
        si.name = weekData3.DateOfMonday.ToString( "yy-MM-dd" );
        si.date = weekData3.DateOfMonday;
        si.guid = gModule;
        si.total_time = weekData3.GetWeekStatisticsOfModule2( moduleName, gModule );
        results.Add( si );
      }
      if ( weekData4 != null ) {
        StatisticsItem si = new StatisticsItem();
        si.name = weekData4.DateOfMonday.ToString( "yy-MM-dd" );
        si.date = weekData4.DateOfMonday;
        si.guid = gModule;
        si.total_time = weekData4.GetWeekStatisticsOfModule2( moduleName, gModule );
        results.Add( si );
      }
      return results;
    }

    /// <summary>
    /// 获取指定日期的某模块的所在一周的统计数据
    /// </summary>
    /// <returns></returns>
    public static List<StatisticsItem> ModuleStatistics_SomeWeek( DateTime dt, string moduleName, Guid gModule ) {
      DateTime monday = GetMondayDate( dt );
      PSPWeek weekData = LoadWeekData2( Configuration.PSP_Data_Path, monday );
      if ( weekData == null ) return null;
      return weekData.GetWeekStatisticsOfModule( moduleName, gModule );
    }

    /// <summary>
    /// 获取某天的模块统计信息
    /// </summary>
    /// <param name="dt"></param>
    /// <returns></returns>
    public static List<StatisticsItem> GetModulesStatistics( DateTime dt ) {
      PSPDay pday = GetDayData( dt );
      if ( pday == null || pday.Statistics == null || pday.Statistics.ModulesStatistics == null )
        return null;
      return pday.Statistics.ModulesStatistics;
    }

    #endregion Statistics

    #region Update

    /// <summary>
    /// 2009.9.30升级:将PSP数据文件(指psp_week_[date_of_monday].psp)的后缀由.xml更改为.psp
    /// </summary>
    /// <returns></returns>
    public static bool Update_30Sept2009() {
      bool state = true;
      // 查找旧的以.xml为后缀的文件,若不存在,则不需要升级
      string[] weekFiles = Directory.GetFiles( Configuration.PSP_Data_Path, Configuration.PSP_WeekFile + "*.xml" );
      if ( weekFiles == null || weekFiles.Length == 0 )
        return state;

      try {
        foreach ( string fn in weekFiles ) {
          // copy
          File.Copy( fn, fn.Substring( 0, fn.Length - 4 ) + ".psp" );
          // delete
          File.Delete( fn );
        }

      }
      catch ( Exception ex ) {
        state = false;
      }

      return state;
    }

    #endregion Update

  }
}


text:
@interface BENoTouchView()<QMPlaySliderDelegate>

//time show
@property (nonatomic, strong) UILabel *currentTimeLabel;
@property (nonatomic, strong) UILabel *durationTimeLabel;
@property (nonatomic, strong) QMPlaySlider *playSlider;

@property (nonatomic, strong) UIButton *playModeButton;
@property (nonatomic, strong) UIButton *preButton;
@property (nonatomic, strong) UIButton *playPauseButton;
@property (nonatomic, strong) UIButton *nextButton;
@property (nonatomic, strong) UIButton *playListButton;

@end

@implementation BENoTouchView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self createTimeShow];

        [self createPlayControlShow];

    }
    return self;
}

- (void)createTimeShow
{
    CGFloat timeLabelWidth = 50;

    self.currentTimeLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, timeLabelWidth, 20)];
    self.currentTimeLabel.text = @"00:00";
    self.currentTimeLabel.textAlignment = NSTextAlignmentCenter;
    self.currentTimeLabel.font = [UIFont systemFontOfSize:12];
    self.currentTimeLabel.textColor = [[UIColor whiteColor] colorWithAlphaComponent:0.75];
    [self addSubview:self.currentTimeLabel];

    self.playSlider = [[QMPlaySlider alloc] initWithFrame:CGRectMake(CGRectGetMaxX(self.currentTimeLabel.frame), 0, CGRectGetMaxX(self.bounds)-2*timeLabelWidth, 20) supportCache:YES];
    self.playSlider.minimumTrackTintColor = RGB(111, 196, 141);
    self.playSlider.maximumTrackTintColor = [RGB(157, 152, 149) colorWithAlphaComponent:0.5];
    self.playSlider.cacheimumTrackTintColor = [RGB(117, 120, 117) colorWithAlphaComponent:0.5];
    [self.playSlider setThumbImage:[UIImage imageNamed:@"player_slider_playback_thumb"] forState:UIControlStateNormal];
    [self.playSlider setThumbImage:[UIImage imageNamed:@"player_slider_playback_thumb"] forState:UIControlStateHighlighted];
    self.playSlider.delegate = self;
    [self addSubview:self.playSlider];

    self.durationTimeLabel = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(self.bounds)-timeLabelWidth, 0, timeLabelWidth, 20)];
    self.durationTimeLabel.font = [UIFont systemFontOfSize:12];
    self.durationTimeLabel.textAlignment = NSTextAlignmentCenter;
    self.durationTimeLabel.textColor = [[UIColor whiteColor] colorWithAlphaComponent:0.75];
    self.durationTimeLabel.text = @"00:00";
    [self addSubview:self.durationTimeLabel];

}

- (void)createPlayControlShow
{
    CGFloat centerY = 60;
    CGFloat padding = 5;

    CGFloat oneSize = 40;
    CGFloat twoSize = 50;
    CGFloat threeSize = 60;

    CGFloat button_padding = (CGRectGetMaxX(self.bounds)-(oneSize+twoSize+threeSize+twoSize+oneSize)-2*padding)/4;

    self.playModeButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.playModeButton.frame = CGRectMake(padding, 0, oneSize, oneSize);
    [self.playModeButton addTarget:self action:@selector(playModeButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:self.playModeButton];
    self.playMode = 0;

    self.preButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.preButton setImage:[UIImage imageNamed:@"player_btn_pre_normal"] forState:UIControlStateNormal];
    [self.preButton setImage:[UIImage imageNamed:@"player_btn_pre_hightlight"] forState:UIControlStateHighlighted];
    self.preButton.frame = CGRectMake(CGRectGetMaxX(self.playModeButton.frame)+button_padding, 0, twoSize, twoSize);
    [self.preButton addTarget:self action:@selector(preButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:self.preButton];

    self.playPauseButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.playPauseButton setImage:[UIImage imageNamed:@"player_btn_play_normal"] forState:UIControlStateNormal];
    [self.playPauseButton setImage:[UIImage imageNamed:@"player_btn_play_highlight"] forState:UIControlStateHighlighted];
    self.playPauseButton.frame = CGRectMake(CGRectGetMaxX(self.preButton.frame)+button_padding, 0, threeSize, threeSize);
    [self.playPauseButton addTarget:self action:@selector(playPauseButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:self.playPauseButton];

    self.nextButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.nextButton setImage:[UIImage imageNamed:@"player_btn_next_normal"] forState:UIControlStateNormal];
    [self.nextButton setImage:[UIImage imageNamed:@"player_btn_next_hightlight"] forState:UIControlStateHighlighted];
    self.nextButton.frame = CGRectMake(CGRectGetMaxX(self.playPauseButton.frame)+button_padding, 0, twoSize, twoSize);
    [self.nextButton addTarget:self action:@selector(nextButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:self.nextButton];

    self.playListButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.playListButton setImage:[UIImage imageNamed:@"player_btn_playlist_normal"] forState:UIControlStateNormal];
    [self.playListButton setImage:[UIImage imageNamed:@"player_btn_playlist_highlight"] forState:UIControlStateHighlighted];
    self.playListButton.frame = CGRectMake(CGRectGetMaxX(self.nextButton.frame)+button_padding, 0, oneSize, oneSize);
    [self.playListButton addTarget:self action:@selector(playListButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:self.playListButton];

    self.playModeButton.centerY = centerY;
    self.preButton.centerY = centerY;
    self.playPauseButton.centerY = centerY;
    self.nextButton.centerY = centerY;
    self.playListButton.centerY = centerY;
}

- (void)setPlayMode:(PlayMode)playMode
{
    _playMode = playMode;
    switch (playMode) {

        case PlayModeRandom:
        {
            [self.playModeButton setImage:[UIImage imageNamed:@"player_btn_random_normal"] forState:UIControlStateNormal];
            [self.playModeButton setImage:[UIImage imageNamed:@"player_btn_random_hightlight"] forState:UIControlStateHighlighted];
        }
            break;

        case PlayModeRepeat:
        {

            [self.playModeButton setImage:[UIImage imageNamed:@"player_btn_repeat_normal"] forState:UIControlStateNormal];
            [self.playModeButton setImage:[UIImage imageNamed:@"player_btn_repeat_highlight"] forState:UIControlStateHighlighted];
        }
            break;
        case PlayModeRepeatOne:
        {

            [self.playModeButton setImage:[UIImage imageNamed:@"player_btn_repeatone_normal"] forState:UIControlStateNormal];
            [self.playModeButton setImage:[UIImage imageNamed:@"player_btn_repeatone_hightlight"] forState:UIControlStateHighlighted];
        }
            break;

        default:
            break;
    }
}

- (void)playModeButtonPressed:(UIButton *)sender
{
    NSInteger currentMode = self.playMode;
    currentMode++;
    if (currentMode >2) {
        currentMode = 0;
    }
    self.playMode = currentMode;
}

- (void)preButtonPressed:(UIButton *)sender
{

}

- (void)playPauseButtonPressed:(UIButton *)sender
{
    sender.selected = !sender.selected;
    if (sender.selected) {
        [self.playPauseButton setImage:[UIImage imageNamed:@"player_btn_pause_normal"] forState:UIControlStateNormal];
        [self.playPauseButton setImage:[UIImage imageNamed:@"player_btn_pause_highlight"] forState:UIControlStateHighlighted];
        if (self.delegate && [self.delegate respondsToSelector:@selector(BENoTouchViewShouldPlay)]) {
            [self.delegate BENoTouchViewShouldPlay];
        }
    }else
    {
        [self.playPauseButton setImage:[UIImage imageNamed:@"player_btn_play_normal"] forState:UIControlStateNormal];
        [self.playPauseButton setImage:[UIImage imageNamed:@"player_btn_play_highlight"] forState:UIControlStateHighlighted];

        if (self.delegate && [self.delegate respondsToSelector:@selector(BENoTouchViewShouldPause)]) {
            [self.delegate BENoTouchViewShouldPause];
        }
    }
}

- (void)nextButtonPressed:(UIButton *)sender
{

}

- (void)playListButtonPressed:(UIButton *)sender
{

}

- (void)thumbTouchesBegan
{
    self.currentTimeLabel.font = [UIFont systemFontOfSize:15];
}

- (void)thumbTouchesEnded
{
     self.currentTimeLabel.font = [UIFont systemFontOfSize:12];
}

- (void)updateCurrentTimeLabel:(NSString *)text
{
    self.currentTimeLabel.text = text;
}

- (void)updateDurationTimeLabel:(NSString *)text
{
    self.durationTimeLabel.text = text;
}

- (void)updateSliderValue:(CGFloat)value
{
    self.playSlider.value = value;
}

@end


text:
/*!
 * \file custom.cc
 * \brief
 * \author Junyuan Xie
*/
#include <mxnet/c_api.h>
#include <mxnet/base.h>
#include <mxnet/ndarray.h>

#include "./c_api_common.h"
#include "../ndarray/autograd.h"

namespace mxnet {
namespace custom_function {

struct CustomFunctionParam {
  size_t num_args, num_outs;
  std::shared_ptr<MXCallbackList> info;
  std::vector<TShape> out_shapes;
  std::vector<int> out_dtypes;
};

std::vector<nnvm::NodeEntry> Gradient(
    const nnvm::NodePtr& n,
    const std::vector<nnvm::NodeEntry>& out_grads) {
  const CustomFunctionParam& params = nnvm::get<CustomFunctionParam>(n->attrs.parsed);

  nnvm::NodePtr g = nnvm::Node::Create();
  g->attrs.op = nnvm::Op::Get("_backward_CustomFunction");
  g->attrs.name = n->attrs.name + "_backward";
  g->attrs.parsed = params;
  g->control_deps.emplace_back(n);

  g->inputs = out_grads;

  std::vector<nnvm::NodeEntry> ret;
  for (index_t i = 0; i < g->num_outputs(); ++i) {
    ret.emplace_back(nnvm::NodeEntry{g, i, 0});
  }

  return ret;
}

OpStatePtr CreateState(const nnvm::NodeAttrs& attrs,
                               Context ctx,
                               const std::vector<TShape>& ishape,
                               const std::vector<int>& itype) {
  LOG(FATAL) << "Not reached";
  return OpStatePtr::Create<void*>(nullptr);
}

void Forward(const OpStatePtr& state,
             const OpContext& ctx,
             const std::vector<NDArray>& inputs,
             const std::vector<OpReqType>& req,
             const std::vector<NDArray>& outputs) {
  LOG(FATAL) << "Not reached";
}

void Backward(const OpStatePtr& state,
              const OpContext& ctx,
              const std::vector<NDArray>& inputs,
              const std::vector<OpReqType>& req,
              const std::vector<NDArray>& outputs) {
  const CustomFunctionParam& params = state.get_state<CustomFunctionParam>();

  std::vector<NDArrayHandle> ptrs;

  for (const auto& i : inputs) {
    NDArray* nd = new NDArray(i.Detach());
    ptrs.push_back(reinterpret_cast<NDArrayHandle>(nd));
  }
  for (const auto& i : outputs) {
    NDArray* nd = new NDArray(i.Detach());
    ptrs.push_back(reinterpret_cast<NDArrayHandle>(nd));
  }

  bool prev_recording = autograd::AutogradRuntime::Get()->SetIsRecording(false);
  bool prev_training = autograd::AutogradRuntime::Get()->SetIsTraining(ctx.is_train);

  CHECK(reinterpret_cast<CustomFunctionBwdFunc>(
      params.info->callbacks[kCustomFunctionBackward])(
          inputs.size(), outputs.size(), ptrs.data(),
          reinterpret_cast<const int*>(req.data()), ctx.is_train,
          params.info->contexts[kCustomFunctionBackward]));

  autograd::AutogradRuntime::Get()->SetIsTraining(prev_training);
  autograd::AutogradRuntime::Get()->SetIsRecording(prev_recording);
}

NNVM_REGISTER_OP(_CustomFunction)
.set_num_inputs([](const NodeAttrs& attrs) {
    const CustomFunctionParam& params = nnvm::get<CustomFunctionParam>(attrs.parsed);
    return params.num_args;
  })
.set_num_outputs([](const NodeAttrs& attrs) {
    const CustomFunctionParam& params = nnvm::get<CustomFunctionParam>(attrs.parsed);
    return params.num_outs;
  })
.set_attr<nnvm::FInferShape>("FInferShape",
  [](const NodeAttrs& attrs, std::vector<TShape> *in_shape,
     std::vector<TShape> *out_shape) {
    const CustomFunctionParam& params = nnvm::get<CustomFunctionParam>(attrs.parsed);
    *out_shape = params.out_shapes;
    return true;
  })
.set_attr<nnvm::FInferType>("FInferType",
  [](const NodeAttrs& attrs, std::vector<int> *in_type,
     std::vector<int> *out_type) {
    const CustomFunctionParam& params = nnvm::get<CustomFunctionParam>(attrs.parsed);
    *out_type = params.out_dtypes;
    return true;
  })
.set_attr<FCreateOpState>("FCreateOpState", CreateState)
.set_attr<nnvm::FGradient>("FGradient", Gradient)
.set_attr<FStatefulComputeEx>("FStatefulComputeEx<cpu>", Forward)
.set_attr<FStatefulComputeEx>("FStatefulComputeEx<gpu>", Forward);

NNVM_REGISTER_OP(_backward_CustomFunction)
.set_num_inputs([](const NodeAttrs& attrs) {
    const CustomFunctionParam& params = nnvm::get<CustomFunctionParam>(attrs.parsed);
    return params.num_outs;
  })
.set_num_outputs([](const NodeAttrs& attrs) {
    const CustomFunctionParam& params = nnvm::get<CustomFunctionParam>(attrs.parsed);
    return params.num_args;
  })
.set_attr<bool>("TIsBackward", true)
.set_attr<bool>("TIsLayerOpBackward", true)
.set_attr<FExecType>("FExecType", [](const NodeAttrs& attrs) {
    return ExecType::kLocal;
  })
.set_attr<FStatefulComputeEx>("FStatefulComputeEx<cpu>", Backward)
.set_attr<FStatefulComputeEx>("FStatefulComputeEx<gpu>", Backward);

}  // namespace custom_function
}  // namespace mxnet

int MXCustomFunctionRecord(int num_inputs, NDArrayHandle *inputs,
                           int num_outputs, NDArrayHandle *outputs,
                           MXCallbackList *callbacks) {
  using namespace mxnet;
  using namespace mxnet::custom_function;
  using mxnet::autograd::AutogradRuntime;
  API_BEGIN();
  CHECK(AutogradRuntime::Get()->IsRecording());
  std::vector<NDArray> ndinputs, ndoutputs;
  for (int i = 0; i < num_inputs; ++i) {
    ndinputs.emplace_back(*reinterpret_cast<NDArray*>(inputs[i]));
  }
  for (int i = 0; i < num_outputs; ++i) {
    ndoutputs.emplace_back(*reinterpret_cast<NDArray*>(outputs[i]));
  }
  CustomFunctionParam params;
  params.num_args = num_inputs;
  params.num_outs = num_outputs;
  params.info.reset(callbacks, [](MXCallbackList* ptr){
      reinterpret_cast<CustomFunctionDelFunc>(ptr->callbacks[kCustomFunctionDelete])(
        ptr->contexts[kCustomFunctionDelete]);
    });
  for (const auto& i : ndoutputs) {
    params.out_shapes.emplace_back(i.shape());
    params.out_dtypes.emplace_back(i.dtype());
  }
  nnvm::NodeAttrs attrs;
  attrs.op = nnvm::Op::Get("_CustomFunction");
  attrs.parsed = params;
  // TODO(piiswrong): remove state by using FComputeEx
  auto state = OpStatePtr::Create<CustomFunctionParam>(params);
  AutogradRuntime::Get()->RecordImperativeOperator(
      state, attrs.op, attrs, &ndinputs, &ndoutputs);

  for (size_t i = 0; i < ndoutputs.size(); ++i) {
    *reinterpret_cast<NDArray*>(outputs[i]) = ndoutputs[i];
  }

  API_END();
}


text:
package rx.internal.operators;

import java.util.ArrayList;
import java.util.List;
import rx.Observable;
import rx.Observable.Operator;
import rx.Producer;
import rx.Subscriber;
import rx.observers.SerializedSubscriber;
import rx.subscriptions.SerialSubscription;

/**
 * Transforms an Observable that emits Observables into a single Observable that
 * emits the items emitted by the most recently published of those Observables.
 *

 *
 *
 * @param <T> the value type
 */
public final class OperatorSwitch<T> implements Operator<T, Observable<? extends T>> {

    @Override
    public Subscriber<? super Observable<? extends T>> call(final Subscriber<? super T> child) {
        return new SwitchSubscriber<T>(child);
    }

    private static final class SwitchSubscriber<T> extends Subscriber<Observable<? extends T>> {
        final SerializedSubscriber<T> s;
        final SerialSubscription ssub;
        final Object guard = new Object();
        final NotificationLite<?> nl = NotificationLite.instance();
        /** Guarded by guard. */
        int index;
        /** Guarded by guard. */
        boolean active;
        /** Guarded by guard. */
        boolean mainDone;
        /** Guarded by guard. */
        List<Object> queue;
        /** Guarded by guard. */
        boolean emitting;
        /** Guarded by guard. */
        InnerSubscriber currentSubscriber;
        /** Guarded by guard. */
        long initialRequested;

        volatile boolean infinite = false;

        public SwitchSubscriber(Subscriber<? super T> child) {
            super(child);
            s = new SerializedSubscriber<T>(child);
            ssub = new SerialSubscription();
            child.add(ssub);
            child.setProducer(new Producer(){

                @Override
                public void request(long n) {
                    if (infinite) {
                        return;
                    }
                    if(n == Long.MAX_VALUE) {
                        infinite = true;
                    }
                    InnerSubscriber localSubscriber;
                    synchronized (guard) {
                        localSubscriber = currentSubscriber;
                        if (currentSubscriber == null) {
                            initialRequested = n;
                        } else {
                            // If n == Long.MAX_VALUE, infinite will become true. Then currentSubscriber.requested won't be used.
                            // Therefore we don't need to worry about overflow.
                            currentSubscriber.requested += n;
                        }
                    }
                    if (localSubscriber != null) {
                        localSubscriber.requestMore(n);
                    }
                }
            });
        }

        @Override
        public void onNext(Observable<? extends T> t) {
            final int id;
            long remainingRequest;
            synchronized (guard) {
                id = ++index;
                active = true;
                if (infinite) {
                    remainingRequest = Long.MAX_VALUE;
                } else {
                    remainingRequest = currentSubscriber == null ? initialRequested : currentSubscriber.requested;
                }
                currentSubscriber = new InnerSubscriber(id, remainingRequest);
                currentSubscriber.requested = remainingRequest;
            }
            ssub.set(currentSubscriber);

            t.unsafeSubscribe(currentSubscriber);
        }

        @Override
        public void onError(Throwable e) {
            s.onError(e);
            unsubscribe();
        }

        @Override
        public void onCompleted() {
            List<Object> localQueue;
            synchronized (guard) {
                mainDone = true;
                if (active) {
                    return;
                }
                if (emitting) {
                    if (queue == null) {
                        queue = new ArrayList<Object>();
                    }
                    queue.add(nl.completed());
                    return;
                }
                localQueue = queue;
                queue = null;
                emitting = true;
            }
            drain(localQueue);
            s.onCompleted();
            unsubscribe();
        }
        void emit(T value, int id, InnerSubscriber innerSubscriber) {
            List<Object> localQueue;
            synchronized (guard) {
                if (id != index) {
                    return;
                }
                if (emitting) {
                    if (queue == null) {
                        queue = new ArrayList<Object>();
                    }
                    innerSubscriber.requested--;
                    queue.add(value);
                    return;
                }
                localQueue = queue;
                queue = null;
                emitting = true;
            }
            boolean once = true;
            boolean skipFinal = false;
            try {
                do {
                    drain(localQueue);
                    if (once) {
                        once = false;
                        synchronized (guard) {
                            innerSubscriber.requested--;
                        }
                        s.onNext(value);
                    }
                    synchronized (guard) {
                        localQueue = queue;
                        queue = null;
                        if (localQueue == null) {
                            emitting = false;
                            skipFinal = true;
                            break;
                        }
                    }
                } while (!s.isUnsubscribed());
            } finally {
                if (!skipFinal) {
                    synchronized (guard) {
                        emitting = false;
                    }
                }
            }
        }
        void drain(List<Object> localQueue) {
            if (localQueue == null) {
                return;
            }
            for (Object o : localQueue) {
                if (nl.isCompleted(o)) {
                    s.onCompleted();
                    break;
                } else
                if (nl.isError(o)) {
                    s.onError(nl.getError(o));
                    break;
                } else {
                    @SuppressWarnings("unchecked")
                    T t = (T)o;
                    s.onNext(t);
                }
            }
        }

        void error(Throwable e, int id) {
            List<Object> localQueue;
            synchronized (guard) {
                if (id != index) {
                    return;
                }
                if (emitting) {
                    if (queue == null) {
                        queue = new ArrayList<Object>();
                    }
                    queue.add(nl.error(e));
                    return;
                }

                localQueue = queue;
                queue = null;
                emitting = true;
            }

            drain(localQueue);
            s.onError(e);
            unsubscribe();
        }
        void complete(int id) {
            List<Object> localQueue;
            synchronized (guard) {
                if (id != index) {
                    return;
                }
                active = false;
                if (!mainDone) {
                    return;
                }
                if (emitting) {
                    if (queue == null) {
                        queue = new ArrayList<Object>();
                    }
                    queue.add(nl.completed());
                    return;
                }

                localQueue = queue;
                queue = null;
                emitting = true;
            }

            drain(localQueue);
            s.onCompleted();
            unsubscribe();
        }

        final class InnerSubscriber extends Subscriber<T> {

            /**
             * The number of request that is not acknowledged.
             *
             * Guarded by guard.
             */
            private long requested = 0;

            private final int id;

            private final long initialRequested;

            public InnerSubscriber(int id, long initialRequested) {
                this.id = id;
                this.initialRequested = initialRequested;
            }

            @Override
            public void onStart() {
                requestMore(initialRequested);
            }

            public void requestMore(long n) {
                request(n);
            }

            @Override
            public void onNext(T t) {
                emit(t, id, this);
            }

            @Override
            public void onError(Throwable e) {
                error(e, id);
            }

            @Override
            public void onCompleted() {
                complete(id);
            }
        }
    }
}


text:
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;

namespace ImgONE
{
    class Screen_Bounds
    {
        public static Rectangle bounds;

        public static void load()
        {
            String[] bounds_arr = Settings.screen_res.Split(',');
            bounds = new Rectangle(
                Convert.ToInt32(bounds_arr[0]),
                Convert.ToInt32(bounds_arr[1]),
                Convert.ToInt32(bounds_arr[2]),
                Convert.ToInt32(bounds_arr[3])
            );
        }
        public static String reset()
        {
            var screen_bounds_temp = new Rectangle(0, 0, 0, 0);

            foreach (var screen in Screen.AllScreens)
                if (screen != Screen.PrimaryScreen)
                    screen_bounds_temp = Rectangle.Union(screen.Bounds, screen_bounds_temp);

            return String.Format(
                "{0},{1},{2},{3}",
                screen_bounds_temp.Left,
                screen_bounds_temp.Top,
                SystemInformation.VirtualScreen.Width,
                SystemInformation.VirtualScreen.Height
            );
        }
    }
}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.helix.web</groupId>
  <artifactId>helix.web</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>

  <dependencies>

  <dependency>
	<groupId>mysql</groupId>
	<artifactId>mysql-connector-java</artifactId>
	<version>5.1.36</version>
  </dependency>

  <dependency>
	<groupId>commons-io</groupId>
	<artifactId>commons-io</artifactId>
	<version>2.4</version>
</dependency>

<dependency>
	<groupId>commons-fileupload</groupId>
	<artifactId>commons-fileupload</artifactId>
	<version>1.3.1</version>
</dependency>

<dependency>
	<groupId>javax.persistence</groupId>
	<artifactId>persistence-api</artifactId>
	<version>1.0.2</version>
</dependency>

<dependency>
	<groupId>org.eclipse.persistence</groupId>
	<artifactId>eclipselink</artifactId>
	<version>2.5.0</version>
</dependency>

<dependency>
	<groupId>com.google.code.gson</groupId>
	<artifactId>gson</artifactId>
	<version>2.5</version>
</dependency>

<dependency>
	<groupId>jstl</groupId>
	<artifactId>jstl</artifactId>
	<version>1.2</version>
</dependency>

</dependencies>

</project>


text:
/**
 * @file
 * @brief		Unidirectional data pipe implementation.
 */

#include <io/request.h>

#include <ipc/pipe.h>

#include <mm/kmem.h>
#include <mm/malloc.h>
#include <mm/slab.h>

#include <proc/thread.h>

#include <assert.h>
#include <kernel.h>
#include <object.h>
#include <status.h>

/** Cache for pipe structures. */
static slab_cache_t *pipe_cache;

/** Constructor for pipe structures.
 * @param obj		Object to construct.
 * @param data		Unused. */
static void pipe_ctor(void *obj, void *data) {
	pipe_t *pipe = obj;

	mutex_init(&pipe->lock, "pipe_lock", 0);
	notifier_init(&pipe->space_notifier, pipe);
	notifier_init(&pipe->data_notifier, pipe);
}

/** Read a byte from a pipe.
 * @param pipe		Pipe structure. Should be locked, and have data.
 * @return		Character read. */
static inline char pipe_get(pipe_t *pipe) {
	char ch;

	ch = pipe->buf[pipe->start];
	if(++pipe->start >= PIPE_SIZE)
		pipe->start = 0;

	semaphore_up(&pipe->space_sem, 1);
	return ch;
}

/** Write a byte to a pipe.
 * @param pipe		Pipe structure. Should be locked, and have space.
 * @param ch		Character to write. */
static inline void pipe_insert(pipe_t *pipe, char ch) {
	pipe->buf[pipe->end] = ch;
	if(++pipe->end >= PIPE_SIZE)
		pipe->end = 0;

	semaphore_up(&pipe->data_sem, 1);
}

/**
 * Read data from a pipe.
 *
 * Reads data from a pipe into a buffer. Reads of less than or equal to
 * PIPE_SIZE will either read all the requested data, or none at all. Reads of
 * greater than PIPE_SIZE may only return part of the data. A read may not be
 * able to read all data if the calling thread is interrupted, or non-blocking
 * mode is requested.
 *
 * @param pipe		Pipe to read from.
 * @param buf		Buffer to read into.
 * @param count		Number of bytes to read.
 * @param nonblock	Whether to allow blocking.
 * @param bytesp	Where to store number of bytes read.
 *
 * @return		Status code describing result of the operation.
 */
status_t pipe_read(pipe_t *pipe, char *buf, size_t count, bool nonblock, size_t *bytesp) {
	status_t ret = STATUS_SUCCESS;
	size_t i = 0;

	if(count && count <= PIPE_SIZE) {
		/* Try to get all required data before reading. */
		for(i = 0; i < count; i++) {
			ret = semaphore_down_etc(&pipe->data_sem, (nonblock) ? 0 : -1,
				SLEEP_INTERRUPTIBLE);
			if(ret != STATUS_SUCCESS) {
				semaphore_up(&pipe->data_sem, i);
				i = 0;
				goto out;
			}
		}

		mutex_lock(&pipe->lock);

		for(i = 0; i < count; i++)
			buf[i] = pipe_get(pipe);

		notifier_run(&pipe->space_notifier, NULL, false);

		mutex_unlock(&pipe->lock);
	} else if(count) {
		for(i = 0; i < count; i++) {
			ret = semaphore_down_etc(&pipe->data_sem, (nonblock) ? 0 : -1,
				SLEEP_INTERRUPTIBLE);
			if(ret != STATUS_SUCCESS)
				goto out;

			mutex_lock(&pipe->lock);
			buf[i] = pipe_get(pipe);
			notifier_run(&pipe->space_notifier, NULL, false);
			mutex_unlock(&pipe->lock);
		}
	}
out:
	if(bytesp)
		*bytesp = i;

	return ret;
}

/**
 * Write data to a pipe.
 *
 * Writes data from a buffer to a pipe. Writes of less than or equal to
 * PIPE_SIZE will either write all the requested data, or none at all. Writes
 * of greater than PIPE_SIZE may only write part of the data. A write may not
 * be able to write all data if the calling thread is interrupted, or
 * non-blocking mode is requested.
 *
 * @param pipe		Pipe to read from.
 * @param buf		Buffer to read into.
 * @param count		Number of bytes to read.
 * @param nonblock	Whether to allow blocking.
 * @param bytesp	Where to store number of bytes written.
 *
 * @return		Status code describing result of the operation.
 */
status_t pipe_write(pipe_t *pipe, const char *buf, size_t count, bool nonblock, size_t *bytesp) {
	status_t ret = STATUS_SUCCESS;
	size_t i = 0;

	if(count && count <= PIPE_SIZE) {
		/* Try to get all required space before writing. */
		for(i = 0; i < count; i++) {
			ret = semaphore_down_etc(&pipe->space_sem, (nonblock) ? 0 : -1,
				SLEEP_INTERRUPTIBLE);
			if(ret != STATUS_SUCCESS) {
				semaphore_up(&pipe->space_sem, i);
				i = 0;
				goto out;
			}
		}

		mutex_lock(&pipe->lock);

		for(i = 0; i < count; i++)
			pipe_insert(pipe, buf[i]);

		/* For atomic writes, we only run the data notifier after
		 * writing everything, so we don't do too many calls. */
		notifier_run(&pipe->data_notifier, NULL, false);

		mutex_unlock(&pipe->lock);
	} else if(count) {
		for(i = 0; i < count; i++) {
			ret = semaphore_down_etc(&pipe->space_sem, (nonblock) ? 0 : -1,
				SLEEP_INTERRUPTIBLE);
			if(ret != STATUS_SUCCESS)
				goto out;

			mutex_lock(&pipe->lock);
			pipe_insert(pipe, buf[i]);
			notifier_run(&pipe->data_notifier, NULL, false);
			mutex_unlock(&pipe->lock);
		}
	}
out:
	if(bytesp)
		*bytesp = i;

	return ret;
}

/** Perform I/O on a pipe.
 * @param pipe		Pipe to perform I/O on.
 * @param request	I/O request.
 * @param nonblock	Whether to allow blocking.
 * @return		Status code describing result of the operation. */
status_t pipe_io(pipe_t *pipe, io_request_t *request, bool nonblock) {
	char *buf;
	size_t count;
	status_t ret, err;

	buf = kmalloc(request->total, MM_USER);
	if(!buf)
		return STATUS_NO_MEMORY;

	if(request->op == IO_OP_READ) {
		ret = pipe_read(pipe, buf, request->total, nonblock, &count);

		if(count) {
			err = io_request_copy(request, buf, count);
			if(err != STATUS_SUCCESS)
				ret = err;
		}
	} else {
		ret = io_request_copy(request, buf, request->total);
		if(ret != STATUS_SUCCESS) {
			kfree(buf);
			return ret;
		}

		ret = pipe_write(pipe, buf, request->total, nonblock, &count);
		request->transferred -= request->total - count;
	}

	kfree(buf);
	return ret;
}

/**
 * Wait for a pipe to be readable or writable.
 *
 * Waits for a pipe to become readable or writable, and notifies the specified
 * object wait pointer when it is. This is a convenience function, for example
 * for devices that use pipes internally.
 *
 * @param pipe		Pipe to wait for.
 * @param write		Whether to wait to be writable (pipe is classed as
 *			        writable when there is space in the buffer).
 * @param event     Object event structure.
 */
void
pipe_wait(pipe_t *pipe, bool write, object_event_t *event)
{
	if(write) {
		if(semaphore_count(&pipe->space_sem)) {
			object_event_signal(event, 0);
		} else {
			notifier_register(&pipe->space_notifier, object_event_notifier, event);
		}
	} else {
		if(semaphore_count(&pipe->data_sem)) {
			object_event_signal(event, 0);
		} else {
			notifier_register(&pipe->data_notifier, object_event_notifier, event);
		}
	}
}

/**
* Stop waiting for a pipe event.
*
* @param pipe		Pipe to stop waiting for.
* @param write		Whether waiting to be writable.
* @param event      Object event structure.
*/
void
pipe_unwait(pipe_t *pipe, bool write, object_event_t *event)
{
	notifier_t *notifier = (write) ? &pipe->space_notifier : &pipe->data_notifier;
	notifier_unregister(notifier, object_event_notifier, event);
}

/** Create a new pipe.
 * @return		Pointer to pipe structure. */
pipe_t *pipe_create(void) {
	pipe_t *pipe;

	pipe = slab_cache_alloc(pipe_cache, MM_KERNEL);
	semaphore_init(&pipe->space_sem, "pipe_space_sem", PIPE_SIZE);
	semaphore_init(&pipe->data_sem, "pipe_data_sem", 0);
	pipe->buf = kmem_alloc(PIPE_SIZE, MM_KERNEL);
	pipe->start = 0;
	pipe->end = 0;
	return pipe;
}

/** Destroy a pipe.
 * @note		Caller must ensure that nothing is using the pipe.
 * @param pipe		Pipe to destroy. */
void pipe_destroy(pipe_t *pipe) {
	assert(!mutex_held(&pipe->lock));
	assert(notifier_empty(&pipe->space_notifier));
	assert(notifier_empty(&pipe->data_notifier));
	kmem_free(pipe->buf, PIPE_SIZE);
	slab_cache_free(pipe_cache, pipe);
}

/** Initialize the pipe slab cache. */
static __init_text void pipe_cache_init(void) {
	pipe_cache = object_cache_create("pipe_cache", pipe_t, pipe_ctor, NULL,
		NULL, 0, MM_BOOT);
}

INITCALL(pipe_cache_init);


text:
package de.l3s.util.encoding;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5 {

	public static String encode(byte[] input) {
		MessageDigest md;
		try {
			md = MessageDigest.getInstance("MD5");
			md.update(input);
			return bytesToHex(md.digest());
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	public static String bytesToHex(byte[] b) {
		char hexDigit[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
				'A', 'B', 'C', 'D', 'E', 'F' };
		StringBuffer buf = new StringBuffer();
		for (int j = 0; j < b.length; j++) {
			buf.append(hexDigit[(b[j] >> 4) & 0x0f]);
			buf.append(hexDigit[b[j] & 0x0f]);
		}
		return buf.toString();
	}
}


text:
<?php

namespace Hicoria\Xpay;

use Nette\DI\CompilerExtension;
use Nette\PhpGenerator\ClassType;

class XpayExtension extends CompilerExtension {
    public function loadConfiguration()
    {
        $builder = $this->getContainerBuilder();

        $builder->addDefinition($this->prefix('xpaySmsDispatcher'))
            ->setClass('Hicoria\Xpay\XpaySmsDispatcher')
            ->addTag('xpaySmsDispatcher');
    }

    /**
     * @param ClassType $class
     */
    public function afterCompile(ClassType $class) {
        $initialize = $class->methods['initialize'];
        $containerBuilder = $this->getContainerBuilder();

        $dispatcher_name = key($containerBuilder->findByTag('xpaySmsDispatcher'));

        foreach($containerBuilder->findByTag("xpaySmsProcessor") as $index => $value) {
            $initialize->addBody(
                '$this->getService(?)->register($this->getService(?));',
                array(
                    $dispatcher_name,
                    $index
                )
            );
        }

        $initialize->addBody('$this->getService(?)->sortByPriority();', array($dispatcher_name));
    }
}


text:
// This file contains the empty implementation for a Sequencer plugin. The app developer can fill in the implemenation
// and add more sequencer plugins in this file.

//
// The namespace object
//
var PLAYER_SEQUENCER = PLAYER_SEQUENCER || {};

PLAYER_SEQUENCER.createCustomSequencerPlugin = function (customPlugin) {
    "use strict";

    // Replace the default pass-through methods

    // This is a sample code to throw exception in manifestToSeekbarTime to test
    // if the plugin is successfully created. Please remove this or replace this with real implementation
    // if you want to implement a custom sequencer plugin
//    customPlugin.manifestToSeekbarTime = function ( params ) {
//        throw new PLAYER_SEQUENCER.SequencerError('If you see this the plugin is correctly added to the project');
//    };
};

PLAYER_SEQUENCER.createCustomSequencerPlugin(PLAYER_SEQUENCER.sequencerPluginChain.createSequencerPlugin());


text:
namespace YAML {
///////////////////////////////////////////////////////////////////////
// Specialization for scanning specific tokens

// Directive
// . Note: no semantic checking is done here (that's for the parser to do)
void Scanner::ScanDirective() {
  std::string name;
  std::vector<std::string> params;

  // pop indents and simple keys
  PopAllIndents();
  PopAllSimpleKeys();

  m_simpleKeyAllowed = false;
  m_canBeJSONFlow = false;

  // store pos and eat indicator
  Token token(Token::DIRECTIVE, INPUT.mark());
  INPUT.eat(1);

  // read name
  while (INPUT && !Exp::BlankOrBreak().Matches(INPUT))
    token.value += INPUT.get();

  // read parameters
  while (1) {
    // first get rid of whitespace
    while (Exp::Blank().Matches(INPUT))
      INPUT.eat(1);

    // break on newline or comment
    if (!INPUT || Exp::Break().Matches(INPUT) || Exp::Comment().Matches(INPUT))
      break;

    // now read parameter
    std::string param;
    while (INPUT && !Exp::BlankOrBreak().Matches(INPUT))
      param += INPUT.get();

    token.params.push_back(param);
  }

  m_tokens.push(token);
}

// DocStart
void Scanner::ScanDocStart() {
  PopAllIndents();
  PopAllSimpleKeys();
  m_simpleKeyAllowed = false;
  m_canBeJSONFlow = false;

  // eat
  Mark mark = INPUT.mark();
  INPUT.eat(3);
  m_tokens.push(Token(Token::DOC_START, mark));
}

// DocEnd
void Scanner::ScanDocEnd() {
  PopAllIndents();
  PopAllSimpleKeys();
  m_simpleKeyAllowed = false;
  m_canBeJSONFlow = false;

  // eat
  Mark mark = INPUT.mark();
  INPUT.eat(3);
  m_tokens.push(Token(Token::DOC_END, mark));
}

// FlowStart
void Scanner::ScanFlowStart() {
  // flows can be simple keys
  InsertPotentialSimpleKey();
  m_simpleKeyAllowed = true;
  m_canBeJSONFlow = false;

  // eat
  Mark mark = INPUT.mark();
  char ch = INPUT.get();
  FLOW_MARKER flowType = (ch == Keys::FlowSeqStart ? FLOW_SEQ : FLOW_MAP);
  m_flows.push(flowType);
  Token::TYPE type =
      (flowType == FLOW_SEQ ? Token::FLOW_SEQ_START : Token::FLOW_MAP_START);
  m_tokens.push(Token(type, mark));
}

// FlowEnd
void Scanner::ScanFlowEnd() {
  if (InBlockContext())
    throw ParserException(INPUT.mark(), ErrorMsg::FLOW_END);

  // we might have a solo entry in the flow context
  if (InFlowContext()) {
    if (m_flows.top() == FLOW_MAP && VerifySimpleKey())
      m_tokens.push(Token(Token::VALUE, INPUT.mark()));
    else if (m_flows.top() == FLOW_SEQ)
      InvalidateSimpleKey();
  }

  m_simpleKeyAllowed = false;
  m_canBeJSONFlow = true;

  // eat
  Mark mark = INPUT.mark();
  char ch = INPUT.get();

  // check that it matches the start
  FLOW_MARKER flowType = (ch == Keys::FlowSeqEnd ? FLOW_SEQ : FLOW_MAP);
  if (m_flows.top() != flowType)
    throw ParserException(mark, ErrorMsg::FLOW_END);
  m_flows.pop();

  Token::TYPE type = (flowType ? Token::FLOW_SEQ_END : Token::FLOW_MAP_END);
  m_tokens.push(Token(type, mark));
}

// FlowEntry
void Scanner::ScanFlowEntry() {
  // we might have a solo entry in the flow context
  if (InFlowContext()) {
    if (m_flows.top() == FLOW_MAP && VerifySimpleKey())
      m_tokens.push(Token(Token::VALUE, INPUT.mark()));
    else if (m_flows.top() == FLOW_SEQ)
      InvalidateSimpleKey();
  }

  m_simpleKeyAllowed = true;
  m_canBeJSONFlow = false;

  // eat
  Mark mark = INPUT.mark();
  INPUT.eat(1);
  m_tokens.push(Token(Token::FLOW_ENTRY, mark));
}

// BlockEntry
void Scanner::ScanBlockEntry() {
  // we better be in the block context!
  if (InFlowContext())
    throw ParserException(INPUT.mark(), ErrorMsg::BLOCK_ENTRY);

  // can we put it here?
  if (!m_simpleKeyAllowed)
    throw ParserException(INPUT.mark(), ErrorMsg::BLOCK_ENTRY);

  PushIndentTo(INPUT.column(), IndentMarker::SEQ);
  m_simpleKeyAllowed = true;
  m_canBeJSONFlow = false;

  // eat
  Mark mark = INPUT.mark();
  INPUT.eat(1);
  m_tokens.push(Token(Token::BLOCK_ENTRY, mark));
}

// Key
void Scanner::ScanKey() {
  // handle keys diffently in the block context (and manage indents)
  if (InBlockContext()) {
    if (!m_simpleKeyAllowed)
      throw ParserException(INPUT.mark(), ErrorMsg::MAP_KEY);

    PushIndentTo(INPUT.column(), IndentMarker::MAP);
  }

  // can only put a simple key here if we're in block context
  m_simpleKeyAllowed = InBlockContext();

  // eat
  Mark mark = INPUT.mark();
  INPUT.eat(1);
  m_tokens.push(Token(Token::KEY, mark));
}

// Value
void Scanner::ScanValue() {
  // and check that simple key
  bool isSimpleKey = VerifySimpleKey();
  m_canBeJSONFlow = false;

  if (isSimpleKey) {
    // can't follow a simple key with another simple key (dunno why, though - it
    // seems fine)
    m_simpleKeyAllowed = false;
  } else {
    // handle values diffently in the block context (and manage indents)
    if (InBlockContext()) {
      if (!m_simpleKeyAllowed)
        throw ParserException(INPUT.mark(), ErrorMsg::MAP_VALUE);

      PushIndentTo(INPUT.column(), IndentMarker::MAP);
    }

    // can only put a simple key here if we're in block context
    m_simpleKeyAllowed = InBlockContext();
  }

  // eat
  Mark mark = INPUT.mark();
  INPUT.eat(1);
  m_tokens.push(Token(Token::VALUE, mark));
}

// AnchorOrAlias
void Scanner::ScanAnchorOrAlias() {
  bool alias;
  std::string name;

  // insert a potential simple key
  InsertPotentialSimpleKey();
  m_simpleKeyAllowed = false;
  m_canBeJSONFlow = false;

  // eat the indicator
  Mark mark = INPUT.mark();
  char indicator = INPUT.get();
  alias = (indicator == Keys::Alias);

  // now eat the content
  while (INPUT && Exp::Anchor().Matches(INPUT))
    name += INPUT.get();

  // we need to have read SOMETHING!
  if (name.empty())
    throw ParserException(INPUT.mark(), alias ? ErrorMsg::ALIAS_NOT_FOUND
                                              : ErrorMsg::ANCHOR_NOT_FOUND);

  // and needs to end correctly
  if (INPUT && !Exp::AnchorEnd().Matches(INPUT))
    throw ParserException(INPUT.mark(), alias ? ErrorMsg::CHAR_IN_ALIAS
                                              : ErrorMsg::CHAR_IN_ANCHOR);

  // and we're done
  Token token(alias ? Token::ALIAS : Token::ANCHOR, mark);
  token.value = name;
  m_tokens.push(token);
}

// Tag
void Scanner::ScanTag() {
  // insert a potential simple key
  InsertPotentialSimpleKey();
  m_simpleKeyAllowed = false;
  m_canBeJSONFlow = false;

  Token token(Token::TAG, INPUT.mark());

  // eat the indicator
  INPUT.get();

  if (INPUT && INPUT.peek() == Keys::VerbatimTagStart) {
    std::string tag = ScanVerbatimTag(INPUT);

    token.value = tag;
    token.data = Tag::VERBATIM;
  } else {
    bool canBeHandle;
    token.value = ScanTagHandle(INPUT, canBeHandle);
    if (!canBeHandle && token.value.empty())
      token.data = Tag::NON_SPECIFIC;
    else if (token.value.empty())
      token.data = Tag::SECONDARY_HANDLE;
    else
      token.data = Tag::PRIMARY_HANDLE;

    // is there a suffix?
    if (canBeHandle && INPUT.peek() == Keys::Tag) {
      // eat the indicator
      INPUT.get();
      token.params.push_back(ScanTagSuffix(INPUT));
      token.data = Tag::NAMED_HANDLE;
    }
  }

  m_tokens.push(token);
}

// PlainScalar
void Scanner::ScanPlainScalar() {
  std::string scalar;

  // set up the scanning parameters
  ScanScalarParams params;
  params.end =
      (InFlowContext() ? &Exp::ScanScalarEndInFlow() : &Exp::ScanScalarEnd());
  params.eatEnd = false;
  params.indent = (InFlowContext() ? 0 : GetTopIndent() + 1);
  params.fold = FOLD_FLOW;
  params.eatLeadingWhitespace = true;
  params.trimTrailingSpaces = true;
  params.chomp = STRIP;
  params.onDocIndicator = BREAK;
  params.onTabInIndentation = THROW;

  // insert a potential simple key
  InsertPotentialSimpleKey();

  Mark mark = INPUT.mark();
  scalar = ScanScalar(INPUT, params);

  // can have a simple key only if we ended the scalar by starting a new line
  m_simpleKeyAllowed = params.leadingSpaces;
  m_canBeJSONFlow = false;

  // finally, check and see if we ended on an illegal character
  // if(Exp::IllegalCharInScalar.Matches(INPUT))
  //   throw ParserException(INPUT.mark(), ErrorMsg::CHAR_IN_SCALAR);

  Token token(Token::PLAIN_SCALAR, mark);
  token.value = scalar;
  m_tokens.push(token);
}

// QuotedScalar
void Scanner::ScanQuotedScalar() {
  std::string scalar;

  // peek at single or double quote (don't eat because we need to preserve (for
  // the time being) the input position)
  char quote = INPUT.peek();
  bool single = (quote == '\'');

  // setup the scanning parameters
  ScanScalarParams params;
  RegEx end = (single ? RegEx(quote) && !Exp::EscSingleQuote() : RegEx(quote));
  params.end = &end;
  params.eatEnd = true;
  params.escape = (single ? '\'' : '\\');
  params.indent = 0;
  params.fold = FOLD_FLOW;
  params.eatLeadingWhitespace = true;
  params.trimTrailingSpaces = false;
  params.chomp = CLIP;
  params.onDocIndicator = THROW;

  // insert a potential simple key
  InsertPotentialSimpleKey();

  Mark mark = INPUT.mark();

  // now eat that opening quote
  INPUT.get();

  // and scan
  scalar = ScanScalar(INPUT, params);
  m_simpleKeyAllowed = false;
  m_canBeJSONFlow = true;

  Token token(Token::NON_PLAIN_SCALAR, mark);
  token.value = scalar;
  m_tokens.push(token);
}

// BlockScalarToken
// . These need a little extra processing beforehand.
// . We need to scan the line where the indicator is (this doesn't count as part
// of the scalar),
//   and then we need to figure out what level of indentation we'll be using.
void Scanner::ScanBlockScalar() {
  std::string scalar;

  ScanScalarParams params;
  params.indent = 1;
  params.detectIndent = true;

  // eat block indicator ('|' or '>')
  Mark mark = INPUT.mark();
  char indicator = INPUT.get();
  params.fold = (indicator == Keys::FoldedScalar ? FOLD_BLOCK : DONT_FOLD);

  // eat chomping/indentation indicators
  params.chomp = CLIP;
  int n = Exp::Chomp().Match(INPUT);
  for (int i = 0; i < n; i++) {
    char ch = INPUT.get();
    if (ch == '+')
      params.chomp = KEEP;
    else if (ch == '-')
      params.chomp = STRIP;
    else if (Exp::Digit().Matches(ch)) {
      if (ch == '0')
        throw ParserException(INPUT.mark(), ErrorMsg::ZERO_INDENT_IN_BLOCK);

      params.indent = ch - '0';
      params.detectIndent = false;
    }
  }

  // now eat whitespace
  while (Exp::Blank().Matches(INPUT))
    INPUT.eat(1);

  // and comments to the end of the line
  if (Exp::Comment().Matches(INPUT))
    while (INPUT && !Exp::Break().Matches(INPUT))
      INPUT.eat(1);

  // if it's not a line break, then we ran into a bad character inline
  if (INPUT && !Exp::Break().Matches(INPUT))
    throw ParserException(INPUT.mark(), ErrorMsg::CHAR_IN_BLOCK);

  // set the initial indentation
  if (GetTopIndent() >= 0)
    params.indent += GetTopIndent();

  params.eatLeadingWhitespace = false;
  params.trimTrailingSpaces = false;
  params.onTabInIndentation = THROW;

  scalar = ScanScalar(INPUT, params);

  // simple keys always ok after block scalars (since we're gonna start a new
  // line anyways)
  m_simpleKeyAllowed = true;
  m_canBeJSONFlow = false;

  Token token(Token::NON_PLAIN_SCALAR, mark);
  token.value = scalar;
  m_tokens.push(token);
}
}


text:
Borowr

Sign up and start sharing

			<form name="userForm" data-ng-submit="signup()" class="signin form-horizontal" novalidate autocomplete="off">
				<fieldset>

						<input type="text" required id="firstName" name="firstName" class="form-control" data-ng-model="credentials.firstName" placeholder="First Name">

						<input type="text" id="lastName" name="lastName" class="form-control" data-ng-model="credentials.lastName" placeholder="Last Name">

						<input type="email" id="email" name="email" class="form-control" data-ng-model="credentials.email" placeholder="Email">

						<input type="text" id="username" name="username" class="form-control" data-ng-model="credentials.username" placeholder="Username">

						<input type="password" id="password" name="password" class="form-control" data-ng-model="credentials.password" placeholder="Password">

						<button type="submit" class="btn btn-large btn-primary">Sign up</button>  or
						Sign in

				</fieldset>
			</form>

Welcome to Borowr!

Borowr aims to move the sharing economy forward by making it easy to share anything.

Start sharing and start borowing.

					Search for items.

					Post something you'd like to share.

					Have fun.

		Borowr is a one man project in early development -
		contact me
		to make a suggestion or just because.


text:
using System.IO;
using Newtonsoft.Json;

namespace Microsoft.Deployment.Site.Test.TestHelpers
{
    public class Credential
    {
        public static Credential Instance { get; private set; }

        public SqlCreds Sql { get; set; }

        public SalesforceCreds Salesforce { get; set; }

        public ServiceAccount ServiceAccount { get; set; }

        public TwitterAccount TwitterAccount { get; set; }

        public SccmSql SccmSql { get; set; }

        public PsaCreds PsaCreds { get; set; }

        public static void Load()
        {
            Credential cred = new Credential();

            if (File.Exists("../../../../../../Private/Credentials/credentials.json"))
            {
                string text = File.ReadAllText("../../../../../../Private/Credentials/credentials.json");
                cred = JsonConvert.DeserializeObject<Credential>(text);
            }

            Instance = cred;
        }
    }
}


text:
package org.mockserver.serialization.model;

import org.mockserver.model.ObjectWithReflectiveEqualsHashCodeToString;

/**
 * @author jamesdbloom
 */
public class WebSocketMessageDTO extends ObjectWithReflectiveEqualsHashCodeToString {

    private String type;

    private String value;

    public String getType() {
        return type;
    }

    public WebSocketMessageDTO setType(String type) {
        this.type = type;
        return this;
    }

    public String getValue() {
        return value;
    }

    public WebSocketMessageDTO setValue(String value) {
        this.value = value;
        return this;
    }
}


text:
module Graphics.HGL.Core
	( module Graphics.HGL.Units
	, module Graphics.HGL.Run
	, module Graphics.HGL.Window
	, module Graphics.HGL.Draw
	, module Graphics.HGL.Key
	) where

import Graphics.HGL.Units
import Graphics.HGL.Run
import Graphics.HGL.Window
import Graphics.HGL.Draw
import Graphics.HGL.Key


text:
/// <reference types="react" />
import React from 'react';
export interface CascaderOptionType {
    value: string;
    label: string;
    disabled?: boolean;
    children?: Array<CascaderOptionType>;
}
export declare type CascaderExpandTrigger = 'click' | 'hover';
export interface ShowSearchType {
    filter?: (inputValue: string, path: CascaderOptionType[]) => boolean;
    render?: (inputValue: string, path: CascaderOptionType[], prefixCls: string) => React.ReactNode;
    sort?: (a: CascaderOptionType[], b: CascaderOptionType[], inputValue: string) => number;
    matchInputWidth?: boolean;
}
export interface CascaderProps {
    /** 可选项数据源 */
    options: CascaderOptionType[];
    /** 默认的选中项 */
    defaultValue?: CascaderOptionType[];
    /** 指定选中项 */
    value?: CascaderOptionType[];
    /** 选择完成后的回调 */
    onChange?: (value: string[], selectedOptions?: CascaderOptionType[]) => void;
    /** 选择后展示的渲染函数 */
    displayRender?: (label: string[], selectedOptions?: CascaderOptionType[]) => React.ReactNode;
    /** 自定义样式 */
    style?: React.CSSProperties;
    /** 自定义类名 */
    className?: string;
    /** 自定义浮层类名 */
    popupClassName?: string;
    /** 浮层预设位置:`bottomLeft` `bottomRight` `topLeft` `topRight` */
    popupPlacement?: string;
    /** 输入框占位文本*/
    placeholder?: string;
    /** 输入框大小,可选 `large` `default` `small` */
    size?: string;
    /** 禁用*/
    disabled?: boolean;
    /** 是否支持清除*/
    allowClear?: boolean;
    showSearch?: boolean | ShowSearchType;
    notFoundContent?: React.ReactNode;
    loadData?: (selectedOptions?: CascaderOptionType[]) => void;
    /** 次级菜单的展开方式,可选 'click' 和 'hover' */
    expandTrigger?: CascaderExpandTrigger;
    /** 当此项为 true 时,点选每级菜单选项值都会发生变化 */
    changeOnSelect?: boolean;
    /** 浮层可见变化时回调 */
    onPopupVisibleChange?: (popupVisible: boolean) => void;
    prefixCls?: string;
    inputPrefixCls?: string;
    getPopupContainer?: (triggerNode?: HTMLElement) => HTMLElement;
}
export default class Cascader extends React.Component<CascaderProps, any> {
    static defaultProps: {
        prefixCls: string;
        inputPrefixCls: string;
        placeholder: string;
        transitionName: string;
        popupPlacement: string;
        options: never[];
        disabled: boolean;
        allowClear: boolean;
        notFoundContent: string;
    };
    cachedOptions: CascaderOptionType[];
    refs: {
        [key: string]: any;
        input: {
            refs: {
                input: HTMLElement;
            };
        };
    };
    constructor(props: any);
    componentWillReceiveProps(nextProps: any): void;
    handleChange: (value: any, selectedOptions: any) => void;
    handlePopupVisibleChange: (popupVisible: any) => void;
    handleInputBlur: () => void;
    handleInputClick: (e: any) => void;
    handleKeyDown: (e: any) => void;
    handleInputChange: (e: any) => void;
    setValue: (value: any, selectedOptions?: never[]) => void;
    getLabel(): any;
    clearSelection: (e: any) => void;
    flattenTree(options: any, changeOnSelect: any, ancestor?: never[]): any;
    generateFilteredOptions(prefixCls: any): any;
    render(): JSX.Element;
}


text:
+++
title = "Benchmarking pratique (partie 5) - Pour aller plus loin"
date = "2017-06-02T09:30:11+01:00"
shortstory = "Vous souhaitez améliorer votre configuration pour votre instance Postgres ? Vous connaissez les paramètres à changer (ou non) et les valeurs à essayer ? Hélas, vous ne pouvez pas prévoir leur impact à l'avance. Quelle est la meilleure configuration d'instance pour VOTRE configuration matérielle et votre utilisation de base de données ? Nous allons voir ensemble comment automatiser les tests de changement de configuration et estimer leur impact sur votre configuration matérielle avec pgbench-tools..."
author = "Emeric Tabakhoff"
description = "Vous souhaitez améliorer votre configuration pour votre instance Postgres ? Vous connaissez les paramètres à changer (ou non) et les valeurs à essayer ? Hélas, vous ne pouvez pas prévoir leur impact à l'avance. Quelle est la meilleure configuration d'instance pour VOTRE configuration matérielle et votre utilisation de base de données ? Nous allons voir ensemble comment automatiser les tests de changement de configuration et estimer leur impact sur votre configuration matérielle avec pgbench-tools..."
banner = "banners/elephant-wrestling.jpg"
categories = ["technique"]
tags = ["automatisation"]
draft = true
+++

<!-- image 820 x 360 -->

Lors du PGDAY Paris de mars de cette année, j'ai pu assister à la conférence de Fabien Coelho sur le benchmarking que je vous ai retranscrit [ici](/post/proper-benchmarking/).
J'ai aussi eu la chance de voir Kaarel Mopel de Cybertec mentionner pgbench-tools que je me suis empressé de regarder.

****
**couper ici pour la 3e partie**
le rapport rates_report n'est pas encore finalisé

****

## Régime "Normal" : la révolution dans le monde du bench

Nous allons donc choisir parmi les sets les plus intéressants les paramètres que nous allons tester

* les différents sous-régimes avec **SETRATES** : 10 100 250 500 et Latence limite 15ms.

Dans cette simulation, on tente de mettre en place une utilisation dite normale de la base de données.

  * 10 tps : une base avec peu de trafic
  * 100 tps : un trafic de production (8 millions de transactions par jour)
  * 250 tps : trafic de production important (20 millions de transactions journalières)
  * 500 tps : environnement avec un fort trafic

 Je ne suis pas allé au-delà de ces valeurs, car passé cette limite, on entre dans un domaine peu courant qui ne fait plus partie d'une utilisation "moyenne".
 En effet, les tps maximum mesurées ici sont de l'ordre de 1500, c'est donc plus un mode de traitement batch.

 L'option latence limite permet de "skipper" toutes les transactions dont la latence est supérieure à une certaine valeur.
 Le but est de lisser le comportement pour obtenir une valeur moyenne.
 C'est une option incluse par mes soins.

 J'ai ajouté un nouveau rapport également pour observer la latence en fonction de taux de tps cible `rates_report`.
 Le but est donc ici d'améliorer la latence en fixant les tps.

* Limiter le nombre de transaction avec **TOTTRANS**

# Problèmes & contournements

****

**partie suivante**

Le script python `log-to-csv` n'est pas compatible avec l'option **SETRATES** ce qui entraîne une absence de latence dans les logs pour 2 raisons :
une colonne supplémentaire dans le fichier pgbench.log et la mention "skipped" pour les requêtes dépassant la valeur limite de latence.
J'ai donc ajouté un un nouveau script pour gérer ce cas `log-to-csv_rates` qui est appelé uniquement quand le paramètres SETRATES n'est pas laissé vide.

****

# Conclusion et discussion

****
**partie suivante**

* Retour sur la mémoire (buffers) : statistiques du pg_stat_bgwriter et répartition des écritures.

* Observation sur les checkpoints (fréquence, pourquoi, leur role et ce qu'il faut chercher à faire)

**Autre article buffers & checkpoints ?**

**brouillon à refaire**
D'autres fonctionnalités valent aussi la peine qu'on s'attarde dessus : log-to-csv, csv2gnuplot, dirty-plot, summary.

Le temps pour ce genre d'entreprise est très chronophage : un bench long (30 minutes) sérialisé de cette façon comptabilise 48h environ.
4 échelles, 6 clients, 4 taux cibles, 30 minutes de test, c'est 2880minutes (donc 48h).

**fin partie suivante**
****

# AMELIORATIONS FUTURES

* Fonctionnalités avancées :
log-to-csv, csv2gnuplot, dirty-plot, summary.
bufreport.sql, bufstats.sql, bufsummary.sql, fastest.sql, report.sql, summary.sql, tps-per-client.sql et les nouveaux : lowest_latency et fastest_w_low_lat

* remplacer pg_archiveshredder par un code propre qui retire des wals les transactions lors de l'initialisation de pgbench (avec une option)

* grapher la latence (90%< vs scale et clients) => OK

* extraire les tests les plus rapides dans limited_webreport dans un tableau

* cumuler les paramètres améliorants les perfs un a un et les comparer sur un graphique final
  puis refaire le test en mode normal

* Wrapper pour faire des séries de test complètes ?

* Après l'intégration continue, le bench continu ?

* Reconfiguration "on the fly"

* Auto Reconfiguration ?

* Obstacles ?

* Les tests en écriture séparés des tests en lecture : le cas de la réplication.

* Pourquoi le bench est une approximation : toutes les Bases sont uniques ! CONTOURNEMENT => Bench avec proxy (dédoubler les requêtes sur les serveurs

* Test sur lru et autovacuum - 3e partie ?

* FILLFACTOR = Ajouter au code puisqu'il est dans pgbench - OK

The secret art of tuning databases

bgwriter_delay = 100ms
lru_max
lru_multiplier 2,3 ,4, 5

cat /proc/sys/vm/overcommit_memory
cat /proc/sys/vm/overcommit_ratio
cat /proc/sys/vm/overcommit_kbytes

Kernel tweaks (EDB)
vm.dirty_background_ratio
vm.dirty_ratio
vm.shmmax
swappiness
shmall
overcommit_memory
kernel.transparent_hugepage.e
kernel.mmm.transparent_hugepage.d

# change the statistics :
random_page_cost
cpu_page_cost

* TEST tuning kernel linux complementaire
 I/O scheduler
 	noop cft anticipatory decline
 /sys/block/sd*/device/queue_depth
 64, 128, 256, 512, 1024
# cat /sys/block/sda/queue/nr_requests
128,256, 512, 1024, 8192
# echo 100000 > /sys/block/sda/queue/nr_requests

# Vers l'infini et au dela - 4e partie

* Wrapper pour faire des séries de test complètes ?

* Après l'intégration continue, le bench continu ?

* Reconfiguration "on the fly"

* Auto Reconfiguration ?

* Obstacles ?

* Les tests en écriture séparés des tests en lecture : le cas de la réplication. Et REPMGR ?

* Pourquoi le bench est une approximation : toutes les Bases sont uniques !

* Test sur lru et autovacuum - 3e partie ?

* FILLFACTOR et intégration à pgbenchtools- 3e partie

* Réplication : répartition de charge
* lru
* Autovacuum
* fill factor
* retour du checkpoint_timeout
* scheduler
* nr_request
* dirty_ratio
* dirty_background_ratio

# L'AUTEUR (G. Smith)