text:
package libnetwork

import (
	"fmt"
	"net"
	"os"
	"os/exec"
	"runtime"

	log "github.com/Sirupsen/logrus"
	"github.com/docker/docker/pkg/reexec"
	"github.com/docker/libnetwork/iptables"
	"github.com/vishvananda/netns"
)

func init() {
	reexec.Register("setup-resolver", reexecSetupResolver)
}

const (
	// outputChain used for docker embed dns
	outputChain = "DOCKER_OUTPUT"
	//postroutingchain used for docker embed dns
	postroutingchain = "DOCKER_POSTROUTING"
)

func reexecSetupResolver() {
	runtime.LockOSThread()
	defer runtime.UnlockOSThread()

	if len(os.Args) < 4 {
		log.Error("invalid number of arguments..")
		os.Exit(1)
	}

	resolverIP, ipPort, _ := net.SplitHostPort(os.Args[2])
	_, tcpPort, _ := net.SplitHostPort(os.Args[3])
	rules := [][]string{
		{"-t", "nat", "-I", outputChain, "-d", resolverIP, "-p", "udp", "--dport", dnsPort, "-j", "DNAT", "--to-destination", os.Args[2]},
		{"-t", "nat", "-I", postroutingchain, "-s", resolverIP, "-p", "udp", "--sport", ipPort, "-j", "SNAT", "--to-source", ":" + dnsPort},
		{"-t", "nat", "-I", outputChain, "-d", resolverIP, "-p", "tcp", "--dport", dnsPort, "-j", "DNAT", "--to-destination", os.Args[3]},
		{"-t", "nat", "-I", postroutingchain, "-s", resolverIP, "-p", "tcp", "--sport", tcpPort, "-j", "SNAT", "--to-source", ":" + dnsPort},
	}

	f, err := os.OpenFile(os.Args[1], os.O_RDONLY, 0)
	if err != nil {
		log.Errorf("failed get network namespace %q: %v", os.Args[1], err)
		os.Exit(2)
	}
	defer f.Close()

	nsFD := f.Fd()
	if err = netns.Set(netns.NsHandle(nsFD)); err != nil {
		log.Errorf("setting into container net ns %v failed, %v", os.Args[1], err)
		os.Exit(3)
	}

	// insert outputChain and postroutingchain
	err = iptables.RawCombinedOutputNative("-t", "nat", "-C", "OUTPUT", "-d", resolverIP, "-j", outputChain)
	if err == nil {
		iptables.RawCombinedOutputNative("-t", "nat", "-F", outputChain)
	} else {
		iptables.RawCombinedOutputNative("-t", "nat", "-N", outputChain)
		iptables.RawCombinedOutputNative("-t", "nat", "-I", "OUTPUT", "-d", resolverIP, "-j", outputChain)
	}

	err = iptables.RawCombinedOutputNative("-t", "nat", "-C", "POSTROUTING", "-d", resolverIP, "-j", postroutingchain)
	if err == nil {
		iptables.RawCombinedOutputNative("-t", "nat", "-F", postroutingchain)
	} else {
		iptables.RawCombinedOutputNative("-t", "nat", "-N", postroutingchain)
		iptables.RawCombinedOutputNative("-t", "nat", "-I", "POSTROUTING", "-d", resolverIP, "-j", postroutingchain)
	}

	for _, rule := range rules {
		if iptables.RawCombinedOutputNative(rule...) != nil {
			log.Errorf("setting up rule failed, %v", rule)
		}
	}
}

func (r *resolver) setupIPTable() error {
	if r.err != nil {
		return r.err
	}
	laddr := r.conn.LocalAddr().String()
	ltcpaddr := r.tcpListen.Addr().String()

	cmd := &exec.Cmd{
		Path:   reexec.Self(),
		Args:   append([]string{"setup-resolver"}, r.resolverKey, laddr, ltcpaddr),
		Stdout: os.Stdout,
		Stderr: os.Stderr,
	}
	if err := cmd.Run(); err != nil {
		return fmt.Errorf("reexec failed: %v", err)
	}
	return nil
}


text:
using System.IO;
using Microsoft.PythonTools.Infrastructure;

namespace Microsoft.PythonTools.Debugger {
    class PythonModule {
        public PythonModule(int moduleId, string filename, string moduleName, bool isUserCode) {
            ModuleId = moduleId;
            Filename = filename;
            ModuleName = moduleName;
            IsUserCode = isUserCode;
        }

        public int ModuleId { get; }
        public string Filename { get; }
        public string ModuleName { get; }
        public bool IsUserCode { get; }

        public string Name {
            get {
                if (!string.IsNullOrEmpty(ModuleName)) {
                    return ModuleName;
                }

                if (PathUtils.IsValidPath(Filename)) {
                    return Path.GetFileNameWithoutExtension(Filename);
                }
                return Filename;
            }
        }

    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

	$this->breadcrumbs=array(
		'Articles'=>array('manage'),
		Phrase::trans($model->cat->name,2),
		$model->title,
	);

	$cs = Yii::app()->getClientScript();
	$cs->registerScriptFile(Yii::app()->request->baseUrl.'/externals/article/plugin/jquery.jcarousellite.min.js', CClientScript::POS_END);
	$js=<<<EOP
		$("#module .slider-box").jCarouselLite({
			btnNext: ".slider .next",
			btnPrev: ".slider .prev",
			speed: 800,
			visible: 4
		});
EOP;
	count($photo > 1) ? $cs->registerScript('jcarousellite', $js, CClientScript::POS_END) : '';

	if($model->media_id != 0 && !isset($_GET['photo']))
		$images = Yii::app()->request->baseUrl.'/public/article/'.$model->article_id.'/'.$model->cover->media;
	else {
		$mediaPhoto = ArticleMedia::model()->findByPk($_GET['photo']);
		$images = Yii::app()->request->baseUrl.'/public/article/'.$mediaPhoto->article_id.'/'.$mediaPhoto->media;
	}
?>

	<?php echo Utility::dateFormat($model->published_date);?>
	<?php echo $model->user->displayname;?>
	<?php if($model->media_file != '') {?><?php echo $model->download?><?php }?>
	<?php echo $model->view?>

<?php if($model->media_id != 0) {?>
	<img class="headline" src="<?php echo Utility::getTimThumb($images, 600, 1024, 3);?>" alt="<?php echo $model->title;?>" />
	<?php if(count($photo) > 1) {?>

			prev
			next

					<?php
					$i=0;
					foreach($photo as $key => $row) {
						$i++;
						$images = Yii::app()->request->baseUrl.'/public/article/'.$row->article_id.'/'.$row->media;
					?>
					<li <?php echo (!isset($_GET['photo']) && $row->cover == 1) ? 'class="active"' : ((isset($_GET['photo']) && $row->media_id == $_GET['photo']) ? 'class="active"' : '');?>><a href="<?php echo Yii::app()->controller->createUrl('view', array('id'=>$row->article_id,'t'=>Utility::getUrlTitle($row->article->title.' Photo #'.$i),'photo'=>$row->media_id));?>" title="<?php echo $row->article->title;?> Photo #<?php echo $i;?>" title=""><img src="<?php echo Utility::getTimThumb($images, 120, 70, 1);?>" alt="<?php echo $row->article->title;?> Photo #<?php echo $i;?>">

					<?php }?>

	<?php }
}?>

<?php echo $model->body;?>

<?php if($model->media_file != '') {
	$extension = pathinfo($model->media_file, PATHINFO_EXTENSION);
	if($extension == 'pdf')
		$file = 'fa-file-pdf-o';
	else if(in_array($extension, array('doc','docx','opt')))
		$file = 'fa-file-word-o';
	else if(in_array($extension, array('xls','xlsx')))
		$file = 'fa-file-excel-o';
	else if(in_array($extension, array('ppt','pptx')))
		$file = 'fa-file-powerpoint-o';
	else if(in_array($extension, array('jpg','jpeg','gif','png','bmp')))
		$file = 'fa-file-photo-o';
	else if(in_array($extension, array('zip','rar','7z')))
		$file = 'fa-file-zip-o';
	else if(in_array($extension, array('mp3')))
		$file = 'fa-file-audio-o';
	else if(in_array($extension, array('mp4','flv')))
		$file = 'fa-file-movie-o';
	else
		$file = 'fa-file-pdf-o';
?>

		Download: <i class="fa <?php echo $file;?>"> <a href="<?php echo Yii::app()->controller->createUrl('download', array('id'=>$model->article_id,'t'=>Utility::getUrlTitle($model->title)));?>" title="<?php echo $model->title;?>"><?php echo $model->media_file;?>

<?php }?>

<?php if($random != null) {?>

Artikel Terkait

		<?php foreach($random as $key => $row) {
			if($row->media_id != 0)
				$images = Yii::app()->request->baseUrl.'/public/article/'.$row->article_id.'/'.$row->cover->media;
			else
				$images = Yii::app()->request->baseUrl.'/public/article/article_default.png';?>

				<a class="photo" href="<?php echo Yii::app()->controller->createUrl('view', array('id'=>$row->article_id,'t'=>Utility::getUrlTitle($row->title)));?>" title="<?php echo $row->title;?>"><img src="<?php echo Utility::getTimThumb($images, 200, 150, 3);?>" alt="<?php echo $row->title;?>" />

					<a href="<?php echo Yii::app()->controller->createUrl('view', array('id'=>$row->article_id,'t'=>Utility::getUrlTitle($row->title)));?>" title="<?php echo $row->title;?>"><?php echo Utility::hardDecode($row->title);?>

						<?php echo Utility::dateFormat($row->published_date);?>
						<?php echo $row->user->displayname;?>
						<?php echo $row->view;?>

<?php echo Utility::shortText(Utility::hardDecode($row->body),100);?>

		<?php }?>

<?php }?>


text:
// Generated on 2016-07-27 using generator-angular-fullstack 3.5.0
'use strict';

module.exports = function (grunt) {
  var localConfig;
  try {
    localConfig = require('./server/config/local.env');
  } catch(e) {
    localConfig = {};
  }

  // Load grunt tasks automatically, when needed
  require('jit-grunt')(grunt, {
    express: 'grunt-express-server',
    useminPrepare: 'grunt-usemin',
    ngtemplates: 'grunt-angular-templates',
    cdnify: 'grunt-google-cdn',
    protractor: 'grunt-protractor-runner',
    buildcontrol: 'grunt-build-control',
    istanbul_check_coverage: 'grunt-mocha-istanbul',
    ngconstant: 'grunt-ng-constant'
  });

  // Time how long tasks take. Can help when optimizing build times
  require('time-grunt')(grunt);

  // Define the configuration for all the tasks
  grunt.initConfig({
    realFavicon: {
      favicons: {
        src: '<%= yeoman.client %>/assets/images/favicon.png',
        dest: '<%= yeoman.dist %>/<%= yeoman.client %>',
        options: {
        iconsPath: '/',
        html: ['<%= yeoman.dist %>/<%= yeoman.client %>/index.html'],
        design: {
          ios: {
          pictureAspect: 'backgroundAndMargin',
          backgroundColor: '#ffffff',
          margin: '25%',
          assets: {
            ios6AndPriorIcons: false,
            ios7AndLaterIcons: false,
            precomposedIcons: false,
            declareOnlyDefaultIcon: true
          }
          },
          desktopBrowser: {},
          windows: {
          pictureAspect: 'whiteSilhouette',
          backgroundColor: '#00748d',
          onConflict: 'override',
          assets: {
            windows80Ie10Tile: false,
            windows10Ie11EdgeTiles: {
            small: false,
            medium: true,
            big: false,
            rectangle: false
            }
          }
          },
          androidChrome: {
          pictureAspect: 'shadow',
          themeColor: '#ffffff',
          manifest: {
            name: 'People\'s Power Station',
            display: 'standalone',
            orientation: 'notSet',
            onConflict: 'override',
            declared: true
          },
          assets: {
            legacyIcon: false,
            lowResolutionIcons: false
          }
          },
          safariPinnedTab: {
          pictureAspect: 'blackAndWhite',
          threshold: 82.03125,
          themeColor: '#5bbad5'
          }
        },
        settings: {
          scalingAlgorithm: 'Mitchell',
          errorOnImageTooSmall: false
        }
        }
      }
    },

    // Project settings
    pkg: grunt.file.readJSON('package.json'),
    yeoman: {
      // configurable paths
      client: require('./bower.json').appPath || 'client',
      server: 'server',
      dist: 'dist'
    },
    express: {
      options: {
        port: process.env.PORT || 9000
      },
      dev: {
        options: {
          script: '<%= yeoman.server %>',
          debug: true
        }
      },
      prod: {
        options: {
          script: '<%= yeoman.dist %>/<%= yeoman.server %>'
        }
      }
    },
    open: {
      server: {
        url: 'http://localhost:<%= express.options.port %>'
      }
    },
    watch: {
      babel: {
        files: ['<%= yeoman.client %>/{admin-app,app,components}/**/!(*.spec|*.mock).js'],
        tasks: ['newer:babel:client']
      },
      ngconstant: {
        files: ['<%= yeoman.server %>/config/environment/shared.js'],
        tasks: ['ngconstant']
      },
      injectJS: {
        files: [
          '<%= yeoman.client %>/{admin-app,app,components}/**/!(*.spec|*.mock).js',
          '!<%= yeoman.client %>/app/app.js',
          '!<%= yeoman.client %>/admin-app/admin-app.js'
        ],
        tasks: ['injector:scripts']
      },
      injectCss: {
        files: ['<%= yeoman.client %>/{admin-app,app,components}/**/*.css'],
        tasks: ['injector:css']
      },
      mochaTest: {
        files: ['<%= yeoman.server %>/**/*.{spec,integration}.js'],
        tasks: ['env:test', 'mochaTest']
      },
      jsTest: {
        files: ['<%= yeoman.client %>/{admin-app,app,components}/**/*.{spec,mock}.js'],
        tasks: ['newer:jshint:all', 'wiredep:test', 'karma']
      },
      injectStylus: {
        files: ['<%= yeoman.client %>/{admin-app,app,components}/**/*.styl'],
        tasks: ['injector:stylus']
      },
      stylus: {
        files: ['<%= yeoman.client %>/{admin-app,app,components}/**/*.styl'],
        tasks: ['stylus', 'postcss']
      },
      gruntfile: {
        files: ['Gruntfile.js']
      },
      livereload: {
        files: [
          '{.tmp,<%= yeoman.client %>}/{admin-app,app,components}/**/*.{css,html}',
          '{.tmp,<%= yeoman.client %>}/{admin-app,app,components}/**/!(*.spec|*.mock).js',
          '<%= yeoman.client %>/assets/images/{,*//*}*.{png,jpg,jpeg,gif,webp,svg}'
        ],
        options: {
          livereload: true
        }
      },
      express: {
        files: ['<%= yeoman.server %>/**/*.{js,json}'],
        tasks: ['express:dev', 'wait'],
        options: {
          livereload: true,
          spawn: false //Without this option specified express won't be reloaded
        }
      },
      bower: {
        files: ['bower.json'],
        tasks: ['wiredep']
      },
    },

    // Make sure code styles are up to par and there are no obvious mistakes
    jshint: {
      options: {
        jshintrc: '<%= yeoman.client %>/.jshintrc',
        reporter: require('jshint-stylish')
      },
      server: {
        options: {
          jshintrc: '<%= yeoman.server %>/.jshintrc'
        },
        src: ['<%= yeoman.server %>/**/!(*.spec|*.integration).js']
      },
      serverTest: {
        options: {
          jshintrc: '<%= yeoman.server %>/.jshintrc-spec'
        },
        src: ['<%= yeoman.server %>/**/*.{spec,integration}.js']
      },
      all: ['<%= yeoman.client %>/{admin-app,app,components}/**/!(*.spec|*.mock|app.constant).js'],
      test: {
        src: ['<%= yeoman.client %>/{admin-app,app,components}/**/*.{spec,mock}.js']
      }
    },

    jscs: {
      options: {
        config: ".jscsrc"
      },
      main: {
        files: {
          src: [
            '<%= yeoman.client %>/app/**/*.js',
            '<%= yeoman.server %>/**/*.js'
          ]
        }
      }
    },

    // Empties folders to start fresh
    clean: {
      dist: {
        files: [{
          dot: true,
          src: [
            '.tmp',
            '<%= yeoman.dist %>/!(.git*|.openshift|Procfile)**'
          ]
        }]
      },
      server: '.tmp'
    },

    // Add vendor prefixed styles
    postcss: {
      options: {
        map: true,
        processors: [
          require('autoprefixer')({browsers: ['last 4 version']})
        ]
      },
      dist: {
        files: [{
          expand: true,
          cwd: '.tmp/',
          src: '{,*/}*.css',
          dest: '.tmp/'
        }]
      }
    },

    // Debugging with node inspector
    'node-inspector': {
      custom: {
        options: {
          'web-host': 'localhost'
        }
      }
    },

    // Use nodemon to run server in debug mode with an initial breakpoint
    nodemon: {
      debug: {
        script: '<%= yeoman.server %>',
        options: {
          nodeArgs: ['--debug-brk'],
          env: {
            PORT: process.env.PORT || 9000
          },
          callback: function (nodemon) {
            nodemon.on('log', function (event) {
              console.log(event.colour);
            });

            // opens browser on initial server start
            nodemon.on('config:update', function () {
              setTimeout(function () {
                require('open')('http://localhost:8080/debug?port=5858');
              }, 500);
            });
          }
        }
      }
    },

    // Automatically inject Bower components into the app and karma.conf.js
    wiredep: {
      options: {
        exclude: [
          'angular-cookies',
          'angular-file-upload',
          'angular-ui-notification',
          '/angular-ui-select/dist/select.css',
          /bootstrap/,
          '/es5-shim/',
          /font-awesome\.css/,
          'jquery',
          '/json3/'
        ]
      },
      client: {
        src: '<%= yeoman.client %>/index.html',
        ignorePath: '<%= yeoman.client %>/',
      },
      clientAdmin: {
        options: {
          exclude: [
          'angular-leaflet-directive',
          '/es5-shim/',
          '/json3/'
          ]
        },
        src: '<%= yeoman.client %>/admin.html',
        ignorePath: '<%= yeoman.client %>/',
      },
      test: {
        src: './karma.conf.js',
        devDependencies: true
      }
    },

    // Renames files for browser caching purposes
    filerev: {
      dist: {
        src: [
          '<%= yeoman.dist %>/<%= yeoman.client %>/!(bower_components){,*/}*.{js,css}',
          '<%= yeoman.dist %>/<%= yeoman.client %>/assets/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}'
        ]
      }
    },

    // Reads HTML for usemin blocks to enable smart builds that automatically
    // concat, minify and revision files. Creates configurations in memory so
    // additional tasks can operate on them
    useminPrepare: {
      html: ['<%= yeoman.client %>/{index,admin}.html'],
      options: {
        dest: '<%= yeoman.dist %>/<%= yeoman.client %>'
      }
    },

    // Performs rewrites based on rev and the useminPrepare configuration
    usemin: {
      html: ['<%= yeoman.dist %>/<%= yeoman.client %>/{,!(bower_components)/**/}*.html'],
      css: ['<%= yeoman.dist %>/<%= yeoman.client %>/!(bower_components){,*/}*.css'],
      js: ['<%= yeoman.dist %>/<%= yeoman.client %>/!(bower_components){,*/}*.js'],
      options: {
        assetsDirs: [
          '<%= yeoman.dist %>/<%= yeoman.client %>',
          '<%= yeoman.dist %>/<%= yeoman.client %>/assets/images'
        ],
        // This is so we update image references in our ng-templates
        patterns: {
          css: [
            [/(assets\/images\/.*?\.(?:gif|jpeg|jpg|png|webp|svg))/gm, 'Update the CSS to reference our revved images']
          ],
          js: [
            [/(assets\/images\/.*?\.(?:gif|jpeg|jpg|png|webp|svg))/gm, 'Update the JS to reference our revved images']
          ]
        }
      }
    },

    // The following *-min tasks produce minified files in the dist folder
    imagemin: {
      dist: {
        files: [{
          expand: true,
          cwd: '<%= yeoman.client %>/assets/images',
          src: '{,*/}*.{png,jpg,jpeg,gif,svg}',
          dest: '<%= yeoman.dist %>/<%= yeoman.client %>/assets/images'
        }]
      }
    },

    // Allow the use of non-minsafe AngularJS files. Automatically makes it
    // minsafe compatible so Uglify does not destroy the ng references
    ngAnnotate: {
      dist: {
        files: [{
          expand: true,
          cwd: '.tmp/concat',
          src: '**/*.js',
          dest: '.tmp/concat'
        }]
      }
    },

    // Dynamically generate angular constant `appConfig` from
    // `server/config/environment/shared.js`
    ngconstant: {
      options: {
        name: 'lowcarbonhubAppAdmin.constants',
        dest: '<%= yeoman.client %>/admin-app/app.constant.js',
        deps: [],
        wrap: true,
        configPath: '<%= yeoman.server %>/config/environment/shared'
      },
      app: {
        constants: function() {
          return {
            appConfig: require('./' + grunt.config.get('ngconstant.options.configPath'))
          };
        }
      }
    },

    // Package all the html partials into a single javascript payload
    ngtemplates: {
      main: {
        options: {
          // This should be the name of your apps angular module
          module: 'lowcarbonhubApp',
          htmlmin: {
            collapseBooleanAttributes: true,
            collapseWhitespace: true,
            removeAttributeQuotes: true,
            removeEmptyAttributes: true,
            removeRedundantAttributes: true,
            removeScriptTypeAttributes: true,
            removeStyleLinkTypeAttributes: true
          },
          usemin: 'app/app.js'
        },
        cwd: '<%= yeoman.client %>',
        src: ['{app,components}/**/*.html'],
        dest: '.tmp/templates.js'
      },
      clientAdmin: {
        options: {
          // This should be the name of your apps angular module
          prefix: 'admin-app',
          module: 'lowcarbonhubAppAdmin',
          htmlmin: {
            collapseBooleanAttributes: true,
            collapseWhitespace: true,
            removeAttributeQuotes: true,
            removeEmptyAttributes: true,
            removeRedundantAttributes: true,
            removeScriptTypeAttributes: true,
            removeStyleLinkTypeAttributes: true
          },
          usemin: 'admin-app/admin-app.js'
        },
        cwd: '<%= yeoman.client %>/admin-app',
        src: ['**/*.html'],
        dest: '.tmp/admin-templates.js'
      },
      tmp: {
        cwd: '.tmp',
        src: ['{app,components}/**/*.html'],
        dest: '.tmp/tmp-templates.js'
      }
    },

    // Replace Google CDN references
    cdnify: {
      dist: {
        html: ['<%= yeoman.dist %>/<%= yeoman.client %>/*.html']
      }
    },

    // Copies remaining files to places other tasks can use
    copy: {
      screenshot: {
        expand: true,
        cwd: '<%= yeoman.client %>',
        dest: '<%= yeoman.dist %>/<%= yeoman.client %>',
        src: ['assets/images/screenshot.*']
      },
      dist: {
        files: [{
          expand: true,
          dot: true,
          cwd: '<%= yeoman.client %>',
          dest: '<%= yeoman.dist %>/<%= yeoman.client %>',
          src: [
            '*.{ico,png,txt}',
            '.htaccess',
            'bower_components/**/*',
            'assets/images/{,*/}*.{webp}',
            'assets/fonts/**/*',
            'assets/json/**/*',
            'admin.html',
            'index.html'
          ]
        }, {
          expand: true,
          cwd: '.tmp/images',
          dest: '<%= yeoman.dist %>/<%= yeoman.client %>/assets/images',
          src: ['generated/*']
        }, {
          expand: true,
          dest: '<%= yeoman.dist %>',
          src: [
            'package.json',
            '<%= yeoman.server %>/**/*',
            '!<%= yeoman.server %>/config/local.env.sample.js'
          ]
        }]
      },
      styles: {
        expand: true,
        cwd: '<%= yeoman.client %>',
        dest: '.tmp/',
        src: ['{admin-app,app,components}/**/*.css']
      }
    },

    buildcontrol: {
      options: {
        dir: '<%= yeoman.dist %>',
        commit: true,
        push: true,
        connectCommits: false,
        message: 'Built %sourceName% from commit %sourceCommit% on branch %sourceBranch%'
      },
      heroku: {
        options: {
          remote: 'heroku',
          branch: 'master'
        }
      },
      openshift: {
        options: {
          remote: 'openshift',
          branch: 'master'
        }
      }
    },

    // Run some tasks in parallel to speed up the build process
    concurrent: {
      pre: [
        'injector:stylus',
        'ngconstant'
      ],
      server: [
        'newer:babel:client',
        'stylus',
      ],
      test: [
        'newer:babel:client',
        'stylus',
      ],
      debug: {
        tasks: [
          'nodemon',
          'node-inspector'
        ],
        options: {
          logConcurrentOutput: true
        }
      },
      dist: [
        'newer:babel:client',
        'stylus',
        'imagemin'
      ]
    },

    // Test settings
    karma: {
      unit: {
        configFile: 'karma.conf.js',
        singleRun: true
      }
    },

    mochaTest: {
      options: {
        reporter: 'spec',
        require: 'mocha.conf.js',
        timeout: 5000 // set default mocha spec timeout
      },
      unit: {
        src: ['<%= yeoman.server %>/**/*.spec.js']
      },
      integration: {
        src: ['<%= yeoman.server %>/**/*.integration.js']
      }
    },

    mocha_istanbul: {
      unit: {
        options: {
          excludes: ['**/*.{spec,mock,integration}.js'],
          reporter: 'spec',
          require: ['mocha.conf.js'],
          mask: '**/*.spec.js',
          coverageFolder: 'coverage/server/unit'
        },
        src: '<%= yeoman.server %>'
      },
      integration: {
        options: {
          excludes: ['**/*.{spec,mock,integration}.js'],
          reporter: 'spec',
          require: ['mocha.conf.js'],
          mask: '**/*.integration.js',
          coverageFolder: 'coverage/server/integration'
        },
        src: '<%= yeoman.server %>'
      }
    },

    istanbul_check_coverage: {
      default: {
        options: {
          coverageFolder: 'coverage/**',
          check: {
            lines: 80,
            statements: 80,
            branches: 80,
            functions: 80
          }
        }
      }
    },

    protractor: {
      options: {
        configFile: 'protractor.conf.js'
      },
      chrome: {
        options: {
          args: {
            browser: 'chrome'
          }
        }
      }
    },

    env: {
      test: {
        NODE_ENV: 'test'
      },
      prod: {
        NODE_ENV: 'production'
      },
      all: localConfig
    },

    // Compiles ES6 to JavaScript using Babel
    babel: {
      options: {
        sourceMap: true
      },
      client: {
        files: [{
          expand: true,
          cwd: '<%= yeoman.client %>',
          src: ['{admin-app,app,components}/**/!(*.spec).js'],
          dest: '.tmp'
        }]
      },
      server: {
        options: {
          plugins: [
            'transform-class-properties',
            'transform-runtime'
          ]
        },
        files: [{
          expand: true,
          cwd: '<%= yeoman.server %>',
          src: [
            '**/*.js',
            '!config/local.env.sample.js'
          ],
          dest: '<%= yeoman.dist %>/<%= yeoman.server %>'
        }]
      }
    },

    // Compiles Stylus to CSS
    stylus: {
      server: {
        options: {
          "include css": true
        },
        files: {
          '.tmp/app/app.css' : '<%= yeoman.client %>/app/app.styl',
          '.tmp/app/critical.css' : '<%= yeoman.client %>/app/critical.styl',
          '.tmp/admin-app/admin-app.css' : '<%= yeoman.client %>/admin-app/admin-app.styl'
        }
      }
    },

    inline: {
      dist: {
        options:{

          tag: 'critical',
          cssmin: true
        },
        src: '<%= yeoman.dist %>/<%= yeoman.client %>/index.html'
      }
    },

    htmlmin: {
      dist: {
        options: {
          removeComments: true,
          collapseWhitespace: true
        },
        files: {
          '<%= yeoman.dist %>/<%= yeoman.client %>/index.html': '<%= yeoman.dist %>/<%= yeoman.client %>/index.html'
        }
      }
    },

    injector: {
      options: {},
      // Inject application script files into index.html (doesn't include bower)
      scripts: {
        options: {
          transform: function(filePath) {
            var yoClient = grunt.config.get('yeoman.client');
            filePath = filePath.replace('/' + yoClient + '/', '');
            filePath = filePath.replace('/.tmp/', '');
            return '<script src="' + filePath + '"></script>';
          },
          sort: function(a, b) {
            var module = /\.module\.(js|ts)$/;
            var aMod = module.test(a);
            var bMod = module.test(b);
            // inject *.module.js first
            return (aMod === bMod) ? 0 : (aMod ? -1 : 1);
          },
          starttag: '<!-- injector:js -->',
          endtag: '<!-- endinjector -->'
        },
        files: {
          '<%= yeoman.client %>/index.html': [
               [
                 '<%= yeoman.client %>/{app,components}/**/!(*.spec|*.mock).js',
                 '!{.tmp,<%= yeoman.client %>}/app/app.{js,ts}'
               ]
            ],
          '<%= yeoman.client %>/admin.html': [
               [
                 '<%= yeoman.client %>/admin-app/**/!(*.spec|*.mock).js',
                 '!{.tmp,<%= yeoman.client %>}/admin-app/admin-app.{js,ts}'
               ]
            ]
        }
      },

      // Inject component styl into app.styl
      stylus: {
        options: {
          transform: function(filePath) {
            var yoClient = grunt.config.get('yeoman.client');
            filePath = filePath.replace('/' + yoClient + '/app/', '');
            filePath = filePath.replace('/' + yoClient + '/components/', '../components/');
            return '@import \'' + filePath + '\';';
          },
          starttag: '/* inject:styl */',
          endtag: '/* endinject */'
        },
        files: {
          '<%= yeoman.client %>/app/app.styl': [
            '<%= yeoman.client %>/{app,components}/**/*.styl',
            '!<%= yeoman.client %>/app/app.styl',
            '!<%= yeoman.client %>/components/_variables.styl',
            '!<%= yeoman.client %>/app/critical.styl',
            '!<%= yeoman.client %>/components/critical/**/*.styl'
          ],
          '<%= yeoman.client %>/app/critical.styl': [
            '<%= yeoman.client %>/components/critical/**/*.styl'
          ]
        }
      },

      // Inject component css into index.html
      css: {
        options: {
          transform: function(filePath) {
            var yoClient = grunt.config.get('yeoman.client');
            filePath = filePath.replace('/' + yoClient + '/', '');
            filePath = filePath.replace('/.tmp/', '');
            return '<link rel="stylesheet" href="' + filePath + '">';
          },
          starttag: '<!-- injector:css -->',
          endtag: '<!-- endinjector -->'
        },
        files: {
          '<%= yeoman.client %>/index.html': [
            '<%= yeoman.client %>/{app,components}/**/*.css'
          ],
          '<%= yeoman.client %>/admin.html': [
            '<%= yeoman.client %>/admin-app/**/*.css'
          ]
        }
      }
    },
  });

  // Used for delaying livereload until after server has restarted
  grunt.registerTask('wait', function () {
    grunt.log.ok('Waiting for server reload...');

    var done = this.async();

    setTimeout(function () {
      grunt.log.writeln('Done waiting!');
      done();
    }, 1500);
  });

  grunt.registerTask('express-keepalive', 'Keep grunt running', function() {
    this.async();
  });

  grunt.registerTask('serve', function (target) {
    if (target === 'dist-no-build') {
      return grunt.task.run(['env:all', 'env:prod', 'express:prod', 'wait', 'open', 'express-keepalive']);
    }

    if (target === 'dist') {
      return grunt.task.run(['build', 'env:all', 'env:prod', 'express:prod', 'wait', 'open', 'express-keepalive']);
    }

    if (target === 'debug') {
      return grunt.task.run([
        'clean:server',
        'env:all',
        'concurrent:pre',
        'concurrent:server',
        'injector',
        'wiredep:client',
        'wiredep:clientAdmin',
        'postcss',
        'concurrent:debug'
      ]);
    }

    grunt.task.run([
      'clean:server',
      'env:all',
      'concurrent:pre',
      'concurrent:server',
      'injector',
      'wiredep:client',
      'wiredep:clientAdmin',
      'postcss',
      'express:dev',
      'wait',
      'open',
      'watch'
    ]);
  });

  grunt.registerTask('server', function () {
    grunt.log.warn('The `server` task has been deprecated. Use `grunt serve` to start a server.');
    grunt.task.run(['serve']);
  });

  grunt.registerTask('test', function(target, option) {
    if (target === 'server') {
      return grunt.task.run([
        'env:all',
        'env:test',
        'mochaTest:unit',
        'mochaTest:integration'
      ]);
    }

    else if (target === 'client') {
      return grunt.task.run([
        'clean:server',
        'env:all',
        'concurrent:pre',
        'concurrent:test',
        'injector',
        'postcss',
        'wiredep:test',
        'karma'
      ]);
    }

    else if (target === 'e2e') {

      if (option === 'prod') {
        return grunt.task.run([
          'build',
          'env:all',
          'env:prod',
          'express:prod',
          'protractor'
        ]);
      }

      else {
        return grunt.task.run([
          'clean:server',
          'env:all',
          'env:test',
          'concurrent:pre',
          'concurrent:test',
          'injector',
          'wiredep:client',
          'wiredep:clientAdmin',
          'postcss',
          'express:dev',
          'protractor'
        ]);
      }
    }

    else if (target === 'coverage') {

      if (option === 'unit') {
        return grunt.task.run([
          'env:all',
          'env:test',
          'mocha_istanbul:unit'
        ]);
      }

      else if (option === 'integration') {
        return grunt.task.run([
          'env:all',
          'env:test',
          'mocha_istanbul:integration'
        ]);
      }

      else if (option === 'check') {
        return grunt.task.run([
          'istanbul_check_coverage'
        ]);
      }

      else {
        return grunt.task.run([
          'env:all',
          'env:test',
          'mocha_istanbul',
          'istanbul_check_coverage'
        ]);
      }

    }

    else grunt.task.run([
      'test:server',
      'test:client'
    ]);
  });

  grunt.registerTask('build', [
    'clean:dist',
    'concurrent:pre',
    'concurrent:dist',
    'injector',
    'wiredep:client',
    'wiredep:clientAdmin',
    'useminPrepare',
    'postcss',
    'ngtemplates:main',
    'ngtemplates:clientAdmin',
    'concat',
    'ngAnnotate',
    'copy:dist',
    'babel:server',
    'cdnify',
    'cssmin',
    'uglify',
    'filerev',
    'usemin',
    'inline',
    'htmlmin',
    'realFavicon',
    'copy:screenshot'
  ]);

  grunt.registerTask('default', [
    'newer:jshint',
    'test',
    'build'
  ]);
};


text:
layout: post
microblog: true
audio:
date: 2017-12-05 19:13:22 -0600
guid: http://craigmcclellan.micro.blog/2017/12/06/turns-out-a.html
---
Turns out, a 3.5 and 2-year-old make getting a tree decorated way more difficult. It's finally up though!

<img src="http://craigmcclellan.com/uploads/2017/5b80a4587b.jpg" width="599" height="600" />


text:
CREATE TABLE taxi_zones (
  location_id UInt16,
  zone String,
  borough String
)
ENGINE = MergeTree
ORDER BY (location_id);

CREATE TABLE fhv_trips (
  hvfhs_license_num String,
  company String,
  dispatching_base_num Nullable(String),
  originating_base_num Nullable(String),
  request_datetime Nullable(DateTime('UTC')),
  on_scene_datetime Nullable(DateTime('UTC')),
  pickup_datetime DateTime('UTC'),
  dropoff_datetime DateTime('UTC'),
  pickup_location_id Nullable(UInt16),
  dropoff_location_id Nullable(UInt16),
  pickup_borough Nullable(String),
  dropoff_borough Nullable(String),
  trip_miles Nullable(Float64),
  trip_time Nullable(UInt32),
  base_passenger_fare Nullable(Float64),
  tolls Nullable(Float64),
  black_car_fund Nullable(Float64),
  sales_tax Nullable(Float64),
  congestion_surcharge Nullable(Float64),
  airport_fee Nullable(Float64),
  tips Nullable(Float64),
  driver_pay Nullable(Float64),
  shared_request Nullable(Bool),
  shared_match Nullable(Bool),
  access_a_ride Nullable(Bool),
  wav_request Nullable(Bool),
  wav_match Nullable(Bool),
  legacy_shared_ride Nullable(UInt16),
  filename String
)
ENGINE = MergeTree
ORDER BY (company, pickup_datetime);

CREATE TABLE taxi_trips (
  car_type String,
  vendor_id Nullable(UInt16),
  pickup_datetime DateTime('UTC'),
  dropoff_datetime DateTime('UTC'),
  pickup_location_id Nullable(UInt16),
  dropoff_location_id Nullable(UInt16),
  pickup_borough Nullable(String),
  dropoff_borough Nullable(String),
  passenger_count Nullable(UInt16),
  trip_distance Nullable(Float64),
  rate_code_id Nullable(UInt16),
  store_and_fwd_flag Nullable(Bool),
  payment_type Nullable(UInt16),
  fare_amount Nullable(Float64),
  extra Nullable(Float64),
  mta_tax Nullable(Float64),
  tip_amount Nullable(Float64),
  tolls_amount Nullable(Float64),
  improvement_surcharge Nullable(Float64),
  total_amount Nullable(Float64),
  congestion_surcharge Nullable(Float64),
  airport_fee Nullable(Float64),
  trip_type Nullable(UInt16),
  ehail_fee Nullable(Float64),
  filename String
)
ENGINE = MergeTree
ORDER BY (car_type, pickup_datetime);


text:
package com.example.android.render;

import com.android.ide.common.rendering.api.RenderSession;
import com.android.ide.common.rendering.api.Result;
import com.android.ide.common.rendering.api.ViewInfo;
import com.android.ide.common.resources.ResourceItem;
import com.android.ide.common.resources.ResourceRepository;
import com.android.ide.common.resources.ResourceResolver;
import com.android.ide.common.resources.configuration.FolderConfiguration;
import com.android.io.FolderWrapper;
import com.android.resources.Density;
import com.android.resources.Keyboard;
import com.android.resources.KeyboardState;
import com.android.resources.Navigation;
import com.android.resources.NavigationState;
import com.android.resources.ScreenOrientation;
import com.android.resources.ScreenRatio;
import com.android.resources.ScreenSize;
import com.android.resources.TouchScreen;

import org.xmlpull.v1.XmlPullParserException;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;

import javax.imageio.ImageIO;

/**
 * Sample code showing how to use the different API used to achieve a layout rendering.
 * This requires the following jar: layoutlib-api.jar, common.jar, sdk-common.jar, sdklib.jar (although
 * we should get rid of this one) and a full SDK (or at least the platform component).
 *
 */
public class Main {

    // path to the SDK and the project to render
    private final static String SDK = "...<insert>...";
    private final static String PROJECT = "...<insert>...";

    /**
     * @param args
     */
    public static void main(String[] args) {
        // load the factory for a given platform
        File f = new File(SDK + "/platforms/android-3.1");
        RenderServiceFactory factory = RenderServiceFactory.create(f);

        if (factory == null) {
            System.err.println("Failed to load platform rendering library");
            System.exit(1);
        }

        // load the project resources
        ResourceRepository projectRes = new ResourceRepository(false /*isFramework*/) {

            @Override
            protected ResourceItem createResourceItem(String name) {
                return new ResourceItem(name);
            }
        };
        try {
            projectRes.loadResources(new FolderWrapper(PROJECT + "/res"));
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(1);
        }

        // create the rendering config
        FolderConfiguration config = RenderServiceFactory.createConfig(
                1280, 800, // size 1 and 2. order doesn't matter.
                           // Orientation will drive which is w and h
                ScreenSize.XLARGE,
                ScreenRatio.LONG,
                ScreenOrientation.LANDSCAPE,
                Density.MEDIUM,
                TouchScreen.FINGER,
                KeyboardState.SOFT,
                Keyboard.QWERTY,
                NavigationState.EXPOSED,
                Navigation.NONAV,
                12); // api level

        // create the resource resolver once for the given config.
        ResourceResolver resources = factory.createResourceResolver(
                config, projectRes,
                "Theme", false /*isProjectTheme*/);

        // create the render service
        RenderService renderService = factory.createService(
                resources, config, new ProjectCallback());

        try {
            RenderSession session = renderService
                    .setLog(new StdOutLogger())
                    .setAppInfo("foo", "icon") // optional
                    .createRenderSession("main" /*layoutName*/);

            // get the status of the render
            Result result = session.getResult();
            if (result.isSuccess() == false) {
                System.err.println(result.getErrorMessage());
                System.exit(1);
            }

            // get the image and save it somewhere.
            BufferedImage image = session.getImage();
            ImageIO.write(image, "png", new File("/path/to/test.png"));

            // read the views
            displayViewObjects(session.getRootViews());

            return;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (XmlPullParserException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        System.exit(1);
    }

    private static void displayViewObjects(List<ViewInfo> rootViews) {
        for (ViewInfo info : rootViews) {
            displayView(info, "");
        }
    }

    private static void displayView(ViewInfo info, String indent) {
        // display info data
        System.out.println(indent + info.getClassName() +
                " [" + info.getLeft() + ", " + info.getTop() + ", " +
                info.getRight() + ", " + info.getBottom() + "]");

        // display the children
        List<ViewInfo> children = info.getChildren();
        if (children != null) {
            indent += "\t";
            for (ViewInfo child : children) {
                displayView(child, indent);
            }
        }
    }
}


text:
from twisted.internet.defer import inlineCallbacks, returnValue

from go.vumitools.opt_out import OptOutStore
from go.vumitools.contact import ContactStore, ContactError
from go.vumitools.handler import EventHandler

from vumi import log

from vxpolls.manager import PollManager

class SNAEventHandler(EventHandler):

    @inlineCallbacks
    def find_contact(self, account_key, msisdn):
        contact_store = ContactStore(
            self.dispatcher.vumi_api.manager, account_key)
        try:
            contact = yield contact_store.contact_for_addr('ussd', msisdn)
            returnValue(contact)
        except ContactError:
            returnValue(None)

class USSDOptOutHandler(SNAEventHandler):

    def setup_handler(self):
        self.pm_prefix = self.config['poll_manager_prefix']
        self.vumi_api = self.dispatcher.vumi_api
        self.pm = PollManager(self.vumi_api.redis, self.pm_prefix)

    def teardown_handler(self):
        self.pm.stop()

    @inlineCallbacks
    def handle_event(self, event, handler_config):
        """

        Expects the event 'content' to be a dict with the following keys
        and values:

        NOTE:   perhaps all we need here is the message_id and lookup the
                rest of the required data from the message in the message store

        :param from_addr:
            the from_addr of the user interaction that triggered the event
        :param message_id:
            the id of the message that triggered the event, used to keep an
            audit trail of opt-outs and which messages they were triggered by.
        :param transport_type:
            the transport_type that the message was received on.

        """
        account_key = event.payload['account_key']
        oo_store = OptOutStore(self.vumi_api.manager, account_key)

        event_data = event.payload['content']

        from_addr = event_data['from_addr']
        message_id = event_data['message_id']
        transport_type = event_data.get('transport_type')

        if transport_type != 'ussd':
            log.info("SNAUSSDOptOutHandler skipping non-ussd"
                     " message for %r" % (from_addr,))
            return
        contact = yield self.find_contact(account_key, from_addr)
        if contact:
            opted_out = contact.extra['opted_out']
            if opted_out is not None and opted_out.isdigit():
                if int(opted_out) > 1:
                    yield oo_store.new_opt_out('msisdn', from_addr, {
                        'message_id': message_id,
                    })
                else:
                    yield oo_store.delete_opt_out('msisdn', from_addr)

class USSDMenuCompletionHandler(SNAEventHandler):

    @inlineCallbacks
    def handle_event(self, event, handler_config):
        sms_copy = handler_config['sms_copy']
        conversation_key = handler_config['conversation_key']

        account_key = event['account_key']
        from_addr = event['content']['from_addr']

        user_api = self.get_user_api(account_key)
        contact = yield self.find_contact(account_key, from_addr)

        if not contact:
            log.msg('Unable to find contact for %s' % (from_addr,))
            return

        content = (sms_copy['swahili'] if contact.extra['language'] == '2'
                    else sms_copy['english'])

        conversation = yield user_api.get_wrapped_conversation(
                                                conversation_key)

        yield conversation.dispatch_command(
            'send_message', account_key, conversation.key,
            command_data={
                'batch_id': conversation.batch.key,
                'to_addr': from_addr,
                'content': content,
                'msg_options': {},
            }
        )


text:
package com.crazyhitty.chdev.ks.predator.core.settings;

import com.crazyhitty.chdev.ks.predator.core.BasePresenter;
import com.crazyhitty.chdev.ks.predator.core.BaseView;

/**
 * Author:      Kartik Sharma
 * Email Id:    cr42yh17m4n@gmail.com
 * Created:     1/16/2017 9:52 AM
 * Description: Unavailable
 */

public interface SettingsContract {
    interface View extends BaseView<Presenter> {
        void cacheCleared();

        void unableToWipeCache();
    }

    interface Presenter extends BasePresenter {
        void clearCache();
    }
}


text:
using System;
using System.Collections;
using System.ComponentModel;
using System.Diagnostics;
using System.Text.RegularExpressions;
using System.Xml.Serialization;

namespace TraceSpy
{
    public class Colorizer : DictionaryObject, IComparable, IComparable<Colorizer>
    {
        private Lazy<Regex> _regex;

        public Colorizer()
        {
            _regex = new Lazy<Regex>(GetRegex, true);
        }

        public Colorizer(string definition, bool ignoreCase)
            : this()
        {
            Definition = definition;
            IgnoreCase = ignoreCase;
        }

        public bool IsActive { get => DictionaryObjectGetPropertyValue(true); set => DictionaryObjectSetPropertyValue(value); }
        public bool IgnoreCase { get => DictionaryObjectGetPropertyValue(true); set => DictionaryObjectSetPropertyValue(value); }
        public string Definition { get => DictionaryObjectGetPropertyValue<string>(); set => DictionaryObjectSetPropertyValue(value); }

        [XmlIgnore]
        public Regex Regex => _regex.Value;

        protected override void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (e.PropertyName == nameof(IgnoreCase) || e.PropertyName == nameof(Definition))
            {
                _regex = new Lazy<Regex>(GetRegex, true);
            }
            base.OnPropertyChanged(sender, e);
        }

        private Regex GetRegex()
        {
            var options = RegexOptions.Compiled;
            if (IgnoreCase)
            {
                options |= RegexOptions.IgnoreCase;
            }

            try
            {
                return new Regex(Definition, options);
            }
            catch (Exception e)
            {
                App.AddTrace(TraceLevel.Error, "*** Error parsing colorizer '" + Definition + "' regular expression: " + e.Message + Environment.NewLine + "*** This message will only be shown once.");
                return null;
            }
        }

        public Colorizer Clone()
        {
            var clone = new Colorizer();
            CopyTo(clone);
            return clone;
        }

        protected override IEnumerable DictionaryObjectGetErrors(string propertyName)
        {
            if (propertyName == null || propertyName == nameof(Definition))
            {
                if (string.IsNullOrWhiteSpace(Definition))
                    yield return "Definition cannot be empty.";
            }
        }

        public override string ToString() => Definition + ":" + (IgnoreCase ? "I" : "C");
        int IComparable.CompareTo(object obj) => CompareTo(obj as Colorizer);
        public int CompareTo(Colorizer other)
        {
            if (other == null)
                throw new ArgumentNullException(nameof(other));

            return Definition.CompareTo(Definition);
        }
    }
}


text:
// logger
import * as Logger from '../log/Logger.js';
const logger = Logger.get();
const debug = Logger.debug;

// imports
import UnauthorizedAccessError from '../errors/UnauthorizedAccessError';
import {getRedisInfo} from '../init/config';

var util = require('util'),
    redis = require("redis"),
    client = redis.createClient({'host': getRedisInfo().tcpAddress}),
    _ = require("lodash"),
    config = require("../init/config.json"),
    jsonwebtoken = require("jsonwebtoken");

const TOKEN_EXPIRATION = 60, TOKEN_EXPIRATION_SEC = TOKEN_EXPIRATION * 60;

client.on('error', function (err) {
    logger.info(err);
});

client.on('connect', function () {
    logger.info("Redis successfully connected");
});

/**
 * Find the authorization headers from the headers in the request
 *
 * @param headers
 * @returns {*}
 */
module.exports.fetch = function (headers) {

    // TODO FINIRE QUI e vedere se committa la cartella del logger...
    debug('HTTP headers : ', headers);

    if (headers && headers.authorization) {
        var authorization = headers.authorization;
        debug('authorization %s', authorization);

        var part = authorization.split(' ');
        if (part.length === 2) {
            var token = part[1];
            return part[1];
        } else {
            return null;
        }
    } else {
        return null;
    }
};

/**
 * Creates a new token for the user that has been logged in
 *
 * @param user
 * @param req
 * @param res
 * @param next
 *
 * @returns {*}
 */
module.exports.create = function (user, req, res, next) {

    logger.debug("Create token");

    if (_.isEmpty(user)) {
        return next(new Error('User data cannot be empty.'));
    }

    var data = {
        _id: user._id,
        username: user.username,
        access: user.access,
        name: user.name,
        email: user.email,
        token: jsonwebtoken.sign({_id: user._id}, config.secret, {
            expiresIn: TOKEN_EXPIRATION_SEC
        })
    };

    var decoded = jsonwebtoken.decode(data.token);

    data.token_exp = decoded.exp;
    data.token_iat = decoded.iat;

    logger.debug("Token generated for user: %s, token: %s", data.username, data.token);

    client.set(data.token, JSON.stringify(data), function (err, reply) {
        if (err) {
            return next(new Error(err));
        }

        if (reply) {
            client.expire(data.token, TOKEN_EXPIRATION_SEC, function (err, reply) {
                if (err) {
                    return next(new Error("Can not set the expire value for the token key"));
                }
                if (reply) {
                    req.user = data;
                    next(); // we have succeeded
                } else {
                    return next(new Error('Expiration not set on redis'));
                }
            });
        }
        else {
            return next(new Error('Token not set in redis'));
        }
    });

    return data;

};

/**
 * Fetch the token from redis for the given key
 *
 * @param id
 * @param done
 * @returns {*}
 */
module.exports.retrieve = function (id, done) {

    logger.debug("Calling retrieve for token: %s", id);

    if (_.isNull(id)) {
        return done(new Error("token_invalid"), {
            "message": "Invalid token"
        });
    }

    client.get(id, function (err, reply) {
        if (err) {
            return done(err, {
                "message": err
            });
        }

        if (_.isNull(reply)) {
            return done(new Error("token_invalid"), {
                "message": "Token doesn't exists, are you sure it hasn't expired or been revoked?"
            });
        } else {
            var data = JSON.parse(reply);
            logger.debug("User data fetched from redis store for user: %s", data.username);

            if (_.isEqual(data.token, id)) {
                return done(null, data);
            } else {
                return done(new Error("token_doesnt_exist"), {
                    "message": "Token doesn't exists, login into the system so it can generate new token."
                });
            }

        }

    });

};

/**
 * Verifies that the token supplied in the request is valid, by checking the redis store to see if it's stored there.
 *
 * @param req
 * @param res
 * @param next
 */
module.exports.verify = function (req, res, next) {

    logger.debug("Verifying token");

    var token = exports.fetch(req.headers);

    jsonwebtoken.verify(token, config.secret, function (err, decode) {

        if (err) {
            req.user = undefined;
            return next(new UnauthorizedAccessError("invalid_token"));
        }

        exports.retrieve(token, function (err, data) {

            if (err) {
                req.user = undefined;
                return next(new UnauthorizedAccessError("invalid_token", data));
            }

            req.user = data;
            next();

        });

    });
};

/**
 * Expires the token, so the user can no longer gain access to the system, without logging in again or requesting new token
 *
 * @param headers
 * @returns {boolean}
 */
module.exports.expire = function (headers) {

    var token = exports.fetch(headers);
    logger.info('Expiring token: ' + token);

    if (token !== null) {
        logger.info('Expires token on Redis');
        client.expire(token, 0);
    }

    return token !== null;

};

/**
 * Middleware for getting the token into the user
 *
 * @param req
 * @param res
 * @param next
 */
module.exports.middleware = function () {

    var func = function (req, res, next) {

        logger.debug('middleware for token');
        var token = exports.fetch(req.headers);

        exports.retrieve(token, function (err, data) {

            if (err) {
                req.user = undefined;
                return next(new UnauthorizedAccessError("invalid_token", data));
            } else {
                req.user = _.merge(req.user, data);
                next();
            }

        });
    };

    func.unless = require("express-unless");

    return func;

};

module.exports.TOKEN_EXPIRATION = TOKEN_EXPIRATION;
module.exports.TOKEN_EXPIRATION_SEC = TOKEN_EXPIRATION_SEC;


text:
package org.meteogroup.pointcompression;

import org.testng.annotations.Test;

import java.util.List;

import static org.assertj.core.api.Assertions.assertThat;

public class PointCompressionTest extends BasePointTest {

  @Test(dataProvider = "arrayOfPoints")
  public void testCorrectCompressionOfPointsToString(List<Point> points, String compressedValue) throws Exception {
    String encodedPoints = new PointCompression().compressAsString(points);
    assertThat(encodedPoints).isEqualTo(compressedValue);
  }

}


text:
package com.alachisoft.tayzgrid.runtime.datasourceprovider;

/**
 Used to log the operations type in Write behind
*/
public enum WriteOperationType
{
	Add,
	Update,
	Delete;

	public int getValue()
	{
		return this.ordinal();
	}

	public static WriteOperationType forValue(int value)
	{
		return values()[value];
	}
}


text:
using System;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore.Migrations;

namespace Dsa.RapidResponse.Migrations
{
    public partial class user_events : Migration
    {
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.DropColumn(
                name: "Discriminator",
                table: "AspNetUsers");

            migrationBuilder.CreateTable(
                name: "EventUser",
                columns: table => new
                {
                    EventId = table.Column<int>(nullable: false),
                    UserId = table.Column<string>(nullable: false)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_EventUser", x => new { x.EventId, x.UserId });
                    table.ForeignKey(
                        name: "FK_EventUser_Events_EventId",
                        column: x => x.EventId,
                        principalTable: "Events",
                        principalColumn: "Id",
                        onDelete: ReferentialAction.Cascade);
                    table.ForeignKey(
                        name: "FK_EventUser_AspNetUsers_UserId",
                        column: x => x.UserId,
                        principalTable: "AspNetUsers",
                        principalColumn: "Id",
                        onDelete: ReferentialAction.Cascade);
                });

            migrationBuilder.CreateIndex(
                name: "IX_EventUser_UserId",
                table: "EventUser",
                column: "UserId");
        }

        protected override void Down(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.DropTable(
                name: "EventUser");

            migrationBuilder.AddColumn<string>(
                name: "Discriminator",
                table: "AspNetUsers",
                nullable: false,
                defaultValue: "");
        }
    }
}


text:
package service

import (
	"global"
	"logger"
	"model"
	"net/url"
	"strconv"
	"strings"
	"util"
)

func FindRolesByPage(conds map[string]string, curPage, limit int) ([]*model.Role, int) {
	conditions := make([]string, 0, len(conds))
	for k, v := range conds {
		conditions = append(conditions, k+"="+v)
	}

	role := model.NewRole()

	limitStr := strconv.Itoa((curPage-1)*limit) + "," + strconv.Itoa(limit)
	roles, err := role.Where(strings.Join(conditions, " AND ")).Limit(limitStr).
		FindAll()
	if err != nil {
		return nil, 0
	}

	total, err := role.Count()
	if err != nil {
		return nil, 0
	}

	return roles, total
}

func FindRole(roleid string) *model.Role {
	if roleid == "" {
		return nil
	}

	role := model.NewRole()
	err := role.Where("roleid=" + roleid).Find()
	if err != nil {
		logger.Errorln("role FindRole error:", err)
		return nil
	}

	return role
}

func SaveRole(form url.Values, opUser string) (errMsg string, err error) {

	role := model.NewRole()
	role.Name = form.Get("name")
	role.OpUser = opUser

	roleid := form.Get("roleid")
	isNew := roleid == ""
	if isNew {
		role.Ctime = util.TimeNow()

		_, err = role.Insert()
	} else {
		role.Roleid, err = strconv.Atoi(roleid)
		if err != nil {
			errMsg = "roleid invalid"
			logger.Errorln(errMsg, ":", err)
			return
		}
		err = role.Persist(role)
	}

	if err != nil {
		errMsg = "内部服务器错误"
		logger.Errorln(errMsg, ":", err)
		return
	}

	roleAuth := model.NewRoleAuthority()
	if !isNew {
		// 如果是更新角色,将之前的角色权限都删除
		roleAuth.Where("roleid=" + strconv.Itoa(role.Roleid)).Delete()
	}

	roleAuth.Roleid = role.Roleid
	roleAuth.OpUser = opUser

	// 增加角色拥有的权限
	for _, aid := range form["authorities[]"] {
		aid, err := strconv.Atoi(aid)
		if err != nil {
			continue
		}
		roleAuth.Aid = aid

		roleAuth.Insert()
	}

	global.RoleChan <- struct{}{}
	global.RoleAuthChan <- struct{}{}

	return
}

func DelRole(roleid string) error {
	err := model.NewRole().Where("roleid=" + roleid).Delete()
	model.NewRoleAuthority().Where("roleid=" + roleid).Delete()

	global.RoleChan <- struct{}{}
	global.RoleAuthChan <- struct{}{}

	return err
}


text:
/* ========================================================================
 * DOM-based Routing
 * Based on http://goo.gl/EUTi53 by Paul Irish
 *
 * Only fires on body classes that match. If a body class contains a dash,
 * replace the dash with an underscore when adding it to the object below.
 *
 * .noConflict()
 * The routing is enclosed within an anonymous function so that you can
 * always reference jQuery with $, even when in .noConflict() mode.
 * ======================================================================== */

(function($) {

  // Use this variable to set up the common and page specific functions. If you
  // rename this variable, you will also need to rename the namespace below.
  var Sage = {
    // All pages
    'common': {
      init: function() {
        // JavaScript to be fired on all pages

        // When the document is ready, remove preloader
        $(document).ready(function($) {

          $('body').addClass('pageloaded');

          // site preloader -- also uncomment the div in the header and the css style for #preloader
          $(window).load(function(){
            $('#spinner-wrapper').fadeOut(1000,function(){$(this).remove();});
          });

        });

      },
      finalize: function() {
        // JavaScript to be fired on all pages, after page specific JS is fired
      }
    },
    // Single pages
    'single': {
      init: function() {
        // JavaScript to be fired on Single pages

        $('.image-slider').slick({
          speed: 500,
          autoplay: true,
          autoplaySpeed: 5000,
          infinite: true,
          fade: true,
          cssEase: 'linear'
        });

      },
      finalize: function() {
        // JavaScript to be fired on Single pages, after the init JS
      }
    },
    // Home page
    'home': {
      init: function() {
        // JavaScript to be fired on the home page
      },
      finalize: function() {
        // JavaScript to be fired on the home page, after the init JS
      }
    },
    // About us page, note the change from about-us to about_us.
    'about_us': {
      init: function() {
        // JavaScript to be fired on the about us page
      }
    }
  };

  // The routing fires all common scripts, followed by the page specific scripts.
  // Add additional events for more control over timing e.g. a finalize event
  var UTIL = {
    fire: function(func, funcname, args) {
      var fire;
      var namespace = Sage;
      funcname = (funcname === undefined) ? 'init' : funcname;
      fire = func !== '';
      fire = fire && namespace[func];
      fire = fire && typeof namespace[func][funcname] === 'function';

      if (fire) {
        namespace[func][funcname](args);
      }
    },
    loadEvents: function() {
      // Fire common init JS
      UTIL.fire('common');

      // Fire page-specific init JS, and then finalize JS
      $.each(document.body.className.replace(/-/g, '_').split(/\s+/), function(i, classnm) {
        UTIL.fire(classnm);
        UTIL.fire(classnm, 'finalize');
      });

      // Fire common finalize JS
      UTIL.fire('common', 'finalize');
    }
  };

  // Load Events
  $(document).ready(UTIL.loadEvents);

})(jQuery); // Fully reference jQuery after this point.


text:
package com.cloud.legacymodel.communication.command;

import java.util.Map;

public final class SnapshotAndCopyCommand extends StorageSubSystemCommand {
    private final String _uuidOfSourceVdi;
    private final Map<String, String> _sourceDetails;
    private final Map<String, String> _destDetails;

    private boolean _executeInSequence = true;

    public SnapshotAndCopyCommand(final String uuidOfSourceVdi, final Map<String, String> sourceDetails, final Map<String, String> destDetails) {
        _uuidOfSourceVdi = uuidOfSourceVdi;
        _sourceDetails = sourceDetails;
        _destDetails = destDetails;
    }

    public String getUuidOfSourceVdi() {
        return _uuidOfSourceVdi;
    }

    public Map<String, String> getSourceDetails() {
        return _sourceDetails;
    }

    public Map<String, String> getDestDetails() {
        return _destDetails;
    }

    @Override
    public void setExecuteInSequence(final boolean executeInSequence) {
        _executeInSequence = executeInSequence;
    }

    @Override
    public boolean executeInSequence() {
        return _executeInSequence;
    }
}


text:
#ifndef TENSORFLOW_LITE_KERNELS_INTERNAL_REFERENCE_NEG_H_
#define TENSORFLOW_LITE_KERNELS_INTERNAL_REFERENCE_NEG_H_

#include "tensorflow/lite/kernels/internal/types.h"

namespace tflite {

namespace reference_ops {

template <typename T>
inline void Negate(const RuntimeShape& input_shape, const T* input_data,
                   const RuntimeShape& output_shape, T* output_data) {
  const int flat_size = MatchingFlatSize(input_shape, output_shape);

  for (int i = 0; i < flat_size; ++i) {
    output_data[i] = -input_data[i];
  }
}

}  // namespace reference_ops
}  // namespace tflite

#endif  // TENSORFLOW_LITE_KERNELS_INTERNAL_REFERENCE_NEG_H_


text:
namespace Crux
{

TCPServer::TCPServer()
{
#ifdef WIN32
	m_pExternalAcceptHandler = new AcceptHandler(
		ACCEPT_EXTERNAL,
		s_Config.GetIP(),
		s_Config.GetPort(),
		s_Config.GetListenBacklog()
		);
#elif defined(LINUX)
	m_pExternalAcceptCompleteOperation = new AcceptCompleteOperation(
		ACCEPT_EXTERNAL,
		s_Config.GetIP(),
		s_Config.GetPort(),
		s_Config.GetListenBacklog()
		);
#endif
}

TCPServer::~TCPServer()
{
#ifdef WIN32
	delete m_pExternalAcceptHandler;
#elif defined(LINUX)
	delete m_pExternalAcceptCompleteOperation;
#endif
}

void TCPServer::Shutdown()
{
	TCPStream::Shutdown();
}

} //namespace Crux


text:
/**
 * @author      Yongnan
 * @version     1.0
 * @time        9/27/2014
 * @name        PathBubble_navInteraction
 */
var $P = PATHBUBBLES;

$P.NavCanvas = $P.defineClass(
	$P.Canvas,
	function (config) {
		$P.Canvas.call(this, config);
		this.state = 'default';
		this.viewbox = new $P.NavViewBox($P.state.mainCanvas, this);
		var self = this;
		$(function() {self.onResize();});
	}, {
		onResize: function() {
			$P.Canvas.prototype.onResize.call(this);
			this.html.width = window.innerWidth;
			this.scale = this.getHeight() / $P.state.mainCanvas.getHeight();
			this.viewbox.updatePosition();},
		mousedown: function(event, x, y) {
			if ('default' !== this.state) {return;}
			if (this.viewbox.contains(x / this.scale, y / this.scale)) {
				this.state = 'dragview';
				this.setCursor('move');
				this.useMouseupGlobally();
				this.useMousemoveGlobally();
				this.lastX = x;
				this.lastY = y;}},
		mousemove: function(event, x, y) {
			if ('dragview' !== this.state) {return;}
			this.scrollTo($P.state.scrollX + (x - this.lastX) / this.scale);
			this.lastX = x;},
		scrollTo: function(x) {
			$P.state.scrollX = x;
			if ($P.state.scrollX < 0) {$P.state.scrollX = 0;}
			this.viewbox.updatePosition();
			$P.state.markDirty();},
		mouseup: function(event, x, y) {
			if ('dragview' !== this.state) {return;}
			this.state = 'default';
			this.setCursor('auto');
			$P.state.setGlobalMouseup(null);
			$P.state.setGlobalMousemove(null);
			this.viewbox.updatePosition();},
		draw: function() {
			$P.Canvas.prototype.draw.call(this);
			this.viewbox.draw(this.context, this.scale);
		}
	});


text:
Visit [johnynogueira.github.io](http://johnynogueira.github.io)

## License

[MIT](http://opensource.org/licenses/MIT)


text:
using System.Collections.Generic;
//using System.Xml;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Services.Search;

namespace DNN.Modules.MailingList.Components
{

    /// -----------------------------------------------------------------------------
    /// <summary>
    /// The Controller class for MailingList
    ///
    /// The FeatureController class is defined as the BusinessController in the manifest file (.dnn)
    /// DotNetNuke will poll this class to find out which Interfaces the class implements.
    ///
    /// The IPortable interface is used to import/export content from a DNN module
    ///
    /// The ISearchable interface is used by DNN to index the content of a module
    ///
    /// The IUpgradeable interface allows module developers to execute code during the upgrade
    /// process for a module.
    ///
    /// Below you will find stubbed out implementations of each, uncomment and populate with your own data
    /// </summary>
    /// -----------------------------------------------------------------------------

    //uncomment the interfaces to add the support.
    public class FeatureController //: IPortable, ISearchable, IUpgradeable
    {

        #region Optional Interfaces

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// ExportModule implements the IPortable ExportModule Interface
        /// </summary>
        /// <param name="ModuleID">The Id of the module to be exported</param>
        /// -----------------------------------------------------------------------------
        //public string ExportModule(int ModuleID)
        //{
        //string strXML = "";

        //List<MailingListInfo> colMailingLists = GetMailingLists(ModuleID);
        //if (colMailingLists.Count != 0)
        //{
        //    strXML += "<MailingLists>";

        //    foreach (MailingListInfo objMailingList in colMailingLists)
        //    {
        //        strXML += "<MailingList>";
        //        strXML += "<content>" + DotNetNuke.Common.Utilities.XmlUtils.XMLEncode(objMailingList.Content) + "</content>";
        //        strXML += "</MailingList>";
        //    }
        //    strXML += "</MailingLists>";
        //}

        //return strXML;

        //	throw new System.NotImplementedException("The method or operation is not implemented.");
        //}

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// ImportModule implements the IPortable ImportModule Interface
        /// </summary>
        /// <param name="ModuleID">The Id of the module to be imported</param>
        /// <param name="Content">The content to be imported</param>
        /// <param name="Version">The version of the module to be imported</param>
        /// <param name="UserId">The Id of the user performing the import</param>
        /// -----------------------------------------------------------------------------
        //public void ImportModule(int ModuleID, string Content, string Version, int UserID)
        //{
        //XmlNode xmlMailingLists = DotNetNuke.Common.Globals.GetContent(Content, "MailingLists");
        //foreach (XmlNode xmlMailingList in xmlMailingLists.SelectNodes("MailingList"))
        //{
        //    MailingListInfo objMailingList = new MailingListInfo();
        //    objMailingList.ModuleId = ModuleID;
        //    objMailingList.Content = xmlMailingList.SelectSingleNode("content").InnerText;
        //    objMailingList.CreatedByUser = UserID;
        //    AddMailingList(objMailingList);
        //}

        //	throw new System.NotImplementedException("The method or operation is not implemented.");
        //}

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// GetSearchItems implements the ISearchable Interface
        /// </summary>
        /// <param name="ModInfo">The ModuleInfo for the module to be Indexed</param>
        /// -----------------------------------------------------------------------------
        //public DotNetNuke.Services.Search.SearchItemInfoCollection GetSearchItems(DotNetNuke.Entities.Modules.ModuleInfo ModInfo)
        //{
        //SearchItemInfoCollection SearchItemCollection = new SearchItemInfoCollection();

        //List<MailingListInfo> colMailingLists = GetMailingLists(ModInfo.ModuleID);

        //foreach (MailingListInfo objMailingList in colMailingLists)
        //{
        //    SearchItemInfo SearchItem = new SearchItemInfo(ModInfo.ModuleTitle, objMailingList.Content, objMailingList.CreatedByUser, objMailingList.CreatedDate, ModInfo.ModuleID, objMailingList.ItemId.ToString(), objMailingList.Content, "ItemId=" + objMailingList.ItemId.ToString());
        //    SearchItemCollection.Add(SearchItem);
        //}

        //return SearchItemCollection;

        //	throw new System.NotImplementedException("The method or operation is not implemented.");
        //}

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// UpgradeModule implements the IUpgradeable Interface
        /// </summary>
        /// <param name="Version">The current version of the module</param>
        /// -----------------------------------------------------------------------------
        //public string UpgradeModule(string Version)
        //{
        //	throw new System.NotImplementedException("The method or operation is not implemented.");
        //}

        #endregion

    }

}


text:
<?php

namespace AppBundle\Entity\Repository;

use Doctrine\ORM\EntityRepository;

/**
 * CityRepository
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class CityRepository extends EntityRepository {

    /**
     * Get all Cities
     * @return array
     */
    public function getAll() {
        $qb = $this->createQueryBuilder('ci')
            ->select('ci, sr, co, r')
            ->leftJoin('ci.subregion', 'sr')
            ->innerJoin('ci.region', 'r')
            ->innerJoin('r.country', 'co');

        return $qb->getQuery()->getResult();
    }

    public function getAllFast() {
        $qb = $this->createQueryBuilder('ci')
            ->select('ci, sr, co, r')
            ->leftJoin('ci.subregion', 'sr')
            ->innerJoin('ci.region', 'r')
            ->innerJoin('r.country', 'co')
            ->setMaxResults(5000);

        return $qb->getQuery()->getArrayResult();
    }

    public function getByEn($en) {
        $qb = $this->createQueryBuilder('c')
            ->select('c')
            ->where('c.en = :en')
            ->setParameter('en', $en);

        return (count($qb->getQuery()->getResult()) == 0) ? false : $qb->getQuery()->getSingleResult();
    }

    /**
     * Get cities by subregionId
     * @param $subregionId
     * @return array
     */
    public function getBySubregion($subregionId) {
        $qb = $this->createQueryBuilder('c')
            ->select('c')
            ->where('c.subregion = :subregionId')
            ->setParameter('subregionId', $subregionId);
        return $qb->getQuery()->getResult();
    }

    /**
     * Get cities by regionId
     * @param $subregionId
     * @return array
     */
    public function getByRegion($regionId) {
        $qb = $this->createQueryBuilder('c')
            ->select('c')
            ->where('c.region = :regionId')
            ->setParameter('regionId', $regionId);
        return $qb->getQuery()->getResult();
    }

    /**
     * Search autocomplete by string
     * @param $string
     * @return array
     */
    public function searchCityByString($string) {
        $qb = $this->createQueryBuilder('c')
            ->select('c')
            ->where('c.en like :string')
            ->orWhere('c.hr like :string')
            ->orWhere('c.de like :string')
            ->orWhere('c.it like :string')
            ->orWhere('c.es like :string')
            ->orWhere('c.fr like :string')
            ->orWhere('c.cs like :string')
            ->orWhere('c.sl like :string')
            ->orWhere('c.pl like :string')
            ->orWhere('c.hu like :string')
            ->orWhere('c.ru like :string')
            ->orWhere('c.pt like :string')
            ->orWhere('c.nl like :string')
            ->orWhere('c.da like :string')
            ->orWhere('c.sv like :string')
            ->orWhere('c.sk like :string')
            ->orWhere('c.no like :string')
            ->orWhere('c.fi like :string')
            ->orWhere('c.ca like :string')
            ->orWhere('c.sr like :string')
            ->orWhere('c.mk like :string')
            ->orWhere('c.bs like :string')
            ->orWhere('c.tr like :string')
            ->orWhere('c.ja like :string')
            ->orWhere('c.zh like :string')
            ->setParameter('string', '%' . $string . '%')
            ->setMaxResults(20);

        return $qb->getQuery()->getResult();
    }

}


text:
ActiveAdmin.register Comment do
  belongs_to :post
  navigation_menu :post

  index do
    selectable_column
    column :user
    column :content
    column :created_at
    default_actions
  end

end


text:
package bheap

type heapTree struct {
	siblings *heapTree
	child    *heapTree
	degree   int
	data     interface{}
}

// Heap is a binomial-heap.
type Heap struct {
	list *heapTree
	size int
	less LessFunc
}

// New returns an initialized heap.
func New(less LessFunc) *Heap {
	return &Heap{
		list: nil,
		size: 0,
		less: less,
	}
}

// IsEmpty returns true if h is empty, otherwise false.
func (h *Heap) IsEmpty() bool {
	return h.size == 0
}

// Len returns the number of elements in h.
func (h *Heap) Len() int {
	return h.size
}

// Clean cleans a heap and sets it to initial state.
func (h *Heap) Clean() *Heap {
	h.size = 0
	h.list = nil
	return h
}

// Merge merges x into h. Note that x is not preserved.
func (h *Heap) Merge(x *Heap) *Heap {
	if x == nil {
		return h
	}
	h.list = h.merge(h.list, x.list)
	h.size += x.size
	return h
}

// merge is the core function of this data structure.
func (h *Heap) merge(x, y *heapTree) *heapTree {
	if x == nil {
		return y
	}
	if y == nil {
		return x
	}

	if x.degree > y.degree {
		y = h.merge(x.siblings, y)
		x.siblings = nil
		if y.degree < x.degree {
			x.siblings = y
			return x
		}
	}
	if x.degree == y.degree {
		rest := h.merge(x.siblings, y.siblings)
		if h.less(x.data, y.data) {
			x, y = y, x
		}
		y.siblings = x.child
		x.child = y
		x.degree++
		x.siblings = rest
		return x
	}
	return h.merge(y, x)
}

// Pop returns the element that has the highest priority and a boolean value
// which indicates whether the heap is not empty.
func (h *Heap) Pop() (v interface{}, ok bool) {
	if h.size == 0 {
		return
	}

	highest := h.list
	ptrToHighest := &h.list
	pos := h.list.siblings
	prev := &h.list.siblings

	for {
		if pos == nil {
			break
		}
		if h.less(highest.data, pos.data) {
			highest = pos
			ptrToHighest = prev
		}
		prev = &pos.siblings
		pos = pos.siblings
	}

	*ptrToHighest = highest.siblings
	h.list = h.merge(h.list, highest.child)
	h.size--
	return highest.data, true
}

// Top returns the element that has the highest priority.
func (h *Heap) Top() (v interface{}, ok bool) {
	if h.size == 0 {
		return
	}

	highest := h.list
	pos := h.list.siblings

	for {
		if pos == nil {
			break
		}
		if h.less(highest.data, pos.data) {
			highest = pos
		}
		pos = pos.siblings
	}

	return highest.data, true
}

// Push inserts x into h.
func (h *Heap) Push(x interface{}) {
	t := newTree(x)
	h.list = h.merge(h.list, t)
	h.size++
}

// helper function
func newTree(x interface{}) *heapTree {
	return &heapTree{
		degree:   0,
		data:     x,
		siblings: nil,
		child:    nil,
	}
}


text:
angular.module('trackit.tasks.controller', [
  'trackit.tasks.service'
])
.controller('TasksCtrl', [
  '$scope',
  '$state',
  '$stateParams',
  'categoriesService',
  'tasksService',
  function (
    $scope,
    $state,
    $stateParams,
    categoriesService,
    tasksService
  ) {

    var categoryId = $stateParams.categoryId;
    $scope.task = {};

    categoriesService.getOne(categoryId).then(function(category) {
      $scope.category = category;
    });

    tasksService.getAll(categoryId).then(function(tasks) {
      $scope.tasks = tasks;
    });

    $scope.gotoCategories = function () {
      $state.go('categories', {categoryId: categoryId});
    };

    $scope.createTask = function () {
      tasksService.create({
        name: $scope.task.name,
        image: $scope.task.image,
        categoryId: categoryId
      }).then(function(task) {
        $scope.task.name = '';
        $scope.task.image = '';
      });
    };

    $scope.edit = function () {
      $state.go('categories.edit', {categoryId: categoryId});
    };

    $scope.gotoAddTaskState = function () {
      $state.go('categories.tasks.add', {categoryId: categoryId});
    };

    $scope.destroyCategory = function () {
      var yes = confirm('are you sure you want to delete this category?');
      if (!yes) return;
      categoriesService.destroy(categoryId).then(function () {
        $state.go('categories');
      });
    };

    $scope.taskClicked = function (task) {
      console.log(task);
      $state.go('categories.tasks.entries', {taskId: task.id});
    };

    return this
  }
]);


text:
asus-download-master-jdk
========================

ASUS Download Master JS API


text:
namespace rx
{

IndexBuffer9::IndexBuffer9(Renderer9 *const renderer) : mRenderer(renderer)
{
    mIndexBuffer = nullptr;
    mBufferSize = 0;
    mIndexType = 0;
    mDynamic = false;
}

IndexBuffer9::~IndexBuffer9()
{
    SafeRelease(mIndexBuffer);
}

gl::Error IndexBuffer9::initialize(unsigned int bufferSize, GLenum indexType, bool dynamic)
{
    SafeRelease(mIndexBuffer);

    updateSerial();

    if (bufferSize > 0)
    {
        D3DFORMAT format = D3DFMT_UNKNOWN;
        if (indexType == GL_UNSIGNED_SHORT || indexType == GL_UNSIGNED_BYTE)
        {
            format = D3DFMT_INDEX16;
        }
        else if (indexType == GL_UNSIGNED_INT)
        {
            ASSERT(mRenderer->getNativeExtensions().elementIndexUint);
            format = D3DFMT_INDEX32;
        }
        else UNREACHABLE();

        DWORD usageFlags = D3DUSAGE_WRITEONLY;
        if (dynamic)
        {
            usageFlags |= D3DUSAGE_DYNAMIC;
        }

        HRESULT result = mRenderer->createIndexBuffer(bufferSize, usageFlags, format, &mIndexBuffer);
        if (FAILED(result))
        {
            return gl::OutOfMemory()
                   << "Failed to allocate internal index buffer of size " << bufferSize;
        }
    }

    mBufferSize = bufferSize;
    mIndexType = indexType;
    mDynamic = dynamic;

    return gl::NoError();
}

gl::Error IndexBuffer9::mapBuffer(unsigned int offset, unsigned int size, void** outMappedMemory)
{
    if (!mIndexBuffer)
    {
        return gl::OutOfMemory() << "Internal index buffer is not initialized.";
    }

    DWORD lockFlags = mDynamic ? D3DLOCK_NOOVERWRITE : 0;

    void *mapPtr   = nullptr;
    HRESULT result = mIndexBuffer->Lock(offset, size, &mapPtr, lockFlags);
    if (FAILED(result))
    {
        return gl::OutOfMemory() << "Failed to lock internal index buffer, " << gl::FmtHR(result);
    }

    *outMappedMemory = mapPtr;
    return gl::NoError();
}

gl::Error IndexBuffer9::unmapBuffer()
{
    if (!mIndexBuffer)
    {
        return gl::OutOfMemory() << "Internal index buffer is not initialized.";
    }

    HRESULT result = mIndexBuffer->Unlock();
    if (FAILED(result))
    {
        return gl::OutOfMemory() << "Failed to unlock internal index buffer, " << gl::FmtHR(result);
    }

    return gl::NoError();
}

GLenum IndexBuffer9::getIndexType() const
{
    return mIndexType;
}

unsigned int IndexBuffer9::getBufferSize() const
{
    return mBufferSize;
}

gl::Error IndexBuffer9::setSize(unsigned int bufferSize, GLenum indexType)
{
    if (bufferSize > mBufferSize || indexType != mIndexType)
    {
        return initialize(bufferSize, indexType, mDynamic);
    }
    else
    {
        return gl::NoError();
    }
}

gl::Error IndexBuffer9::discard()
{
    if (!mIndexBuffer)
    {
        return gl::OutOfMemory() << "Internal index buffer is not initialized.";
    }

    void *dummy;
    HRESULT result;

    result = mIndexBuffer->Lock(0, 1, &dummy, D3DLOCK_DISCARD);
    if (FAILED(result))
    {
        return gl::OutOfMemory() << "Failed to lock internal index buffer, " << gl::FmtHR(result);
    }

    result = mIndexBuffer->Unlock();
    if (FAILED(result))
    {
        return gl::OutOfMemory() << "Failed to unlock internal index buffer, " << gl::FmtHR(result);
    }

    return gl::NoError();
}

D3DFORMAT IndexBuffer9::getIndexFormat() const
{
    switch (mIndexType)
    {
      case GL_UNSIGNED_BYTE:    return D3DFMT_INDEX16;
      case GL_UNSIGNED_SHORT:   return D3DFMT_INDEX16;
      case GL_UNSIGNED_INT:     return D3DFMT_INDEX32;
      default: UNREACHABLE();   return D3DFMT_UNKNOWN;
    }
}

IDirect3DIndexBuffer9 * IndexBuffer9::getBuffer() const
{
    return mIndexBuffer;
}

}


text:
//
//  HPAccount.m
//  HiPDA
//
//  Created by wujichao on 13-11-11.
//  Copyright (c) 2013年 wujichao. All rights reserved.
//

#import "HPCommon.h"
#import "HPAccount.h"
#import "HPHttpClient.h"
#import "HPSetting.h"
#import "HPTheme.h"
#import "RegExCategories.h"
#import "HPMessage.h"
#import "HPAccountPassword.h"

#import "HPRearViewController.h"

#import "NSString+Additions.h"
#import "AFHTTPRequestOperation.h"
#import "NSHTTPCookieStorage+info.h"

#import "HPLoginViewController.h"

#import <AudioToolbox/AudioToolbox.h>

@interface HPAccount ()

@property (nonatomic, strong) NSTimer *checkTimer;
@property (nonatomic, strong) HPHttpClient *checkPmClient;

@end

@implementation HPAccount

+ (HPAccount *)sharedHPAccount {
    static HPAccount *_sharedHPAccount = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedHPAccount = [[HPAccount alloc] init];
        _sharedHPAccount.checkPmClient = [[HPHttpClient alloc] initWithBaseURL:[NSURL URLWithString:HP_BASE_URL]];
    });

    return _sharedHPAccount;
}

+ (BOOL)isSetAccount {
    NSString *username = [NSStandardUserDefaults stringForKey:kHPAccountUserName or:@""];

    return [username length] && [HPAccountPassword isSetAccountFor:username];
}

+ (BOOL)isAccountForReviewer
{
    NSString *username = [NSStandardUserDefaults stringForKey:kHPAccountUserName or:@""];
    return [username isEqualToString:@"wujichao"];
}

+ (BOOL)isMasterAccount
{
    NSString *username = [NSStandardUserDefaults stringForKey:kHPAccountUserName or:@""];
    return [username isEqualToString:@"geka"];
}

- (void)loginWithBlock:(void (^)(BOOL isLogin, NSError *error))block {
    [self _loginWithBlock:^(BOOL isLogin, NSError *error) {

        if (block) {
            block(isLogin, error);
        }

        if (isLogin) {
            [[NSNotificationCenter defaultCenter] postNotificationName:kHPUserLoginSuccess object:nil];
        } else {
            if (error.code != kHPNoAccountCode) {
                [[NSNotificationCenter defaultCenter] postNotificationName:kHPUserLoginError object:nil userInfo:@{@"error":error}];
            }
        }
    }];
}

- (void)_loginWithBlock:(void (^)(BOOL isLogin, NSError *error))block {

    // acquire account info
    if (![HPAccount isSetAccount]) {
        HPLoginViewController *loginvc = [[HPLoginViewController alloc] init];
        UINavigationController *nvc = [HPCommon NVCWithRootVC:loginvc];
        nvc.modalPresentationStyle = UIModalPresentationFullScreen;
        [[[[UIApplication sharedApplication] keyWindow] rootViewController] presentViewController:nvc animated:YES completion:nil];
        block(NO, [NSError errorWithDomain:@".hi-pda.com" code:kHPNoAccountCode userInfo:nil]);
        return;
    }

    DDLogInfo(@"login step1");
    [[HPHttpClient sharedClient] getPath:@"forum/logging.php?action=login" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSString *src = [HPHttpClient GBKresponse2String:responseObject];

        if ([src indexOf:@"欢迎您回来"] != -1) {
            if (block) {
                block(YES, nil);
            }
            return;
        }

        NSString *formhash = [src stringBetweenString:@"formhash\" value=\"" andString:@"\""];
        if (formhash) {

            DDLogInfo(@"login get formhash %@", formhash);
            [self _loginWithFormhash:formhash block:block];

        } else {

            NSString *alert_info = [src stringBetweenString:@"
\n
" andString:@"
"];
            NSString *alert_error = [src stringBetweenString:@"
\n
" andString:@"

"];
            NSString *msg = nil;
            if (alert_info) msg = alert_info;
            else if (alert_error) msg = alert_error;
            else msg = src;

            if (block) {
                DDLogWarn(@"login step1 找不到token %@", src);
                block(NO, [NSError errorWithDomain:@".hi-pda.com" code:NSURLErrorUserAuthenticationRequired userInfo:@{NSLocalizedDescriptionKey:S(@"找不到token, 错误信息: %@", msg)}]);
            }
        }

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        if (block) {
            block(NO, error);
        }
    }];
}

- (void)_loginWithFormhash:(NSString *)formhash block:(void (^)(BOOL isLogin, NSError *error))block {

    NSString *username = [NSStandardUserDefaults stringForKey:kHPAccountUserName or:@""];

    HPAccountCredential *credential = [HPAccountPassword credentialFor:username];
    if (!credential) {
        DDLogWarn(@"login credential does not contain 3 components");
        block(NO, [NSError errorWithDomain:@".hi-pda.com" code:NSURLErrorUserAuthenticationRequired userInfo:@{NSLocalizedDescriptionKey:@"Keychain出问题了"}]);
        return;
    }
    NSString *password = credential.password;
    NSString *questionid = credential.questionid;
    NSString *answer = credential.answer;

    NSDictionary *parameters = @{
         @"loginfield":@"username",
         @"username":username,
         @"password":password,
         @"questionid":questionid,
         @"answer":answer,
         @"cookietime":@"2592000",
         @"referer":S(@"%@/forum/index.php", HP_BASE_URL),
         @"formhash":formhash
    };

    DDLogInfo(@"login step2 parameters %@", parameters);

    [[HPHttpClient sharedClient] postPath:@"forum/logging.php?action=login&loginsubmit=yes&inajax=1&inajax=1" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {

        NSString *html = [HPHttpClient GBKresponse2String:responseObject];
        //NSLog(@"login html : %@",html);

        BOOL isSuccess = ([html indexOf:@"欢迎您回来"] != -1);
        NSString *errMsg = [html stringBetweenString:@"<![CDATA[" andString:@"]]"];
        if (!errMsg) errMsg = html;
        if (!html) errMsg = @"null response";

        if (block) {
            block(isSuccess, [NSError errorWithDomain:@".hi-pda.com" code:NSURLErrorUserAuthenticationRequired userInfo:@{NSLocalizedDescriptionKey:errMsg}]);
        }

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        if (block) {
            block(NO, error);
        }
    }];
}

/*
 * 登录成功会先调用 [Setting loadSetting] 加载设置, 然后发送 kHPUserLoginSuccess 通知
 * 登出会先清除设置, 同时调用 [Setting loadDefaults] 加载默认设置, 然后发送 kHPUserLogout 通知
 */
- (void)logout {

    NSString *username = [NSStandardUserDefaults stringForKey:kHPAccountUserName or:@""];

    // clear username
    [NSStandardUserDefaults saveObject:@"" forKey:kHPAccountUserName];
    // clear password
    [HPAccountPassword clearPasswordFor:username];

    //clear userDefaults
    // 有些不清空
    NSMutableDictionary *keepSettings = [NSMutableDictionary dictionary];
    NSDictionary *d = [NSStandardUserDefaults dictionaryRepresentation];
    [d enumerateKeysAndObjectsUsingBlock:^(NSString *key, id obj, BOOL *stop) {
        // 用户的设置不清空
        if ([key hasPrefix:HPSettingDic]) {
            [keepSettings setObject:obj forKey:key];
        }
    }];
    //
    NSString *appDomain = [[NSBundle mainBundle] bundleIdentifier];
    [[NSUserDefaults standardUserDefaults] removePersistentDomainForName:appDomain];
    //
    [keepSettings enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
        [NSStandardUserDefaults setObject:obj forKey:key];
    }];
    [NSStandardUserDefaults synchronize];

    //
    [Setting loadDefaults];

    // clear cookies
    NSHTTPCookieStorage *cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    for (NSHTTPCookie *each in cookieStorage.cookies) {
        [cookieStorage deleteCookie:each];
    }

    DDLogInfo(@"logout done");

    [[NSNotificationCenter defaultCenter] postNotificationName:kHPUserLogout object:nil];
}

//fake
- (void)registerWithBlock:(void (^)(BOOL isLogin, NSError *error))block {

    NSString *loginPath = @"forum/register.php";
    [[HPHttpClient sharedClient] getPath:loginPath parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {

        if (block) {
            block(YES, nil);
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        if (block) {
            block(NO, error);
        }
    }];
}

- (void)startCheckWithDelay:(NSTimeInterval)delay {
    DDLogInfo(@"startCheckWithDelay %f", delay);
    if (delay == 0.f) {
        [self _checkMsgAndNoticeStep1];
    } else {
        [self performSelector:@selector(checkMsgAndNotice) withObject:nil afterDelay:delay];
    }
}

- (void)checkMsgAndNotice {

    _checkTimer = [NSTimer scheduledTimerWithTimeInterval:60 target:self selector: @selector(_checkMsgAndNoticeStep1) userInfo:nil repeats:YES];
    //_checkTimer = [NSTimer scheduledTimerWithTimeInterval:10 target:self selector: @selector(_checkMsgAndNoticeStep1) userInfo:nil repeats:YES];
    [_checkTimer fire];
}

- (void)_checkMsgAndNoticeStep1 {

    DDLogInfo(@"_checkMsgAndNoticeStep1...");

    NSTimeInterval t = [[NSDate date] timeIntervalSince1970];
    NSString *randomPath = [NSString stringWithFormat:@"forum/pm.php?checknewpm=%d&inajax=1&ajaxtarget=myprompt_check", (int)t];
    //NSLog(@"%@", randomPath);

    [self.checkPmClient getPath:randomPath
                              parameters:nil
                                 success:
     ^(AFHTTPRequestOperation *operation, id responseObject) {

         NSString *html = [HPHttpClient GBKresponse2String:responseObject];
         if ([html indexOf:@"您还未登录"] == -1) {

             [self _checkMsgAndNoticeStep2];

         } else {

             [[HPAccount sharedHPAccount] loginWithBlock:^(BOOL isLogin, NSError *err) {
                 DDLogInfo(@"relogin %@", isLogin?@"success":@"fail");

                 if (isLogin) {

                     [self _checkMsgAndNoticeStep2];

                 } else {

                     if (_noticeRetrieveBlock) {
                         _noticeRetrieveBlock(UIBackgroundFetchResultFailed);
                         _noticeRetrieveBlock = nil;
                     }
                 }
             }];
         }
     }
                                 failure:
     ^(AFHTTPRequestOperation *operation, NSError *error)
    {
        DDLogInfo(@"_checkMsgAndNoticeSetp1 error %@", error);
        if (_noticeRetrieveBlock) {
            _noticeRetrieveBlock(UIBackgroundFetchResultFailed);
            _noticeRetrieveBlock = nil;
        }
    }];
}

- (void)_checkMsgAndNoticeStep2 {

     DDLogInfo(@"_checkMsgAndNoticeStep2...");

    [self.checkPmClient getPathContent:@"forum/memcp.php?action=credits" parameters:nil success:^(AFHTTPRequestOperation *operation, NSString *html) {
        //NSLog(@"checkMsgAndNotice %@", html);

        NSInteger pm_count = 0, notice_count = 0;
        RxMatch *m1 = [RX(@"私人消息 \\((\\d+)\\)") firstMatchWithDetails:html];
        RxMatch *m2 = [RX(@"帖子消息 \\((\\d+)\\)") firstMatchWithDetails:html];

        if (m1) {
            RxMatchGroup *g1 = [m1.groups objectAtIndex:1];
            pm_count = [g1.value integerValue];
            DDLogInfo(@"get new pm_count %d", pm_count);
        }
        if (m2) {
            RxMatchGroup *g2 = [m2.groups objectAtIndex:1];
            notice_count = [g2.value integerValue];
            DDLogInfo(@"get new notice_count %d", notice_count);
        }

        [Setting saveInteger:pm_count forKey:HPPMCount];
        [Setting saveInteger:notice_count forKey:HPNoticeCount];

        if (pm_count || notice_count) {
            [self addLocalNotification];

            if (_noticeRetrieveBlock) {
                _noticeRetrieveBlock(UIBackgroundFetchResultNewData);
                _noticeRetrieveBlock = nil;
            }
        } else {
            if (_noticeRetrieveBlock) {
                _noticeRetrieveBlock(UIBackgroundFetchResultNoData);
                _noticeRetrieveBlock = nil;
            }
        }

        [[HPRearViewController sharedRearVC] updateBadgeNumber];

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        DDLogWarn(@"_checkMsgAndNoticeSetp2 error %@", error);
        if (_noticeRetrieveBlock) {
            _noticeRetrieveBlock(UIBackgroundFetchResultFailed);
            _noticeRetrieveBlock = nil;
        }
    }];
}

- (void)checkMsgAndNoticeFromAnyPage:(NSString *)html {
    //NSLog(@"checkMsgAndNotice %@", html);

    NSInteger pm_count = 0, notice_count = 0;
    RxMatch *m1 = [RX(@"私人消息 \\((\\d+)\\)") firstMatchWithDetails:html];
    RxMatch *m2 = [RX(@"帖子消息 \\((\\d+)\\)") firstMatchWithDetails:html];

    if (m1) {
        RxMatchGroup *g1 = [m1.groups objectAtIndex:1];
        pm_count = [g1.value integerValue];
        DDLogInfo(@"get new pm_count %d", pm_count);
    }
    if (m2) {
        RxMatchGroup *g2 = [m2.groups objectAtIndex:1];
        notice_count = [g2.value integerValue];
        DDLogInfo(@"get new notice_count %d", notice_count);
    }

    if (pm_count || notice_count) {
        [Setting saveInteger:pm_count forKey:HPPMCount];
        [Setting saveInteger:notice_count forKey:HPNoticeCount];
        [[HPRearViewController sharedRearVC] updateBadgeNumber];
    }
}

- (void)addLocalNotification {

    // clear older
    [[UIApplication sharedApplication] cancelAllLocalNotifications];

    NSInteger pm_count = [Setting integerForKey:HPPMCount];
    NSInteger notice_count = [Setting integerForKey:HPNoticeCount];

    NSString *msg = nil;
    if (pm_count > 0) {
        msg = S(@"您有新的短消息(%d)", pm_count);
    } else if (notice_count > 0){
        msg = S(@"您有新的帖子消息(%d)", notice_count);
    } else {
        //
        return;
    }

    // Creates the notification
    UILocalNotification *localNotification = [[UILocalNotification alloc] init];
    localNotification.fireDate = [[NSDate date] dateByAddingTimeInterval:1];
    localNotification.alertBody = msg;
    localNotification.repeatInterval = 0;
    localNotification.soundName = UILocalNotificationDefaultSoundName;
    localNotification.applicationIconBadgeNumber = [[HPAccount sharedHPAccount] badgeNumber];

    // And then sets it
    [[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
}

- (NSInteger)badgeNumber {
    NSInteger pm_count = [Setting integerForKey:HPPMCount];
    NSInteger notice_count = [Setting integerForKey:HPNoticeCount];
    return pm_count+notice_count;
}

- (BOOL)checkLocalNotificationPermission {
    if ([UIApplication instancesRespondToSelector:@selector(registerUserNotificationSettings:)]) {

        UIUserNotificationSettings *s = [[UIApplication sharedApplication] currentUserNotificationSettings];
        DDLogInfo(@"UIUserNotificationSettings %@", s);
        if (s.types == UIUserNotificationTypeNone) {
            return NO;
        } else {
            return YES;
        }
    }
    return YES;
}

- (void)askLocalNotificationPermission {
    [[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSound categories:nil]];
    [NSStandardUserDefaults saveBool:YES forKey:kHPAskNotificationPermission];
}

@end