text:
<?php
session_start();
if(isset($_SESSION['unm']) && $_SESSION['unm']!="admin" && $_SESSION['unm']!="verifier")
{
	header("location:student.php");
}
if(isset($_SESSION['unm']) && $_SESSION['unm']=="verifier")
{
	header("location:verifier.php");
}
if(isset($_SESSION['unm']) && $_SESSION['unm']=="admin")
{
	header("location:admin.php");
}
if(isset($_SESSION['exid']))
{
	header("location:exampage.php");

}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
  <link href="css/bootstrap.min.css" type="text/css" rel="stylesheet" />

Home

About Us

Policy

User Dashboard

Polict of company Towards the small large developments.

Present Scene

To understand company's current situation and problem we verified the workflow manual provided by the company. We observed the conventional steps performed by the company which is time consuming. The procedural workflow is as below.

1.	Communication with customer and contract for the management of examination, training, assessment.
2.	Hiring of experts for crating papers of respective subjects .(Offline mode)
3.	Dealing with the Training Partners and Expert Assessors for the students' training and teaching purpose.
4.	Collecting examination forms and different documents with the exam fees from student. (offline mode/ postal mode)
5.	Conduction examination at customer site.
6.	Collection of papers and assessment by the experts.
7.	Marks entry after assessment.
8.	Result display via excel sheet preparation and forwarding it to the respective students through mail.
9.	Result Hard-Copy distribution.

As above procedure suggests it starts with hiring of experts.
After a contract with customer. Company also provides customer with their training centers if customer is willing to go for it and do not have regional training centers.
		But as per reference of company's work manual we observed the selection procedure of experts before personal interview is lengthy and in written examination mode.
        To solve problem of TUV SUD, South Asia we observed their quality manual designed by their senior management. Thus we came to know that a web application which is capable enough for solving the exact problem and fulfilling the company's requirements is to be developed yet.
		We have taken references of such systems for online examinations like learn hub, GATEFORUM, ACE academy, India-Bix,   engineering institutes etc.
		Hence it is very much clear to us now that systems which are existing in current situation can be combined or partially referred and deployed to build the solution.
		Using quality manual of TUV SUD's senior management and the work-charts the research was very much feasible to deal with and they can be easily used for problem scope as well as the solution.
		To handle the documentation procedure of company a solution research can be put on effectively using the reference of www.gujacpc.nic.in where online mode of the details and document submission is provided.
		To deal with the expert selection and examination of students a system like www.learnhub.com and, private companies like gate-forum, ace, RTO-tests is observed and can be used as a reference for development and deployment of company's requirement.
		Thus by taking such references and some literature reviews a new evolutionary, portable, secure, feasible and cost effective system can be built.


text:
layout: post
title:  "Spring security (2) configuration"
date:   "2016-09-07 00:00:00"
categories: spring
keywords: java, spring, security
---

talking about CORS, CSRF, and how to add filters

## Add More authenticationManager

```java
@Override
protected void configure(AuthenticationManagerBuilder builder) {
    builder.parentAuthenticationManager(new OAuth2AuthenticationManager());
}
```

在 WebsecurityConfigurer 中可以配置可用额外的 authenticationManager, 其实大多数
情况下没有必要配置额外的 authenticationManager, 只要添加 AuthenticationProvider 即可

```java
public interface AuthenticationManager
    Authentication authenticate(Authentication authentication) throws AuthenticationException;

public interface AuthenticationProvider
    Authentication authenticate(Authentication authentication) throws AuthenticationException;
```

![AuthenticationManager](/images/posts/spring/security/AuthenticationManager.png)

从上面看, AuthenticationManager 与 AuthenticationProvider 的函数签名都是一样的, 想不出哪种场景
是必须用 AuthenticationManager 而不是 AuthenticationProvider 的 (OAuth2AuthenticationManager 是
AuthenticationManager 的子类, 与 ProviderManager 平级)

## add more SSO client

`update: 2016年12月28日 星期三`
关于 SSO 的更多知识

假设 oauth2 client 有多种 Oauth2ClientFilter 需要添加

```java
protected void configure(HttpSecurity http) throws Exception {

    http.antMatcher("/**").authorizeRequests()
        .antMatchers("/", "/login**", "/webjars/**").permitAll()
        .anyRequest().authenticated().and()
		.exceptionHandling()
		    .authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("/")).and().logout()
		.logoutSuccessUrl("/").permitAll().and()
		.csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()).and()
		.addFilterBefore(ssoFilter(), BasicAuthenticationFilter.class);

private Filter ssoFilter()
	CompositeFilter filter = new CompositeFilter();
	List<Filter> filters = new ArrayList<>();
	filters.add(ssoFilter(facebook(), "/login/facebook"));
	filters.add(ssoFilter(github(), "/login/github"));
	filter.setFilters(filters);
	return filter;

private Filter ssoFilter(ClientResources client, String path) {
	OAuth2ClientAuthenticationProcessingFilter filter = new OAuth2ClientAuthenticationProcessingFilter(path);
	OAuth2RestTemplate template = new OAuth2RestTemplate(client.getClient(), oauth2ClientContext);
	filter.setRestTemplate(template);
	filter.setTokenServices(new UserInfoTokenServices(
	    client.getResource().getUserInfoUri(), client.getClient().getClientId()));
	return filter;

```

compositeFilter 的工作原理,

```java
public class CompositeFilter implements Filter {
    private List<? extends Filter> filters = new ArrayList();
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        (new CompositeFilter.VirtualFilterChain(chain, this.filters)).doFilter(request, response);

```

## enable remember me service

The following configuration demonstrates how to allow token based remember me authentication.
Upon authenticating if the HTTP parameter named "remember-me" exists, then the user will be remembered
even after their session expires.

```java
public class RememberMeSecurityConfig extends WebSecurityConfigurerAdapter {
    void configure(HttpSecurity http) throws Exception {
        auth.rememberMe();
    }
}
```

![](/images/posts/spring/security/remember_me_flow.png)

![](/images/posts/spring/security/remember_me_arch.png)

**TokenBasedRememberMeService**

cookie 中记录的数据为:

```
Base64(username + expirationTime + md5Hex(username + expirationTime + password + key) 组成的
```

用户登录时,用 base64.decode,然后比较用户名密码是否正确

**PersistentTokenBasedRememberMeService**

如上图所示, 他有两种实现形式, 分别是 `JDBCTokenRepositoryImpl` 和 `InMemoryTokenRepositoryImpl`

InMemory 一般作为测试, 用户名密码往往存放到 Map 中

Jdbc 的实现需要创建一张表 persistent_logins

```
persistent_logins
    username varchar
    series varchar primary key
    token varchar
    last_used timestamp
```

这个时候 cookie 中记录的是 seris 和 username, 登录成功后 refresh token

```java
try
    tokenRepository.updateToken(newToken.getSeries(), newToken.getTokenValue(),newToken.getDate());
    addCookie(newToken, request, response);
```

验证成功后, 填充 SecurityContextHolder

```java
rememberMeAuth = authenticationManager.authenticate(rememberMeAuth);
SecurityContextHolder.getContext().setAuthentication(rememberMeAuth);
onSuccessfulAuthentication(request, response, rememberMeAuth);
```

**summary**

1) When the user successfully logs in with Remember Me checked, a login cookie is generated in addition to the standard session management cookie.

2) The login cookie contains the user's username and a random number and a current date time(this cookie is also called Token). The username and token are stored as a pair in a database table.

3) And this cookie is sent back in user response header. And this cookie is associated in every request sent to server.

4) When a non-logged-in user visits the site and presents a login cookie, the username and token are looked up in the database.
If the pair is present, the user is considered authenticated. The used token is removed from the database. A new token is generated, stored in database with the username, and issued to the user via a new login cookie.

5) If the pair is not present, the login cookie is ignored. Then redirect to login operations, then user must first successfully submit a normal username/password login form.If username is successfully authenticated then a new token is generated and persists username & token are stored as a pair in a database table and sent back new token to user as in response.

参考
[Remember-Me Authentication in Spring Security](http://sunilkumarpblog.blogspot.com/2016/01/remember-me-authentication-in-spring.html)

## logout 流程

RememberMe service 会影响到 logout 么?

Polls a series of LogoutHandlers. The handlers should be specified in the order they are required. Generally you will
want to call logout handlers TokenBasedRememberMeServices and SecurityContextLogoutHandler.

After logout, a redirect will be performed to the URL determined by either the configured LogoutSuccessHandler or
the logoutSuccessUrl, depending on which constructor was used.

```java
doFilter
    if(requiresLogout) // url pattern matching
        for(LogoutHandler handler: handlers)
            handler.logout(request, response, auth)
        logoutSuccessHandler.onLogoutSuccess(request, response, auth)

// 一个 onLogoutSuccess 的例子

AbstractAuthenticationTargetUrlRequestHandler
    RedirectStrategy redirectStrategy = new DefaultRedirectStrategy

    handle
        targetUrl = determineTargetUrl(request, response)
        redirectStrategy.sendRedirect(request, response, targetUrl)
```

没看到 Session 和 Logout 之间的配置, 只能通过单步调试来走了

## AccessDecisionManager

```java
// 获取这个 request 对应的 role 也可能是别的东西
Collection<ConfigAttribute> attributes = this.obtainSecurityMetadataSource()
   .getAttributes(object);

this.accessDecisionManager.decide(authenticated, object, attributes);
```

![](/images/posts/spring/security/Interceptor.png)

默认情况下使用 AffirmativeBased, 也就是说主要符合一个要求,就能成功。Voter 除了 Role 以外,还有
WebExpressionVoter, ACLVoter, DenyVoter, RoleHierarchyVoter 等等,用的比较多的 scope 应该是 WebExpressionVoter 的范畴,scope 定义在 client 信息中

Voter 里最常见的 Voter 是 Role voter, 它的认证过程非常简单,从 Authentication 中拿出 grantedAuthorities,如果包含 ConfigAttribute,那么认证通过,如果一个都没有则返回未通过

常用的 Voter 还有 ScopeVoter,在 Oauth2 的代码里提供,WebExpressionVoters

## Session 处理

share session, xss 可以放到另外一篇 blog 中

@todo

## 配置不同的数据库

redpajama_set_name: RedPajamaGithub


text:
using System.Collections.Generic;
using MarginTrading.Backend.Core.MatchedOrders;

namespace MarginTrading.Backend.Core
{
    public interface IFplService
    {
        void UpdateOrderFpl(IOrder order, FplData fplData);
        decimal GetMatchedOrdersPrice(List<MatchedOrder> matchedOrders, string instrument);
        void CalculateMargin(IOrder order, FplData fplData);
    }
}


text:
$pattern = ';'
$content = Get-Content D:\vm.csv
Connect-VIServer -Server vm-vcenter
foreach ($line in $content){
	$item = $line.Split($pattern)
    $a = New-Object PSOBject -Property @{
		Num=$item[0]
		Name=$item[1]
		Project = $item[2]
		PMManager=$item[3]
		Role=$item[4]
		Contact=$item[5]
		Soft=$item[6]
	}
    Get-VM $a.Name | Set-Annotation	-CustomAttribute "Contact" -Value $a.Contact
	Get-VM $a.Name | Set-Annotation	-CustomAttribute "Project" -Value $a.Project
	Get-VM $a.Name | Set-Annotation	-CustomAttribute "PM Contact" -Value $a.PMManager
	Get-VM $a.Name | Set-Annotation	-CustomAttribute "Software" -Value $a.Soft
	Get-VM $a.Name | Set-Annotation	-CustomAttribute "VM Role" -Value $a.Role

}


text:
module HydraAttribute
  module ActiveRecord
    module Relation
      module Calculation
        extend ActiveSupport::Concern

        included do
          attr_accessor :hydra_attribute_performs_calculation
        end

        # Notifies +#build_arel+ method that it builds query for calculation
        def execute_simple_calculation(operation, column_name, distinct)
          self.hydra_attribute_performs_calculation = true
          super(operation, column_name, distinct)
        end
      end
    end
  end
end


text:
package com.miicard.consumers.service.v1.claims.impl;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for anonymous complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType>
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="IsUserAssuredResult" type="{http://schemas.datacontract.org/2004/07/miiCard.STS.Model.Api}MiiApiResponseOfboolean" minOccurs="0"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@SuppressWarnings("restriction")
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "isUserAssuredResult"
})
@XmlRootElement(name = "IsUserAssuredResponse", namespace = "http://tempuri.org/")
class IsUserAssuredResponse {

    @XmlElement(name = "IsUserAssuredResult", namespace = "http://tempuri.org/", nillable = true)
    protected MiiApiResponseOfBoolean isUserAssuredResult;

    /**
     * Gets the value of the isUserAssuredResult property.
     *
     * @return possible object is
     * {@link MiiApiResponseOfBoolean }
     *
     */
    public final MiiApiResponseOfBoolean getIsUserAssuredResult() {
        return isUserAssuredResult;
    }

    /**
     * Sets the value of the isUserAssuredResult property.
     *
     * @param value allowed object is
     * {@link MiiApiResponseOfBoolean }
     *
     */
    public void setIsUserAssuredResult(MiiApiResponseOfBoolean value) {
        this.isUserAssuredResult = value;
    }
}


text:
require 'set'
require 'optparse'

module ChefRelevantTests
  class Cli
    class << self
      def parse_args!(argv)
        parser = OptionParser.new do |opts|
          opts.banner = <<-BANNER.strip
Usage: chef-relevant-tests [revision] [expander]
Available Expanders: #{EXPANDER_REGISTRY.keys.join ','}
BANNER
        end

        parser.parse!(argv)

        unless set_revision(ARGV.shift)
          puts "Error: Unknown revision.\n\n#{parser.help}"
          exit(1)
        end

        unless set_expander(ARGV.shift)
          puts "Error: Unknown expander.\n\n#{parser.help}"
          exit(1)
        end
      end

      def set_revision(rev)
        return unless system('git rev-parse #{rev} >/dev/null 2>&1')

        @@revision = rev
      end

      def set_expander(exp)
        return if !exp || exp.empty?

        @@expander = exp
      end

      def run
        changed_cookbooks = find_cookbook_diffs(@@revision)

        EXPANDER_REGISTRY[@@expander]
          .new(@@revision, changed_cookbooks)
          .expand
      end

      private

        CHANGE_DETECTOR_REGISTRY = [
          ChefRelevantTests::ChangeDetectors::Berkshelf,
        ].freeze

        EXPANDER_REGISTRY = {
          'test-kitchen' => ChefRelevantTests::Expanders::TestKitchen,
        }.freeze

        def find_cookbook_diffs(rev)
          enabled_change_detectors = CHANGE_DETECTOR_REGISTRY.map do |klass|
            detector = klass.new(rev)

            detector if detector.should_run?
          end.compact

          raise 'Unable to find changes - try `gem install berkshelf`.' if enabled_change_detectors.none?

          enabled_change_detectors.each_with_object(Set.new) do |detector, cookbooks|
            cookbooks.merge(detector.changed_cookbooks)
          end
        end
    end
  end
end


text:
fleetctl stop zookeeper.presence\@{1,2,3}.service
fleetctl destroy zookeeper.presence\@{1,2,3}.service
fleetctl stop zookeeper\@{1,2,3}.service
fleetctl destroy zookeeper\@{1,2,3}.service
fleetctl destroy zookeeper.presence\@.service
fleetctl destroy zookeeper\@.service


text:
#ifndef FCP_BASE_SCHEDULER_H_
#define FCP_BASE_SCHEDULER_H_

/**
 * Overview
 * ========
 *
 * A simple implementation of a scheduler (thread pool). Allows to schedule
 * tasks and futures.
 */

#include <functional>
#include <memory>

#include "fcp/base/monitoring.h"
#include "fcp/base/move_to_lambda.h"

namespace fcp {

/**
 * A Worker allows to schedule tasks which are executed sequentially.
 * Workers are created from a Scheduler.
 *
 * Lifetime and destruction:
 *
 *   - The scheduler from which a worker is created must not be destructed
 *     before the worker.
 *
 *   - The worker must not be destructed before all its tasks are finished.
 */
class Worker {
 public:
  virtual ~Worker() = default;
  Worker() = default;

  Worker(Worker const&) = delete;
  Worker& operator=(Worker const&) = delete;

  /**
   * Schedules a task on this worker. Tasks are executed strictly sequentially
   * in the order they are scheduled.
   */
  virtual void Schedule(std::function<void()> task) = 0;
};

/**
 * A Scheduler which allows to schedule 'tasks'.
 *
 * Lifetime and destruction:
 *
 *   - A Scheduler *must* be idle (no active or pending work) at destruction
 *     time. See WaitUntilIdle.
 *
 *   - Implies: A Scheduler *must not* be destructed by one of its own tasks
 *
 *   - Implies: Task closures may safely hold raw pointers to their thread pool.
 *     They should *not* have ownership (via a smart-pointer or similar).
 */
class Scheduler {
 public:
  virtual ~Scheduler() = default;
  Scheduler() = default;

  Scheduler(Scheduler const&) = delete;
  Scheduler& operator=(Scheduler const&) = delete;

  /**
   * Creates a new Worker based on this scheduler.
   */
  virtual std::unique_ptr<Worker> CreateWorker();

  /**
   * Schedules a task that will execute on the scheduler.
   */
  virtual void Schedule(std::function<void()> task) = 0;

  /**
   * Waits until there are no tasks running or pending.
   *
   * In this state, the thread pool will not restart working until some
   * external entity is scheduling new tasks, as work caused by tasks spawning
   * other tasks has ceased.
   */
  virtual void WaitUntilIdle() = 0;
};

/**
 * Creates a scheduler using a fixed-size pool of threads to run tasks.
 */
std::unique_ptr<Scheduler> CreateThreadPoolScheduler(std::size_t thread_count);

}  // namespace fcp

#endif  // FCP_BASE_SCHEDULER_H_


text:
my-first-repository
===================


text:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical">

    <com.example.nayon.nanjicamp.widget.CustomLinearLayout
        android:id="@+id/item_root_reserve_1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@android:color/transparent"
        android:gravity="center"
        android:orientation="vertical">

        <RelativeLayout
            android:layout_width="235dp"
            android:layout_height="235dp"
            android:id="@+id/lay_reserve_1"
            android:gravity="center">

            <LinearLayout
                android:layout_width="235dp"
                android:layout_height="235dp"
                android:gravity="center"
                android:orientation="vertical"
                android:background="@drawable/background_reserve_3">

                <ImageView
                    android:id="@+id/img_reserve_1"
                    android:layout_marginBottom="10dp"
                    android:layout_width="160dp"
                    android:layout_height="120dp" />

                <com.example.nayon.nanjicamp.widget.NanumBoldTextView
                    android:text="담요"
                    android:id="@+id/txt_reserve_1_1"
                    android:layout_margin="2dp"
                    android:textSize="16dp"
                    android:textColor="@color/NanjiGreen"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content" />

                <com.example.nayon.nanjicamp.widget.NanumTextView
                    android:text="울랄라우랄랄"
                    android:layout_width="wrap_content"
                    android:layout_margin="4dp"
                    android:textSize="14dp"
                    android:id="@+id/txt_reserve_1_2"
                    android:textColor="@color/NanjiTextGray"
                    android:layout_height="wrap_content" />

                <com.example.nayon.nanjicamp.widget.NanumTextView
                    android:text="느앙앙"
                    android:id="@+id/txt_reserve_1_3"
                    android:layout_width="wrap_content"
                    android:textColor="@color/NanjiTextGray"
                    android:textSize="11dp"
                    android:layout_margin="2dp"
                    android:layout_height="wrap_content"/>

            </LinearLayout>

            <ImageView
                android:id="@+id/backgroud_reserve_1_check"
                android:layout_width="225dp"
                android:layout_height="225dp"
                android:layout_centerInParent="true"
                android:background="@drawable/background_reserve_3_checked" />

            <ImageView
                android:id="@+id/video_reserve_1_checked"
                android:layout_width="145dp"
                android:layout_height="145dp"
                android:scaleType="fitCenter"
                android:layout_centerHorizontal="true"
                android:layout_centerVertical="true"
                android:background="#00ffffff" />

        </RelativeLayout>

    </com.example.nayon.nanjicamp.widget.CustomLinearLayout>

</LinearLayout>


text:
import os
import re

try:
    from setuptools import setup
    setup_params = {'scripts': ['tmux-chooser'],
                    'install_requires': ['paramiko'],
                   }
except ImportError:
    from distutils.core import setup
    setup_params = {'scripts': ['tmux-chooser']}

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

def get_version():
    f = open(os.path.join(here, 'tmux-chooser'))
    version_file = f.read()
    f.close()
    version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]",
                              version_file, re.M)
    if version_match:
        return version_match.group(1)
    raise RuntimeError("Unable to find version string.")

setup(
    name='tmux-chooser',
    version=get_version(),
    description="tmux session chooser for busy people",
    classifiers=[
        'Development Status :: 4 - Beta',
        'Environment :: Console :: Curses',
        'Intended Audience :: Developers',
        'Intended Audience :: System Administrators',
        'License :: OSI Approved :: MIT License',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2.7',
        'Topic :: Utilities',
    ],
    zip_safe=False,
    keywords='setuptools deployment installation distutils',
    author='Peter Debacker',
    author_email='peter@peterdebacker.com',
    url='https://github.com/peter-d/tmux-chooser',
    download_url='https://github.com/peter-d/tmux-chooser/tarball/%s.tar.gz' % get_version(),
    license='MIT',
    long_description=open(os.path.join(here, "README.md")).read(),
    **setup_params
)


text:
var should = require('should'),
    User = require('../../models/user');

describe('UserModel', function() {

  describe('インスタンス生成', function() {

    it('指定した属性でインスタンスを生成できること', function() {
      var user = new User({
        name: 'pochi',
        email: 'hoge@example.com',
        password: 'pass'
      });
      user.id.length.should.not.be.equal(0);
      user.name.should.equal('pochi');
      user.email.should.equal('hoge@example.com');
      user.password.should.equal('pass');
    });

  });

});


text:
var request = require('superagent')

var auth = {
  signin: function(email, password, cb) {
    if (sessionStorage.token) {
      cb && cb(true)
      this.onChange(true)
      return
    }
    if (arguments.length === 0) {
      return
    }
    request
      .post('/api/sessions')
      .send({ email: email, password: password })
      .set('Accept', 'application/json')
      .end(function(error, res){
        if (error === null && res.ok) {
          cb && cb(true)
          this.onChange(true)
          sessionStorage.token = JSON.parse(res.text).token
        } else {
          cb && cb(false)
          this.onChange(false)
        }
      }.bind(this))
  },

  signup: function(email, password, cb) {
    if (sessionStorage.token) {
      cb && cb(true)
      this.onChange(true)
      return
    }
    if (arguments.length === 0) {
      return
    }
    request
      .post('/api/registrations')
      .send({ email: email, password: password })
      .set('Accept', 'application/json')
      .end(function(error, res){
        if (error === null && res.ok) {
          cb && cb(true)
          this.onChange(true)
          sessionStorage.token = JSON.parse(res.text).token
        } else {
          cb && cb(false)
          this.onChange(false)
        }
      }.bind(this))
  },

  getToken: function() {
    return sessionStorage.token
  },

  signout: function(cb) {
    delete sessionStorage.token
    cb && cb()
    this.onChange(false)
  },

  signedIn: function() {
    return !!sessionStorage.token
  },

  onChange: function() {}
}

module.exports = auth


text:
package testsSherafgan;

import org.joda.time.tz.ZoneInfoCompiler;
import org.junit.Test;

import static org.junit.Assert.assertNotEquals;

/**
 * @author Sherafgan Kandov (sherafgan.kandov@gmail.com)
 * @version 4/5/17
 */
public class TestZoneInfoCompiler {
    @Test
    public void testZoneInfoProviderConstructor() throws Exception {
        ZoneInfoCompiler zoneInfoCompiler = new ZoneInfoCompiler();
        zoneInfoCompiler.main(new String[]{});
        assertNotEquals(null, zoneInfoCompiler);
    }
}


text:
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ExcelFilter
{
    public class Files
    {
        /// <summary>
        /// Открыть диалоговое окно открытия файла
        /// </summary>
        /// <param name="Title">Заголовок окна</param>
        /// <param name="Filter">Фильтр файлов</param>
        /// <returns></returns>
        public static string OpenFile(string Title, string Filter = "Файлы Excel 2007+ (*.xlsx)|*.xlsx|Все файлы (*.*)|*.*")
        {
            Microsoft.Win32.OpenFileDialog openFileDialog = new Microsoft.Win32.OpenFileDialog()
            {
                Filter=Filter,
                Title=Title,
                Multiselect=false,
                CheckPathExists=true,
                CheckFileExists = true
            };
            if (openFileDialog.ShowDialog() == true)
            {
                return openFileDialog.FileName;
            }
            return null;
        }

        /// <summary>
        /// Открыть диалоговое окно открытия нескольких файлов
        /// </summary>
        /// <param name="Title">Заголовок окна</param>
        /// <param name="Filter">Фильтр файлов</param>
        /// <returns></returns>
        public static string[] OpenFiles(string Title, string Filter = "Файлы Excel 2007+ (*.xlsx)|*.xlsx|Все файлы (*.*)|*.*")
        {
            Microsoft.Win32.OpenFileDialog openFileDialog = new Microsoft.Win32.OpenFileDialog()
            {
                Filter = Filter,
                Title = Title,
                Multiselect = true,
                CheckPathExists = true,
                CheckFileExists = true
            };
            if (openFileDialog.ShowDialog() == true)
            {
                return openFileDialog.FileNames;
            }
            return null;
        }

        /// <summary>
        /// Открыть диалоговое окно открытия нескольких файлов
        /// </summary>
        /// <param name="Title">Заголовок окна</param>
        /// <param name="Filter">Фильтр файлов</param>
        /// <returns></returns>
        public static string OpenDirectory(string Title, string Filter = "Файлы Excel 2007+ (*.xlsx)|*.xlsx|Все файлы (*.*)|*.*")
        {
            FolderBrowserDialog folderBrowser = new FolderBrowserDialog();

            DialogResult result = folderBrowser.ShowDialog();

            if (string.IsNullOrWhiteSpace(folderBrowser.SelectedPath))
                return null;
            else
            {
                return folderBrowser.SelectedPath;
            }
        }

        /// <summary>
        /// Открыть диалоговое окно сохранения файла
        /// </summary>
        /// <param name="Title">Заголовок окна</param>
        /// <param name="Filter">Фильтр файлов</param>
        /// <returns></returns>
        public static string SaveFile(string Title, string Filter = "Файлы Excel 2007+ (*.xlsx)|*.xlsx|Все файлы (*.*)|*.*")
        {
            Microsoft.Win32.SaveFileDialog saveFileDialog = new Microsoft.Win32.SaveFileDialog()
            {
                Filter = Filter,
                Title = Title,
                CheckPathExists = true,
                AddExtension = true
            };
            if (saveFileDialog.ShowDialog() == true)
            {
                return saveFileDialog.FileName;
            }
            return null;
        }
    }

}


text:
namespace gpu {
class GLInProcessContext;
}

namespace gpu_blink {
class WebGraphicsContext3DInProcessCommandBufferImpl;
}

namespace content {

class SynchronousCompositorFactoryImpl : public SynchronousCompositorFactory {
 public:
  SynchronousCompositorFactoryImpl();
  virtual ~SynchronousCompositorFactoryImpl();

  // SynchronousCompositorFactory
  virtual scoped_refptr<base::MessageLoopProxy> GetCompositorMessageLoop()
      override;
  virtual bool RecordFullLayer() override;
  virtual scoped_ptr<cc::OutputSurface> CreateOutputSurface(
      int routing_id,
      scoped_refptr<content::FrameSwapMessageQueue> frame_swap_message_queue)
      override;
  virtual InputHandlerManagerClient* GetInputHandlerManagerClient() override;
  virtual scoped_ptr<cc::BeginFrameSource> CreateExternalBeginFrameSource(
      int routing_id) override;
  virtual scoped_refptr<webkit::gpu::ContextProviderWebContext>
      CreateOffscreenContextProvider(
          const blink::WebGraphicsContext3D::Attributes& attributes,
          const std::string& debug_name) override;
  virtual scoped_refptr<StreamTextureFactory> CreateStreamTextureFactory(
      int view_id) override;
  virtual gpu_blink::WebGraphicsContext3DInProcessCommandBufferImpl*
      CreateOffscreenGraphicsContext3D(
          const blink::WebGraphicsContext3D::Attributes& attributes) override;

  SynchronousInputEventFilter* synchronous_input_event_filter() {
    return &synchronous_input_event_filter_;
  }

  void SetDeferredGpuService(
      scoped_refptr<gpu::InProcessCommandBuffer::Service> service);
  void SetRecordFullDocument(bool record_full_document);
  void CompositorInitializedHardwareDraw();
  void CompositorReleasedHardwareDraw();

  scoped_refptr<cc::ContextProvider>
      CreateOnscreenContextProviderForCompositorThread();

 private:
  bool CanCreateMainThreadContext();
  scoped_refptr<StreamTextureFactorySynchronousImpl::ContextProvider>
      TryCreateStreamTextureFactory();
  void RestoreContextOnMainThread();

  SynchronousInputEventFilter synchronous_input_event_filter_;

  scoped_refptr<gpu::InProcessCommandBuffer::Service> service_;

  class VideoContextProvider;
  scoped_refptr<VideoContextProvider> video_context_provider_;

  bool record_full_layer_;

  // |num_hardware_compositor_lock_| is updated on UI thread only but can be
  // read on renderer main thread.
  base::Lock num_hardware_compositor_lock_;
  unsigned int num_hardware_compositors_;
  scoped_refptr<base::MessageLoopProxy> main_thread_proxy_;
};

}  // namespace content

#endif  // CONTENT_BROWSER_ANDROID_IN_PROCESS_SYNCHRONOUS_COMPOSITOR_FACTORY_IMPL_H_


text:
@interface JPPlayingViewController : UIViewController

@end


text:
<!DOCTYPE html>

    <title>The Drive module Specification</title>
    <meta http-equiv='Content-Type' content='text/html;charset=utf-8'/>

      This specification defines APIs to get the driving information from an automotive device.

Summary of Methods

Interface	Method

			DriveObject

			Drive

				Odometer getOdometer()

				float getSpeed()

				float getCurrentFuelEconomy()

				long watchVehicleSpeed(SpeedSuccessCallback successCallback, ErrorCallback errorCallback)

				void clearWatchVehicleSpeed(long watchId)

				void setEngineMode(EngineMode mode)

				EngineStatus  getEngineMode()

			Odometer

			Speed

			SpeedSuccessCallback

			  void onsuccess(Speed speed)

Introduction

		This API provides the driving information.

Type Definitions

SpeedUnit

The unit of speed.

			 enum SpeedUnit { "KMH", "MPH"};

KMH: km/h.

MPH: mph.

EngineMode

The mode of a vehicle engine.

			enum EngineMode {"STOP", "START" };

STOP: Stopping a vehicle engine.

START: Staring a vehicle engine.

EngineStatus

The status of a vehicle engine.

			enum EngineStatus { "OFF", "RUNNING" };

OFF: The engine off.

RUNNING: The engine running.

Interfaces

DriveObject

			Defines what is instantiated in the motor object.

			There will be a motor.drive object that allows accessing the functionality of the drive module.

readonly attribute Drive drive

Drive

			Drive interface.

Odometer getOdometer()

Gets an Odometer object.

Signature

Odometer getOdometer()

Return value

An odometer object.

						Exceptions

						MotorAPIError:

						with error code TYPE_MISMATCH_ERR if any input parameter is not compatible with the expected type for that parameter.

						with error code INVALID_VALUES_ERR if the input parameter contains an invalid value.

						with error code NOT_SUPPORTED_ERR if this function is not supported.

						var odometer = motor.drive.getOdometer();
						alert("Total Mileage : " + odometer.totalMileage);

float getSpeed()

Gets the speed of a vehicle.

Signature

							float getSpeed()

Return value

The speed of a vehicle, which unit is km/h.

							Exceptions

							MotorAPIError:

							with error code NOT_SUPPORTED_ERR if this function is not supported.

							var speed = motor.drive.getSpeed();
							alert("Speed : " + speed);

float getCurrentFuelEconomy()

Gets the current fuel economy of a vehicle.

Signature

							float getCurrentFuelEconomy()

Return value

The current fuel economy of a vehicle, which unit is km/l.

							Exceptions

							MotorAPIError:

							with error code NOT_SUPPORTED_ERR if this function is not supported.

							var curFuel = motor.drive.getCurrentFuelEconomy();
							alert("Current Fuel Economy : " + curFuel);

long watchVehicleSpeed(SpeedSuccessCallback successCallback, optional ErrorCallback errorCallback)

Subscribes to receive notifications about the change in speed of a vehicle.

Signature

								long watchVehicleSpeed(SpeedSuccessCallback successCallback, optional ErrorCallback errorCallback)

Return value

								The identifier used to clear the watch subscription.

								Exceptions

								MotorAPIError:

								with error code TYPE_MISMATCH_ERR if any input parameter is not compatible with the expected type for that parameter.

								with error code NOT_SUPPORTED_ERR if this function is not supported.

							function SuccessCB(speed)	{
								motor.drive.clearWatchVehicleSpeed(watchSpeed);
								alert("Speed : " + speed.speed + "\nUnit : " + speed.unit);
								/* watchSpeed is cleared after first call */
							}

							function ErrorCB(err)	{
								alert("Error : " + err.message);
							}

							var watchSpeed = motor.drive.watchVehicleSpeed(SuccessCB, ErrorCB);

void clearWatchVehicleSpeed(long watchId)

Unsubscribes the watch operation by the watchVehicleSpeed() method.

Signature

								void clearWatchVehicleSpeed(long watchId)

								Exceptions

								MotorAPIError:

								with error code TYPE_MISMATCH_ERR if any input parameter is not compatible with the expected type for that parameter.

								with error code INVALID_VALUES_ERR if the input parameter contains an invalid value.

								with error code NOT_SUPPORTED_ERR if this function is not supported.

							function SuccessCB(speed)	{
								motor.drive.clearWatchVehicleSpeed(watchSpeed);
								alert("Speed : " + speed.speed + "\nUnit : " + speed.unit);
								 /* watchSpeed is cleared after first call */
							}

							function ErrorCB(err)	{
								alert("Error : " + err.message);
							}

							var watchSpeed = motor.drive.watchVehicleSpeed(SuccessCB, ErrorCB);

void setEngineMode(EngineMode mode)

Sets the mode of a vehicle engine.

Signature

void setEngineMode(EngineMode mode)

Return value

none.

Exceptions

								MotorAPIError:

								with error code TYPE_MISMATCH_ERR if any input parameter is not compatible with the expected type for that parameter.

								with error code INVALID_VALUES_ERR if the input parameter contains an invalid value.

								with error code NOT_SUPPORTED_ERR if this function is not supported.

							motor.drive.setEngineMode("STOP");
							/* EngineMode {"STOP", "START" } */

EngineStatus getEngineMode()

Gets the status of a vehicle engine.

Signature

EngineStatus getEngineMode()

Return value

The status of a vehicle engine.

Exceptions

								MotorAPIError:

								with error code UNKNOWN_ERR if an unknown error has occurred in this function.

								with error code NOT_SUPPORTED_ERR if this function is not supported.

							var engineMode = motor.drive.getEngineMode();
							alert("Engine Mode : " + engineMode);

Odometer

			Define the attributes of an odometer.

			It is used as the return value of the getOdometer() method.

readonly attribute float totalMileage

The total mileage of a vehicle, which unit is km.

Speed

			It is used in the successCallback of the watchVehicleSpeed() method.

readonly attribute int speed

The Speed of a vehicle.

readonly attribute SpeedUnit unit

The unit of speed.

SpeedSuccessCallback

			This callback interface specifies a success callback with a function taking a Speed object as input argument. It is used in asynchronous operations such as watchVehicleSpeed() method.
Methods

void onsuccess(Speed speed)

Method invoked when the asynchronous call completes successfully.

Features

	  When the feature

http://hyundai.com/api/drive

		or any of the features hierarchically under that feature is successfully requested, the interface Drive is instantiated, and the resulting object appears in the global namespace as motor.drive.

		This is the list of URIs used to declare this API's features, for use in the widget config.xml. For each URL, the list of functions covered is provided.

		http://hyundai.com/api/drive.get

		Access to all the feature except the following methods: setEngineMode()

		http://hyundai.com/api/drive.set

		Access to all the feature except the following methods:

		getOdometer(), getSpeed(), getCurrentFuelEconomy(), watchVehicleSpeed(), clearWatchVehicleSpeed(), getEngineMode()

		http://hyundai.com/api/drive

		Access to all the features in this module


text:
/*
 * WS Proxy bridging from websockets to VNC
 *
 * @author Jannis Moßhammer <mojadev@gmail.com>
 */
/* [LICENCE START] */
/**
 * Copyright 2012 Jannis Mosshammer <mojadev@gmail.com>
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 **/
/* [LICENCE END] */

var myport = process.argv[4] || 4430;
var WebSocketServer = require('websocket').server,
    net = require('net'),
    util = require('util'),
    http = require('http');

var vnchost = process.argv[2] || 'localhost';
var vncport = process.argv[3] || 5901;

var server = http.createServer(function(request, response) {
    response.writeHead(404);
    response.end();
});
server.listen(myport, function() {
    util.debug("Listening on port "+myport);
});

wsServer = new WebSocketServer({
    httpServer: server
});

wsServer.on('request', function(request) {
    var connection = request.accept();
    var vnc = net.connect(vncport,vnchost).on("error",function(e) {
        util.error(e);
    });
    var useBinary = false;
    vnc.on("data", function(buffer) {
//        console.log("Server message ",buffer);
        if(useBinary == false) {
            connection.sendUTF(buffer.toString('base64'));
        } else {
            connection.sendBytes(buffer);
        }
    }).on("error",function(e) {
        util.error(e);
    }).on("close",function() {
        util.debug("VNC disconnected, closing websocket");
        connection.close();
    });
    connection.on('message',function(message) {
        console.log("in",message);
   //     console.log("Client message ",message);
        if(message.type === 'utf8') {
            useBinary = false;
            vnc.write(new Buffer(message.utf8Data).toString('base64'));
        } else {
            useBinary = true;
            vnc.write(message.binaryData);
        }

    }).on("error",function(e) {
        util.error(e);
    }).on("close",function() {
        util.debug("Websocket disconnected, closing VNC connection");
        vnc.end();
    })
});


text:
from pyvisdk.base.managed_object_types import ManagedObjectTypes

from pyvisdk.mo.managed_entity import ManagedEntity

import logging

########################################
# Automatically generated, do not edit.
########################################

log = logging.getLogger(__name__)

class Network(ManagedEntity):
    '''Represents a network accessible by either hosts or virtual machines. This can
    be a physical network or a logical network, such as a VLAN.Networks are
    created:* explicitly when configuring a host. * automatically when adding a
    host to VirtualCenter. * automatically when adding a new virtual machine to a
    host or to VirtualCenter.'''

    def __init__(self, core, name=None, ref=None, type=ManagedObjectTypes.Network):
        super(Network, self).__init__(core, name=name, ref=ref, type=type)

    @property
    def host(self):
        '''Hosts attached to this network.'''
        return self.update('host')
    @property
    def name(self):
        '''Name of this network.'''
        return self.update('name')
    @property
    def summary(self):
        '''Properties of a network.'''
        return self.update('summary')
    @property
    def vm(self):
        '''Virtual machines using this network.'''
        return self.update('vm')

    def DestroyNetwork(self):
        '''Deprecated. As of VI API 2.5 do not use this method. This method
        throws ResourceInUse. Networks are automatically removed when no longer in use,
        so this method is unnecessary. Removes a network. A network can be removed
        only if it is not used by any host or virtual machine.

        '''
        return self.delegate("DestroyNetwork")()


text:
import Component from '../editors/editor-xp';

export default Component;


text:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const cli_utils_1 = require("@ionic/cli-utils");
exports.CORDOVA_INTENT = 'CORDOVA';
/**
 * Filter and gather arguments from command line to be passed to Cordova
 */
function filterArgumentsForCordova(metadata, inputs, options) {
    const results = cli_utils_1.filterOptionsByIntent(metadata, options, exports.CORDOVA_INTENT);
    const args = cli_utils_1.minimistOptionsToArray(results, { useEquals: false, allowCamelCase: true });
    let unparsedCdvArgs = [];
    const indexOfSep = inputs.indexOf('--');
    if (indexOfSep >= 0) {
        unparsedCdvArgs = inputs.splice(indexOfSep);
    }
    return [metadata.name].concat(inputs, args, unparsedCdvArgs);
}
exports.filterArgumentsForCordova = filterArgumentsForCordova;
/**
 * Start the app scripts server for emulator or device
 */
function generateBuildOptions(metadata, options) {
    const results = cli_utils_1.filterOptionsByIntent(metadata, options);
    // Serve specific options not related to the actual run or emulate code
    return Object.assign({}, results, { iscordovaserve: true, nobrowser: true });
}
exports.generateBuildOptions = generateBuildOptions;


text:
ActionController::Routing::Routes.draw do |map|
  map.signup  "signup", :controller => "users", :action => "new"
  map.login   "login",  :controller => "user_sessions", :action => "new"
  map.logout  "logout", :controller => "user_sessions", :action => "destroy"

  map.namespace(:admin) do |admin|
     admin.resources :users, :member => { :confirm_destruction => :get }
  end

  map.resources :user_sessions, :only => [:new, :create, :destroy]
  map.resources :users, :only => [:new, :create, :edit, :update]
  map.resources :password_resets, :only => [:new, :create, :edit, :update]
end


text:
import pytest
import numpy as np

from keras import metrics
from keras import backend as K

all_metrics = [
    metrics.binary_accuracy,
    metrics.categorical_accuracy,
    metrics.mean_squared_error,
    metrics.mean_absolute_error,
    metrics.mean_absolute_percentage_error,
    metrics.mean_squared_logarithmic_error,
    metrics.squared_hinge,
    metrics.hinge,
    metrics.categorical_crossentropy,
    metrics.binary_crossentropy,
    metrics.poisson,
    metrics.cosine_proximity,
]

all_sparse_metrics = [
    metrics.sparse_categorical_accuracy,
    metrics.sparse_categorical_crossentropy,
]

def test_metrics():
    y_a = K.variable(np.random.random((6, 7)))
    y_b = K.variable(np.random.random((6, 7)))
    for metric in all_metrics:
        output = metric(y_a, y_b)
        assert K.eval(output).shape == ()

def test_sparse_metrics():
    for metric in all_sparse_metrics:
        y_a = K.variable(np.random.randint(0, 7, (6,)), dtype=K.floatx())
        y_b = K.variable(np.random.random((6, 7)), dtype=K.floatx())
        assert K.eval(metric(y_a, y_b)).shape == ()

if __name__ == "__main__":
    pytest.main([__file__])


text:
//
//  NewsInformationViewController.m
//  长春国税
//
//  Created by A-XIU on 16/3/23.
//  Copyright © 2016年 XIU. All rights reserved.
//

/*
 * 新闻资讯页面
 */
#import "NewsInformationViewController.h"

#import "NewInformationTableViewCell.h"
#import "NewsInformationDetialVC.h"
#import "HeaderView.h"
#import "NewsInformationModel.h"
#import "MBProgressHUD.h"
@interface NewsInformationViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) MBProgressHUD *HUD;

@property (nonatomic, strong) NSMutableArray *dataSouce;

//@property (nonatomic, strong) NSArray *detialSource;

@end

@implementation NewsInformationViewController

-(NSMutableArray *)dataSouce {
    if (_dataSouce == nil) {
        _dataSouce = [NSMutableArray array];
    }
    return _dataSouce;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    UIBarButtonItem *backIetm = [[UIBarButtonItem alloc] init];
    backIetm.title =@"返回";
    self.navigationItem.backBarButtonItem = backIetm;
    XIULabel *lab = [XIULabel setUpNavgationTitleLableWithTitle:@"+资讯"];
    self.navigationItem.titleView = lab;
    [self requestNetwork];

    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, MainWidth, MainHeight) style:UITableViewStyleGrouped];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.backgroundColor = [UIColor clearColor];
    _tableView.separatorStyle = 0;
    [self.view addSubview:_tableView];

    UINib *nib = [UINib nibWithNibName:@"NewInformationTableViewCell" bundle:nil];
    [_tableView registerNib:nib forCellReuseIdentifier:@"UITableViewCell"];

    self.HUD = [[MBProgressHUD alloc] initWithView:self.view];
    [self.HUD show:YES];
    [self.view addSubview:_HUD];

}
#pragma mark  tableView delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    [self.HUD removeFromSuperview];
    return 1;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataSouce.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return  200;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *identifier = @"UITableViewCell";

    NewInformationTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {

        cell = [[NewInformationTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    cell.newsTitleLabel.text = [self.dataSouce[indexPath.section] title];
    cell.newsDetialLabel.text =[self.dataSouce[indexPath.section] descriptions];
    cell.newsTimeLabel.text = @"2016年03月20日 06:06 长春国税专+";
    return cell;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (section == 0) {

        HeaderView *headView = [HeaderView headView];
        headView.frame = CGRectMake(0, 0,self.view.frame.size.width, 130);
        headView.contentlabel = @"      不出国门,一览天下。税务资讯,尽在掌握。这里涵盖国内外税务要闻、税收政策、专题报道、政策解读,内容全面、信息专业、解读权威。及时追踪税务新闻,各类咨询一网打尽";
        headView.sublabel = @"+资讯";
        headView.xiuimages = @"xwzx";
        return headView;
    }
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return 140;
    }
    return 2;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 1;
}

#pragma mark chickedCellMethod
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    NewsInformationDetialVC *newsDetial = [[NewsInformationDetialVC alloc] init];
    newsDetial.ids = [self.dataSouce[indexPath.section] ids];
    [self.navigationController pushViewController:newsDetial animated:YES];
}

/*
 +资讯
 PHP
 *http://guoshui.siruisheng.com/Mobile.php/Home/API/newsList/type/1

 新版本更新
 http://139.129.21.128:8080/CCGS/GetNewsByType.action?newsType=1
 */

- (void)requestNetwork {

    NSString *path = [CHANGEBASE_URLSTRING stringByAppendingString:@"GetNewsByType.action?newsType=1"];
    [HTTPHandier getDataByString:path WithBodyString:nil WithDataBlock:^(id responceObject) {
        NSArray *arr = [[NSArray alloc] init];
        arr = [responceObject objectForKey:@"newslist"];
        for (NSDictionary *dic in arr) {
            NewsInformationModel *model = [[NewsInformationModel alloc] init];
            model.title  =[dic objectForKey:@"title"];
            model.descriptions = [dic objectForKey:@"description"];
            model.ids = [dic objectForKey:@"id"];
            model.content = [dic objectForKey:@"content"];
            [self.dataSouce addObject:model];

    }
        [_tableView reloadData];
    }];
}

@end


text:
Public Class ListeUtilisateur

    Private Sub ListeUtilisateur_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Util.HandButtonCursor(Me)
        LoadUser()
    End Sub

    Sub LoadUser()
        Database.Query("SELECT users.id, username, roles.libelle, password, roles.id FROM users INNER JOIN roles ON users.role_id = roles.id WHERE users.state = 1")
        Dim resul = Database.ExecuteResult
        ListeUser.Items.Clear()
        Try
            While resul.Read
                Dim item As New ListViewItem(resul.GetValue(0).ToString)
                item.SubItems.Add(resul.GetValue(1).ToString)
                item.SubItems.Add(resul.GetValue(2).ToString)
                Dim pass = resul.GetValue(3).ToString
                Dim formatedPassword As String = pass(0).ToString & pass(1).ToString

                For Each a As Char In pass.Substring(2).ToCharArray
                    formatedPassword &= "*"
                Next

                item.SubItems.Add(formatedPassword)
                item.SubItems.Add(pass)
                item.SubItems.Add(resul.GetValue(4).ToString)
                ListeUser.Items.Add(item)
            End While
        Catch ex As Exception
            If My.Settings.app_debug_mode Then
                Util.ShowMessage(ex.ToString)
            Else
                Util.ShowMessage("Impossible d'afficher la liste des utilisateurs", 2)
            End If
        End Try
    End Sub

    Private Sub btnAjout_Click(sender As Object, e As EventArgs) Handles btnAjout.Click
        Dim addForm As New Utilisateur
        addForm.ShowDialog()
        LoadUser()
    End Sub

    '
    '   Alter
    '
    Private Sub btnModifier_Click(sender As Object, e As EventArgs) Handles btnModifier.Click
        alter()
    End Sub

    Sub alter()
        Try
            Dim id = ListeUser.SelectedItems(0).Text
            Dim uname = ListeUser.SelectedItems(0).SubItems(1).Text
            Dim pass = ListeUser.SelectedItems(0).SubItems(4).Text
            Dim role = ListeUser.SelectedItems(0).SubItems(5).Text

            Dim alterForm As New Utilisateur

            With alterForm
                .user_id = id
                .pseudo = uname
                .pass = pass
                .role_id = role
                .ShowDialog()
            End With

            LoadUser()
        Catch ex As Exception
            Util.ShowMessage("Veuillez selectioner un utilisateur", 1)
        End Try
    End Sub

    Private Sub btnDelete_Click(sender As Object, e As EventArgs) Handles btnDelete.Click
        Try
            Dim id = ListeUser.SelectedItems(0).Text
            Beep()
            Dim msg = "Voulez-vous vraiment supprimer cet utilisateur ? " & vbCrLf & vbCrLf & "l'operation n'affectera pas les operations associe a ce dernier" & vbCrLf & vbCrLf & " - cet utilisateur n'aura plus le droit de se connecter a l'application "
            If MsgBox(msg, MsgBoxStyle.YesNo) = MsgBoxResult.Yes Then
                Database.Query("UPDATE users SET state = 0 WHERE id = '" & id & "'")
                Database.ExecuteResult()
                Util.ShowMessage("Operation effectuer avec succes")
                LoadUser()
            End If
        Catch ex As Exception
            Util.ShowMessage("Veuillez selectioner un utilisateur", 1)
        End Try
    End Sub

    Private Sub btnClose_Click(sender As Object, e As EventArgs) Handles btnClose.Click
        Close()
    End Sub
End Class


text:
<?php

/**
 * This code was generated by
 * \ / _    _  _|   _  _
 * | (_)\/(_)(_|\/| |(/_  v1.0.0
 * /       /
 */

namespace Twilio\Rest\Preview\TrustedComms;

use Twilio\Exceptions\TwilioException;
use Twilio\InstanceContext;
use Twilio\ListResource;
use Twilio\Rest\Preview\TrustedComms\BrandedChannel\ChannelList;
use Twilio\Values;
use Twilio\Version;

/**
 * PLEASE NOTE that this class contains preview products that are subject to change. Use them with caution. If you currently do not have developer preview access, please contact help@twilio.com.
 *
 * @property ChannelList $channels
 */
class BrandedChannelContext extends InstanceContext {
    protected $_channels;

    /**
     * Initialize the BrandedChannelContext
     *
     * @param Version $version Version that contains the resource
     * @param string $sid Branded Channel Sid.
     */
    public function __construct(Version $version, $sid) {
        parent::__construct($version);

        // Path Solution
        $this->solution = ['sid' => $sid, ];

        $this->uri = '/BrandedChannels/' . \rawurlencode($sid) . '';
    }

    /**
     * Fetch the BrandedChannelInstance
     *
     * @return BrandedChannelInstance Fetched BrandedChannelInstance
     * @throws TwilioException When an HTTP error occurs.
     */
    public function fetch(): BrandedChannelInstance {
        $payload = $this->version->fetch('GET', $this->uri);

        return new BrandedChannelInstance($this->version, $payload, $this->solution['sid']);
    }

    /**
     * Access the channels
     */
    protected function getChannels(): ChannelList {
        if (!$this->_channels) {
            $this->_channels = new ChannelList($this->version, $this->solution['sid']);
        }

        return $this->_channels;
    }

    /**
     * Magic getter to lazy load subresources
     *
     * @param string $name Subresource to return
     * @return ListResource The requested subresource
     * @throws TwilioException For unknown subresources
     */
    public function __get(string $name): ListResource {
        if (\property_exists($this, '_' . $name)) {
            $method = 'get' . \ucfirst($name);
            return $this->$method();
        }

        throw new TwilioException('Unknown subresource ' . $name);
    }

    /**
     * Magic caller to get resource contexts
     *
     * @param string $name Resource to return
     * @param array $arguments Context parameters
     * @return InstanceContext The requested resource context
     * @throws TwilioException For unknown resource
     */
    public function __call(string $name, array $arguments): InstanceContext {
        $property = $this->$name;
        if (\method_exists($property, 'getContext')) {
            return \call_user_func_array(array($property, 'getContext'), $arguments);
        }

        throw new TwilioException('Resource does not have a context');
    }

    /**
     * Provide a friendly representation
     *
     * @return string Machine friendly representation
     */
    public function __toString(): string {
        $context = [];
        foreach ($this->solution as $key => $value) {
            $context[] = "$key=$value";
        }
        return '[Twilio.Preview.TrustedComms.BrandedChannelContext ' . \implode(' ', $context) . ']';
    }
}


text:
package org.springframework.cloud.vault.config;

import javax.validation.constraints.NotEmpty;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.Environment;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;

/**
 * Configuration properties for Vault using the generic backend.
 *
 * @author Mark Paluch
 */
@ConfigurationProperties("spring.cloud.vault.generic")
@Validated
public class VaultGenericBackendProperties
		implements EnvironmentAware, VaultKeyValueBackendPropertiesSupport {

	/**
	 * Enable the generic backend.
	 */
	private boolean enabled = true;

	/**
	 * Name of the default backend.
	 */
	@NotEmpty
	private String backend = "secret";

	/**
	 * Name of the default context.
	 */
	@NotEmpty
	private String defaultContext = "application";

	/**
	 * Profile-separator to combine application name and profile.
	 */
	@NotEmpty
	private String profileSeparator = "/";

	/**
	 * Application name to be used for the context.
	 */
	private String applicationName = "application";

	public VaultGenericBackendProperties() {
	}

	@Override
	public void setEnvironment(Environment environment) {

		String springCloudVaultAppName = environment
				.getProperty("spring.cloud.vault.application-name");

		if (StringUtils.hasText(springCloudVaultAppName)) {
			this.applicationName = springCloudVaultAppName;
		}
		else {
			String springAppName = environment.getProperty("spring.application.name");

			if (StringUtils.hasText(springAppName)) {
				this.applicationName = springAppName;
			}
		}
	}

	public boolean isEnabled() {
		return this.enabled;
	}

	public String getBackend() {
		return this.backend;
	}

	public String getDefaultContext() {
		return this.defaultContext;
	}

	public String getProfileSeparator() {
		return this.profileSeparator;
	}

	public String getApplicationName() {
		return this.applicationName;
	}

	public void setEnabled(boolean enabled) {
		this.enabled = enabled;
	}

	public void setBackend(String backend) {
		this.backend = backend;
	}

	public void setDefaultContext(String defaultContext) {
		this.defaultContext = defaultContext;
	}

	public void setProfileSeparator(String profileSeparator) {
		this.profileSeparator = profileSeparator;
	}

	public void setApplicationName(String applicationName) {
		this.applicationName = applicationName;
	}

	@Override
	public String toString() {
		StringBuffer sb = new StringBuffer();
		sb.append(getClass().getSimpleName());
		sb.append(" [enabled=").append(this.enabled);
		sb.append(", backend='").append(this.backend).append('\'');
		sb.append(", defaultContext='").append(this.defaultContext).append('\'');
		sb.append(", profileSeparator='").append(this.profileSeparator).append('\'');
		sb.append(", applicationName='").append(this.applicationName).append('\'');
		sb.append(']');
		return sb.toString();
	}

}


text:
JNI_EXPORT jint JNI_OnLoad(JavaVM* vm, void* reserved) {
  base::android::InitVM(vm);
  JNIEnv* env = base::android::AttachCurrentThread();

  if (!content::RegisterLibraryLoaderEntryHook(env))
    return -1;

  // To be called only from the UI thread.  If loading the library is done on
  // a separate thread, this should be moved elsewhere.
  if (!content::android::RegisterShellJni(env))
    return -1;

  if (!content::RegisterLinkerTestsJni(env))
    return -1;

  content::Compositor::Initialize();
  content::SetContentMainDelegate(new content::ShellMainDelegate());
  return JNI_VERSION_1_4;
}


text:
package cc5114.perceptron;

public class ANDPerceptron extends TwoInputPerceptron {

    public ANDPerceptron() {

        super(2, 2, -3);
    }

}


text:
package cabf_br

import (
	"github.com/zmap/zcrypto/x509"
	"github.com/zmap/zlint/v3/lint"
	"github.com/zmap/zlint/v3/util"
)

type caKeyCertSignNotSet struct{}

/************************************************
BRs: 7.1.2.1b
This extension MUST be present and MUST be marked critical. Bit positions for keyCertSign and cRLSign MUST be set.
If the Root CA Private Key is used for signing OCSP responses, then the digitalSignature bit MUST be set.
************************************************/

func init() {
	lint.RegisterLint(&lint.Lint{
		Name:          "e_ca_key_cert_sign_not_set",
		Description:   "Root CA Certificate: Bit positions for keyCertSign and cRLSign MUST be set.",
		Citation:      "BRs: 7.1.2.1",
		Source:        lint.CABFBaselineRequirements,
		EffectiveDate: util.CABEffectiveDate,
		Lint:          &caKeyCertSignNotSet{},
	})
}

func (l *caKeyCertSignNotSet) Initialize() error {
	return nil
}

func (l *caKeyCertSignNotSet) CheckApplies(c *x509.Certificate) bool {
	return c.IsCA && util.IsExtInCert(c, util.KeyUsageOID)
}

func (l *caKeyCertSignNotSet) Execute(c *x509.Certificate) *lint.LintResult {
	if c.KeyUsage&x509.KeyUsageCertSign != 0 {
		return &lint.LintResult{Status: lint.Pass}
	} else {
		return &lint.LintResult{Status: lint.Error}
	}
}


text:
- a part of the assemblying process is parallelized for some speedup, contributed by [@emchristiansen][@emchristiansen] as [#73][73].
- sbt-assembly now outputs fat jars into `crossTarget` (`target/scala_X.X/`) instead of `target` (`target/`). [#70][70] reported by [@maddogg14524][@maddogg14524]

  [@emchristiansen]: https://github.com/emchristiansen
  [@maddogg14524]: https://github.com/maddogg14524
  [70]: https://github.com/sbt/sbt-assembly/issues/70
  [73]: https://github.com/sbt/sbt-assembly/pull/73


text:
<?php
/**
 * Class PHPUnitAbstract
 *
 * @package PowderBlue\Converter\Test\Feed
 * @author Christos Georgiou <christos@powder-blue.com>
 */

namespace PowderBlue\Converter\Test;

class PHPUnitAbstract extends \PHPUnit_Framework_TestCase
{
    /**
     * @param string $name
     * @param string $className
     * @return \ReflectionProperty
     */
    protected static function getProperty($name, $className)
    {
        $rc = new \ReflectionClass($className);
        $property = $rc->getProperty($name);
        $property->setAccessible(true);

        return $property;
    }

    /**
     * @param string $name
     * @param string $className
     * @return \ReflectionMethod
     */
    protected static function getMethod($name, $className)
    {
        $rc = new \ReflectionClass($className);
        $method = $rc->getMethod($name);
        $method->setAccessible(true);

        return $method;
    }

    /**
     * Returns the full name (with namespace) of an object
     *
     * @param $object
     * @return string
     */
    protected static function getFullClassName($object)
    {
        $rc = new \ReflectionClass($object);

        return $rc->getName();
    }

    /**
     * @param        $filename
     * @param null $ext
     * @param string $path
     * @return string
     */
    protected static function loadFixturePath($filename, $ext = null, $path = 'tests/fixtures/')
    {
        if (isset($ext)) {
            $ext = 'exports/' . $ext . '/';
        }

        return $path . $ext . $filename;
    }
}


text:
<?php
function getFreqValue($val){
	if($val == 100)
		$ret = "Daily";
	else if($val == 110)
		$ret = "Weekly";
	else if($val == 111)
		$ret = "Monthly";
	else
		$ret = "Adhoc";

	return $ret;
}
function getEmpLevel($val){
	if($val == 0)
		$ret = "Individual Contributor";
	else if($val == 1)
		$ret = "Team Leader";
	else if($val == 2)
		$ret = "Manager";
	else
		$ret = "Unknown";

	return $ret;
}

function getWorkingDays($startDate,$endDate,$holidays){
	//The function returns the no. of business days between two dates and it skips the holidays
    // do strtotime calculations just once
    $endDate = strtotime($endDate);
    $startDate = strtotime($startDate);

    //The total number of days between the two dates. We compute the no. of seconds and divide it to 60*60*24
    //We add one to inlude both dates in the interval.
    $days = ($endDate - $startDate) / 86400 + 1;

    $no_full_weeks = floor($days / 7);
    $no_remaining_days = fmod($days, 7);

    //It will return 1 if it's Monday,.. ,7 for Sunday
    $the_first_day_of_week = date("N", $startDate);
    $the_last_day_of_week = date("N", $endDate);

    //---->The two can be equal in leap years when february has 29 days, the equal sign is added here
    //In the first case the whole interval is within a week, in the second case the interval falls in two weeks.
    if ($the_first_day_of_week <= $the_last_day_of_week) {
        if ($the_first_day_of_week <= 6 && 6 <= $the_last_day_of_week) $no_remaining_days--;
        if ($the_first_day_of_week <= 7 && 7 <= $the_last_day_of_week) $no_remaining_days--;
    }
    else {
        // (edit by Tokes to fix an edge case where the start day was a Sunday
        // and the end day was NOT a Saturday)

        // the day of the week for start is later than the day of the week for end
        if ($the_first_day_of_week == 7) {
            // if the start date is a Sunday, then we definitely subtract 1 day
            $no_remaining_days--;

            if ($the_last_day_of_week == 6) {
                // if the end date is a Saturday, then we subtract another day
                $no_remaining_days--;
            }
        }
        else {
            // the start date was a Saturday (or earlier), and the end date was (Mon..Fri)
            // so we skip an entire weekend and subtract 2 days
            $no_remaining_days -= 2;
        }
    }

    //The no. of business days is: (number of weeks between the two dates) * (5 working days) + the remainder
//---->february in none leap years gave a remainder of 0 but still calculated weekends between first and last day, this is one way to fix it
   $workingDays = $no_full_weeks * 5;
    if ($no_remaining_days > 0 )
    {
      $workingDays += $no_remaining_days;
    }

    //We subtract the holidays
    foreach($holidays as $holiday){
        $time_stamp=strtotime($holiday);
        //If the holiday doesn't fall in weekend
        if ($startDate <= $time_stamp && $time_stamp <= $endDate && date("N",$time_stamp) != 6 && date("N",$time_stamp) != 7)
            $workingDays--;
    }

    return $workingDays;
	//Example:
	//$holidays=array("2008-12-25","2008-12-26","2009-01-01");
	//echo getWorkingDays("2008-12-22","2009-01-02",$holidays)
	// => will return 7
}

function date_check_in_range($start_date, $end_date, $date_from_user)
{
  // Convert to timestamp
  $start_ts = strtotime($start_date);
  $end_ts = strtotime($end_date);
  $user_ts = strtotime($date_from_user);

  // Check that user date is between start & end
  return (($user_ts >= $start_ts) && ($user_ts <= $end_ts));
}

function getDayValue(){
	//$date =
	$dayofweek = date('w');
	//$res = date('Y-m-d', strtotime(($day - $dayofweek).' day', strtotime($date)));
	return $dayofweek;
}

//DB Functions
function getLoginDetails($db,$uname,$psw){
	$ret = $db->rawQuery('SELECT me.*,md.`discipline_name`,mj.`job_name` FROM `msc_employee` me,`msc_discipline` md,`msc_job` mj WHERE me.emp_ibmid ="'.$psw.'" AND me.emp_email = "'.$uname.'" AND md.id =me.emp_discipline AND mj.id = me.emp_job');
	return $ret[0];
}
function getDiscJob($db,$discid,$jobid){
	$ret = $db->rawQuery('SELECT md.`discipline_name`,mj.`job_name` FROM `msc_discipline` md,`msc_job` mj WHERE md.id ="'.$discid.'" AND mj.id = "'.$jobid.'"');
	return $ret[0];
}
function getTlMngrNames($db,$tlid,$mngid){
	$ret = $db->rawQuery('SELECT me.`emp_name` FROM `msc_employee` me WHERE me.`id` in ('.$tlid.','.$mngid.')');
	//print_r($ret);
	return $ret;
}
?>


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!--2016/05/18 Complete redo-->

    <color name="accent_material_light">#fff</color>
    <color name="activity_background">#50000000</color>

    <color name="camera_controlbar_bg_dark">#dd000000</color>
    <color name="camera_controlbar_bg_light">#dd000000</color>
    <color name="camera_error_text">#ffcc0000</color>
    <color name="camera_info_text_dark">#fff</color>
    <color name="camera_info_text_instant">#99ffffff</color>
    <color name="camera_info_text_light">#fff</color>
    <color name="camera_instant_bar">#55ffffff</color>
    <color name="camera_instant_bar_bg">#11ffffff</color>
    <color name="camera_instant_secondary">#33ffffff</color>
    <color name="camera_toolbar_bg_dark">#89000000</color>
    <color name="camera_toolbar_bg_light">#89000000</color>
    <color name="camera_tools_back">#88ffffff</color>
    <color name="candidate_strip_divider_color">#11ffffff</color>
    <color name="card_divider">#11ffffff</color>
    <color name="card_pressed_background">#33333333</color>
    <color name="card_pressed_background_dark">#33333333</color>

    <color name="card_tap_to_translate">#ff00bcd4</color>
    <color name="card_update_pkg">#fffdd835</color>
    <color name="card_upgrade_to_larger_pkg">#ff303f9f</color>
    <color name="card_with_img_title_red">#fff1524b</color>
    <color name="card_wl_download">#ff4285f4</color>
    <color name="copydrop_dark_grey">#ff434343</color>
    <color name="copydrop_light_grey">#ffcccccc</color>
    <color name="copydrop_onboarding_bg">#ff3949ab</color>
    <color name="copydrop_tooltip_bg">#ff333333</color>
    <color name="copydrop_tooltip_text_color">#ffdddddd</color>
    <color name="copydrop_translated_text">#fff</color>
    <color name="copydrop_white_alpha_88">#88ffffff</color>
    <color name="copydrop_white_alpha_aa">#aaffffff</color>

    <color name="divider_grey">#11ffffff</color>
    <color name="focused_background">#99111111</color>

    <color name="design_snackbar_background_color">#ff323232</color>
    <color name="design_textinput_error_color_dark">#ffff6e6e</color>
    <color name="design_textinput_error_color_light">#ffd50000</color>

    <color name="foreground_material_dark">@android:color/white</color>
    <color name="foreground_material_light">@android:color/black</color>

    <color name="gf_foreground_content">#ffffffff</color>
    <color name="gf_header_background">#80000000</color>
    <color name="gf_shadow">#10000000</color>
    <color name="gtrStrokeColor">#aaffffff</color>
    <color name="gtrStrokeColorHistory">#99ffffff</color>
    <color name="gtrStrokeColorPreviousRecognition">#ddffffff</color>
    <color name="gtrStrokeColorRecognized">#fff</color>
    <color name="gtr_btn_candidate_normal">#ffe5e5e5</color>
    <color name="gtr_btn_candidate_pressed">#ff3dccff</color>
    <color name="gtr_candidate_first">#ff0099cc</color>
    <color name="gtr_candidate_normal">#ff0099cc</color>
    <color name="gtr_candidate_not_selectable">#ff0099cc</color>
    <color name="gtr_candidate_selected">#ff0099cc</color>
    <color name="gtr_candidate_strip_divider">#ffa0a0a0</color>
    <color name="handwriting_pad_bg">#80000000</color>
    <color name="handwriting_results">#ffe5e5e5</color>

    <color name="icon_dark_disabled">#4cffffff</color>
    <color name="icon_dark_normal">#ddffffff</color>
    <color name="icon_light_disabled">#4cffffff</color>
    <color name="icon_light_normal">#ddffffff</color>
    <color name="icon_pressed_blue">#fff</color>
    <color name="indicator_text">#ccffffff</color>
    <color name="info_panel_background">#80000000</color>
    <color name="input_hint_text">#aaffffff</color>
    <color name="input_method_color_blue">#ff0099cc</color>
    <color name="input_method_color_red">#fff93238</color>
    <color name="langpicker_text">#ffffffff</color>
    <color name="link_text">#ddffffff</color>
    <color name="offline_pin_downloading">#fff</color>
    <color name="offline_pin_idle">#89ffffff</color>
    <color name="offline_pin_progress_background_pressed">#80111111</color>

    <color name="input_method_color_blue_light">#770099cc</color>
    <color name="input_method_color_red_light">#77f93238</color>

    <color name="nav_drawer_header_bg">#ff3f51b5</color>
    <color name="offline_activity_list_divider_grey">#22ffffff</color>
    <!--<color name="offline_dialog_banner_background">@color/quantum_indigo500</color>-->

    <color name="primary_blue_500_90alpha">#e54285f4</color>
    <color name="primary_text">#fff</color>
    <color name="quantum_googblue50">#80000000</color>
    <color name="quantum_grey">#000</color>
    <color name="quantum_grey400">#aaffffff</color>
    <color name="quantum_grey500">#aaffffff</color>
    <color name="quantum_grey600">#aaffffff</color>

    <color name="offline_state_bg">#80000000</color>
    <!--<color name="primary_blue">@color/quantum_googblue500</color>-->
    <!--<color name="primary_blue_dark">@color/quantum_googblue700</color>-->

    <color name="quantum_black_100">#fff</color>
    <color name="quantum_black_divider">#1fffffff</color>
    <color name="quantum_black_hint_text">#61ffffff</color>
    <color name="quantum_black_secondary_text">#89ffffff</color>
    <color name="quantum_black_text">#ddffffff</color>

    <!--<color name="quantum_grey">@color/quantum_grey500</color>-->
    <!--<color name="quantum_grey100">#fff5f5f5</color>-->
    <!--<color name="quantum_grey200">#ffeeeeee</color>-->
    <!--<color name="quantum_grey300">#ffe0e0e0</color>-->
    <!--<color name="quantum_grey400">#ffbdbdbd</color>-->
    <!--<color name="quantum_grey50">#fffafafa</color>-->
    <!--<color name="quantum_grey500">#ff9e9e9e</color>-->
    <!--<color name="quantum_grey600">#ff757575</color>-->
    <!--<color name="quantum_grey700">#ff616161</color>-->
    <!--<color name="quantum_grey800">#ff424242</color>-->
    <!--<color name="quantum_grey900">#ff212121</color>-->
    <color name="quantum_greyblack1000">#ff000000</color>
    <color name="quantum_greywhite1000">#ffffffff</color>

    <color name="quantum_white_100">#ffffffff</color>
    <color name="quantum_white_divider">#1fffffff</color>
    <color name="quantum_white_hint_text">#80ffffff</color>
    <color name="quantum_white_secondary_text">#b3ffffff</color>
    <color name="quantum_white_text">#ffffffff</color>

    <color name="result_background">#33000000</color>
    <color name="result_text">#fff</color>
    <color name="secondary_text">#ddffffff</color>
    <color name="selected_background">#80111111</color>
    <color name="selected_text">#fff</color>

    <color name="suggest_title">#ffcc0000</color>

    <color name="tertiary_text">#aaffffff</color>
    <color name="tooltip_background">#bb000000</color>
    <color name="tooltip_text">#ffffffff</color>
    <color name="voice_active_text_color">#ffff4545</color>
    <color name="voice_button_back_active">#fff93238</color>
    <color name="voice_button_back_loading">#fffcfcfc</color>
    <color name="voice_button_back_paused">#fff5f5f5</color>
    <color name="voice_button_border_loading">#ffe8e8e8</color>
    <color name="voice_button_border_paused">#ffededed</color>
    <color name="voice_button_border_tts_active1">#ff4285f4</color>
    <color name="voice_button_border_tts_active2">#ff3367d6</color>
    <color name="voice_button_border_voice_active1">#fff</color>
    <color name="voice_button_border_voice_active2">#fff</color>
    <color name="voice_button_icon_active">#ffffffff</color>
    <color name="voice_button_icon_paused">#ffa8a8a8</color>
    <color name="voice_button_icon_tts_loading">#ff4285f4</color>
    <color name="voice_button_icon_voice_loading">#ffff4545</color>
    <color name="voice_error_color">#fff93238</color>
    <color name="voice_pulse_color_1">#333333</color>
    <color name="voice_pulse_color_2">#222222</color>
    <color name="voice_pulse_color_border">#111111</color>
    <color name="voice_result_pressed">#22ffffff</color>
    <color name="voice_timer_color">#fff93238</color>
    <color name="voice_translation_text_color">#ff4545ff</color>

</resources>


text:
'use strict';

require('./orders.state.js');
require('./ordersList.controller.js');


text:
return cross_.bind(function (callback, onerror) {
    var response, responseObject, responseType = "", decoder, error;
    var xhr = {
        status: 0,
        readyState: 0,
        method: null,
        url: null,
        http: null,
        headers: {},
        responseHeaders: {},
        get response() {
            if (responseType === "" || responseType === "text") {
                if (this.readyState !== 4) return '';
                return decoder ? decoder(response) : String(response);
            }
            else if (error) return null;
            if (responseObject !== null) return responseObject;
            switch (responseType) {
                case "arraybuffer":
                    return response.buffer;
                case "json":
                    if (!response) return null;
                    responseObject = JSON.parse(decoder ? decoder(response) : String(response));
                    return responseObject;
            }
            return responseObject;

        },
        set response(v) {
            response = v;
        },
        getResponseHeader(key) {
            key = String(key).toLowerCase();
            if (this.responseHeaders[key]) return this.responseHeaders[key];
            if (key === "access-control-expose-headers") {
                return 'set-cookie,location';
            }
            return null;
        },
        send(data) {
            var { hostname, port, path, auth } = parseURL(this.url);
            if (data instanceof FormData) data = String(data);
            if (data) {
                data = Buffer.from(data);
                this.headers["Content-Length"] = data.length;
            }
            var options = {
                method: this.method,
                hostname,
                port,
                path,
                auth,
                headers: this.headers,
            };
            var req = this.http.request(options, function (res) {
                var data = [];
                xhr.status = res.statusCode;
                xhr.responseHeaders = res.headers;
                res.on("data", function (chunk) {
                    xhr.readyState = 4;
                    data.push(chunk);
                });
                res.on("end", function () {
                    response = Buffer.concat(data);
                    xhr.readyState = 4;
                    callback();
                });
                var onerror1 = function (e) {
                    xhr.readyState = 4;
                    error = e;
                    onerror(e);
                };
                res.on("error", onerror1);
                res.on('timeout', onerror1);
                this.readyState = 2;
            });
            this.readyState = 1;
            req.setTimeout(3000);
            if (data) req.end(data);
            else req.end();
        },
        open(method, url) {
            this.method = method;
            this.url = url;
            this.status = 0;
            this.readyState = 0;
            response = null;
            responseObject = null;
            error = null;
            var http;
            if (/^http\:/i.test(url)) {
                http = require("http");
            }
            else {
                http = require("https");
            }
            this.http = http;
        },
        get responseType() {
            return responseType;
        },
        set responseType(v) {
            if (v === "document") return;
            if (this.status !== 0) throw new Error("状态错误");
            responseType = v;
        },
        setRequestHeader(key, value) {
            this.headers[key] = value;
        },
        overrideMimeType(type) {
            responseType = type;
            if (/gb(k|2312|18030)/.test(type)) {
                decoder = require("../efront/gbk2utf8");
            }
        },
    };
    return xhr;
}, null, undefined);


text:
"""Module for default values.

This module contains many of the default values we use in various places in
the codebase.

NOTE: We should minimise the dependencies from this module.
"""

# pylint: disable=line-too-long

# NOTE: Whenever you update any of the default values below, please also make
# the same updates at the following locations:
# * AnomalyConfig defined in ../proto/sheriff.proto
# * anomaly_configs_defaults defined in
#   https://chrome-internal.googlesource.com/infra/infra_internal/+/HEAD/infra/config/subprojects/chromeperf-sheriffs.star

# pylint: enable=line-too-long

from __future__ import print_function
from __future__ import division
from __future__ import absolute_import

# Maximum number of points to consider at one time.
MAX_WINDOW_SIZE = 50

# Minimum number of points in a segment. This can help filter out erroneous
# results by ignoring results that were found from looking at too few points.
MIN_SEGMENT_SIZE = 6

# Minimum absolute difference between medians before and after.
MIN_ABSOLUTE_CHANGE = 0

# Minimum relative difference between medians before and after.
MIN_RELATIVE_CHANGE = 0.1

# "Steppiness" is a number between 0 and 1 that indicates how similar the
# shape is to a perfect step function, where 1 represents a step function.
MIN_STEPPINESS = 0.5

# The "standard deviation" is based on a subset of points in the series.
# This parameter is the minimum acceptable ratio of the relative change
# and this standard deviation.
MULTIPLE_OF_STD_DEV = 2.5


text:
//
//  RKObjectMapping+INExtensions.h
//
//  Created by Hernan Gonzalez on 01/11/14.
//  Copyright (c) 2013 Indeba.com. All rights reserved.
//

#import <RestKit/ObjectMapping.h>

@interface RKObjectMapping (Mapping)

/**
 */
+ (RKObjectMapping*)responseMappingForClass:(Class)responseClass
                               mappingInfo:(NSDictionary *)dict;
/**
 otherwise return nil
 */
+ (RKObjectMapping *)requestMappingForClass:(Class)requestClass
                                mappingInfo:(NSDictionary *)dict;
@end


text:
var $loginMSG, $profile, $profile2, chatRef, fireChat, currentUser, messageListRef, messageField, messageContainer, userlist;

$(function(){

  $loginMSG = $('#login-message');
  $profile = $('#profile');
  $profile2 = $('#profile2');

  $('.myWrapper, .myWrapperSmall').easyTicker({
    direction: 'up',
    easing: 'swing',
    speed: 'slow',
    interval: 5000,
    height: 'auto',
    visible: 1,
    mousePause: 0,
  });

  $('#logoutBTN').hide();
  $('#firechat-wrapper').hide();
  $('#smallPlayer').hide();

  chatRef = new Firebase('https://oc-radio.firebaseio.com');
  messageListRef = new Firebase('https://oc-radio.firebaseio.com/messages');
  userlist = new Firebase('https://oc-radio.firebaseio.com/users');

  messageField = $('#messageInput');
  messageContainer = $('#messages');

  chatRef.onAuth(function(authData) {
    if (authData) {
      authDataCallback(authData, true);
    } else {
      authDataCallback(authData, false);
    }
  });
  changeCheckStatus();
});

function changeCheckStatus(){
  // NEED TO SAVE THIS VALUE INTO FIREBASE USER ACCOUNTS -- FINISHED
  $("#enterSender").change(function(){
    var c = this.checked ? true : false;
    sendMessageWithEnter(c);
  });
}
// FOR SEND WITH ENTER OPTION
function sendMessageWithEnter(b){
  switch(b){
    case true:
      console.log(true);
      messageField.keypress(function(e){
        if ( e.which == 13 ) {
          e.preventDefault();
          postNewMessage();
        }
      });
      break;

    case false:
    console.log(false);
      break;
  }
}

//SEND NEW MESSAGE TO FIREBASE SERVER
function postNewMessage(){
    messageField.val().replace(/\n/g, "");
    var authData = chatRef.getAuth();
    var username = authData.password.email.split('@')[0];
    var message = messageField.val();

    var time = new Date();
    var hours = time.getHours();
    var minutes = time.getMinutes();

    /*
      FOR TWELVE HOUR FORMAT
      if(hours > 12){
        hours-=12;
      }else if(hours == 0){
        hours = 12;
      }
    */

    if(minutes < 10){
      minutes = "0" + minutes;
    }

    var timeOfDay = hours + ":" + minutes + " ";
    timestamp = timeOfDay + " ";

    //SAVE DATA TO FIREBASE AND EMPTY FIELD
    messageListRef.push({
        'userid': username,
        'text': message,
        'date': timestamp
      });
    messageField.val("");

}

// GET FIREBASE MESSAGE LIST ON LOGIN
function getMessages(authData){
  messageListRef.limitToLast(100).on("child_added", function(snapshot, previousKey) {
    var currentkey = snapshot.key();
    var data = snapshot.val();
    var username, message, messageRow, nameElement, messageElement;
    username = data.date + "" + data.userid;
    message = data.text;
    messageRow = $("
");
    nameElement = $("");
    messageElement = $("

")
    messageElement.text(message);
    nameElement.text(username);
    messageRow.append(messageElement).prepend(nameElement);
    messageContainer.append(messageRow);
    $(messageContainer).scrollTop($(messageContainer)[0].scrollHeight);
  });

}

function register(){
  var email = $('#email').val();
  var pass = $('#password').val();

  var mailName = email.split('@')[0];

  var myUser = {
    email: email,
    password: pass
  }

  chatRef.createUser(myUser, function (error, user) {
    var newProfileObj = {};
    if (error) {
      $loginMSG.empty();
      $loginMSG.append("User " + user + " already exists");
    } else {
        newProfileObj[user.uid] = {
          email: email,
          name: mailName,
          // Would be useful to make a default propteies object and append that to users
          // that don't have options. For example, if I add the ability to go offline, all current users
          // should get that option without creating a new account.
          // DEAFULT OPTIONS -> USERLIST OPTIONS -> if(USERLIST_OPTIONS are less than DEFAULT_OPTIONS) -> ADD
          // DEFAULT OPTIONS
          options: {
            sendWithEnter: true,
            hideTicker: false,
            autoPlay: true,
            private: true
          }
        };
        userlist.push(newProfileObj);
        $loginMSG.empty();
        $loginMSG.append("User successfully created");
      }
    });
}

function login (){
  var user = $('#email').val();
  var pass = $('#password').val();
  chatRef.authWithPassword({
    email    : user,
    password : pass
  }, authHandler);
}

function logout(){

  var r = confirm('Are you sure you want logout?');
  if (r == true) {
    chatRef.unauth();
    location.reload();
  } else {
    return;
  }
}

function resetPass(){
  alert("Cannot rest");
}

function showForm(){
  $('#login-wrapper').show(500);
  $('#loginBTN-container').hide();
}

// find a suitable name based on the meta info given by each provider
function getName(authData) {
  switch(authData.provider) {
     case 'password':
       return authData.password.email.replace(/@.*/, '');
     case 'twitter':
       return authData.twitter.displayName;
     case 'facebook':
       return authData.facebook.displayName;
  }
}

function clearMessages(){
    var day =new Date().getDay();
    var hours =new Date().getHours();

    if (day === 0 && hours >12 && hours < 13)  // day is a 0 index base
                                               // sunday between 12:00 and 13:00

                                               //What you want to do goes here
  messageListRef.remove();
}

// Create a callback which logs the current auth state
function authDataCallback(authData, loggedin) {
  if(loggedin){

    $('#login-wrapper').hide(500);
    $('.messages-container').show(500);
    $('#logoutBTN').show();
    $('#loginBTN').hide();
    $('.input-container').show(500);
    $('header').show(500);
    $("#smallPlayer").show(500);

    messageContainer.empty();

    $profile.empty();
    $profile.append(getName(authData));

    $profile2.empty();
    $profile2.append(getName(authData));
    getMessages(authData);
  }else{
    $('.messages-container').hide();
    $('.input-container').hide();
    $('#login-wrapper').show(500);
    $('#logoutBTN').hide();
    $('header').hide();
    $("#smallPlayer").hide();
    messageContainer.empty();
    $loginMSG.empty();
    $loginMSG.append("OC Radio | Player");
  }

}

// Create a callback to handle the result of the authentication
function authHandler(error, authData) {
  if (error) {
    $loginMSG.empty();
    $loginMSG.append(error);
  } else {
    var userID = authData.uid;
    var user = userlist.child(userID);

    var userName = user.child('name');
    var userOptions = user.child('options');
    var path = userOptions.toString();

    // Attach an asynchronous callback to read the data at our posts reference
    userlist.on("value", function(snapshot) {
      var data = snapshot.val()
      for(key in data){
        var userKey = data[key];
        for(nkey in userKey){
          if(userID == nkey){
            $("#enterSender").prop('checked', data[key][nkey].options.sendWithEnter);
            var check = data[key][nkey].options.sendWithEnter;
            sendMessageWithEnter(check);
          }
        }
      }

    }, function (errorObject) {
      console.log("The read failed: " + errorObject.code);
    });

    //$('#enterSender').prop('checked', authData.options.sendWithEnter);
  }
}


text:
$(document).ready(function () {
    $("#saveUserInfo").click(function () {
        var $saveForm = $('#saveForm');
        $saveForm.validate({
            errorClass: "has-error",
            rules: {
                email: "required",
                phone: "required",
                nickname: "required"
            },
            onkeyup: false
        });
        if ($saveForm.valid()) {
            var data = Commons.formData("#saveForm");
            if (data.password && !data.affirmPassword) {
                Messager.warn("两次密码不一致,请重新输入");
                return;
            }
            if (data.password && data.affirmPassword && data.password !== data.affirmPassword) {
                Messager.warn("两次密码不一致,请重新输入");
                return;
            }
            if (data.password && !data.oldPassword) {
                Messager.warn("请输入原始密码");
                return;
            }
            Ajax.Post('/user/info/save', JSON.stringify(data), function (result) {
                if (result.code === 200) {
                    Messager.success('保存成功');
                    location.reload()
                } else {
                    Messager.warn(result.msg);
                }
            });
        }
    });
});


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

namespace TradeAndTravel
{
    public class Forest : GatheringLocation
    {
        public Forest(string name) :
            base(name, LocationType.Forest, ItemType.Wood, ItemType.Weapon)
        {
        }

        public override Item ProduceItem(string itemName)
        {
            return new Wood(itemName, null);
        }
    }
}


text:
module Tins
  class Bijection < Hash
    def self.[](*pairs)
      pairs.size % 2 == 0 or
        raise ArgumentError, "odd number of arguments for #{self}"
      new.fill do |obj|
        (pairs.size / 2).times do |i|
          j = 2 * i
          key = pairs[j]
          value = pairs[j + 1]
          obj.key?(key) and raise ArgumentError, "duplicate key #{key.inspect} for #{self}"
          obj.inverted.key?(value) and raise ArgumentError, "duplicate value #{value.inspect} for #{self}"
          obj[pairs[j]] = pairs[j + 1]
        end
      end
    end

    def initialize(inverted = Bijection.new(self))
      @inverted = inverted
    end

    def fill
      if empty?
        yield self
        freeze
      end
      self
    end

    def freeze
      r = super
      unless @inverted.frozen?
        @inverted.freeze
      end
      r
    end

    def []=(key, value)
      key?(key) and return
      super
      @inverted[value] = key
    end

    attr_reader :inverted
  end
end


text: Doctrine ORM adapter for Conpago framework.


text:
module.exports = function(RED) {
    function nodeFunction(config) {
        RED.nodes.createNode(this,config);
    }
    RED.nodes.registerType("Iter",nodeFunction);
}


text:
<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>

    <style name="AppTheme.NoActionBar">
        <item name="windowActionBar">false</item>
        <item name="windowNoTitle">true</item>
    </style>

    <style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />

    <style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />

    <style name="FabStyle">
        <item name="android:layout_width">wrap_content</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:layout_margin">@dimen/spacing_large</item>
        <item name="android:src">@drawable/ic_popup_sync</item>
        <item name="borderWidth">0dp</item>
        <item name="elevation">6dp</item>
        <item name="pressedTranslationZ">12dp</item>
        <item name="rippleColor">@android:color/white</item>
    </style>

</resources>


text:
package org.clockwise.util;
/**
* A strategy for handling errors. This is especially useful for handling
* errors that occur during asynchronous execution of tasks that have been
* submitted to a TaskScheduler. In such cases, it may not be possible to
* throw the error to the original caller.
*
* @author Mark Fisher
* @since 3.0
*/
public interface ErrorHandler {
/**
* Handle the given error, possibly rethrowing it as a fatal exception.
*/
void handleError(Throwable t);
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- From: file:/tmp/tmp-deduplicated8343575191335814618/blaze-out/gcc-4.X.Y-crosstool-v18-hybrid-grtev4-k8-opt/genfiles/java/com/google/android/gmscore/integ/client/places/res/values-el/strings.xml -->
    <eat-comment/>
    <string msgid="1303870564366209730" name="place_autocomplete_clear_button">"Διαγραφή αναζητήσεων"</string>
    <string msgid="2809095107724486040" name="place_autocomplete_search_hint">"Αναζήτηση"</string>
</resources>