text:
<?php

namespace Pagekit\Site\Controller;

use Pagekit\Application as App;
use Pagekit\Application\Controller;
use Pagekit\Application\Exception;
use Pagekit\Site\Entity\Node;

/**
 * @Access("system: manage site")
 * @Response("json")
 */
class NodeController extends Controller
{
    /**
     * @Route("/", methods="GET")
     */
    public function indexAction()
    {
        return Node::findAll();
    }

    /**
     * @Route("/{id}", methods="GET", requirements={"id"="\d+"})
     */
    public function getAction($id)
    {
        return Node::find($id);
    }

    /**
     * @Route("/", methods="POST")
     * @Route("/{id}", methods="POST", requirements={"id"="\d+"})
     * @Request({"node": "array", "id": "int"}, csrf=true)
     */
    public function saveAction($data, $id = 0)
    {
        try {

            if (!$node = Node::find($id)) {
                $node = new Node;
                unset($data['id']);
            }

            $node->save($data);

            return $node;

        } catch (Exception $e) {
            return ['message' => $e->getMessage(), 'error' => true];
        }
    }

    /**
     * @Route("/{id}", methods="DELETE", requirements={"id"="\d+"})
     * @Request({"id": "int"}, csrf=true)
     */
    public function deleteAction($id)
    {
        try {

            if ($node = Node::find($id)) {
                $node->delete();
            }

        } catch (Exception $e) {
            return ['message' => $e->getMessage(), 'error' => true];
        }

        return ['message' => __('Success')];
    }

    /**
     * @Route("/bulk", methods="POST")
     * @Request({"nodes": "array"}, csrf=true)
     */
    public function bulkSaveAction($nodes = [])
    {
        foreach ($nodes as $data) {
            $this->saveAction($data, isset($data['id']) ? $data['id'] : 0);
        }

        return Node::findAll();
    }

    /**
     * @Route("/bulk", methods="DELETE")
     * @Request({"ids": "array"}, csrf=true)
     */
    public function bulkDeleteAction($ids = [])
    {
        foreach (array_filter($ids) as $id) {
            $this->deleteAction($id);
        }

        return Node::findAll();
    }
}


text:
#ifndef CR_ERROR_H
#define CR_ERROR_H

#ifdef __cplusplus
extern "C" {
#endif

#ifndef __GNUC__
#define NORETURN_PRINTF
#define PRINTF
#else
#define NORETURN_PRINTF __attribute__ ((__noreturn__,format(printf,1,2)))
#define PRINTF __attribute__ ((format(printf,1,2)))
#endif

void crEnableWarnings(int onOff);

void crDebug( char *format, ... ) PRINTF;
void crWarning( char *format, ... ) PRINTF;
void crInfo( char *format, ... ) PRINTF;

void crError( char *format, ... ) NORETURN_PRINTF;

#ifndef NDEBUG
#define CRASSERT( PRED ) ((PRED)?(void)0:crError( "Assertion failed: %s, file %s, line %d", #PRED, __FILE__, __LINE__))
#define THREADASSERT( PRED ) ((PRED)?(void)0:crError( "Are you trying to run a threaded app ?\nBuild with 'make threadsafe'\nAssertion failed: %s, file %s, line %d", #PRED, __FILE__, __LINE__))
#else
#define CRASSERT( PRED ) ((void)0)
#define THREADASSERT( PRED ) ((void)0)
#endif

#ifdef __cplusplus
}
#endif

#endif /* CR_ERROR_H */

redpajama_set_name: RedPajamaGithub


text:
//
//  ZYSettingTableViewController.m
//  ZYLottery
//
//  Created by 朝阳 on 2017/11/1.
//  Copyright © 2017年 sunny. All rights reserved.
//

#import "ZYSettingTableViewController.h"
#import "ZYPushTableViewController.h"
#import "MBProgressHUD+XMG.h"

@interface ZYSettingTableViewController ()

@end

@implementation ZYSettingTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.title = @"设置";

    // 第0组
    [self setupGroup0];

    // 第1组
    [self setupGroup1];

    // 第2组
    [self setupGroup2];

}

- (void)setupGroup0
{
    ZYSettingArrowItem *item = [ZYSettingArrowItem itemWithIcon:[UIImage imageNamed:@"RedeemCode"] title:@"使用兑换码"];

    //    item.destVC = [UIViewController class];

    // block 防止循环引用.
    // block 会对代码块中的强指针强引用,导致控制器无法释放
    /*
     block 会对self.navigationController 的self强引用着
     */
    // __strong
    //     __weak ZYSettingTableViewController *weakSelf = self;

    // typeof(x) 动态根据x判断x的真实类型
    __weak typeof(self) weakSelf = self;

    // 使用block跳转控制器传参
    item.OperationBlock = ^(NSIndexPath *indexPath){

        UIViewController *vc= [[UIViewController alloc] init];
        vc.navigationItem.title = @"ZY";
        vc.view.backgroundColor = [UIColor greenColor];

        [weakSelf.navigationController pushViewController:vc animated:YES];

    };

    // 把行模型都放到一个行模型数组中
    NSArray *items = @[item];
    // 把行模型数组放到组模型中
    ZYSettingGroup *group = [ZYSettingGroup groupWithItem:items];
    group.headerTitle = @"会当凌绝顶";
    group.footerTitle = @"一览众山小";

    //    item.type = ZYSettingItemRightViewStateArrow;

    // 把组模型放到 组模型数组中
    [self.groups addObject:group];
}

- (void)setupGroup1
{
    ZYSettingArrowItem *item11 = [ZYSettingArrowItem itemWithIcon:[UIImage imageNamed:@"MorePush"] title:@"推送和提醒"];
    //    item11.type = ZYSettingItemRightViewStateArrow;

    item11.destVC = [ZYPushTableViewController class];

    ZYSettingSwitchItem *item12 = [ZYSettingSwitchItem itemWithIcon:[UIImage imageNamed:@"handShake"] title:@"使用摇一摇机选"];
    //    item12.type = ZYSettingItemRightViewStateSwitch;
    item12.on = YES;

    ZYSettingItem *item13 = [ZYSettingSwitchItem itemWithIcon:[UIImage imageNamed:@"sound_Effect"] title:@"声音效果"];
    //    item13.type = ZYSettingItemRightViewStateSwitch;

    ZYSettingItem *item14 = [ZYSettingSwitchItem itemWithIcon:[UIImage imageNamed:@"More_LotteryRecommend"] title:@"购彩小助手"];
    //    item14.type = ZYSettingItemRightViewStateSwitch;

    NSArray *items = @[item11,item12,item13,item14];

    ZYSettingGroup *group = [ZYSettingGroup groupWithItem:items];
    group.headerTitle = @"会当凌绝顶";
    group.footerTitle = @"一览众山小";

    [self.groups addObject:group];
}

- (void)setupGroup2
{
    // 创建行模型
    ZYSettingItem *item21 = [ZYSettingArrowItem itemWithIcon:[UIImage imageNamed:@"RedeemCode"] title:@"检查版本更新"];
    item21.OperationBlock = ^(NSIndexPath *indexPath){
        [MBProgressHUD showSuccess:@"没有版本更新"];
    };

    ZYSettingItem *item22 = [ZYSettingArrowItem itemWithIcon:[UIImage imageNamed:@"MoreShare"] title:@"分享"];

    ZYSettingItem *item23 = [ZYSettingArrowItem itemWithIcon:[UIImage imageNamed:@"MoreNetease"] title:@"产品推荐"];

    ZYSettingItem *item24 = [ZYSettingArrowItem itemWithIcon:[UIImage imageNamed:@"MoreAbout"] title:@"关于"];

    NSArray *items = @[item21, item22, item23, item24];

    ZYSettingGroup *group = [ZYSettingGroup groupWithItem:items];
    group.headerTitle = @"海内存知己";
    group.footerTitle = @"天涯若比邻";

    // 将行模型数组添加到数组总数
    [self.groups addObject:group];

}

@end


text:
.oo-ui-icon-stripeFlow {
	background-image: /* @embed */ url(themes/mediawiki/images/icons/stripeFlow-rtl.png);
}
.oo-ui-icon-stripeSideMenu {
	background-image: /* @embed */ url(themes/mediawiki/images/icons/stripeSideMenu.png);
}
.oo-ui-icon-stripeSummary {
	background-image: /* @embed */ url(themes/mediawiki/images/icons/stripeSummary-rtl.png);
}
.oo-ui-icon-stripeToC {
	background-image: /* @embed */ url(themes/mediawiki/images/icons/stripeToC-rtl.png);
}


text:
package org.apereo.cas.services;

import org.apereo.cas.support.events.service.CasRegisteredServiceLoadedEvent;

import lombok.val;
import org.springframework.context.ApplicationEventPublisher;

import java.util.Collection;

/**
 * This is {@link DynamoDbServiceRegistry}.
 *
 * @author Misagh Moayyed
 * @since 5.1.0
 */
public class DynamoDbServiceRegistry extends AbstractServiceRegistry {
    private final DynamoDbServiceRegistryFacilitator dbTableService;

    public DynamoDbServiceRegistry(final ApplicationEventPublisher eventPublisher, final DynamoDbServiceRegistryFacilitator dbTableService) {
        super(eventPublisher);
        this.dbTableService = dbTableService;
    }

    @Override
    public RegisteredService save(final RegisteredService registeredService) {
        dbTableService.put(registeredService);
        return registeredService;
    }

    @Override
    public boolean delete(final RegisteredService registeredService) {
        return dbTableService.delete(registeredService);
    }

    @Override
    public Collection<RegisteredService> load() {
        val svc = dbTableService.getAll();
        svc.forEach(s -> publishEvent(new CasRegisteredServiceLoadedEvent(this, s)));
        return svc;
    }

    @Override
    public RegisteredService findServiceById(final long id) {
        return dbTableService.get(id);
    }

    @Override
    public RegisteredService findServiceById(final String id) {
        return dbTableService.get(id);
    }

    @Override
    public long size() {
        return dbTableService.count();
    }
}


text:
package it.cnr.isti.hpc.net;

import it.cnr.isti.hpc.io.IOUtils;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;

/**
 * Simulates a Firefox browser in order to send queries to google/wikipedia...
 *
 * @author Diego Ceccarelli, diego.ceccarelli@isti.cnr.it created on 06/giu/2012
 */
public class FakeBrowser {

	private final Map<String, String> properties;

	public FakeBrowser() {
		properties = new HashMap<String, String>();
		properties
				.put("User-Agent",
						"Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11");
	}

	/**
	 * Fetches the url and returns a reader with the content of the page.
	 *
	 * @param url
	 *            the url to fetch.
	 * @return a reader to the page of the url.
	 * @throws IOException
	 *             if an errors occurs during the fetching.
	 */
	public Reader fetch(URL url) throws IOException {
		URLConnection urlc;
		urlc = url.openConnection();
		for (Map.Entry<String, String> entry : properties.entrySet()) {
			urlc.setRequestProperty(entry.getKey(), entry.getValue());
		}

		InputStream is = urlc.getInputStream();
		BufferedReader br = new BufferedReader(new InputStreamReader(is));
		return br;
	}

	/**
	 * Fetches the url and returns a reader with the content of the page.
	 *
	 * @param url
	 *            the url to fetch.
	 * @return a reader to the page of the url.
	 * @throws IOException
	 *             if an errors occurs during the fetching.
	 */
	public Reader fetchUTF8(URL url) throws IOException {
		URLConnection urlc;
		urlc = url.openConnection();
		for (Map.Entry<String, String> entry : properties.entrySet()) {
			urlc.setRequestProperty(entry.getKey(), entry.getValue());
		}

		InputStream is = urlc.getInputStream();
		BufferedReader br = new BufferedReader(new InputStreamReader(is,
				"UTF-8"));
		return br;
	}

	/**
	 * Adds a property to the request (e.g., a cookie..)
	 *
	 * @param name
	 *            the name fo the property
	 * @param value
	 *            the value of the property
	 */
	public void addProperty(String name, String value) {
		properties.put(name, value);
	}

	/**
	 * Fetches the url and returns a reader with the content of the page.
	 *
	 * @param url
	 *            the url to fetch.
	 * @return a reader to the page of the url.
	 * @throws IOException
	 *             if an errors occurs during the fetching.
	 */
	public Reader fetch(String url) throws IOException {
		return fetch(new URL(url));
	}

	/**
	 * Fetches the url and returns a reader with the content of the page.
	 *
	 * @param url
	 *            the url to fetch.
	 * @return a reader to the page of the url.
	 * @throws IOException
	 *             if an errors occurs during the fetching.
	 */
	public Reader fetchUTF8(String url) throws IOException {
		return fetchUTF8(new URL(url));
	}

	/**
	 * Fetches the url and returns a string with the content of the page.
	 *
	 * @param url
	 *            the url to fetch.
	 * @return string containing the content of the page.
	 * @throws IOException
	 *             if an errors occurs during the fetching.
	 */
	public String fetchAsString(String url) throws IOException {
		return asString(fetch(url));
	}

	/**
	 * Fetches the url and returns a string with the content of the page.
	 *
	 * @param url
	 *            the url to fetch.
	 * @return string containing the content of the page.
	 * @throws IOException
	 *             if an errors occurs during the fetching.
	 */
	public String fetchAsUTF8String(String url) throws IOException {
		return asString(fetchUTF8(url));
	}

	private String asString(Reader r) throws IOException {
		StringBuilder sb = new StringBuilder();
		BufferedReader br = new BufferedReader(r);
		String line = "";
		while ((line = br.readLine()) != null) {
			sb.append(line).append(" ");
		}
		return sb.toString();

	}

	public static void main(String[] args) throws IOException {
		FakeBrowser fb = new FakeBrowser();
		System.out
				.println(fb
						.fetchAsUTF8String("http://node5.novello.isti.cnr.it:8080/dexter-webapp/api/rest/get-desc?id=2982390&title-only=false"));
		BufferedWriter wr = IOUtils
				.getPlainOrCompressedUTF8Writer("/tmp/test.json.gz");
		wr.write(fb
				.fetchAsUTF8String("http://node5.novello.isti.cnr.it:8080/dexter-webapp/api/rest/get-desc?id=2982390&title-only=false"));
		wr.close();
	}

}


text:
layout: post
title: "Fix lỗi khi brew không thể update"
description: ""
category: Configure
tags: [brew update]
comments: true
author: rockkhuya
---
* TOC
{:toc}

Đang định cài Hugo về chơi mà update brew thì gặp tình trạng này :

```text
brew update
/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/rubygems/core_ext/kernel_require.rb:55:in `require': cannot load such file -- mach (LoadError)
    from /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/rubygems/core_ext/kernel_require.rb:55:in `require'
    from /usr/local/Library/Homebrew/extend/pathname.rb:2:in `<top (required)>'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/rubygems/core_ext/kernel_require.rb:55:in `require'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/rubygems/core_ext/kernel_require.rb:55:in `require'
    from /usr/local/Library/Homebrew/global.rb:3:in `<top (required)>'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/rubygems/core_ext/kernel_require.rb:55:in `require'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/rubygems/core_ext/kernel_require.rb:55:in `require'
    from /usr/local/Library/brew.rb:15:in `<main>'
```

Lý do thì mình không hiểu tại sao, nhưng có lẽ là do update version của osx lên El Capitan.

Lỗi này chắc những người dùng mac cũng hay gặp, nên mình sẽ share luôn cách mình đã xử lý vấn đề này.

<!-- more -->

## reset lại /usr/local

Lệnh brew không thể sử dụng được nên mình cần phải vào reset và clean lại folder của brew.

```text
cd /usr/local
git reset --hard && git clean -df
```

## change lại quyền của folder /usr/local

Khi sử dụng `brew doctor` thì gặp vấn đề này :

```text
local|master brew doctor
Please note that these warnings are just used to help the Homebrew maintainers
with debugging if you file an issue. If everything you use Homebrew for is
working fine: please don't worry and just ignore them. Thanks!

Warning: The /usr/local directory is not writable.
Even if this directory was writable when you installed Homebrew, other
software may change permissions on this directory. Some versions of the
"InstantOn" component of Airfoil are known to do this.

You should probably change the ownership and permissions of /usr/local
back to your user account.

Warning: You are using OS X 10.11.
We do not provide support for this pre-release version.
You may encounter build failures or other breakage.
```

Trong phần warning thì folder `/usr/local` không có quyền write, nên ta sẽ cấp quyền như sau :

```text
sudo chown -R $(whoami):admin /usr/local
```

`brew doctor` lại thì thấy vấn đề đã được giải quyết.

## Brew update

Cuối cùng thì thử xem `brew update` có hoạt động bình thường không :

```text
brew update

Checking out files: 100% (3749/3749), done.
==> Migrating Homebrew to v0.9.9
remote: Counting objects: 466, done.
remote: Compressing objects: 100% (423/423), done.
remote: Total 466 (delta 26), reused 301 (delta 17), pack-reused 0
Receiving objects: 100% (466/466), 768.34 KiB | 143.00 KiB/s, done.
Resolving deltas: 100% (26/26), done.
From https://github.com/Homebrew/brew
 + 53c5089...b0d906f master     -> origin/master  (forced update)
HEAD is now at b0d906f compilers: support gcc 6
==> Homebrew has enabled anonymous aggregate user behaviour analytics
Read the analytics documentation (and how to opt-out) here:
  https://git.io/brew-analytics
==> Tapping homebrew/core
Cloning into '/usr/local/Library/Taps/homebrew/homebrew-core'...
remote: Counting objects: 3684, done.
remote: Compressing objects: 100% (3571/3571), done.
remote: Total 3684 (delta 14), reused 530 (delta 1), pack-reused 0
Receiving objects: 100% (3684/3684), 2.82 MiB | 298.00 KiB/s, done.
Resolving deltas: 100% (14/14), done.
Checking connectivity... done.
Checking out files: 100% (3687/3687), done.
Tapped 3559 formulae (3,710 files, 8.8M)
Already up-to-date.
```

Đến đây thì vấn đề đã được giải quyết :).


text:
import * as console from '../../utils/console';
import {AuthenticatedGithubClient, GithubClient} from '../../utils/git/github';
import {installVirtualGitClientSpies, mockNgDevConfig} from '../../utils/testing';

import {GithubQueriesModule} from './github';

describe('GithubQueriesModule', () => {
  let githubApiSpy: jasmine.Spy;
  let infoSpy: jasmine.Spy;
  let infoGroupSpy: jasmine.Spy;

  beforeEach(() => {
    githubApiSpy = spyOn(AuthenticatedGithubClient.prototype, 'graphql')
                       .and.throwError(
                           'The graphql query response must always be manually defined in a test.');
    installVirtualGitClientSpies();
    infoGroupSpy = spyOn(console.info, 'group');
    infoSpy = spyOn(console, 'info');
  });

  describe('gathering stats', () => {
    it('unless githubQueries are `undefined`', async () => {
      const module =
          new GithubQueriesModule({...mockNgDevConfig, caretaker: {githubQueries: undefined}});

      expect(await module.data).toBe(undefined);
    });

    it('unless githubQueries are an empty array', async () => {
      const module = new GithubQueriesModule({...mockNgDevConfig, caretaker: {githubQueries: []}});

      expect(await module.data).toBe(undefined);
    });

    it('for the requested Github queries', async () => {
      githubApiSpy.and.returnValue({
        'keynamewithspaces': {issueCount: 1, nodes: [{url: 'http://github.com/owner/name/issue/1'}]}
      });
      const module = new GithubQueriesModule({
        ...mockNgDevConfig,
        caretaker: {githubQueries: [{name: 'key name with spaces', query: 'issue: yes'}]}
      });

      expect(await module.data).toEqual([{
        queryName: 'key name with spaces',
        count: 1,
        queryUrl: 'https://github.com/owner/name/issues?q=issue:%20yes',
        matchedUrls: ['http://github.com/owner/name/issue/1'],
      }]);
    });
  });

  describe('printing the data retrieved', () => {
    it('if there are no matches of the query', async () => {
      const fakeData = Promise.resolve([
        {
          queryName: 'query1',
          count: 0,
          queryUrl: 'https://github.com/owner/name/issues?q=issue:%20no',
          matchedUrls: [],
        },
        {
          queryName: 'query2',
          count: 0,
          queryUrl: 'https://github.com/owner/name/issues?q=something',
          matchedUrls: [],
        },
      ]);

      const module = new GithubQueriesModule({caretaker: {}, ...mockNgDevConfig});
      Object.defineProperty(module, 'data', {value: fakeData});

      await module.printToTerminal();

      expect(infoGroupSpy).toHaveBeenCalledWith('Github Tasks');
      expect(infoSpy).toHaveBeenCalledWith('query1  0');
      expect(infoSpy).toHaveBeenCalledWith('query2  0');
    });

    it('if there are maches of the query', async () => {
      const fakeData = Promise.resolve([
        {
          queryName: 'query1',
          count: 1,
          queryUrl: 'https://github.com/owner/name/issues?q=issue:%20yes',
          matchedUrls: ['http://github.com/owner/name/issue/1'],
        },
        {
          queryName: 'query2',
          count: 0,
          queryUrl: 'https://github.com/owner/name/issues?q=something',
          matchedUrls: [],
        },
      ]);

      const module = new GithubQueriesModule({caretaker: {}, ...mockNgDevConfig});
      Object.defineProperty(module, 'data', {value: fakeData});

      await module.printToTerminal();

      expect(infoGroupSpy).toHaveBeenCalledWith('Github Tasks');
      expect(infoSpy).toHaveBeenCalledWith('query1  1');
      expect(infoGroupSpy)
          .toHaveBeenCalledWith('https://github.com/owner/name/issues?q=issue:%20yes');
      expect(infoSpy).toHaveBeenCalledWith('- http://github.com/owner/name/issue/1');
      expect(infoSpy).toHaveBeenCalledWith('query2  0');
    });
  });
});


text:
<?xml version="1.0" encoding="UTF-8"?>
<SAXEvents>
  <startDocument/>
  <processingInstruction>
    <target>pi</target>
    <data>stuff</data>
  </processingInstruction>
  <fatalError>syntax error</fatalError>
  <endDocument/>
</SAXEvents>


text:
#include "tensorflow/cc/saved_model/loader.h"

#include "tensorflow/cc/saved_model/constants.h"
#include "tensorflow/core/framework/tensor_testutil.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/lib/core/status_test_util.h"
#include "tensorflow/core/lib/io/path.h"
#include "tensorflow/core/platform/test.h"

namespace tensorflow {
namespace {

constexpr char kTestDataPb[] = "cc/saved_model/testdata/half_plus_two";
constexpr char kTestDataPbTxt[] = "cc/saved_model/testdata/half_plus_two_pbtxt";
constexpr char kTestDataSharded[] =
    "cc/saved_model/testdata/half_plus_two_sharded";

class LoaderTest : public ::testing::Test {
 protected:
  LoaderTest() {}

  void CheckSavedModelBundle(const SavedModelBundle& bundle) {
    // Validate the half plus two behavior.
    Tensor input = test::AsTensor<float>({0, 1, 2, 3}, TensorShape({4, 1}));

    // Retrieve the regression signature from meta graph def.
    const auto signature_def_map = bundle.meta_graph_def.signature_def();
    const auto signature_def = signature_def_map.at("regression");

    const string input_name = signature_def.inputs().at("input").name();
    const string output_name = signature_def.outputs().at("output").name();

    std::vector<Tensor> outputs;
    TF_ASSERT_OK(bundle.session->Run({{input_name, input}}, {output_name}, {},
                                     &outputs));
    ASSERT_EQ(outputs.size(), 1);
    test::ExpectTensorEqual<float>(
        outputs[0],
        test::AsTensor<float>({2, 2.5, 3, 3.5}, TensorShape({4, 1})));
  }
};

// Test for resource leaks related to TensorFlow session closing requirements
// when loading and unloading large numbers of SavedModelBundles.
// TODO(sukritiramesh): Increase run iterations and move outside of the test
// suite.
TEST_F(LoaderTest, ResourceLeakTest) {
  SavedModelBundle bundle;
  SessionOptions session_options;
  RunOptions run_options;

  const string export_dir =
      io::JoinPath(testing::TensorFlowSrcRoot(), kTestDataPb);
  for (int i = 0; i < 100; ++i) {
    TF_ASSERT_OK(LoadSavedModel(session_options, run_options, export_dir,
                                {kSavedModelTagServe}, &bundle));
    CheckSavedModelBundle(bundle);
  }
}

TEST_F(LoaderTest, TagMatch) {
  SavedModelBundle bundle;
  SessionOptions session_options;
  RunOptions run_options;

  const string export_dir =
      io::JoinPath(testing::TensorFlowSrcRoot(), kTestDataPb);
  TF_ASSERT_OK(LoadSavedModel(session_options, run_options, export_dir,
                              {kSavedModelTagServe}, &bundle));
  CheckSavedModelBundle(bundle);
}

TEST_F(LoaderTest, NoTagMatch) {
  SavedModelBundle bundle;
  RunOptions run_options;
  SessionOptions session_options;

  const string export_dir =
      io::JoinPath(testing::TensorFlowSrcRoot(), kTestDataPb);
  Status st = LoadSavedModel(session_options, run_options, export_dir,
                             {"missing-tag"}, &bundle);
  EXPECT_FALSE(st.ok());
  EXPECT_TRUE(
      StringPiece(st.error_message())
          .contains("Could not find meta graph def matching supplied tags."))
      << st.error_message();
}

TEST_F(LoaderTest, NoTagMatchMultiple) {
  SavedModelBundle bundle;
  RunOptions run_options;
  SessionOptions session_options;

  const string export_dir =
      io::JoinPath(testing::TensorFlowSrcRoot(), kTestDataPb);
  Status st = LoadSavedModel(session_options, run_options, export_dir,
                             {kSavedModelTagServe, "missing-tag"}, &bundle);
  EXPECT_FALSE(st.ok());
  EXPECT_TRUE(
      StringPiece(st.error_message())
          .contains("Could not find meta graph def matching supplied tags."))
      << st.error_message();
}

TEST_F(LoaderTest, PbtxtFormat) {
  SavedModelBundle bundle;
  SessionOptions session_options;
  RunOptions run_options;

  const string export_dir =
      io::JoinPath(testing::TensorFlowSrcRoot(), kTestDataPbTxt);
  TF_ASSERT_OK(LoadSavedModel(session_options, run_options, export_dir,
                              {kSavedModelTagServe}, &bundle));
  CheckSavedModelBundle(bundle);
}

TEST_F(LoaderTest, ShardedVariables) {
  SavedModelBundle bundle;
  SessionOptions session_options;
  RunOptions run_options;

  const string export_dir =
      io::JoinPath(testing::TensorFlowSrcRoot(), kTestDataSharded);
  TF_ASSERT_OK(LoadSavedModel(session_options, run_options, export_dir,
                              {kSavedModelTagServe}, &bundle));
  CheckSavedModelBundle(bundle);
}

TEST_F(LoaderTest, InvalidExportPath) {
  SavedModelBundle bundle;
  RunOptions run_options;
  SessionOptions session_options;

  const string export_dir =
      io::JoinPath(testing::TensorFlowSrcRoot(), "missing-path");
  Status st = LoadSavedModel(session_options, run_options, export_dir,
                             {kSavedModelTagServe}, &bundle);
  EXPECT_FALSE(st.ok());
}

TEST_F(LoaderTest, MaybeSavedModelDirectory) {
  // Valid SavedModel directory.
  const string export_dir =
      io::JoinPath(testing::TensorFlowSrcRoot(), kTestDataPb);
  EXPECT_TRUE(MaybeSavedModelDirectory(export_dir));

  // Directory that does not exist.
  const string missing_export_dir =
      io::JoinPath(testing::TensorFlowSrcRoot(), "missing-path");
  EXPECT_FALSE(MaybeSavedModelDirectory(missing_export_dir));

  // Directory that exists but is an invalid SavedModel location.
  const string invalid_export_dir =
      io::JoinPath(testing::TensorFlowSrcRoot(), "cc/saved_model/testdata");
  EXPECT_FALSE(MaybeSavedModelDirectory(invalid_export_dir));
}

}  // namespace
}  // namespace tensorflow


text:
function getTemplates( templateCallback ) {
  $.get( "/templates/",
         function( data ) {
           data.reverse();
           var templates = {};
           $.each(data,function(hucars,template){
             templates[template.name] = template;
           });
           templateCallback(templates);
         });
}

function inputByType(type) {
  var input = {};
  input.element = $("<span>");
  if(type == "int") {
    var numberInput = $("<input type=\"text\">");
    input.setValue = function( num ) { numberInput.val("" + num); };
    input.getValue = function() { return parseInt( numberInput.val() ); };
    input.element.append(numberInput);
  } else if (type == "text" || type == "time") {
    var textInput = $("<input type=\"text\">");
    input.setValue = function( text ) { textInput.val(text); };
    input.getValue = function() { return textInput.val(); };
    input.element.append(textInput)
  } else if (type == "location") {
    input.setValue = function(nope){};
    input.getValue = function() { return {"location": "location"}; };
  } else if (typeof(type["maybe"] !== undefined)) {
    var maybeInput=$("<select>");
    maybeInput.append($("<option value=\"just\">Just</option>"));
    maybeInput.append($("<option value=\"nothing\">Nothing</option>"));
    var recInput = inputByType(type["maybe"]);
    input.setValue = function( val ) { if( val == null ) { maybeInput.val("nothing"); } else { maybeInput.val("just"); recInput.setValue( val ); }};
    input.getValue = function() { if( maybeInput.val() == "nothing" ) { return null; } else { return recInput.getValue(); }};
    input.element.append(maybeInput);
    input.element.append(recInput.element);
  }
  return input;
}

templateTypes = {
  "location_id": {"maybe": "int"},
  "slave_parameter_id": {"maybe": "int"},
  "parameter_tag_id": {"maybe": "int"},
  "description": {"maybe": "text"},
  "unit_id": {"maybe": "int"},
  "status_active": {"maybe": "int"},
  "status_writable": {"maybe": "int"},
  "last_update": {"maybe": "time"},
  "result": {"maybe": "text"},
  "validation_code": {"maybe": "text"},
  "permissions": {"maybe": "int"},
  "delete": {"maybe": "int"},
  "companyIdRef": {"maybe": "int"},
  "siteIdRef": {"maybe": "int"},
  "location": {"maybe": "location"},
  "pid": {"maybe": "int"}
};


text:
RSpec.describe Faraday::Adapter::EMHttp do
  features :request_body_on_query_methods, :reason_phrase_parse, :trace_method,
           :skip_response_body_on_head, :parallel, :local_socket_binding

  it_behaves_like 'an adapter'

  it 'allows to provide adapter specific configs' do
    url = URI('https://example.com:1234')
    adapter = described_class.new nil, inactivity_timeout: 20
    req = adapter.create_request(url: url, request: {})

    expect(req.connopts.inactivity_timeout).to eq(20)
  end

  context 'Options' do
    let(:request) { Faraday::RequestOptions.new }
    let(:env) { { request: request } }
    let(:options) { {} }
    let(:adapter) { Faraday::Adapter::EMHttp.new }

    it 'configures timeout' do
      request.timeout = 5
      adapter.configure_timeout(options, env)
      expect(options[:inactivity_timeout]).to eq(5)
      expect(options[:connect_timeout]).to eq(5)
    end

    it 'configures timeout and open_timeout' do
      request.timeout = 5
      request.open_timeout = 1
      adapter.configure_timeout(options, env)
      expect(options[:inactivity_timeout]).to eq(5)
      expect(options[:connect_timeout]).to eq(1)
    end

    it 'configures all timeout settings' do
      request.timeout = 5
      request.read_timeout = 3
      request.open_timeout = 1
      adapter.configure_timeout(options, env)
      expect(options[:inactivity_timeout]).to eq(3)
      expect(options[:connect_timeout]).to eq(1)
    end
  end
end


text:
CXX		= g++
CXXFLAGS	= -ggdb -Wall

# The driver outputs TAP (Test Anything Protocol), so it can also be used with
# any TAP test harness (e.g. prove).  Set the path to your test harness here,
# then use the `prove' target to run the tests with that harness.
PROVE		= prove
PROVEFLAGS	= -e ""

ifeq ($(OS),Windows_NT)
EXEEXT = .exe
endif

all: driver$(EXEEXT)

clean:
	rm -f driver$(EXEEXT)

distclean: clean
	rm -f TwoCardsDraw

run: all
	./driver$(EXEEXT)

test: all
	./driver$(EXEEXT) --abort-on-fail

prove: all
	$(PROVE) $(PROVEFLAGS) ./driver$(EXEEXT)

%$(EXEEXT): %.cc
	$(LINK.cc) $^ $(LOADLIBES) $(LDLIBS) -o $@

driver$(EXEEXT): TwoCardsDraw.cc

.PHONY: all clean distclean run test prove

# vim:ft=make:noet:ts=8


text:
import os

import pytest

@pytest.fixture(scope='function')
def fake_bar():
    from libqtile.bar import Bar
    height = 24
    b = Bar([], height)
    b.height = height
    return b

TEST_DIR = os.path.dirname(os.path.abspath(__file__))
DATA_DIR = os.path.join(os.path.dirname(TEST_DIR), 'data')

@pytest.fixture(scope='module')
def svg_img_as_pypath():
    "Return the py.path object of a svg image"
    import py
    audio_volume_muted = os.path.join(
        DATA_DIR, 'svg', 'audio-volume-muted.svg',
    )
    audio_volume_muted = py.path.local(audio_volume_muted)
    return audio_volume_muted


text:
package org.ohdsi.webapi.feasibility;

import javax.persistence.Column;
import javax.persistence.Embeddable;
import javax.persistence.Lob;
import javax.persistence.Table;
import org.hibernate.annotations.Type;

/**
 *
 * @author Chris Knoll <cknoll@ohdsi.org>
 */
@Embeddable
public class InclusionRule {

  @Column(name="name")
  private String name;

  @Column(name="description")
  private String description;

  @Column(name="expression")
  @Lob
  @Type(type = "org.hibernate.type.TextType")
  private String expression;
  public String getName() {
    return name;
  }

  public InclusionRule setName(String name) {
    this.name = name;
    return this;
  }

  public String getDescription() {
    return description;
  }

  public InclusionRule setDescription(String description) {
    this.description = description;
    return this;
  }

  public String getExpression() {
    return expression;
  }

  public InclusionRule setExpression(String expression) {
    this.expression = expression;
    return this;
  }
}


text:
package org.apereo.cas.oidc.discovery.webfinger.userinfo;

import org.apereo.cas.configuration.support.RestEndpointProperties;
import org.apereo.cas.oidc.discovery.webfinger.OidcWebFingerUserInfoRepository;
import org.apereo.cas.util.CollectionUtils;
import org.apereo.cas.util.HttpUtils;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.hjson.JsonValue;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * This is {@link OidcRestfulWebFingerUserInfoRepository}.
 *
 * @author Misagh Moayyed
 * @since 6.1.0
 */
@RequiredArgsConstructor
@Slf4j
public class OidcRestfulWebFingerUserInfoRepository implements OidcWebFingerUserInfoRepository {
    private static final ObjectMapper MAPPER = new ObjectMapper()
        .findAndRegisterModules()
        .configure(DeserializationFeature.READ_ENUMS_USING_TO_STRING, false)
        .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    private final RestEndpointProperties properties;

    @Override
    public Map<String, Object> findByEmailAddress(final String email) {
        return findAccountViaRestApi(CollectionUtils.wrap("email", email));
    }

    @Override
    public Map<String, Object> findByUsername(final String username) {
        return findAccountViaRestApi(CollectionUtils.wrap("username", username));
    }

    /**
     * Find account via rest api and return user-info map.
     *
     * @param headers the headers
     * @return the map
     */
    protected Map<String, Object> findAccountViaRestApi(final Map<String, Object> headers) {
        HttpResponse response = null;
        try {
            response = HttpUtils.execute(properties.getUrl(), properties.getMethod(),
                properties.getBasicAuthUsername(), properties.getBasicAuthPassword(),
                new HashMap<>(0), headers);
            if (response != null && response.getEntity() != null && response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                val result = IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8);
                return MAPPER.readValue(JsonValue.readHjson(result).toString(), Map.class);
            }
        } catch (final Exception e) {
            LOGGER.error(e.getMessage(), e);
        } finally {
            HttpUtils.close(response);
        }
        return new HashMap<>(0);
    }
}


text:
<?php namespace Illuminate\Contracts\Container;

use Closure;

interface Container {

	/**
	 * Determine if the given abstract type has been bound.
	 *
	 * @param  string  $abstract
	 * @return bool
	 */
	public function bound($abstract);

	/**
	 * Alias a type to a different name.
	 *
	 * @param  string  $abstract
	 * @param  string  $alias
	 * @return void
	 */
	public function alias($abstract, $alias);

	/**
	 * Assign a set of tags to a given binding.
	 *
	 * @param  array|string  $abstracts
	 * @param  array|mixed   ...$tags
	 * @return void
	 */
	public function tag($abstracts, $tags);

	/**
	 * Resolve all of the bindings for a given tag.
	 *
	 * @param  array  $tag
	 * @return array
	 */
	public function tagged($tag);

	/**
	 * Register a binding with the container.
	 *
	 * @param  string|array  $abstract
	 * @param  \Closure|string|null  $concrete
	 * @param  bool  $shared
	 * @return void
	 */
	public function bind($abstract, $concrete = null, $shared = false);

	/**
	 * Register a binding if it hasn't already been registered.
	 *
	 * @param  string  $abstract
	 * @param  \Closure|string|null  $concrete
	 * @param  bool  $shared
	 * @return void
	 */
	public function bindIf($abstract, $concrete = null, $shared = false);

	/**
	 * Register a shared binding in the container.
	 *
	 * @param  string  $abstract
	 * @param  \Closure|string|null  $concrete
	 * @return void
	 */
	public function singleton($abstract, $concrete = null);

	/**
	 * "Extend" an abstract type in the container.
	 *
	 * @param  string    $abstract
	 * @param  \Closure  $closure
	 * @return void
	 *
	 * @throws \InvalidArgumentException
	 */
	public function extend($abstract, Closure $closure);

	/**
	 * Register an existing instance as shared in the container.
	 *
	 * @param  string  $abstract
	 * @param  mixed   $instance
	 * @return void
	 */
	public function instance($abstract, $instance);

	/**
	 * Define a contextual binding.
	 *
	 * @param  string  $concrete
	 * @return \Illuminate\Contracts\Container\ContextualBindingBuilder
	 */
	public function when($concrete);

	/**
	 * Resolve the given type from the container.
	 *
	 * @param  string  $abstract
	 * @param  array   $parameters
	 * @return mixed
	 */
	public function make($abstract, $parameters = []);

	/**
	 * Call the given Closure / class@method and inject its dependencies.
	 *
	 * @param  callable|string  $callback
	 * @param  array  $parameters
	 * @param  string|null  $defaultMethod
	 * @return mixed
	 */
	public function call($callback, array $parameters = [], $defaultMethod = null);

	/**
	 * Determine if the given abstract type has been resolved.
	 *
	 * @param  string $abstract
	 * @return bool
	 */
	public function resolved($abstract);

	/**
	 * Register a new resolving callback.
	 *
	 * @param  string    $abstract
	 * @param  \Closure  $callback
	 * @return void
	 */
	public function resolving($abstract, Closure $callback);

	/**
	 * Register a new resolving callback for all types.
	 *
	 * @param  \Closure  $callback
	 * @return void
	 */
	public function resolvingAny(Closure $callback);

}


text:
using System.Drawing;

namespace DotSpatial.Controls.Header
{
    /// <summary>
    /// A textbox item
    /// </summary>
    public class TextEntryActionItem : ActionItem
    {
        private string text;
        private int width;
        private Color fontColor;

        /// <summary>
        /// Gets or sets the width of the item displayed in the header control.
        /// </summary>
        /// <value>
        /// The width.
        /// </value>
        public int Width
        {
            get
            {
                return width;
            }
            set
            {
                if (width == value) return;
                width = value;
                OnPropertyChanged("Width");
            }
        }

        /// <summary>
        /// Gets or sets the text.
        /// </summary>
        /// <value>
        /// The text.
        /// </value>
        public string Text
        {
            get { return text; }
            set
            {
                if (text == value) return;
                text = value;
                OnPropertyChanged("Text");
            }
        }

        /// <summary>
        /// Gets or sets a value indicating the color of the text in the dropdownbox
        /// </summary>
        public Color FontColor
        {
            get { return fontColor; }
            set
            {
                if (fontColor == value) return;
                fontColor = value;
                OnPropertyChanged("FontColor");
            }
        }
    }
}


text:
using UnityEngine;
using System.Collections;

public class EnemyChoice : MonoBehaviour {
	float endTime = 1;
	float Tps = 5;
	// Use this for initialization
	void Start () {

	}

	// Update is called once per frame
	void Update () {
		if(Time.time >= endTime){
			Global.Choice = Random.Range(0,2);
			endTime += Tps;
		}
	}
}


text:
using CSSBot.Services;
using Discord;
using Discord.Commands;
using Discord.WebSocket;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace CSSBot.Commands
{
    public class RetryModuleBase : ModuleBase
    {
        public MessageRetryService messageRetry;

        public RetryModuleBase(MessageRetryService messageRetry)
        {
            this.messageRetry = messageRetry;
        }

        /// <summary>
        ///     Replies to the original message, or updates if there was an edit.
        ///     Does not work with commands with multiple message responses.
        /// </summary>
        /// <param name="message"></param>
        internal async Task<IUserMessage> ReplyOrUpdateAsync(string message = null, bool isTTS = false, Embed embed = null)
        {
            var id = messageRetry.GetMessageToUpdate(Context);
            if (id.HasValue)
            {
                // id already exists
                var m = await Context.Channel.GetMessageAsync(id.Value);
                if (m is IUserMessage usermessage)
                {
                    // update the existing message
                    await usermessage.ModifyAsync(x =>
                    {
                        x.Content = message;
                        x.Embed = embed;
                    });
                    // don't need to update message IDs
                    return usermessage;
                }
            }
            else
            {
                // id doesn't already exist, so create a new message
                var msg = await ReplyAsync(message, isTTS, embed);
                messageRetry.RegisterSuccessfulCommand(Context.Message.Id, msg.Id);
                return msg;
            }
            // error
            return null;
        }
    }
}


text:
Password

        <form data-bind="submit: ok">

Please enter new password

            <input data-bind="value: input, valueUpdate: 'afterkeydown'" class="form-control autofocus"/>
        </form>

        <button class="btn btn-primary" data-bind="click: ok">Ok</button>


text:
//  (C) Copyright 2006-8 Anthony Williams
//  (C) Copyright 2011-2012,2017-2018 Vicente J. Botet Escriba
//
//  Distributed under the Boost Software License, Version 1.0. (See
//  accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)

#include <boost/assert.hpp>
#include <boost/detail/interlocked.hpp>
#include <boost/thread/win32/thread_primitives.hpp>
#include <boost/static_assert.hpp>
#include <limits.h>
#include <boost/thread/thread_time.hpp>
#ifdef BOOST_THREAD_USES_CHRONO
#include <boost/chrono/system_clocks.hpp>
#include <boost/chrono/ceil.hpp>
#endif
#include <boost/thread/detail/delete.hpp>
#include <boost/thread/detail/platform_time.hpp>

#include <boost/config/abi_prefix.hpp>

namespace boost
{
    class shared_mutex
    {
    private:
        struct state_data
        {
            unsigned long shared_count:11,
                shared_waiting:11,
                exclusive:1,
                upgrade:1,
                exclusive_waiting:7,
                exclusive_waiting_blocked:1;

            friend bool operator==(state_data const& lhs,state_data const& rhs)
            {
                return *reinterpret_cast<unsigned long const*>(&lhs)==*reinterpret_cast<unsigned long const*>(&rhs);
            }
        };

        state_data interlocked_compare_exchange(state_data* target, state_data new_value, state_data comparand)
        {
            long const res=BOOST_INTERLOCKED_COMPARE_EXCHANGE(reinterpret_cast<long*>(target),
                                                              *reinterpret_cast<long*>(&new_value),
                                                              *reinterpret_cast<long*>(&comparand));
            return *reinterpret_cast<state_data const*>(&res);
        }

        enum
        {
            unlock_sem = 0,
            exclusive_sem = 1
        };

        state_data state;
        detail::win32::handle semaphores[2];
        detail::win32::handle upgrade_sem;

        void release_waiters(state_data old_state)
        {
            if(old_state.exclusive_waiting)
            {
                BOOST_VERIFY(winapi::ReleaseSemaphore(semaphores[exclusive_sem],1,0)!=0);
            }

            if(old_state.shared_waiting || old_state.exclusive_waiting)
            {
                BOOST_VERIFY(winapi::ReleaseSemaphore(semaphores[unlock_sem],old_state.shared_waiting + (old_state.exclusive_waiting?1:0),0)!=0);
            }
        }
        void release_shared_waiters(state_data old_state)
        {
            if(old_state.shared_waiting || old_state.exclusive_waiting)
            {
                BOOST_VERIFY(winapi::ReleaseSemaphore(semaphores[unlock_sem],old_state.shared_waiting + (old_state.exclusive_waiting?1:0),0)!=0);
            }
        }

    public:
        BOOST_THREAD_NO_COPYABLE(shared_mutex)
        shared_mutex()
        {
            semaphores[unlock_sem]=detail::win32::create_anonymous_semaphore(0,LONG_MAX);
            semaphores[exclusive_sem]=detail::win32::create_anonymous_semaphore_nothrow(0,LONG_MAX);
            if (!semaphores[exclusive_sem])
            {
              detail::win32::release_semaphore(semaphores[unlock_sem],LONG_MAX);
              boost::throw_exception(thread_resource_error());
            }
            upgrade_sem=detail::win32::create_anonymous_semaphore_nothrow(0,LONG_MAX);
            if (!upgrade_sem)
            {
              detail::win32::release_semaphore(semaphores[unlock_sem],LONG_MAX);
              detail::win32::release_semaphore(semaphores[exclusive_sem],LONG_MAX);
              boost::throw_exception(thread_resource_error());
            }
            state_data state_={0,0,0,0,0,0};
            state=state_;
        }

        ~shared_mutex()
        {
            winapi::CloseHandle(upgrade_sem);
            winapi::CloseHandle(semaphores[unlock_sem]);
            winapi::CloseHandle(semaphores[exclusive_sem]);
        }

        bool try_lock_shared()
        {
            state_data old_state=state;
            for(;;)
            {
                state_data new_state=old_state;
                if(!new_state.exclusive && !new_state.exclusive_waiting_blocked)
                {
                    ++new_state.shared_count;
                    if(!new_state.shared_count)
                    {
                        return false;
                    }
                }

                state_data const current_state=interlocked_compare_exchange(&state,new_state,old_state);
                if(current_state==old_state)
                {
                    break;
                }
                old_state=current_state;
            }
            return !(old_state.exclusive| old_state.exclusive_waiting_blocked);
        }

        void lock_shared()
        {
            for(;;)
            {
                state_data old_state=state;
                for(;;)
                {
                    state_data new_state=old_state;
                    if(new_state.exclusive || new_state.exclusive_waiting_blocked)
                    {
                        ++new_state.shared_waiting;
                        if(!new_state.shared_waiting)
                        {
                            boost::throw_exception(boost::lock_error());
                        }
                    }
                    else
                    {
                        ++new_state.shared_count;
                        if(!new_state.shared_count)
                        {
                            boost::throw_exception(boost::lock_error());
                        }
                    }

                    state_data const current_state=interlocked_compare_exchange(&state,new_state,old_state);
                    if(current_state==old_state)
                    {
                        break;
                    }
                    old_state=current_state;
                }

                if(!(old_state.exclusive| old_state.exclusive_waiting_blocked))
                {
                    return;
                }

                BOOST_VERIFY(winapi::WaitForSingleObjectEx(semaphores[unlock_sem],::boost::detail::win32::infinite,0)==0);
            }
        }

    private:
        unsigned long getMs(detail::platform_duration const& d)
        {
            return static_cast<unsigned long>(d.getMs());
        }

        template <typename Duration>
        unsigned long getMs(Duration const& d)
        {
            return static_cast<unsigned long>(chrono::ceil<chrono::milliseconds>(d).count());
        }

        template <typename Clock, typename Timepoint, typename Duration>
        bool do_lock_shared_until(Timepoint const& t, Duration const& max)
        {
            for(;;)
            {
                state_data old_state=state;
                for(;;)
                {
                    state_data new_state=old_state;
                    if(new_state.exclusive || new_state.exclusive_waiting_blocked)
                    {
                        ++new_state.shared_waiting;
                        if(!new_state.shared_waiting)
                        {
                            boost::throw_exception(boost::lock_error());
                        }
                    }
                    else
                    {
                        ++new_state.shared_count;
                        if(!new_state.shared_count)
                        {
                            boost::throw_exception(boost::lock_error());
                        }
                    }

                    state_data const current_state=interlocked_compare_exchange(&state,new_state,old_state);
                    if(current_state==old_state)
                    {
                        break;
                    }
                    old_state=current_state;
                }

                if(!(old_state.exclusive| old_state.exclusive_waiting_blocked))
                {
                    return true;
                }

                // If the clock is the system clock, it may jump while this function
                // is waiting. To compensate for this and time out near the correct
                // time, we call WaitForSingleObjectEx() in a loop with a short
                // timeout and recheck the time remaining each time through the loop.
                unsigned long res=0;
                for(;;)
                {
                    Duration d(t - Clock::now());
                    if(d <= Duration::zero()) // timeout occurred
                    {
                        res=detail::win32::timeout;
                        break;
                    }
                    if(max != Duration::zero())
                    {
                        d = (std::min)(d, max);
                    }
                    res=winapi::WaitForSingleObjectEx(semaphores[unlock_sem],getMs(d),0);
                    if(res!=detail::win32::timeout) // semaphore released
                    {
                        break;
                    }
                }

                if(res==detail::win32::timeout)
                {
                    for(;;)
                    {
                        state_data new_state=old_state;
                        if(new_state.exclusive || new_state.exclusive_waiting_blocked)
                        {
                            if(new_state.shared_waiting)
                            {
                                --new_state.shared_waiting;
                            }
                        }
                        else
                        {
                            ++new_state.shared_count;
                            if(!new_state.shared_count)
                            {
                                return false;
                            }
                        }

                        state_data const current_state=interlocked_compare_exchange(&state,new_state,old_state);
                        if(current_state==old_state)
                        {
                            break;
                        }
                        old_state=current_state;
                    }

                    if(!(old_state.exclusive| old_state.exclusive_waiting_blocked))
                    {
                        return true;
                    }
                    return false;
                }

                BOOST_ASSERT(res==0);
            }
        }
    public:

#if defined BOOST_THREAD_USES_DATETIME
        template<typename TimeDuration>
        bool timed_lock_shared(TimeDuration const & relative_time)
        {
            const detail::mono_platform_timepoint t(detail::mono_platform_clock::now() + detail::platform_duration(relative_time));
            // The reference clock is steady and so no need to poll periodically, thus 0 ms max (i.e. no max)
            return do_lock_shared_until<detail::mono_platform_clock>(t, detail::platform_duration::zero());
        }
        bool timed_lock_shared(boost::system_time const& wait_until)
        {
            const detail::real_platform_timepoint t(wait_until);
            return do_lock_shared_until<detail::real_platform_clock>(t, detail::platform_milliseconds(BOOST_THREAD_POLL_INTERVAL_MILLISECONDS));
        }
#endif

#ifdef BOOST_THREAD_USES_CHRONO
        template <class Rep, class Period>
        bool try_lock_shared_for(const chrono::duration<Rep, Period>& rel_time)
        {
            const chrono::steady_clock::time_point t(chrono::steady_clock::now() + rel_time);
            typedef typename chrono::duration<Rep, Period> Duration;
            typedef typename common_type<Duration, typename chrono::steady_clock::duration>::type common_duration;
            // The reference clock is steady and so no need to poll periodically, thus 0 ms max (i.e. no max)
            return do_lock_shared_until<chrono::steady_clock>(t, common_duration::zero());
        }
        template <class Duration>
        bool try_lock_shared_until(const chrono::time_point<chrono::steady_clock, Duration>& t)
        {
            typedef typename common_type<Duration, typename chrono::steady_clock::duration>::type common_duration;
            // The reference clock is steady and so no need to poll periodically, thus 0 ms max (i.e. no max)
            return do_lock_shared_until<chrono::steady_clock>(t, common_duration::zero());
        }
        template <class Clock, class Duration>
        bool try_lock_shared_until(const chrono::time_point<Clock, Duration>& t)
        {
            typedef typename common_type<Duration, typename Clock::duration>::type common_duration;
            return do_lock_shared_until<Clock>(t, common_duration(chrono::milliseconds(BOOST_THREAD_POLL_INTERVAL_MILLISECONDS)));
        }
#endif

        void unlock_shared()
        {
            state_data old_state=state;
            for(;;)
            {
                state_data new_state=old_state;
                bool const last_reader=!--new_state.shared_count;

                if(last_reader)
                {
                    if(new_state.upgrade)
                    {
                        new_state.upgrade=false;
                        new_state.exclusive=true;
                    }
                    else
                    {
                        if(new_state.exclusive_waiting)
                        {
                            --new_state.exclusive_waiting;
                            new_state.exclusive_waiting_blocked=false;
                        }
                        new_state.shared_waiting=0;
                    }
                }

                state_data const current_state=interlocked_compare_exchange(&state,new_state,old_state);
                if(current_state==old_state)
                {
                    if(last_reader)
                    {
                        if(old_state.upgrade)
                        {
                            BOOST_VERIFY(winapi::ReleaseSemaphore(upgrade_sem,1,0)!=0);
                        }
                        else
                        {
                            release_waiters(old_state);
                        }
                    }
                    break;
                }
                old_state=current_state;
            }
        }

        bool try_lock()
        {
            state_data old_state=state;
            for(;;)
            {
                state_data new_state=old_state;
                if(new_state.shared_count || new_state.exclusive)
                {
                    return false;
                }
                else
                {
                    new_state.exclusive=true;
                }

                state_data const current_state=interlocked_compare_exchange(&state,new_state,old_state);
                if(current_state==old_state)
                {
                    break;
                }
                old_state=current_state;
            }
            return true;
        }

        void lock()
        {
            for(;;)
            {
                state_data old_state=state;
                for(;;)
                {
                    state_data new_state=old_state;
                    if(new_state.shared_count || new_state.exclusive)
                    {
                        ++new_state.exclusive_waiting;
                        if(!new_state.exclusive_waiting)
                        {
                            boost::throw_exception(boost::lock_error());
                        }

                        new_state.exclusive_waiting_blocked=true;
                    }
                    else
                    {
                        new_state.exclusive=true;
                    }

                    state_data const current_state=interlocked_compare_exchange(&state,new_state,old_state);
                    if(current_state==old_state)
                    {
                        break;
                    }
                    old_state=current_state;
                }

                if(!old_state.shared_count && !old_state.exclusive)
                {
                    return;
                }

                #ifndef UNDER_CE
                const bool wait_all = true;
                #else
                const bool wait_all = false;
                #endif
                BOOST_VERIFY(winapi::WaitForMultipleObjectsEx(2,semaphores,wait_all,::boost::detail::win32::infinite,0)<2);
            }
        }

    private:
        template <typename Clock, typename Timepoint, typename Duration>
        bool do_lock_until(Timepoint const& t, Duration const& max)
        {
            for(;;)
            {
                state_data old_state=state;
                for(;;)
                {
                    state_data new_state=old_state;
                    if(new_state.shared_count || new_state.exclusive)
                    {
                        ++new_state.exclusive_waiting;
                        if(!new_state.exclusive_waiting)
                        {
                            boost::throw_exception(boost::lock_error());
                        }

                        new_state.exclusive_waiting_blocked=true;
                    }
                    else
                    {
                        new_state.exclusive=true;
                    }

                    state_data const current_state=interlocked_compare_exchange(&state,new_state,old_state);
                    if(current_state==old_state)
                    {
                        break;
                    }
                    old_state=current_state;
                }

                if(!old_state.shared_count && !old_state.exclusive)
                {
                    return true;
                }

                // If the clock is the system clock, it may jump while this function
                // is waiting. To compensate for this and time out near the correct
                // time, we call WaitForMultipleObjectsEx() in a loop with a short
                // timeout and recheck the time remaining each time through the loop.
                unsigned long wait_res=0;
                for(;;)
                {
                    Duration d(t - Clock::now());
                    if(d <= Duration::zero()) // timeout occurred
                    {
                        wait_res=detail::win32::timeout;
                        break;
                    }
                    if(max != Duration::zero())
                    {
                        d = (std::min)(d, max);
                    }
                    #ifndef UNDER_CE
                    wait_res=winapi::WaitForMultipleObjectsEx(2,semaphores,true,getMs(d),0);
                    #else
                    wait_res=winapi::WaitForMultipleObjectsEx(2,semaphores,false,getMs(d),0);
                    #endif
                    //wait_res=winapi::WaitForMultipleObjectsEx(2,semaphores,wait_all,getMs(d), 0);

                    if(wait_res!=detail::win32::timeout) // semaphore released
                    {
                        break;
                    }
                }

                if(wait_res==detail::win32::timeout)
                {
                    for(;;)
                    {
                        bool must_notify = false;
                        state_data new_state=old_state;
                        if(new_state.shared_count || new_state.exclusive)
                        {
                            if(new_state.exclusive_waiting)
                            {
                                if(!--new_state.exclusive_waiting)
                                {
                                    new_state.exclusive_waiting_blocked=false;
                                    must_notify = true;
                                }
                            }
                        }
                        else
                        {
                            new_state.exclusive=true;
                        }

                        state_data const current_state=interlocked_compare_exchange(&state,new_state,old_state);
                        if (must_notify)
                        {
                          BOOST_VERIFY(winapi::ReleaseSemaphore(semaphores[unlock_sem],1,0)!=0);
                        }

                        if(current_state==old_state)
                        {
                            break;
                        }
                        old_state=current_state;
                    }
                    if(!old_state.shared_count && !old_state.exclusive)
                    {
                        return true;
                    }
                    return false;
                }

                BOOST_ASSERT(wait_res<2);
            }
        }
    public:

#if defined BOOST_THREAD_USES_DATETIME
        bool timed_lock(boost::system_time const& wait_until)
        {
            const detail::real_platform_timepoint t(wait_until);
            return do_lock_until<detail::real_platform_clock>(t, detail::platform_milliseconds(BOOST_THREAD_POLL_INTERVAL_MILLISECONDS));
        }
        template<typename TimeDuration>
        bool timed_lock(TimeDuration const & relative_time)
        {
            const detail::mono_platform_timepoint t(detail::mono_platform_clock::now() + detail::platform_duration(relative_time));
            // The reference clock is steady and so no need to poll periodically, thus 0 ms max (i.e. no max)
            return do_lock_until<detail::mono_platform_clock>(t, detail::platform_duration::zero());
        }
#endif
#ifdef BOOST_THREAD_USES_CHRONO
        template <class Rep, class Period>
        bool try_lock_for(const chrono::duration<Rep, Period>& rel_time)
        {
            const chrono::steady_clock::time_point t(chrono::steady_clock::now() + rel_time);
            typedef typename chrono::duration<Rep, Period> Duration;
            typedef typename common_type<Duration, typename chrono::steady_clock::duration>::type common_duration;
            // The reference clock is steady and so no need to poll periodically, thus 0 ms max (i.e. no max)
            return do_lock_until<chrono::steady_clock>(t, common_duration::zero());
        }
        template <class Duration>
        bool try_lock_until(const chrono::time_point<chrono::steady_clock, Duration>& t)
        {
            typedef typename common_type<Duration, typename chrono::steady_clock::duration>::type common_duration;
            // The reference clock is steady and so no need to poll periodically, thus 0 ms max (i.e. no max)
            return do_lock_until<chrono::steady_clock>(t, common_duration::zero());
        }
        template <class Clock, class Duration>
        bool try_lock_until(const chrono::time_point<Clock, Duration>& t)
        {
            typedef typename common_type<Duration, typename Clock::duration>::type common_duration;
            return do_lock_until<Clock>(t, common_duration(chrono::milliseconds(BOOST_THREAD_POLL_INTERVAL_MILLISECONDS)));
        }
#endif

        void unlock()
        {
            state_data old_state=state;
            for(;;)
            {
                state_data new_state=old_state;
                new_state.exclusive=false;
                if(new_state.exclusive_waiting)
                {
                    --new_state.exclusive_waiting;
                    new_state.exclusive_waiting_blocked=false;
                }
                new_state.shared_waiting=0;

                state_data const current_state=interlocked_compare_exchange(&state,new_state,old_state);
                if(current_state==old_state)
                {
                    break;
                }
                old_state=current_state;
            }
            release_waiters(old_state);
        }

        void lock_upgrade()
        {
            for(;;)
            {
                state_data old_state=state;
                for(;;)
                {
                    state_data new_state=old_state;
                    if(new_state.exclusive || new_state.exclusive_waiting_blocked || new_state.upgrade)
                    {
                        ++new_state.shared_waiting;
                        if(!new_state.shared_waiting)
                        {
                            boost::throw_exception(boost::lock_error());
                        }
                    }
                    else
                    {
                        ++new_state.shared_count;
                        if(!new_state.shared_count)
                        {
                            boost::throw_exception(boost::lock_error());
                        }
                        new_state.upgrade=true;
                    }

                    state_data const current_state=interlocked_compare_exchange(&state,new_state,old_state);
                    if(current_state==old_state)
                    {
                        break;
                    }
                    old_state=current_state;
                }

                if(!(old_state.exclusive|| old_state.exclusive_waiting_blocked|| old_state.upgrade))
                {
                    return;
                }

                BOOST_VERIFY(winapi::WaitForSingleObjectEx(semaphores[unlock_sem],winapi::infinite,0)==0);
            }
        }

        bool try_lock_upgrade()
        {
            state_data old_state=state;
            for(;;)
            {
                state_data new_state=old_state;
                if(new_state.exclusive || new_state.exclusive_waiting_blocked || new_state.upgrade)
                {
                    return false;
                }
                else
                {
                    ++new_state.shared_count;
                    if(!new_state.shared_count)
                    {
                        return false;
                    }
                    new_state.upgrade=true;
                }

                state_data const current_state=interlocked_compare_exchange(&state,new_state,old_state);
                if(current_state==old_state)
                {
                    break;
                }
                old_state=current_state;
            }
            return true;
        }

        void unlock_upgrade()
        {
            state_data old_state=state;
            for(;;)
            {
                state_data new_state=old_state;
                new_state.upgrade=false;
                bool const last_reader=!--new_state.shared_count;

                new_state.shared_waiting=0;
                if(last_reader)
                {
                    if(new_state.exclusive_waiting)
                    {
                        --new_state.exclusive_waiting;
                        new_state.exclusive_waiting_blocked=false;
                    }
                }

                state_data const current_state=interlocked_compare_exchange(&state,new_state,old_state);
                if(current_state==old_state)
                {
                    if(last_reader)
                    {
                        release_waiters(old_state);
                    }
                    else {
                        release_shared_waiters(old_state);
                    }
                    // #7720
                    //else {
                    //    release_waiters(old_state);
                    //}
                    break;
                }
                old_state=current_state;
            }
        }

        void unlock_upgrade_and_lock()
        {
            state_data old_state=state;
            for(;;)
            {
                state_data new_state=old_state;
                bool const last_reader=!--new_state.shared_count;

                if(last_reader)
                {
                    new_state.upgrade=false;
                    new_state.exclusive=true;
                }

                state_data const current_state=interlocked_compare_exchange(&state,new_state,old_state);
                if(current_state==old_state)
                {
                    if(!last_reader)
                    {
                        BOOST_VERIFY(winapi::WaitForSingleObjectEx(upgrade_sem,detail::win32::infinite,0)==0);
                    }
                    break;
                }
                old_state=current_state;
            }
        }

        void unlock_and_lock_upgrade()
        {
            state_data old_state=state;
            for(;;)
            {
                state_data new_state=old_state;
                new_state.exclusive=false;
                new_state.upgrade=true;
                ++new_state.shared_count;
                if(new_state.exclusive_waiting)
                {
                    --new_state.exclusive_waiting;
                    new_state.exclusive_waiting_blocked=false;
                }
                new_state.shared_waiting=0;

                state_data const current_state=interlocked_compare_exchange(&state,new_state,old_state);
                if(current_state==old_state)
                {
                    break;
                }
                old_state=current_state;
            }
            release_waiters(old_state);
        }

        void unlock_and_lock_shared()
        {
            state_data old_state=state;
            for(;;)
            {
                state_data new_state=old_state;
                new_state.exclusive=false;
                ++new_state.shared_count;
                if(new_state.exclusive_waiting)
                {
                    --new_state.exclusive_waiting;
                    new_state.exclusive_waiting_blocked=false;
                }
                new_state.shared_waiting=0;

                state_data const current_state=interlocked_compare_exchange(&state,new_state,old_state);
                if(current_state==old_state)
                {
                    break;
                }
                old_state=current_state;
            }
            release_waiters(old_state);
        }
        void unlock_upgrade_and_lock_shared()
        {
            state_data old_state=state;
            for(;;)
            {
                state_data new_state=old_state;
                new_state.upgrade=false;
                if(new_state.exclusive_waiting)
                {
                    --new_state.exclusive_waiting;
                    new_state.exclusive_waiting_blocked=false;
                }
                new_state.shared_waiting=0;

                state_data const current_state=interlocked_compare_exchange(&state,new_state,old_state);
                if(current_state==old_state)
                {
                    break;
                }
                old_state=current_state;
            }
            release_waiters(old_state);
        }

    };
    typedef shared_mutex upgrade_mutex;

}

#include <boost/config/abi_suffix.hpp>

#endif


text:
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json.Linq;

namespace Orchard.Tokens.Services
{
    public interface ITokenizer
    {
        /// <summary>
        /// Evaluates the template with the specified data object as the context.
        /// The method requires an <see cref="IDictionary{TKey, TValue}"/> for performance reasons
        /// as reflection over dynamic and <see cref="JObject"/> is very expensive.
        /// </summary>
        string Tokenize(string template, IDictionary<string, object> context);
    }

    public static class TokenizerExtensions
    {
        public static string Tokenize(this ITokenizer tokenizer, string template, JObject obj)
        {
            var parameters = obj.ToDictionary<KeyValuePair<string, JToken>, string, object>(x => x.Key, y =>
            {
                switch (y.Value.Type)
                {
                    case JTokenType.Boolean:
                        return y.Value.ToObject<bool>();
                    case JTokenType.String:
                        return y.Value.ToObject<string>();
                    case JTokenType.Float:
                        return y.Value.ToObject<float>();
                }

                return y.Value.ToString();
            });

            return tokenizer.Tokenize(template, parameters);
        }
    }
}


text:
using DertInfo.WEB.ViewModels.Base;
using DertInfo.WEB.ViewModels.GroupVMs;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace DertInfo.WEB.ViewModels.GroupMemberVMs
{
    public class GroupMemberViewModel : DertViewModelBase_Accessible
    {
        //Constructors
        public GroupMemberViewModel()
            :base("disallow")
        {
            //note - Default constructor required for model binding on post. Only to be used in this scenario.
        }

        public GroupMemberViewModel(Models.GroupMember groupMember)
            : base(groupMember.AccessToken)
        {

            this.ToView(groupMember);
        }

        //Properties
        [Required]
        public int GroupMemberId { get; set; }
        [Required]
        public int GroupId { get; set; }
        [Required]
        [DisplayName("Member Name")]
        public string Name { get; set; }

        [DisplayName("Date Of Birth")]
        [DataType(DataType.Date)]
        [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
        public DateTime? DateOfBirth { get; set; }

        //Additional
        //public string GroupName { get; set; }

        //Status
        public string AccessToken { get; set; }
        public DateTime DateCreated { get; set; }
        public DateTime DateModified { get; set; }
        public string CreatedBy { get; set; }
        public string ModifiedBy { get; set; }
        public bool IsDeleted { get; set; }

        //ToView ToModel Methods
        private void ToView(Models.GroupMember groupMember)
        {
            this.GroupMemberId = groupMember.Id;
            this.GroupId = groupMember.GroupId;
            this.Name = groupMember.Name;
            this.DateOfBirth = groupMember.DateOfBirth;

            //Additional
            //this.GroupName = groupMember.Group.GroupName;

            this.AccessToken = groupMember.AccessToken;
            this.DateCreated = groupMember.DateCreated;
            this.DateModified = groupMember.DateModified;
            this.CreatedBy = groupMember.CreatedBy;
            this.ModifiedBy = groupMember.ModifiedBy;
            this.IsDeleted = groupMember.IsDeleted;
        }

        internal Models.GroupMember ToModel()
        {
            Models.GroupMember groupMember = new Models.GroupMember();

            groupMember.Id = this.GroupMemberId;
            groupMember.GroupId = this.GroupId;
            groupMember.Name = this.Name;
            groupMember.DateOfBirth = this.DateOfBirth;

            groupMember.AccessToken = this.AccessToken;
            groupMember.DateCreated = this.DateCreated;
            groupMember.DateModified = this.DateModified;
            groupMember.CreatedBy = this.CreatedBy;
            groupMember.ModifiedBy = this.ModifiedBy;
            groupMember.IsDeleted = this.IsDeleted;

            return groupMember;
        }
    }
}


text:
"""Simple REST service for creating users with useradd"""

from __future__ import print_function

import json
import os
import sys
from pwd import getpwnam
from subprocess import Popen, PIPE

from tornado import gen, web
from tornado.log import app_log
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop
from tornado.netutil import bind_unix_socket
from tornado.options import define, parse_command_line, options

class UserHandler(web.RequestHandler):

    def get_user(self, name):
        """Get a user struct by name, None if no such user"""
        try:
            return getpwnam(name)
        except KeyError:
            return None

    def write_error(self, status_code, **kwargs):
        """Simple (not html) errors"""
        exc = kwargs['exc_info'][1]
        self.write(exc.log_message or str(error))

    def new_user(self, name):
        """Create a new user.

        Return the new user's struct
        """
        group = self.settings.get('group', None)
        shell = self.settings.get('shell', '/bin/bash')
        skeldir = self.settings.get('skeldir', None)
        cmd = ['useradd', '-m', '-s', shell]
        if group:
            cmd.extend(['-G', group])
        if skeldir and os.path.exists(skeldir):
            cmd.extend(['-k', skeldir])
        cmd.append(name)

        app_log.info("Running %s", cmd)
        p = Popen(cmd, stderr=PIPE)
        _, err = p.communicate()
        if p.returncode:
            err = err.decode('utf8', 'replace').strip()
            raise web.HTTPError(400, err)
        return self.get_user(name)

    def post(self, name):
        user = self.get_user(name)
        d = {}
        if user is None:
            self.finish(json.dumps(d))
            #user = self.new_user(name)
        for attr in ['name', 'dir', 'shell', 'uid', 'gid']:
            d[attr] = getattr(user, 'pw_' + attr)
        self.finish(json.dumps(d))

def main():
    define('ip', default=None, help='IP to listen on')
    define('port', default=None, help='port to listen on')
    define('socket', default=None, help='unix socket path to bind (instead of ip:port)')
    define('group', default='', help='comma separated group list for new users `students,other`')
    define('skeldir', default='', help='skeleton directory that will be used for new homedirs')
    define('shell', default='/bin/bash', help='default shell')

    parse_command_line()

    if not options.socket and not (options.port):
        options.socket = '/var/run/restuser.sock'

    app = web.Application(
        [(r'/([^/]+)', UserHandler)],
        group=options.group,
        skeldir=options.skeldir,
        shell=options.shell)
    if options.socket:
        socket = bind_unix_socket(options.socket, mode=0o600)
        server = HTTPServer(app)
        server.add_socket(socket)
    else:
        app.listen(options.port, options.ip)
    try:
        IOLoop.current().start()
    except KeyboardInterrupt:
        print("\ninterrupted\n", file=sys.stderr)
        return

if __name__ == '__main__':
    main()


text:
package fun.web.mvc.common;

import fun.util.ConstructorUtil;

import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.support.WebBindingInitializer;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/**
 * Binding Initializer.
 * @author Open Source
 *
 */
@ControllerAdvice
public class BindingInitializer implements WebBindingInitializer {

  /**
   * Default Constructor.
   */
  public BindingInitializer() {
    super();
    ConstructorUtil.logInstanceCreation(BindingInitializer.class);
  }

  /**
   * Initialization binder.
   */
  @Override
  @org.springframework.web.bind.annotation.InitBinder
  public void initBinder(final org.springframework.web.bind.WebDataBinder binder,
      final org.springframework.web.context.request.WebRequest request) {
    final SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy", Locale.ENGLISH);
    final CustomDateEditor editor = new CustomDateEditor(dateFormat, true);
    binder.registerCustomEditor(Date.class, editor);

    final StringValidationEditor stringEditor = new StringValidationEditor();
    binder.registerCustomEditor(String.class, stringEditor);

    final CustomErrorProcessor errorProcessor = new CustomErrorProcessor();
    binder.setBindingErrorProcessor(errorProcessor);

  }

}


text:
#include "mongoc-log.h"
#include "mongoc-write-concern.h"
#include "mongoc-write-concern-private.h"

static BSON_INLINE bool
_mongoc_write_concern_warn_frozen (mongoc_write_concern_t *write_concern)
{
   if (write_concern->frozen) {
      MONGOC_WARNING("Cannot modify a frozen write-concern.");
   }

   return write_concern->frozen;
}

/**
 * mongoc_write_concern_new:
 *
 * Create a new mongoc_write_concern_t.
 *
 * Returns: A newly allocated mongoc_write_concern_t. This should be freed
 *    with mongoc_write_concern_destroy().
 */
mongoc_write_concern_t *
mongoc_write_concern_new (void)
{
   mongoc_write_concern_t *write_concern;

   write_concern = bson_malloc0(sizeof *write_concern);
   write_concern->w = -2;

   return write_concern;
}

mongoc_write_concern_t *
mongoc_write_concern_copy (const mongoc_write_concern_t *write_concern)
{
   mongoc_write_concern_t *ret = NULL;

   if (write_concern) {
      ret = mongoc_write_concern_new();
      ret->fsync_ = write_concern->fsync_;
      ret->journal = write_concern->journal;
      ret->w = write_concern->w;
      ret->wtimeout = write_concern->wtimeout;
      ret->frozen = false;
      ret->wtag = bson_strdup (write_concern->wtag);
   }

   return ret;
}

/**
 * mongoc_write_concern_destroy:
 * @write_concern: A mongoc_write_concern_t.
 *
 * Releases a mongoc_write_concern_t and all associated memory.
 */
void
mongoc_write_concern_destroy (mongoc_write_concern_t *write_concern)
{
   if (write_concern) {
      if (write_concern->compiled.len) {
         bson_destroy (&write_concern->compiled);
      }

      bson_free (write_concern->wtag);
      bson_free (write_concern);
   }
}

bool
mongoc_write_concern_get_fsync (const mongoc_write_concern_t *write_concern)
{
   bson_return_val_if_fail(write_concern, false);
   return write_concern->fsync_;
}

/**
 * mongoc_write_concern_set_fsync:
 * @write_concern: A mongoc_write_concern_t.
 * @fsync_: If the write concern requires fsync() by the server.
 *
 * Set if fsync() should be called on the server before acknowledging a
 * write request.
 */
void
mongoc_write_concern_set_fsync (mongoc_write_concern_t *write_concern,
                                bool             fsync_)
{
   bson_return_if_fail(write_concern);

   if (!_mongoc_write_concern_warn_frozen(write_concern)) {
      write_concern->fsync_ = fsync_;
   }
}

bool
mongoc_write_concern_get_journal (const mongoc_write_concern_t *write_concern)
{
   bson_return_val_if_fail(write_concern, false);
   return write_concern->journal;
}

/**
 * mongoc_write_concern_set_journal:
 * @write_concern: A mongoc_write_concern_t.
 * @journal: If the write should be journaled.
 *
 * Set if the write request should be journaled before acknowledging the
 * write request.
 */
void
mongoc_write_concern_set_journal (mongoc_write_concern_t *write_concern,
                                  bool             journal)
{
   bson_return_if_fail(write_concern);

   if (!_mongoc_write_concern_warn_frozen(write_concern)) {
      write_concern->journal = journal;
   }
}

int32_t
mongoc_write_concern_get_w (const mongoc_write_concern_t *write_concern)
{
   bson_return_val_if_fail(write_concern, MONGOC_WRITE_CONCERN_W_DEFAULT);
   return write_concern->w;
}

/**
 * mongoc_write_concern_set_w:
 * @w: The number of nodes for write or -1 for "majority".
 *
 * Sets the number of nodes that must acknowledge the write request before
 * acknowledging the write request to the client.
 *
 * You may specifiy @w as -1 to request that a "majority" of nodes
 * acknowledge the request.
 */
void
mongoc_write_concern_set_w (mongoc_write_concern_t *write_concern,
                            int32_t            w)
{
   bson_return_if_fail(write_concern);
   bson_return_if_fail(w >= -3);

   if (!_mongoc_write_concern_warn_frozen(write_concern)) {
      write_concern->w = w;
   }
}

int32_t
mongoc_write_concern_get_wtimeout (const mongoc_write_concern_t *write_concern)
{
   bson_return_val_if_fail(write_concern, 0);
   return write_concern->wtimeout;
}

/**
 * mongoc_write_concern_set_wtimeout:
 * @write_concern: A mongoc_write_concern_t.
 * @wtimeout_msec: Number of milliseconds before timeout.
 *
 * Sets the number of milliseconds to wait before considering a write
 * request as failed.
 */
void
mongoc_write_concern_set_wtimeout (mongoc_write_concern_t *write_concern,
                                   int32_t            wtimeout_msec)
{
   bson_return_if_fail(write_concern);

   if (!_mongoc_write_concern_warn_frozen(write_concern)) {
      write_concern->wtimeout = wtimeout_msec;
   }
}

bool
mongoc_write_concern_get_wmajority (const mongoc_write_concern_t *write_concern)
{
   bson_return_val_if_fail(write_concern, false);
   return (write_concern->w == -3);
}

/**
 * mongoc_write_concern_set_wmajority:
 * @write_concern: A mongoc_write_concern_t.
 * @wtimeout_msec: Number of milliseconds before timeout.
 *
 * Sets the "w" of a write concern to "majority". It is suggested that
 * you provide a reasonable @wtimeout_msec to wait before considering the
 * write request failed.
 */
void
mongoc_write_concern_set_wmajority (mongoc_write_concern_t *write_concern,
                                    int32_t                 wtimeout_msec)
{
   bson_return_if_fail(write_concern);

   if (!_mongoc_write_concern_warn_frozen(write_concern)) {
      write_concern->w = MONGOC_WRITE_CONCERN_W_MAJORITY;
      write_concern->wtimeout = wtimeout_msec;
   }
}

const char *
mongoc_write_concern_get_wtag (const mongoc_write_concern_t *write_concern)
{
   bson_return_val_if_fail (write_concern, NULL);

   if (write_concern->w == MONGOC_WRITE_CONCERN_W_TAG) {
      return write_concern->wtag;
   }

   return NULL;
}

void
mongoc_write_concern_set_wtag (mongoc_write_concern_t *write_concern,
                               const char             *wtag)
{
   bson_return_if_fail (write_concern);

   if (!_mongoc_write_concern_warn_frozen (write_concern)) {
      bson_free (write_concern->wtag);
      write_concern->wtag = bson_strdup (wtag);
      write_concern->w = MONGOC_WRITE_CONCERN_W_TAG;
   }
}

/**
 * mongoc_write_concern_freeze:
 * @write_concern: A mongoc_write_concern_t.
 *
 * This is an internal function.
 *
 * Freeze the write concern if necessary and compile the getlasterror command
 * associated with it.
 *
 * You may not modify the write concern further after calling this function.
 *
 * Returns: A bson_t that should not be modified or freed as it is owned by
 *    the mongoc_write_concern_t instance.
 */
const bson_t *
_mongoc_write_concern_freeze (mongoc_write_concern_t *write_concern)
{
   bson_t *b;

   bson_return_val_if_fail(write_concern, NULL);

   b = &write_concern->compiled;

   if (!write_concern->frozen) {
      write_concern->frozen = true;

      bson_init (b);

      BSON_APPEND_INT32 (b, "getlasterror", 1);

      if (write_concern->w == MONGOC_WRITE_CONCERN_W_TAG) {
         BSON_ASSERT (write_concern->wtag);
         BSON_APPEND_UTF8 (b, "w", write_concern->wtag);
      } else if (write_concern->w == MONGOC_WRITE_CONCERN_W_MAJORITY) {
         BSON_APPEND_UTF8 (b, "w", "majority");
      } else if (write_concern->w == MONGOC_WRITE_CONCERN_W_DEFAULT) {
         /* Do Nothing */
      } else if (write_concern->w > 0) {
         BSON_APPEND_INT32 (b, "w", write_concern->w);
      }

      if (write_concern->fsync_) {
         bson_append_bool(b, "fsync", 5, true);
      }

      if (write_concern->journal) {
         bson_append_bool(b, "j", 1, true);
      }

      if (write_concern->wtimeout) {
         bson_append_int32(b, "wtimeout", 8, write_concern->wtimeout);
      }
   }

   return b;
}

/**
 * mongoc_write_concern_has_gle:
 * @concern: (in): A mongoc_write_concern_t.
 *
 * Checks to see if @write_concern requests that a getlasterror command is to
 * be delivered to the MongoDB server.
 *
 * Returns: true if a getlasterror command should be sent.
 */
bool
_mongoc_write_concern_has_gle (const mongoc_write_concern_t *write_concern)
{
   if (write_concern) {
      return ((write_concern->w != 0) && (write_concern->w != -1));
   }
   return false;
}