text:
"""Test for preservation of unknown fields in the pure Python implementation."""

__author__ = 'bohdank@google.com (Bohdan Koval)'

from google.apputils import basetest
from google.protobuf import unittest_mset_pb2
from google.protobuf import unittest_pb2
from google.protobuf import unittest_proto3_arena_pb2
from google.protobuf.internal import api_implementation
from google.protobuf.internal import encoder
from google.protobuf.internal import missing_enum_values_pb2
from google.protobuf.internal import test_util
from google.protobuf.internal import type_checkers

class UnknownFieldsTest(basetest.TestCase):

  def setUp(self):
    self.descriptor = unittest_pb2.TestAllTypes.DESCRIPTOR
    self.all_fields = unittest_pb2.TestAllTypes()
    test_util.SetAllFields(self.all_fields)
    self.all_fields_data = self.all_fields.SerializeToString()
    self.empty_message = unittest_pb2.TestEmptyMessage()
    self.empty_message.ParseFromString(self.all_fields_data)

  def testSerialize(self):
    data = self.empty_message.SerializeToString()

    # Don't use assertEqual because we don't want to dump raw binary data to
    # stdout.
    self.assertTrue(data == self.all_fields_data)

  def testSerializeProto3(self):
    # Verify that proto3 doesn't preserve unknown fields.
    message = unittest_proto3_arena_pb2.TestEmptyMessage()
    message.ParseFromString(self.all_fields_data)
    self.assertEqual(0, len(message.SerializeToString()))

  def testByteSize(self):
    self.assertEqual(self.all_fields.ByteSize(), self.empty_message.ByteSize())

  def testListFields(self):
    # Make sure ListFields doesn't return unknown fields.
    self.assertEqual(0, len(self.empty_message.ListFields()))

  def testSerializeMessageSetWireFormatUnknownExtension(self):
    # Create a message using the message set wire format with an unknown
    # message.
    raw = unittest_mset_pb2.RawMessageSet()

    # Add an unknown extension.
    item = raw.item.add()
    item.type_id = 1545009
    message1 = unittest_mset_pb2.TestMessageSetExtension1()
    message1.i = 12345
    item.message = message1.SerializeToString()

    serialized = raw.SerializeToString()

    # Parse message using the message set wire format.
    proto = unittest_mset_pb2.TestMessageSet()
    proto.MergeFromString(serialized)

    # Verify that the unknown extension is serialized unchanged
    reserialized = proto.SerializeToString()
    new_raw = unittest_mset_pb2.RawMessageSet()
    new_raw.MergeFromString(reserialized)
    self.assertEqual(raw, new_raw)

  # C++ implementation for proto2 does not currently take into account unknown
  # fields when checking equality.
  #
  # TODO(haberman): fix this.
  @basetest.unittest.skipIf(
      api_implementation.Type() == 'cpp' and api_implementation.Version() == 2,
      'C++ implementation does not expose unknown fields to Python')
  def testEquals(self):
    message = unittest_pb2.TestEmptyMessage()
    message.ParseFromString(self.all_fields_data)
    self.assertEqual(self.empty_message, message)

    self.all_fields.ClearField('optional_string')
    message.ParseFromString(self.all_fields.SerializeToString())
    self.assertNotEqual(self.empty_message, message)

@basetest.unittest.skipIf(
    api_implementation.Type() == 'cpp' and api_implementation.Version() == 2,
    'C++ implementation does not expose unknown fields to Python')
class UnknownFieldsAccessorsTest(basetest.TestCase):

  def setUp(self):
    self.descriptor = unittest_pb2.TestAllTypes.DESCRIPTOR
    self.all_fields = unittest_pb2.TestAllTypes()
    test_util.SetAllFields(self.all_fields)
    self.all_fields_data = self.all_fields.SerializeToString()
    self.empty_message = unittest_pb2.TestEmptyMessage()
    self.empty_message.ParseFromString(self.all_fields_data)
    self.unknown_fields = self.empty_message._unknown_fields

  def GetField(self, name):
    field_descriptor = self.descriptor.fields_by_name[name]
    wire_type = type_checkers.FIELD_TYPE_TO_WIRE_TYPE[field_descriptor.type]
    field_tag = encoder.TagBytes(field_descriptor.number, wire_type)
    result_dict = {}
    for tag_bytes, value in self.unknown_fields:
      if tag_bytes == field_tag:
        decoder = unittest_pb2.TestAllTypes._decoders_by_tag[tag_bytes][0]
        decoder(value, 0, len(value), self.all_fields, result_dict)
    return result_dict[field_descriptor]

  def testEnum(self):
    value = self.GetField('optional_nested_enum')
    self.assertEqual(self.all_fields.optional_nested_enum, value)

  def testRepeatedEnum(self):
    value = self.GetField('repeated_nested_enum')
    self.assertEqual(self.all_fields.repeated_nested_enum, value)

  def testVarint(self):
    value = self.GetField('optional_int32')
    self.assertEqual(self.all_fields.optional_int32, value)

  def testFixed32(self):
    value = self.GetField('optional_fixed32')
    self.assertEqual(self.all_fields.optional_fixed32, value)

  def testFixed64(self):
    value = self.GetField('optional_fixed64')
    self.assertEqual(self.all_fields.optional_fixed64, value)

  def testLengthDelimited(self):
    value = self.GetField('optional_string')
    self.assertEqual(self.all_fields.optional_string, value)

  def testGroup(self):
    value = self.GetField('optionalgroup')
    self.assertEqual(self.all_fields.optionalgroup, value)

  def testCopyFrom(self):
    message = unittest_pb2.TestEmptyMessage()
    message.CopyFrom(self.empty_message)
    self.assertEqual(self.unknown_fields, message._unknown_fields)

  def testMergeFrom(self):
    message = unittest_pb2.TestAllTypes()
    message.optional_int32 = 1
    message.optional_uint32 = 2
    source = unittest_pb2.TestEmptyMessage()
    source.ParseFromString(message.SerializeToString())

    message.ClearField('optional_int32')
    message.optional_int64 = 3
    message.optional_uint32 = 4
    destination = unittest_pb2.TestEmptyMessage()
    destination.ParseFromString(message.SerializeToString())
    unknown_fields = destination._unknown_fields[:]

    destination.MergeFrom(source)
    self.assertEqual(unknown_fields + source._unknown_fields,
                     destination._unknown_fields)

  def testClear(self):
    self.empty_message.Clear()
    self.assertEqual(0, len(self.empty_message._unknown_fields))

  def testUnknownExtensions(self):
    message = unittest_pb2.TestEmptyMessageWithExtensions()
    message.ParseFromString(self.all_fields_data)
    self.assertEqual(self.empty_message._unknown_fields,
                     message._unknown_fields)

@basetest.unittest.skipIf(
    api_implementation.Type() == 'cpp' and api_implementation.Version() == 2,
    'C++ implementation does not expose unknown fields to Python')
class UnknownEnumValuesTest(basetest.TestCase):

  def setUp(self):
    self.descriptor = missing_enum_values_pb2.TestEnumValues.DESCRIPTOR

    self.message = missing_enum_values_pb2.TestEnumValues()
    self.message.optional_nested_enum = (
      missing_enum_values_pb2.TestEnumValues.ZERO)
    self.message.repeated_nested_enum.extend([
      missing_enum_values_pb2.TestEnumValues.ZERO,
      missing_enum_values_pb2.TestEnumValues.ONE,
      ])
    self.message.packed_nested_enum.extend([
      missing_enum_values_pb2.TestEnumValues.ZERO,
      missing_enum_values_pb2.TestEnumValues.ONE,
      ])
    self.message_data = self.message.SerializeToString()
    self.missing_message = missing_enum_values_pb2.TestMissingEnumValues()
    self.missing_message.ParseFromString(self.message_data)
    self.unknown_fields = self.missing_message._unknown_fields

  def GetField(self, name):
    field_descriptor = self.descriptor.fields_by_name[name]
    wire_type = type_checkers.FIELD_TYPE_TO_WIRE_TYPE[field_descriptor.type]
    field_tag = encoder.TagBytes(field_descriptor.number, wire_type)
    result_dict = {}
    for tag_bytes, value in self.unknown_fields:
      if tag_bytes == field_tag:
        decoder = missing_enum_values_pb2.TestEnumValues._decoders_by_tag[
          tag_bytes][0]
        decoder(value, 0, len(value), self.message, result_dict)
    return result_dict[field_descriptor]

  def testUnknownEnumValue(self):
    self.assertFalse(self.missing_message.HasField('optional_nested_enum'))
    value = self.GetField('optional_nested_enum')
    self.assertEqual(self.message.optional_nested_enum, value)

  def testUnknownRepeatedEnumValue(self):
    value = self.GetField('repeated_nested_enum')
    self.assertEqual(self.message.repeated_nested_enum, value)

  def testUnknownPackedEnumValue(self):
    value = self.GetField('packed_nested_enum')
    self.assertEqual(self.message.packed_nested_enum, value)

  def testRoundTrip(self):
    new_message = missing_enum_values_pb2.TestEnumValues()
    new_message.ParseFromString(self.missing_message.SerializeToString())
    self.assertEqual(self.message, new_message)

if __name__ == '__main__':
  basetest.main()


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">

    <ProgressBar
        android:id="@+id/progressBar"
        style="?android:attr/progressBarStyleLarge"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_alignParentStart="true" />

    <ProgressBar
        android:id="@+id/progressBar2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/progressBar"
        android:layout_alignParentStart="true" />

    <ProgressBar
        android:id="@+id/progressBar3"
        style="?android:attr/progressBarStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/progressBar2"
        android:layout_alignParentStart="true" />

    <ProgressBar
        android:secondaryProgress="80"
        android:progress="50"
        android:max="100"
        android:id="@+id/horiz"
        style="@android:style/Widget.ProgressBar.Horizontal"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/progressBar3"
        android:layout_alignParentStart="true"
        android:layout_alignEnd="@+id/show" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/add"
        android:id="@+id/add"
        android:layout_below="@+id/horiz"
        android:layout_toEndOf="@+id/progressBar3"
        android:layout_marginTop="23dp" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/reduce"
        android:id="@+id/reduce"
        android:layout_below="@+id/add"
        android:layout_alignEnd="@+id/add"
        android:layout_marginTop="29dp" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/reset"
        android:id="@+id/reset"
        android:layout_below="@+id/reduce"
        android:layout_alignEnd="@+id/reduce"
        android:layout_marginTop="27dp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="New Text"
        android:id="@+id/text"
        android:layout_below="@+id/reset"
        android:layout_alignStart="@+id/reset"
        android:layout_marginTop="33dp" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/show"
        android:id="@+id/show"
        android:layout_alignTop="@+id/text"
        android:layout_toEndOf="@+id/reset"
        android:layout_marginStart="54dp" />

</RelativeLayout>

redpajama_set_name: RedPajamaGithub


text:
package build.tools.generatenimbus;

import javax.xml.bind.annotation.XmlAttribute;

public class UIDefault<T> {
    @XmlAttribute private String name;
    private T value;

    public String getName() {
        return name;
    }

    public T getValue() {
        return value;
    }

    public void setValue(T value) {
        this.value = value;
    }
}


text:
from __future__ import unicode_literals
class MessageNotInflight(Exception):
    description = "The message referred to is not in flight."
    status_code = 400

class ReceiptHandleIsInvalid(Exception):
    description = "The receipt handle provided is not valid."
    status_code = 400

class MessageAttributesInvalid(Exception):
	status_code = 400

	def __init__(self, description):
		self.description = description


text:
test_description='git apply submodule tests'

. ./test-lib.sh

test_expect_success setup '
	cat > create-sm.patch <<EOF &&
diff --git a/dir/sm b/dir/sm
new file mode 160000
index 0000000..0123456
--- /dev/null
+++ b/dir/sm
@@ -0,0 +1 @@
+Subproject commit 0123456789abcdef0123456789abcdef01234567
EOF
	cat > remove-sm.patch <<EOF
diff --git a/dir/sm b/dir/sm
deleted file mode 160000
index 0123456..0000000
--- a/dir/sm
+++ /dev/null
@@ -1 +0,0 @@
-Subproject commit 0123456789abcdef0123456789abcdef01234567
EOF
'

test_expect_success 'removing a submodule also removes all leading subdirectories' '
	git apply --index create-sm.patch &&
	test -d dir/sm &&
	git apply --index remove-sm.patch &&
	test \! -d dir
'

test_done


text:
//
//  WBBaseViewController.m
//  FreeShuQiNovel
//
//  Created by wangbing on 16/4/19.
//  Copyright © 2016年 wangbing. All rights reserved.
//

#import "WBBaseViewController.h"
#import "UIBarButtonItem+WBCustomButton.h"
#import "UIViewController+RESideMenu.h"
#import "RESideMenu.h"
#import "Const.h"

@interface WBBaseViewController ()

@end

@implementation WBBaseViewController

- (void)setHasReturnArrow:(BOOL)hasReturnArrow
{
    _hasReturnArrow = hasReturnArrow;
    if (hasReturnArrow) {
        self.navigationItem.leftBarButtonItems = [UIBarButtonItem barButtonItemWithImageName:@"arrow_left" withHighlightedImageName:@"arrow_left" withTarget:self withAction:@selector(returnBtnAction) WithNegativeSpacerWidth:-4];
    }

}

- (void)setHideReturnBtn:(BOOL)hideReturnBtn
{
    _hideReturnBtn = hideReturnBtn;
    if (hideReturnBtn) {
         self.navigationItem.hidesBackButton = YES;
    }

}

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

}

- (instancetype)initWithViewControllerNavItemStyle:(ViewControllerNavItemStyle)viewControllerNavItemStyle{
    self = [super init];
    if (self) {
        //不让view受navbar的影响

        switch (viewControllerNavItemStyle) {
            case ViewControllerNavItemStyleMain:
            {

//                self.navigationItem.leftBarButtonItems = [UIBarButtonItem barButtonItemWithImageName:@"navbar_menu" withHighlightedImageName:nil withTarget:self withAction:@selector(MainMenuBtnAction:) WithNegativeSpacerWidth:-5];
//
//
//                self.navigationItem.rightBarButtonItems = [UIBarButtonItem barButtonItemWithImageName:@"navbar_search" withHighlightedImageName:nil withTarget:self withAction:@selector(mainSearchBtnAction:) WithNegativeSpacerWidth:-5];

            }
                break;

            case ViewControllerNavItemStyleForum:
            {
                self.navigationItem.rightBarButtonItems = [UIBarButtonItem barButtonItemWithImageName:@"navbar_back" withHighlightedImageName:nil withTarget:self withAction:@selector(ForumPublishBtnAction:)  WithNegativeSpacerWidth:-10];

            }
                break;

            case ViewControllerNavItemStyleGuidance:
            {

            }
                break;
            case ViewControllerNavItemStylePhoneBook:
            {

            }
                break;

            default:
                break;
        }

    }
    return self;
}

#pragma mark---设置navBar上面title的文字及属性
- (void)setNavBarTitleWithText:(NSString *)title withFontSize:(CGFloat)fontSize withTextColor:(UIColor *)color{
    self.navigationItem.title = title;
    // 设置导航默认标题的颜色及字体大小
    NSDictionary *attributes = @{NSForegroundColorAttributeName : color, NSFontAttributeName : [UIFont systemFontOfSize:fontSize]};
    self.navigationController.navigationBar.titleTextAttributes = attributes;
}

#pragma mark----navBar按钮单击事件

- (void)MainMenuBtnAction:(UIButton *)sender
{
    [self.sideMenuViewController presentLeftMenuViewController];
}

- (void)mainSearchBtnAction:(UIButton *)sender
{
   NSLog(@"mainSearchBtnAction");
}

- (void)ForumPublishBtnAction:(UIButton *)sender
{
    NSLog(@"ForumPublishBtnAction");
}

- (void)pop{

    [self.navigationController popViewControllerAnimated:YES];

}

- (void)returnBtnAction
{
    [self pop];
}

//从隐藏navbar到显示navbar之间的处理
- (void)loadView {
    [super loadView];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
//    return;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.view.backgroundColor = kBGDefaultColor;

    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end


text:
import React from 'react';
import PropTypes from 'prop-types';
import { Set, Map, is, Record } from 'immutable';
import { connect } from 'react-redux';
import { shallowEqualImmutable } from 'react-immutable-render-mixin';
import moment from 'moment';
import { Link } from 'react-router-dom';

import compose from 'recompose/compose';
import { withStyles } from '@material-ui/core/styles';
import ListItem from '@material-ui/core/ListItem';
import ListItemText from '@material-ui/core/ListItemText';
import ListItemAvatar from '@material-ui/core/ListItemAvatar';
import List from '../../../components/List/EnhancedList';

import UserAvatar from '../../User/components/UserAvatar';

import { DiscussionRemote } from '../DiscussionActions';
import { getRootDiscussions } from '../DiscussionReducer';
import { getIsFirstRender } from '../../MyApp/MyAppReducer';

const styles = theme => ({
  root: {
    backgroundColor: theme.palette.background.paper,
    width: '100%',
    height: '100%',
    overflow: 'auto',
  },
});

const FORUM_BOARD_GROUP_ALL = '_all';

const PageInfo = Record({
  forumBoardGroup: FORUM_BOARD_GROUP_ALL,
  limit: 10,
  page: 1,
});

class RootDiscussionList extends React.Component {
  static propTypes = {
    forumBoardId: PropTypes.string,
    forumBoardGroup: PropTypes.string,
    dataSource: PropTypes.object,
    isFirstRender: PropTypes.bool,
    sort: PropTypes.string,
  };

  static defaultProps = {
    forumBoardGroup: FORUM_BOARD_GROUP_ALL,
    dataSource: Set(),
    isFirstRender: false,
    sort: '-updatedAt',
  };

  constructor(props) {
    super(props);
    const pageInfo = this.createPageInfo();
    const pageTable = Map().merge(pageInfo);
    this.state = {
      pageTable,
    };
  }

  componentWillReceiveProps(nextProps) {
    if (this.props.forumBoardGroup !== nextProps.forumBoardGroup) {
      const { pageTable } = this.state;
      const nextPageTable = pageTable.merge(this.createPageInfo(nextProps, { page: 1 }));
      this.setState({ pageTable: nextPageTable }, () => {
        this.handleRequestMore({ direction: 'top' });
      });
    }
  }

  getForumBoardGroup = (props = this.props) => {
    return props.forumBoardGroup || FORUM_BOARD_GROUP_ALL;
  };

  handleRequestMore = async ({ direction }) => {
    const { pageTable } = this.state;
    const { forumBoardId, forumBoardGroup, sort } = this.props;
    const pageInfo = pageTable.get(this.getForumBoardGroup());
    const { page, limit } = pageInfo;
    if (!forumBoardId) {
      return Promise.resolve(null);
    }
    const nextPage = direction === 'bottom' ? page + 1 : 1;
    const prevDataSource = this.props.dataSource;
    // TODO
    // cancel fetch when componemntWillUnmount
    const discussionsJSON = await this.props.dispatch(
      DiscussionRemote.getRootDiscussions(forumBoardId, {
        page: nextPage,
        limit,
        sort,
        forumBoardGroup,
      })
    );
    const currentDataSource = this.props.dataSource;
    if (
      discussionsJSON.length < limit ||
      prevDataSource.count() === currentDataSource.count() ||
      is(prevDataSource, currentDataSource)
    ) {
      return null;
    } else {
      const currentPageTable = this.state.pageTable;
      const nextPageInfo = currentPageTable.get(pageInfo.get('forumBoardGroup'));
      const nextPageTable = pageTable.set(
        nextPageInfo.get('forumBoardGroup'),
        nextPageInfo.set('page', nextPageInfo.get('page') + 1)
      );
      this.setState({ pageTable: nextPageTable });
      return null;
    }
  };

  createPageInfo = (props = this.props) => {
    const { dataSource } = props;
    const forumBoardGroup = this.getForumBoardGroup(props);
    const limit = props.limit || 10;
    const page = props.page || Math.floor(dataSource.count() / limit) || 1;
    return Map({
      [forumBoardGroup]: new PageInfo({
        forumBoardGroup,
        limit,
        page,
      }),
    });
  };

  sortBy = payload => {
    return -1 * new Date(payload.updatedAt).getTime();
  };

  listItemHref = payload => {
    return `/discussions/${payload._id}`;
  };

  listItemSecondaryText = discussion => {
    const { isFirstRender } = this.props;
    const fromNowTime = isFirstRender
      ? moment(discussion.updatedAt).format('ll')
      : moment(discussion.updatedAt).fromNow();
    const childDiscussionCount = discussion.childDiscussionCount || 0;
    const Delimeter = () => •;
    const { authorBasicInfo } = discussion;
    const displayName = authorBasicInfo ? authorBasicInfo.displayName : 'Guest';
    return (

        {displayName}
        <Delimeter />
        {`${fromNowTime}`}
        <Delimeter />
        {`${childDiscussionCount}`}
        留言

    );
  };

  listItemLeftAvatar = discussion => {
    const { authorBasicInfo } = discussion;
    return <UserAvatar user={authorBasicInfo} />;
  };

  render() {
    const { id, forumBoardId } = this.props;
    if (!forumBoardId) {
      return
Loading...
;
    }
    const { dataSource: dataSourceInput } = this.props;
    const dataSource = dataSourceInput.sortBy(this.sortBy);
    const { classes } = this.props;
    return (
      <List
        id={id ? `${id}/List` : undefined}
        onRequestMore={this.handleRequestMore}
        className={classes.root}
      >
        {dataSource.map(discussion => {
          const key = discussion._id;
          const to = this.listItemHref(discussion);
          const avatar = this.listItemLeftAvatar(discussion);
          const primary = discussion.title;
          const secondary = this.listItemSecondaryText(discussion);
          return (
            <ListItem key={key} button component={Link} to={to} divider>
              <ListItemAvatar>{avatar}</ListItemAvatar>
              <ListItemText primary={primary} secondary={secondary} />
            </ListItem>
          );
        })}
      </List>
    );
  }
}

function mapStateToProps(store, props) {
  const { forumBoard, forumBoardGroup } = props;
  let { forumBoardId } = props;
  forumBoardId = forumBoard ? forumBoard._id || forumBoardId : forumBoardId;
  const dataSource = forumBoardId
    ? getRootDiscussions(store, forumBoardId, forumBoardGroup)
    : Set();
  const isFirstRender = getIsFirstRender(store);
  return { forumBoardId, forumBoardGroup, dataSource, isFirstRender };
}

export default compose(
  withStyles(styles),
  connect(
    mapStateToProps,
    dispatch => {
      return { dispatch };
    },
    null,
    {
      areStatePropsEqual: shallowEqualImmutable,
    }
  )
)(RootDiscussionList);


text:
package GUI.Vue3.Joueur;

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Enumeration;

import javax.swing.*;

import Controleur.ControleurPlacement;
import Model.Joueur;
import Model.Personnage;

/**
 *
 * Classe interface qui etend VueJoueur et qui gere la partie Joueur (droite et gauche) lors du placement des Personnage sur le plateau
 * @author Warlot/Gasquez
 */
public class VueJoueurPlacement extends VueJoueur {
	private ButtonGroup radioGroup;

	/**
	 * Constructeur
 Va instancier selon l'axe Y : la liste des Personnage
	 * @param controleur controleur de cette interface
	 * @param monJoueur joueur associe a ce panel
	 */
	public VueJoueurPlacement(ControleurPlacement controleur, Joueur monJoueur){
		super(controleur, monJoueur);

		setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));

		radioGroup = new ButtonGroup();
		for (Personnage o : monJoueur.listerEquipe()){

			RadioButton radio = new RadioButton(o.getClasse());
			radio.addActionListener(new ActionListener() {

				@Override
				public void actionPerformed(ActionEvent e) {
					RadioButton monRadioButton = (RadioButton) e.getSource();

					getControleur().selectionnerPersonnage(monRadioButton.getPersonnage());
				}
			});
			radio.setPersonnage(o);
			radioGroup.add(radio);

			add(radio);
		}
	}

	/**
	 * Indique qu'un personnage est place
	 * @param o Personnage dont on veut indiquer qu'il est placer
	 */
	public void indiquerPersonnagePlace(Personnage o){
		 for (Enumeration<AbstractButton> buttons = radioGroup.getElements(); buttons.hasMoreElements();) {
			 AbstractButton button = buttons.nextElement();

			 if (button.isSelected()){
				 button.setForeground(Color.GREEN);
				 return;
			 }
		 }
	}

	/****************** GETTERS ******************/
	public ControleurPlacement getControleur() {
		return (ControleurPlacement) controleur;
	}
}


text:
const ProtocolAction = require('./_base-action.js');

/**
 * Get a list of the available contexts.
 *
 * Used by Appium when testing hybrid mobile web apps. More info here: https://github.com/appium/appium/blob/master/docs/en/advanced-concepts/hybrid.md.
 *
 * @method contexts
 * @param {function} callback Callback function to be called when the command finishes.
 * @returns {Array} an array of strings representing available contexts, e.g 'WEBVIEW', or 'NATIVE'
 * @api protocol.mobile
 */
module.exports = class Session extends ProtocolAction {
  command(callback) {
    return this.transportActions.getAvailableContexts(callback);
  }
};


text:
copy src.png smiley000.png
convert -background #000000 src.png -rotate 15 smiley015.png
convert -background #000000 src.png -rotate 30 smiley030.png
convert -background #000000 src.png -rotate 45 smiley045.png
convert -background #000000 src.png -rotate 60 smiley060.png
convert -background #000000 src.png -rotate 75 smiley075.png
convert -background #000000 src.png -rotate 90 smiley090.png
convert -background #000000 src.png -rotate 105 smiley105.png
convert -background #000000 src.png -rotate 120 smiley120.png
convert -background #000000 src.png -rotate 135 smiley135.png
convert -background #000000 src.png -rotate 150 smiley150.png
convert -background #000000 src.png -rotate 165 smiley165.png
convert -background #000000 src.png -rotate 180 smiley180.png
convert -background #000000 src.png -rotate 195 smiley195.png
convert -background #000000 src.png -rotate 210 smiley210.png
convert -background #000000 src.png -rotate 225 smiley225.png
convert -background #000000 src.png -rotate 240 smiley240.png
convert -background #000000 src.png -rotate 255 smiley255.png
convert -background #000000 src.png -rotate 270 smiley270.png
convert -background #000000 src.png -rotate 285 smiley285.png
convert -background #000000 src.png -rotate 300 smiley300.png
convert -background #000000 src.png -rotate 315 smiley315.png
convert -background #000000 src.png -rotate 330 smiley330.png
convert -background #000000 src.png -rotate 345 smiley345.png


text:
<link rel="stylesheet" href="terminal.css">

<template>

Type 'help' to get started.

      <content></content>

</template>


text:
<?php

namespace Base\Repository;

use Doctrine\ORM\EntityRepository;

class PassagemRepository extends EntityRepository
{
    public function findLeiloes(){
        $qb =  $this->createQueryBuilder('p');
        $qb->select('p');
        $qb->innerJoin('Base\Entity\Leilao', 'l', 'WITH', 'p.leilao = l.idleilao');
        $qb->where("l.datainicio <= :now");
        $qb->setParameter('now', new \DateTime('now'));
        $query = $qb->getQuery();
        $results = $query->getResult();
        return $results;
    }
}


text:
PROJECT_NAME := tests

include $(IDF_PATH)/make/project.mk


text:
package net.sf.sparql.benchmarking.operations.query;

import net.sf.sparql.benchmarking.operations.AbstractOperation;
import net.sf.sparql.benchmarking.stats.impl.QueryRun;

/**
 * Abstract implementation of a query operation
 *
 * @author rvesse
 *
 */
public abstract class AbstractQueryOperation extends AbstractOperation implements QueryOperation {

    /**
     * Creates a new operation
     *
     * @param name
     *            Query name
     */
    public AbstractQueryOperation(String name) {
        super(name);
    }

    @Override
    public QueryRun createErrorInformation(String message, int category, long runtime) {
        return new QueryRun(message, category, runtime);
    }

    @Override
    public String getContentString() {
        return this.getQueryString();
    }

    /**
     * Gets the string representation (i.e. the name) of the operation
     */
    @Override
    public String toString() {
        return this.getName();
    }
}


text:
<?php defined('BASEPATH') OR exit('No direct script access allowed');

class Recheck_model extends CI_Model {

	public function __construct()
	{
		parent::__construct();
		//Do your magic here
		$this->set_db_admission();
		$this->load->model('Money_quaota_model','money_quaota');
		$this->load->model('Money_exams_model','money_exams');
	}

	public $admission;

	public function set_db_admission(){
		$this->admission = $this->load->database('admission', TRUE);
	}

	public function get_department_all(){
		$this->admission->select("branchID,branch,major,typeOfCourse,level,course,branchId3");
		$this->admission->from('tblbranch');
		$this->admission->order_by('branchId3');

		$query = $this->admission->get();

	   if($query -> num_rows() >0)
	   {
	     return $query->result();
	   }
	   else
	   {

	     return false;
	   }
	}
	/* -------------------------- std check q+m */

	/*ข้อมูลเด็กสอบ*/
	public function query_std_exams($branchId=NULL,$stdCardID=NULL,$where_stdCardID=NULL,$search=NULL,$where_array=NULL,$orderby=NULL){

		if(is_array($stdCardID) && $stdCardID != false){
			if($where_stdCardID == NULL){
				$this->admission->where_not_in('stdCardID', $stdCardID);
			}else{
				$this->admission->where_in('stdCardID', $stdCardID);
			}

		}else if($stdCardID != false){
			$this->admission->where('stdCardID',$stdCardID);
		}

		if($branchId != NULL){
			$this->admission->where('stdAdmisResult',$branchId);
		}
		$this->admission->select("stdCardID,stdApplyNo,prefix_id_th,stu_fname_th,stu_lname_th,stdAdmisResult,stat_into,stdAdmisResult,total")
						->from('tblcandidate')
						//->where('stat_into','0')
						->where('round>','0');
		if($orderby == NULL){
			$this->admission->order_by('stdApplyNo','ASC');
		}else{
			$this->admission->order_by($orderby,'DESC');
		}

		//echo $search."||";
		if($search != NULL){
			//echo "OK";
			$this->admission->group_start();
			$this->admission->or_like('stdCardID',$search);
			$this->admission->or_like('stdApplyNo',$search);
			$this->admission->or_like('stu_fname_th',$search);
			$this->admission->or_like('stu_lname_th',$search);
			$this->admission->group_end();
		}

		if(is_array($where_array) && $where_array != false){
			foreach ($where_array as $key => $value) {
				$this->admission->where($key,$value);
			}
		}

		$query = $this->admission->get();

		//echo $this->admission->last_query();
		//exit();
		if($query->num_rows() == 0){
			$data['data'] = false;
			$data['key'] =false;
			$data['count'] = false;
			return $data;
		}

		$surrender = $this->get_surrender_exams_teacher();

		//check money
		$money_check = $this->money_exams->check_money_exams();

		if($query->num_rows() > 0){
			foreach ($query->result_array() as $row){

				$row = array_merge($row,$this->get_department_by_id($row['stdAdmisResult']));
				$row['in'] = 'exams';

				//start check money
				if($money_check !== false){
					if(isset($money_check[$row['stdApplyNo']])){
						$row['money'] = 1;
					}else{
						$row['money'] = 0;
					}
				}
				//end check money

				//check surrender

					if($surrender !== false){
						if(@isset($surrender[$row['stdApplyNo']])){
							$row['surrender'] = $surrender[$row['stdApplyNo']];
						}else{
							$row['surrender'] = 0;
						}
					}else{
						$row['surrender'] = 0;
					}
				//end check surrender

				$data['data'][] = $row;
				$data['key'][] =$row['stdCardID'];
			}
				$data['count'] = $query->num_rows();
			return $data;
				//return false;
		}else{
			 return false;
		}

	}
	public function query_std_quaota($branchId=NULL,$stdCardID=NULL,$where_stdCardID=NULL,$search=NULL,$where_array=NULL,$orderby=NULL){

		if(is_array($stdCardID) && $stdCardID != false){

			if($where_stdCardID == NULL){
				$this->admission->where_not_in('stdCardID', $stdCardID);
			}else{
				$this->admission->where_in('stdCardID', $stdCardID);
			}
		}else if($stdCardID != false){
			$this->admission->where('stdCardID',$stdCardID);
		}

		if($branchId != NULL){
			$this->admission->where('std_admis_result',$branchId);
		}
		$this->admission->select("stdCardID,stdApplyNo,prefix_id_th,stu_fname_th,stu_lname_th,std_admis_result,stat_into,stdAdmisResult,stdGPA")
						->from('tblcandidate_q')
						->where('stat_into','0')
						//**add new 2/17/2017
						->where('stdAdmisResult !=','')
						->where('comment','');
					//	->order_by('stdApplyNo','ASC');
		if($orderby == NULL){
			$this->admission->order_by('stdApplyNo','ASC');
		}else{
			$this->admission->order_by($orderby,'DESC');
		}

		if($search != null){
			//echo "MMMMMMM";

			$this->admission->group_start();
			$this->admission->or_like('stdCardID',$search);
			$this->admission->or_like('stdApplyNo',$search);
			$this->admission->or_like('stu_fname_th',$search);
			$this->admission->or_like('stu_lname_th',$search);
			$this->admission->group_end();
		}

		if(is_array($where_array) && $where_array != false){
			foreach ($where_array as $key => $value) {
				$this->admission->where($key,$value);
			}
		}

		$query = $this->admission->get();
		//echo " || ".$this->admission->last_query();
		if($query->num_rows() == 0){
			$data['data'] = false;
			$data['key'] =false;
			$data['count'] = false;
			return $data;
		}

		//check money
		$money_check = $this->money_quaota->check_money_quaota();

		if($query->num_rows() > 0){
			foreach ($query->result_array() as $row){
				//start check money
				if($money_check !== false){
					if(isset($money_check[$row['stdApplyNo']])){
						$row['money'] = 1;
					}else{
						$row['money'] = 0;
					}
				}
				//end check money

				$row = array_merge($row,$this->get_department_by_id($row['stdAdmisResult']));
				$row['in'] = 'quaota';
				$data['data'][] = $row;
				$data['key'][] =$row['stdCardID'];
			}
				$data['count'] = $query->num_rows();
			return $data;
		}else{
			 return false;
		}

	}

	//get by branchID => branch
	public	function get_department_by_id($id_department){
		$this->admission->select("branch,major,level")
						->from('tblbranch')
						->where('branchID',$id_department);
		$query = $this->admission->get();

		$row = $query->row();
		if(isset($row)){
				$data['branch'] = $row->branch;
				$data['major'] = $row->major;
				$data['level'] = $row->level;
				return $data;

		}
				$data['branch'] = "ไม่พบ";
				$data['major'] = "ไม่พบ";
				$data['level'] = "ไม่พบ";
				return $data;

	}

	public function merge_quaota_exams($branchId=NULL,$stdCardID=NULL,$where_stdCardID=NULL,$search=NULL){
		//echo "(".$search.")";
		$data['exams'] = $this->query_std_exams($branchId,$stdCardID,$where_stdCardID,$search);
		//$data['exams'] = NULL;
		$data['quaota'] = $this->query_std_quaota($branchId,$stdCardID,$where_stdCardID,$search);
		//$data['quaota'] = NULL;

		if($data['exams']['data'] == false && $data['quaota']['data'] != false){
			$data_main = $data['quaota']['data'];

		}else if($data['exams']['data'] != false && $data['quaota']['data'] == false){
			$data_main= $data['exams']['data'];

		}else if($data['exams']['data'] == false && $data['quaota']['data'] == false){
			$data_main= false;

		}else{
		$data_main = array_merge($data['exams']['data'],$data['quaota']['data']);

		}
		$data_return['data'] = $data_main;
		$data_return['exams'] = $data['exams']['count'];
		$data_return['quaota'] = $data['quaota']['count'];
		$data_return['sum'] = $data['exams']['count']+$data['quaota']['count'];
		return $data_return;

	}

	public function std_full(){
		$data = $this->merge_quaota_exams();
		return $data;
	}

	//Dep count by std
	public function get_dep_count_by_std(){
		$query_exams = $this->admission->query("SELECT stdAdmisResult,COUNT(stdAdmisResult) AS count FROM `tblcandidate` WHERE round > '0' AND stdAdmisResult !='' GROUP BY stdAdmisResult");
		foreach ($query_exams->result_array() as $row)
		{
				$row['count'] = intval($row['count']);
		        $row = array_merge($row,$this->get_department_by_id($row['stdAdmisResult']));
		        $data[$row['stdAdmisResult']] = $row;

		}

		$query_quaota = $this->admission->query("SELECT std_admis_result AS stdAdmisResult,COUNT(std_admis_result) AS count FROM `tblcandidate_q` WHERE stat_into = 0 AND comment='' AND std_admis_result != ''  GROUP BY std_admis_result");
		foreach ($query_quaota->result_array() as $row) {

			if(isset($data[$row['stdAdmisResult']]['count'])){
				$data[$row['stdAdmisResult']]['count']= intval($row['count']) + intval($data[$row['stdAdmisResult']]['count']);
			}else{
				$row = array_merge($row,$this->get_department_by_id($row['stdAdmisResult']));
		        $data[$row['stdAdmisResult']] = $row;
			}
		}//end foreach quaota;

		return $data;
	}

	public function get_surrender_exams_teacher(){
		$query = $this->db->get('surrender_exams_teacher');
		if($query->num_rows() == 0)
			return false;

		foreach ($query->result_array() as  $row) {
			$data[$row['stdApplyNo']] = $row['surrender_status'];
		}
		//var_dump($data);
		return $data;
	}

	public function change_surrender_exams_teacher($data){
		$insert = $this->db->replace('surrender_exams_teacher', $data);
		if($insert){
			return true;
		}else{
			return false;
		}
	}
//check std ===============================================================>
	public function data_std_group_error(){

		 $data  = array('exams' =>array(),
							'quaota' =>array(),
							'no' =>array() );

		$std_group = $this->get_std_group_all();

		if($std_group === false) return false;

			foreach ($std_group as $key => $group) {
			$where = array('stdCardID' =>$group['stdCardID'],
							'stdApplyNo' =>$group['stdApplyNo']
							);
			//exams
			$exams = $this->check_std_exams($where);
			if($exams !== false){
					if($exams['stdAdmisResult'] != $group['branchId'] || $exams['round'] == 0){
						$group['data'] = $exams;
						$data['exams'][] = $group;
					}
					continue;
			}
			//quaota
			$quaota = $this->check_std_quaota($where);
			if($quaota !== false){
					if($quaota['stdAdmisResult'] != $group['branchId'] || $quaota['stat_into'] == 1 || $quaota['stat_into'] ==2){
						$group['data'] = $quaota;
						$data['quaota'][] = $group;
					}
					continue;
			}

			//no std
			$data['no'][] = $group;

		}//endforeach

		return $data;

	}

	public function check_std_exams($where_array){
		$this->admission->where($where_array);
		$query = $this->admission->get('tblcandidate');
		if($query->num_rows() == 0) return false;
		foreach ($query->result_array() as  $row) {
			$data = $row;

		}
		return $data;
	}
	public function check_std_quaota($where_array){
		$this->admission->where($where_array);
		$query = $this->admission->get('tblcandidate_q');
		if($query->num_rows() == 0) return false;
		foreach ($query->result_array() as  $row) {
			$data = $row;

		}
		return $data;
	}

	public function get_std_group_all(){
		$this->db->where('std_group !=','99');
		$query = $this->db->get('std_group');
		if($query->num_rows() ==0) return false;

		foreach ($query->result_array() as $row) {
			$data[] = $row;
		}
		return $data;
	}
}

/* End of file Recheck_model.php */
/* Location: ./application/models/Recheck_model.php */
?>


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <include layout="@layout/test_template"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:weightSum="5">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:orientation="vertical">

            <Button
                android:id="@+id/test_score_total"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_margin="@dimen/sep_size_m"
                android:background="@drawable/patch_yellow"
                android:text="@string/test_score_total"
                android:textSize="@dimen/font_size_l"/>
        </LinearLayout>

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="2"
            android:orientation="vertical">

            <TextView
                android:layout_above="@+id/test_score_value"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:text="@string/test_score_description"
                android:textSize="@dimen/font_size_m"/>

            <TextView
                android:id="@+id/test_score_value"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_centerVertical="true"
                android:gravity="center"
                android:text="@string/test_score_value"
                android:textSize="@dimen/font_size_x"/>

            <TextView
                android:id="@+id/test_score_incorrect"
                android:layout_below="@+id/test_score_value"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:text="@string/test_score_incorrect"
                android:textSize="@dimen/font_size_m"/>
        </RelativeLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:orientation="vertical">

            <Button
                android:id="@+id/test_score_repeat"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_margin="@dimen/sep_size_m"
                android:background="@drawable/patch_cyan"
                android:text="@string/test_score_repeat"/>
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:orientation="vertical">

            <Button
                android:id="@+id/test_score_tests"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_margin="@dimen/sep_size_m"
                android:background="@drawable/patch_cyan"
                android:text="@string/test_score_tests"/>
        </LinearLayout>
    </LinearLayout>

</LinearLayout>


text:
extern crate kolmogorov_smirnov as ks;

use ks::test_f64;

use std::env;
use std::io::{BufReader, BufRead};
use std::fs::File;
use std::path::Path;

fn parse_float(s: String) -> f64 {
    s.parse::<f64>().expect("Not a floating point number.")
}

/// Runs a Kolmogorov-Smirnov test on floating point data files.
///
/// Input files must be single-column headerless data files. The data samples
/// are tested against each other at the 95% confidence level.
///
/// # Examples
///
/// ```bash
/// cargo run --bin ks_f64 <file1> <file2>
/// ```
///
/// This will print the test result to standard output.
fn main() {
    let args: Vec<String> = env::args().collect();

    let path1 = Path::new(&args[1]);
    let path2 = Path::new(&args[2]);

    let file1 = BufReader::new(File::open(&path1).unwrap());
    let file2 = BufReader::new(File::open(&path2).unwrap());

    let lines1 = file1.lines().map(|line| line.unwrap());
    let lines2 = file2.lines().map(|line| line.unwrap());

    let xs: Vec<f64> = lines1.map(parse_float).collect();
    let ys: Vec<f64> = lines2.map(parse_float).collect();

    let result = ks::test_f64(&xs, &ys, 0.95);

    if result.is_rejected {
        println!("Samples are from different distributions.");
    } else {
        println!("Samples are from the same distribution.");
    }

    println!("test statistic = {}", result.statistic);
    println!("critical value = {}", result.critical_value);
    println!("reject probability = {}", result.reject_probability);
}


text:
package com.streamsets.pipeline.stage.destination.kafka.util;

import com.streamsets.pipeline.config.DataFormat;
import com.streamsets.pipeline.kafka.api.PartitionStrategy;
import com.streamsets.pipeline.stage.destination.lib.DataGeneratorFormatConfig;
import com.streamsets.pipeline.stage.destination.kafka.KafkaTarget;
import com.streamsets.pipeline.stage.destination.kafka.KafkaTargetConfig;
import com.streamsets.pipeline.stage.destination.lib.ToOriginResponseConfig;

import java.util.Map;

public class KafkaTargetUtil {

  public static KafkaTarget createKafkaTarget(
      String metadataBrokerList,
      String topic,
      String partition,
      Map<String, String> kafkaProducerConfigs,
      boolean singleMessagePerBatch,
      PartitionStrategy partitionStrategy,
      boolean runtimeTopicResolution,
      String topicExpression,
      String topicWhiteList,
      KafkaTargetConfig kafkaConfig,
      DataFormat dataFormat,
      DataGeneratorFormatConfig dataGeneratorFormatConfig
  ) {
    kafkaConfig.metadataBrokerList = metadataBrokerList;
    kafkaConfig.topic = topic;
    kafkaConfig.partition = partition;
    if (kafkaProducerConfigs != null) {
      kafkaConfig.kafkaProducerConfigs = kafkaProducerConfigs;
    }
    kafkaConfig.singleMessagePerBatch = singleMessagePerBatch;
    kafkaConfig.partitionStrategy = partitionStrategy;
    kafkaConfig.runtimeTopicResolution = runtimeTopicResolution;
    kafkaConfig.topicExpression = topicExpression;
    kafkaConfig.topicWhiteList = topicWhiteList;
    kafkaConfig.dataFormat = dataFormat;
    kafkaConfig.dataGeneratorFormatConfig = dataGeneratorFormatConfig;

    return new KafkaTarget(kafkaConfig, new ToOriginResponseConfig());
  }
}


text:
<?hh // strict

namespace Titon\Debug\Exception;

/**
 * Exception thrown when a directory is not writable.
 *
 * @package Titon\Debug\Exception
 */
class UnwritableDirectoryException extends \RuntimeException {

}


text:
import mock
from netaddr import IPNetwork
from oslo_serialization import jsonutils

from nailgun import consts
from nailgun.db.sqlalchemy import models
from nailgun import objects
from nailgun.test.base import BaseIntegrationTest
from nailgun.utils import reverse

class TestHandlers(BaseIntegrationTest):

    def setUp(self):
        super(TestHandlers, self).setUp()
        self.cluster = self.env.create_cluster(api=False)

    def test_create_network_group_w_cidr(self):
        resp = self.env._create_network_group()
        self.assertEqual(201, resp.status_code)
        ng_data = resp.json_body
        ng = objects.NetworkGroup.get_by_uid(ng_data['id'])
        self.assertEqual(len(ng.ip_ranges), 1)
        self.assertEqual(ng.ip_ranges[0].first, "10.3.0.2")
        self.assertEqual(ng.ip_ranges[0].last, "10.3.0.254")

    def test_create_network_group_w_ip_range(self):
        resp = self.env._create_network_group(
            meta={
                "notation": consts.NETWORK_NOTATION.ip_ranges,
                "ip_range": ["10.3.0.33", "10.3.0.158"]
            }
        )
        self.assertEqual(201, resp.status_code)
        ng_data = resp.json_body
        ng = objects.NetworkGroup.get_by_uid(ng_data['id'])
        self.assertEqual(len(ng.ip_ranges), 1)
        self.assertEqual(ng.ip_ranges[0].first, "10.3.0.33")
        self.assertEqual(ng.ip_ranges[0].last, "10.3.0.158")

    def test_create_network_group_wo_notation(self):
        resp = self.env._create_network_group(meta={"notation": None})
        self.assertEqual(201, resp.status_code)
        ng_data = resp.json_body
        ng = objects.NetworkGroup.get_by_uid(ng_data['id'])
        self.assertEqual(len(ng.ip_ranges), 0)

    def test_create_network_group_error(self):
        resp = self.env._create_network_group(
            meta={"notation": "new"},
            expect_errors=True
        )
        self.assertEqual(400, resp.status_code)
        self.assertEqual(
            resp.json_body["message"],
            "IPAddrRange object cannot be created for network "
            "'external' with notation='new', ip_range='None'")

        resp = self.env._create_network_group(
            meta={"notation": consts.NETWORK_NOTATION.ip_ranges},
            expect_errors=True
        )
        self.assertEqual(400, resp.status_code)
        self.assertEqual(resp.json_body["message"],
                         "IPAddrRange object cannot be created for network "
                         "'external' with notation='ip_ranges', "
                         "ip_range='None'")

        resp = self.env._create_network_group(
            meta={"notation": consts.NETWORK_NOTATION.ip_ranges,
                  "ip_range": ["10.3.0.33"]},
            expect_errors=True
        )
        self.assertEqual(400, resp.status_code)
        self.assertEqual(resp.json_body["message"],
                         "IPAddrRange object cannot be created for network "
                         "'external' with notation='ip_ranges', "
                         "ip_range='[u'10.3.0.33']'")

    def test_get_network_group(self):
        resp = self.env._create_network_group(name='test')
        self.assertEqual(201, resp.status_code)
        new_ng = resp.json_body

        net_group = resp.json_body

        resp = self.app.get(
            reverse(
                'NetworkGroupHandler',
                kwargs={'obj_id': net_group['id']}
            ),
            headers=self.default_headers
        )
        self.assertEqual(200, resp.status_code)
        self.assertEqual(resp.json_body, new_ng)

    def test_delete_network_group(self):
        resp = self.env._create_network_group(name='test')
        self.assertEqual(201, resp.status_code)

        net_group = resp.json_body

        resp = self.app.delete(
            reverse(
                'NetworkGroupHandler',
                kwargs={'obj_id': net_group['id']}
            ),
            headers=self.default_headers
        )
        self.assertEqual(204, resp.status_code)

    def test_delete_network_group_cleanup_ip_range(self):
        ng_id = self.env._create_network_group(
            meta={
                "notation": "ip_ranges",
                "ip_range": ["10.3.0.33", "10.3.0.158"]
            }
        ).json["id"]
        self.app.delete(
            reverse(
                'NetworkGroupHandler',
                kwargs={'obj_id': ng_id}
            ),
            headers=self.default_headers,
        )
        ip_range = self.db.query(models.IPAddrRange)\
            .filter_by(network_group_id=ng_id)\
            .first()
        self.assertIsNone(ip_range)

    def test_delete_network_group_cleanup_ip_addrs(self):
        ng_id = self.env._create_network_group().json["id"]
        node = self.env.create_node(api=False)

        ip_address = []
        for ip_addr in ('10.3.0.2', '10.3.0.3'):
            ip_addr_data = {'network': ng_id,
                            'node': node.id,
                            'ip_addr': ip_addr}
            ip_address.append(ip_addr_data)

        self.db.add_all([models.IPAddr(**ips) for ips in ip_address])
        self.db.flush()

        self.app.delete(
            reverse(
                'NetworkGroupHandler',
                kwargs={'obj_id': ng_id}
            ),
            headers=self.default_headers,
        )
        ips_db = self.db.query(models.IPAddr)\
            .filter_by(network=ng_id)\
            .all()
        self.assertFalse(ips_db)

    def test_cannot_delete_admin_network_group(self):
        admin = objects.Cluster.get_network_manager().get_admin_network_group()
        resp = self.app.delete(
            reverse(
                'NetworkGroupHandler',
                kwargs={'obj_id': admin.id}
            ),
            headers=self.default_headers,
            expect_errors=True
        )
        self.assertEqual(400, resp.status_code)
        self.assertEqual(resp.json_body['message'],
                         'Default Admin-pxe network cannot be deleted')

    def test_cannot_delete_locked_cluster_network_group(self):
        resp = self.env._create_network_group(name='test')
        self.assertEqual(201, resp.status_code)

        net_group = resp.json_body

        with mock.patch('nailgun.db.sqlalchemy.models.Cluster.is_locked',
                        return_value=True):
            resp = self.app.delete(
                reverse(
                    'NetworkGroupHandler',
                    kwargs={'obj_id': net_group['id']}
                ),
                headers=self.default_headers,
                expect_errors=True
            )
            self.assertEqual(400, resp.status_code)
            self.assertEqual(resp.json_body['message'],
                             'Networks cannot be deleted after deployment')

    def test_create_network_group_non_default_name(self):
        resp = self.env._create_network_group(name='test')
        new_ng = resp.json_body
        self.assertEqual(201, resp.status_code)
        self.assertEqual('test', new_ng['name'])

    def test_modify_network_group(self):
        resp = self.env._create_network_group(name='test')

        new_ng = resp.json_body
        new_ng['name'] = 'test2'

        resp = self.env._update_network_group(new_ng)
        updated_ng = resp.json_body

        self.assertEquals('test2', updated_ng['name'])

    def test_update_network_group_ipranges_regenerated(self):
        resp = self.env._create_network_group(
            meta={
                "notation": "ip_ranges",
                "ip_range": ["10.3.0.33", "10.3.0.158"],
            }
        )
        new_ng = resp.json_body
        new_ng["name"] = "test"

        new_ip_ranges = [["172.16.0.1", "172.16.0.10"],
                         ["10.20.0.2", "10.20.0.20"]]
        new_ng["ip_ranges"] = new_ip_ranges

        self.app.put(
            reverse(
                'NetworkGroupHandler',
                kwargs={'obj_id': new_ng['id']}
            ),
            jsonutils.dumps(new_ng),
            headers=self.default_headers
        )

        ip_ranges = self.db.query(models.IPAddrRange)\
            .filter_by(network_group_id=new_ng["id"])\
            .all()
        self.assertItemsEqual(
            new_ip_ranges,
            [[ipr.first, ipr.last] for ipr in ip_ranges]
        )

    def test_update_network_group_ipranges_regenerated_for_cidr(self):
        resp = self.env._create_network_group()
        new_ng = resp.json_body

        new_cidr = "10.3.0.0/20"
        new_ng['cidr'] = new_cidr
        new_ng['name'] = 'test'
        new_ng['meta']['use_gateway'] = True

        generated_range = IPNetwork("10.3.0.0/20")
        new_ip_range = [str(generated_range[2]), str(generated_range[-2])]

        self.app.put(
            reverse(
                'NetworkGroupHandler',
                kwargs={'obj_id': new_ng['id']}
            ),
            jsonutils.dumps(new_ng),
            headers=self.default_headers
        )

        ip_range = self.db.query(models.IPAddrRange)\
            .filter_by(network_group_id=new_ng["id"])\
            .one()
        self.assertEqual(ip_range.first, new_ip_range[0])
        self.assertEqual(ip_range.last, new_ip_range[1])

    def test_duplicate_network_name_on_creation(self):
        resp = self.env._create_network_group()
        self.assertEqual(201, resp.status_code)
        resp = self.env._create_network_group(expect_errors=True)
        self.assertEqual(409, resp.status_code)
        self.assertRegexpMatches(resp.json_body["message"],
                                 'Network with name .* already exists')

    def test_duplicate_network_name_on_change(self):
        resp = self.env._create_network_group(name='test')
        new_ng = resp.json_body

        new_ng['name'] = 'public'

        resp = self.env._update_network_group(new_ng, expect_errors=True)
        self.assertEqual(409, resp.status_code)
        self.assertRegexpMatches(resp.json_body["message"],
                                 'Network with name .* already exists')

    def test_update_same_name(self):
        resp = self.env._create_network_group(name='test')
        new_ng = resp.json_body

        resp = self.env._update_network_group(new_ng, expect_errors=False)
        self.assertEqual(200, resp.status_code)

    def test_update_doesnt_require_group_id(self):
        resp = self.env._create_network_group(name='test')
        new_ng = resp.json_body
        del new_ng['group_id']

        resp = self.env._update_network_group(new_ng, expect_errors=False)
        self.assertEqual(200, resp.status_code)

    def test_update_doesnt_require_id_in_data(self):
        ng_id = self.env._create_network_group(name='test').json_body['id']

        update_data = {'name': 'test2'}

        update_resp = self.app.put(
            reverse(
                'NetworkGroupHandler',
                kwargs={'obj_id': ng_id}
            ),
            jsonutils.dumps(update_data),
            headers=self.default_headers
        )

        self.assertEqual(200, update_resp.status_code)
        self.assertEqual(update_resp.json_body['name'], 'test2')

    def test_invalid_group_id_on_creation(self):
        resp = self.env._create_network_group(expect_errors=True, group_id=-1)
        self.assertEqual(400, resp.status_code)
        self.assertRegexpMatches(resp.json_body["message"],
                                 'Node group with ID -1 does not exist')

    def test_create_network_group_without_vlan(self):
        resp = self.env._create_network_group(vlan=None)
        self.assertEqual(201, resp.status_code)

    def test_modify_network_no_ip_ranges(self):
        resp = self.env._create_network_group(
            name='test',
            meta={"notation": consts.NETWORK_NOTATION.ip_ranges,
                  "ip_range": ["10.3.0.33", "10.3.0.158"]},
            expect_errors=True
        )
        new_ng = resp.json_body

        new_ng.pop('ip_ranges', None)
        new_ng.pop('name', None)

        db_ng = objects.NetworkGroup.get_by_uid(new_ng['id'])
        db_ng.ip_ranges = []
        self.db.flush()

        resp = self.env._update_network_group(new_ng, expect_errors=True)
        self.assertEqual(400, resp.status_code)
        self.assertRegexpMatches(
            resp.json_body['message'],
            'No IP ranges were specified for network {0}'.format(new_ng['id'])
        )

    def test_modify_network_no_cidr(self):
        resp = self.env._create_network_group(name='test', expect_errors=True)
        new_ng = resp.json_body

        new_ng['meta']['notation'] = consts.NETWORK_NOTATION.ip_ranges
        new_ng['ip_ranges'] = ["10.3.0.33", "10.3.0.158"]
        new_ng.pop('cidr', None)
        new_ng.pop('name', None)

        db_ng = objects.NetworkGroup.get_by_uid(new_ng['id'])
        db_ng.cidr = None
        self.db.flush()

        resp = self.env._update_network_group(new_ng, expect_errors=True)
        self.assertEqual(400, resp.status_code)
        self.assertRegexpMatches(
            resp.json_body['message'],
            'No CIDR was specified for network {0}'.format(new_ng['id'])
        )

    def test_modify_network_no_gateway(self):
        resp = self.env._create_network_group(
            meta={"use_gateway": True},
            gateway=None,
            expect_errors=True
        )
        new_ng = resp.json_body

        new_ng['meta']['notation'] = consts.NETWORK_NOTATION.ip_ranges
        new_ng['ip_ranges'] = []
        new_ng.pop('name', None)

        db_ng = objects.NetworkGroup.get_by_uid(new_ng['id'])
        db_ng.gateway = None
        self.db.flush()

        resp = self.env._update_network_group(new_ng, expect_errors=True)
        self.assertEqual(400, resp.status_code)
        self.assertRegexpMatches(
            resp.json_body['message'],
            "'use_gateway' cannot be provided without gateway"
        )

    def test_modify_network_release(self):
        resp = self.env._create_network_group(name='test', expect_errors=True)
        new_ng = resp.json_body

        new_ng['release'] = 100
        new_ng.pop('name', None)

        resp = self.env._update_network_group(new_ng, expect_errors=True)
        self.assertEqual(400, resp.status_code)
        self.assertRegexpMatches(resp.json_body['message'],
                                 'Network release could not be changed.')

    def test_modify_admin_network_group_with_wrong_group_id(self):
        admin = objects.Cluster.get_network_manager().get_admin_network_group()
        admin_network_data = {
            'id': admin.id,
            'group_id': objects.Cluster.get_default_group(self.cluster).id,
            'meta': admin.meta
        }
        resp = self.env._update_network_group(admin_network_data,
                                              expect_errors=True)
        self.assertEqual(400, resp.status_code)
        self.assertRegexpMatches(
            resp.json_body['message'],
            'Default Admin-pxe network cannot be changed'
        )


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

/// <summary>
/// https://judge.softuni.bg/Contests/Compete/Index/430#5
/// </summary>

namespace _06._Valid_Usernames
{
    class ValidUsernames
    {
        static void Main()
        {

            string text=Console.ReadLine();
            //Pattern for valid user names.
            string pattent = @"\b[A-Za-z][\w]{2,25}\b";

            //We store valids here.
            List<string>validNames= new List<string>();
            foreach (Match m in Regex.Matches(text,pattent))
            {
                validNames.Add(m.Value);
            }

            int sum=0;
            int longest=0;
            string[]longestNames=new string[2];

            //We check for the longest pair.
            for (int i = 0; i < validNames.Count-1; i++)
            {
                sum=validNames[i].Length+validNames[i+1].Length;

                if (sum>longest)
                {
                    longest=sum;
                    longestNames[0]=validNames[i];
                    longestNames[1]=validNames[i+1];
                }
            }

            Console.WriteLine(string.Join(Environment.NewLine,longestNames));
        }
    }
}


text:
package com.tscfdi.comprobante.nomina;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import java.math.BigDecimal;

/**
 * Created by lugty on 12/9/16.
 */
@XmlAccessorType(XmlAccessType.FIELD)
public class DataOtroPago {

    @XmlAttribute(name = "TipoOtroPago", required = true)
    private String tipoOtroPago;

    @XmlAttribute(name = "Clave", required = true)
    private String clave;

    @XmlAttribute(name = "Concepto", required = true)
    private String concepto;

    @XmlAttribute(name = "Importe", required = true)
    private BigDecimal importe;

    @XmlElement(name = "SubsidioAlEmpleo", required = false)
    private DataSubsidioAlEmpleo dataSubsidioAlEmpleo;

    @XmlElement(name = "CompensacionSaldosAFavor", required = false)
    private DataCompensacionSaldosAFavor dataCompensacionSaldosAFavor;

    public String getTipoOtroPago() {
        return tipoOtroPago;
    }

    public void setTipoOtroPago(String tipoOtroPago) {
        this.tipoOtroPago = tipoOtroPago;
    }

    public String getClave() {
        return clave;
    }

    public void setClave(String clave) {
        this.clave = clave;
    }

    public String getConcepto() {
        return concepto;
    }

    public void setConcepto(String concepto) {
        this.concepto = concepto;
    }

    public BigDecimal getImporte() {
        return importe;
    }

    public void setImporte(BigDecimal importe) {
        this.importe = importe;
    }

    public DataSubsidioAlEmpleo getDataSubsidioAlEmpleo() {
        return dataSubsidioAlEmpleo;
    }

    public void setDataSubsidioAlEmpleo(DataSubsidioAlEmpleo dataSubsidioAlEmpleo) {
        this.dataSubsidioAlEmpleo = dataSubsidioAlEmpleo;
    }

    public DataCompensacionSaldosAFavor getDataCompensacionSaldosAFavor() {
        return dataCompensacionSaldosAFavor;
    }

    public void setDataCompensacionSaldosAFavor(DataCompensacionSaldosAFavor dataCompensacionSaldosAFavor) {
        this.dataCompensacionSaldosAFavor = dataCompensacionSaldosAFavor;
    }
}


text:
function layerAdded(layer){
	if(layer.type == "WMS"){
		console.log("WMS hinzugefügt");
	}
	else if(layer.type == "CSV"){
		console.log("CSV hinzugefügt");
	}
	else if(layer.type == "GeoJSON"){
		console.log("GeoJSON hinzugefügt");
	}
	else if(layer.type == "Shapefile"){
		console.log("Shapefile hinzugefügt");
	}
	else {
		console.log("fehler!");
	}
}

function layerModified(name, url, type){
	console.log("layerAdded: " + name + ", " + url + ", " + type);
}

function layerUpdated(id){

}


text:
<?php

namespace CodeIgniter\Commands\Generators;

use CodeIgniter\CLI\BaseCommand;
use CodeIgniter\CLI\GeneratorTrait;

/**
 * Generates a skeleton Entity file.
 */
class EntityGenerator extends BaseCommand
{
	use GeneratorTrait;

	/**
	 * The Command's Group
	 *
	 * @var string
	 */
	protected $group = 'Generators';

	/**
	 * The Command's Name
	 *
	 * @var string
	 */
	protected $name = 'make:entity';

	/**
	 * The Command's Description
	 *
	 * @var string
	 */
	protected $description = 'Generates a new entity file.';

	/**
	 * The Command's Usage
	 *
	 * @var string
	 */
	protected $usage = 'make:entity <name> [options]';

	/**
	 * The Command's Arguments
	 *
	 * @var array
	 */
	protected $arguments = [
		'name' => 'The entity class name.',
	];

	/**
	 * The Command's Options
	 *
	 * @var array
	 */
	protected $options = [
		'--namespace' => 'Set root namespace. Default: "APP_NAMESPACE".',
		'--suffix'    => 'Append the component title to the class name (e.g. User => UserEntity).',
		'--force'     => 'Force overwrite existing file.',
	];

	/**
	 * Actually execute a command.
	 *
	 * @param array $params
	 */
	public function run(array $params)
	{
		$this->component = 'Entity';
		$this->directory = 'Entities';
		$this->template  = 'entity.tpl.php';

		$this->classNameLang = 'CLI.generator.className.entity';
		$this->execute($params);
	}
}


text:
import {Statement} from '@angular/compiler';
import * as ts from 'typescript';

import {TypeScriptReflectionHost} from '../../metadata';
import {getDeclaration, makeProgram} from '../../testing/in_memory_typescript';
import {ImportManager, translateStatement} from '../../translator';
import {generateSetClassMetadataCall} from '../src/metadata';

const CORE = {
  name: 'node_modules/@angular/core/index.d.ts',
  contents: `
    export declare function Input(...args: any[]): any;
    export declare function Inject(...args: any[]): any;
    export declare function Component(...args: any[]): any;
    export declare class Injector {}
  `
};

describe('ngtsc setClassMetadata converter', () => {
  it('should convert decorated class metadata', () => {
    const res = compileAndPrint(`
    import {Component} from '@angular/core';

    @Component('metadata') class Target {}
    `);
    expect(res).toEqual(
        `/*@__PURE__*/ i0.ɵsetClassMetadata(Target, [{ type: Component, args: ['metadata'] }], null, null);`);
  });

  it('should convert decorated class constructor parameter metadata', () => {
    const res = compileAndPrint(`
    import {Component, Inject, Injector} from '@angular/core';
    const FOO = 'foo';

    @Component('metadata') class Target {
      constructor(@Inject(FOO) foo: any, bar: Injector) {}
    }
    `);
    expect(res).toContain(
        `function () { return [{ type: undefined, decorators: [{ type: Inject, args: [FOO] }] }, { type: Injector }]; }, null);`);
  });

  it('should convert decorated field metadata', () => {
    const res = compileAndPrint(`
    import {Component, Input} from '@angular/core';

    @Component('metadata') class Target {
      @Input() foo: string;

      @Input('value') bar: string;

      notDecorated: string;
    }
    `);
    expect(res).toContain(`{ foo: [{ type: Input }], bar: [{ type: Input, args: ['value'] }] })`);
  });

  it('should not convert non-angular decorators to metadata', () => {
    const res = compileAndPrint(`
    declare function NotAComponent(...args: any[]): any;

    @NotAComponent('metadata') class Target {}
    `);
    expect(res).toBe('');
  });
});

function compileAndPrint(contents: string): string {
  const {program} = makeProgram([
    CORE, {
      name: 'index.ts',
      contents,
    }
  ]);
  const host = new TypeScriptReflectionHost(program.getTypeChecker());
  const target = getDeclaration(program, 'index.ts', 'Target', ts.isClassDeclaration);
  const call = generateSetClassMetadataCall(target, host, false);
  if (call === null) {
    return '';
  }
  const sf = program.getSourceFile('index.ts') !;
  const im = new ImportManager(false, 'i');
  const tsStatement = translateStatement(call, im);
  const res = ts.createPrinter().printNode(ts.EmitHint.Unspecified, tsStatement, sf);
  return res.replace(/\s+/g, ' ');
}


text:
require File.expand_path(File.dirname(__FILE__) + '/spec_helper')

describe "Aqua" do
  describe 'loading internal storage libraries' do
    it 'loading without an argument should not raise an error' do
      lambda{ Aqua.set_storage_engine }.should_not raise_error
    end
  end

  describe 'loading external storage libraries' do
  end

  describe 'configuration generalities' do
    it 'gem should allow persistance on all objects'
    it 'gem should allow persistance with a class declaration'
    it 'gem should allow persistance via module inclusion'
    it 'gem should allow persistance via Aquaed inheritance'
  end
end


text:
package org.trianacode.shiwaall.bundle;

//import org.shiwa.desktop.data.description.ConcreteBundle;
import org.shiwa.desktop.data.description.SHIWABundle;
import org.shiwa.desktop.data.util.DataUtils;
import org.trianacode.annotation.Process;
import org.trianacode.annotation.TextFieldParameter;
import org.trianacode.annotation.Tool;
import org.trianacode.enactment.logging.stampede.StampedeLog;
import org.trianacode.shiwaall.utils.BrokerUtils;
import org.trianacode.taskgraph.Task;
import org.trianacode.taskgraph.annotation.TaskConscious;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

// TODO: Auto-generated Javadoc
/**
 * Created by IntelliJ IDEA.
 * User: Ian Harvey
 * Date: 10/05/2012
 * Time: 17:31
 * To change this template use File | Settings | File Templates.
 */

@Tool
public class BundleToTrianaCloud implements TaskConscious {

    /** The bundle file. */
    @TextFieldParameter
    public String bundleFile = "";

    /** The task. */
    private Task task;

    /**
     * Process.
     *
     * @param list the list
     */
    @Process(gather = true)
    public void process(List list) {

        for (Object object : list) {
            if (object instanceof String) {
                bundleFile = String.valueOf(object);
            }
            if (object instanceof File) {
                bundleFile = ((File) object).getAbsolutePath();
            }
        }
        ArrayList<File> toSend = new ArrayList<File>();
        try {
            ShiwaBundleHelper shiwaBundleHelper = new ShiwaBundleHelper(new SHIWABundle(new File(bundleFile)));
            BrokerUtils.prepareSubworkflow(task, UUID.randomUUID(), shiwaBundleHelper.getWorkflowImplementation());

            File tempBundleFile = File.createTempFile(
                    shiwaBundleHelper.getWorkflowImplementation().getDefinition().getFilename(), "tmp");

            File updatedBundle = DataUtils.bundle(tempBundleFile, shiwaBundleHelper.getWorkflowImplementation());

            toSend.add(updatedBundle);
        } catch (Exception e) {
            System.out.println("Issue with bundle " + bundleFile);
            e.printStackTrace();
        }

        if (toSend.size() == 1) {
            for (File bundle : toSend) {
                try {
                    String key = BrokerUtils.postBundle(
                            "http://s-vmc.cs.cf.ac.uk:7025/Broker/broker",
                            "*.triana",
                            bundle.getName() + BrokerUtils.getTimeStamp(),
                            bundle);

                    BrokerUtils.getResultBundle(
                            "http://s-vmc.cs.cf.ac.uk:7025/Broker/results",
                            key
                    );
                } catch (Exception e) {
                    System.out.println("Issue with bundle " + bundleFile);
                    e.printStackTrace();
                }
            }
        } else {
            System.out.println("Error creating bundle, not sending.");
        }
    }

    /* (non-Javadoc)
     * @see org.trianacode.taskgraph.annotation.TaskConscious#setTask(org.trianacode.taskgraph.Task)
     */
    @Override
    public void setTask(Task task) {
        this.task = task;
        task.setParameter(StampedeLog.STAMPEDE_TASK_TYPE, StampedeLog.JobType.dax.desc);
    }
}


text:
package by.bsuir.verkpavel.saimmod.distributions;

public class SimpsonDistribution extends BaseDistribution{
    private double startInterval;
    private double endInterval;
    private BaseDistribution firstGenerator;
    private BaseDistribution secondGenerator;

    public SimpsonDistribution(double a, double b, int length) {
        super(length);
        this.startInterval = a;
        this.endInterval = b;

        this.firstGenerator = new LemerDistribution(3, 69712349, 1, length);
        this.secondGenerator = new LemerDistribution(3, 4397149, 1, length);

        this.firstGenerator.build();
        this.secondGenerator.build();
    }

    @Override
    public void build() {
        double intervalLength = endInterval/2 - startInterval/2;
        for(int i=0; i< firstGenerator.items.size(); i++){
            items.add(startInterval/2+intervalLength*firstGenerator.items.get(i)+ startInterval/2+intervalLength*secondGenerator.items.get(i));
        }

    }

    @Override
    public void introduce() {
        System.out.println(String.format(
                "Simpson distribution with parameters a = %f, b = %f", this.startInterval, this.endInterval));

    }
}


text:
package net.sourceforge.squirrel_sql.client.util.codereformat;

/**
 * An interface to allow alternate implementations of the CodeReformator to be configured by plugins.
 */
public interface ICodeReformator
{
	/**
	 * Reformats the specified String, returning the reformatted version.
	 *
	 * @param in
	 *           the string to apply formatting to.
	 * @return the formatted result
	 */
	String reformat(String in);
}


text:
package net.acomputerdog.OBFUtil.util;

import net.acomputerdog.OBFUtil.parse.FileParser;
import net.acomputerdog.OBFUtil.table.DirectOBFTable;
import net.acomputerdog.OBFUtil.table.OBFTable;

import java.io.File;
import java.io.IOException;

/**
 * Utility class that allows converting a file from one type to another.
 */
public class FileConverter {

    /**
     * Converts an obfuscation table in one format to another.
     *
     * @param in      The input FileParser
     * @param out     The output FileParser
     * @param inFile  The input file
     * @param outFile The output file
     * @throws IOException If an IO error occurs
     */
    @SuppressWarnings("rawtypes")
	public static void convert(FileParser in, FileParser out, File inFile, File outFile) throws IOException {
        OBFTable table = new DirectOBFTable();
        in.loadEntries(inFile, table, true);
        out.storeEntries(outFile, table);
    }
}


text:
package org.apache.causeway.extensions.sse.wicket.markup;

import java.io.IOException;
import java.util.UUID;

import org.apache.causeway.applib.value.LocalResourcePath;
import org.apache.causeway.commons.internal.resources._Resources;
import org.apache.causeway.core.config.viewer.web.WebAppContextPath;

import static org.apache.causeway.commons.internal.base._Strings.isNullOrEmpty;

import lombok.extern.log4j.Log4j2;

@Log4j2
final class ListeningMarkupComponent_observing  {

    private static final String jScriptTemplateResource = "js/ObservingComponent.js";

    static CharSequence decorate(
            final CharSequence htmlContent,
            final LocalResourcePath observing,
            final WebAppContextPath webAppContextPath) {
        if(observing==null) {
            return htmlContent;
        }
        final String jScriptTemplate;
        try {
            jScriptTemplate = _Resources.loadAsStringUtf8(
                    ListeningMarkupComponent_observing.class, jScriptTemplateResource);

        } catch (IOException e) {
            log.warn("resource not found class:{} path:{}",
                    ListeningMarkupComponent_observing.class, jScriptTemplateResource, e);
            return resourceNotFound();
        }

        if(isNullOrEmpty(jScriptTemplate)) {
            return resourceNotFound();
        }

        final String targetId = UUID.randomUUID().toString();
        final String observingPath = observing.getEffectivePath(webAppContextPath::prependContextPath);

        final StringBuilder sb = new StringBuilder();
        sb
        .append("
\n")
        .append(htmlContent)
        .append("\n
\n")
        .append("\n");

        return sb.toString();
    }

    private static String resourceNotFound() {
        return "Template resource not found: '"+jScriptTemplateResource+"'.";
    }

}


text:
package me.regexp;

import java.io.Reader;
import java.io.IOException;

/**
 * Encapsulates java.io.Reader as CharacterIterator
 *
 * @author Ales Novak
 * @version CVS $Id: ReaderCharacterIterator.java 518156 2007-03-14 14:31:26Z vgritsenko $
 */
public final class ReaderCharacterIterator implements CharacterIterator
{
    /** Underlying reader */
    private final Reader reader;

    /** Buffer of read chars */
    private final StringBuffer buff;

    /** read end? */
    private boolean closed;

    /** @param reader a Reader, which is parsed */
    public ReaderCharacterIterator(Reader reader)
    {
        this.reader = reader;
        this.buff = new StringBuffer(512);
        this.closed = false;
    }

    /** @return a substring */
    public String substring(int beginIndex, int endIndex)
    {
        try
        {
            ensure(endIndex);
            return buff.toString().substring(beginIndex, endIndex);
        }
        catch (IOException e)
        {
            throw new StringIndexOutOfBoundsException(e.getMessage());
        }
    }

    /** @return a substring */
    public String substring(int beginIndex)
    {
        try
        {
            readAll();
            return buff.toString().substring(beginIndex);
        }
        catch (IOException e)
        {
            throw new StringIndexOutOfBoundsException(e.getMessage());
        }
    }

    /** @return a character at the specified position. */
    public char charAt(int pos)
    {
        try
        {
            ensure(pos);
            return buff.charAt(pos);
        }
        catch (IOException e)
        {
            throw new StringIndexOutOfBoundsException(e.getMessage());
        }
    }

    /** @return <tt>true</tt> iff if the specified index is after the end of the character stream */
    public boolean isEnd(int pos)
    {
        if (buff.length() > pos)
        {
            return false;
        }
        else
        {
            try
            {
                ensure(pos);
                return (buff.length() <= pos);
            }
            catch (IOException e)
            {
                throw new StringIndexOutOfBoundsException(e.getMessage());
            }
        }
    }

    /** Reads n characters from the stream and appends them to the buffer */
    private int read(int n) throws IOException
    {
        if (closed)
        {
            return 0;
        }

        char[] c = new char[n];
        int count = 0;
        int read = 0;

        do
        {
            read = reader.read(c);
            if (read < 0) // EOF
            {
                closed = true;
                break;
            }
            count += read;
            buff.append(c, 0, read);
        }
        while (count < n);

        return count;
    }

    /** Reads rest of the stream. */
    private void readAll() throws IOException
    {
        while(! closed)
        {
            read(1000);
        }
    }

    /** Reads chars up to the idx */
    private void ensure(int idx) throws IOException
    {
        if (closed)
        {
            return;
        }

        if (idx < buff.length())
        {
            return;
        }
        read(idx + 1 - buff.length());
    }
}


text:
Object.defineProperty(exports, "__esModule", { value: true });
exports.Record = void 0;
var Record = /** @class */ (function () {
    function Record(instance, modTime, scriptName, fullPath) {
        this.Instance = instance;
        this.IndexScriptModTime = modTime;
        this.IndexScriptFileName = scriptName;
        this.DirectoryFullPath = fullPath;
    }
    ;
    return Record;
}());
exports.Record = Record;
//# sourceMappingURL=Record.js.map


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

namespace MeetupOrganizing;

use Assert\Assert;
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\DriverManager;
use MeetupOrganizing\Command\ConsoleApplication;
use MeetupOrganizing\Command\ScheduleMeetupCommand;
use MeetupOrganizing\Controller\CancelMeetupController;
use MeetupOrganizing\Controller\ListMeetupsController;
use MeetupOrganizing\Controller\MeetupDetailsController;
use MeetupOrganizing\Controller\RsvpForMeetupController;
use MeetupOrganizing\Controller\ScheduleMeetupController;
use MeetupOrganizing\Controller\SwitchUserController;
use MeetupOrganizing\Entity\RsvpRepository;
use MeetupOrganizing\Entity\UserHasRsvpd;
use MeetupOrganizing\Entity\UserRepository;
use MeetupOrganizing\Resources\Views\FlashExtension;
use MeetupOrganizing\Resources\Views\TwigTemplates;
use MeetupOrganizing\Resources\Views\UserExtension;
use Psr\Http\Message\RequestInterface;
use Symfony\Component\ErrorHandler\Debug;
use Symfony\Component\Mailer\Mailer;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mailer\Transport;
use Xtreamwayz\Pimple\Container;
use Psr\Http\Message\ResponseInterface;
use Throwable;
use Zend\Expressive\Application;
use Zend\Expressive\Container\ApplicationFactory;
use Zend\Expressive\Helper\ServerUrlHelper;
use Zend\Expressive\Helper\UrlHelper;
use Zend\Expressive\Router\FastRouteRouter;
use Zend\Expressive\Router\RouterInterface;
use Zend\Expressive\Template\TemplateRendererInterface;
use Zend\Expressive\TemplatedErrorHandler;
use Zend\Expressive\Twig\TwigRendererFactory;

final class ServiceContainer extends Container
{
    public function __construct(string $projectRootDir)
    {
        Assert::that($projectRootDir)->directory();

        parent::__construct(
            [
                'project_root_dir' => $projectRootDir
            ]
        );

        /*
         * Not a best practice for containers, but hey.
         */
        Debug::enable();

        $this['config'] = function () {
            return [
                'debug' => true,
                'templates' => [
                    'extension' => 'html.twig',
                    'paths' => [
                        TwigTemplates::getPath()
                    ]
                ],
                'twig' => [
                    'extensions' => [
                        $this[UserExtension::class],
                        $this[FlashExtension::class]
                    ]
                ],
                'routes' => [
                    [
                        'name' => 'list_meetups',
                        'path' => '/',
                        'middleware' => ListMeetupsController::class,
                        'allowed_methods' => ['GET']
                    ],
                    [
                        'name' => 'meetup_details',
                        'path' => '/meetup/{id}',
                        'middleware' => MeetupDetailsController::class,
                        'allowed_methods' => ['GET']
                    ],
                    [
                        'name' => 'schedule_meetup',
                        'path' => '/schedule-meetup',
                        'middleware' => ScheduleMeetupController::class,
                        'allowed_methods' => ['GET', 'POST']
                    ],
                    [
                        'name' => 'cancel_meetup',
                        'path' => '/cancel-meetup',
                        'middleware' => CancelMeetupController::class,
                        'allowed_methods' => ['POST']
                    ],
                    [
                        'name' => 'switch_user',
                        'path' => '/switch-user',
                        'middleware' => SwitchUserController::class,
                        'allowed_methods' => ['POST']
                    ],
                    [
                        'name' => 'rsvp_for_meetup',
                        'path' => '/rsvp-for-meetup',
                        'middleware' => RsvpForMeetupController::class,
                        'allowed_methods' => ['POST']
                    ]
                ]
            ];
        };

        /*
         * Zend Expressive Application
         */
        $this['Zend\Expressive\FinalHandler'] = function () {
            return function (
                RequestInterface $request,
                ResponseInterface $response,
                $err = null
            ) {
                if ($err instanceof Throwable) {
                    throw $err;
                }

                return $this[TemplatedErrorHandler::class]($request, $response, $err);
            };
        };
        $this[TemplatedErrorHandler::class] = function () {
            return new TemplatedErrorHandler(
                $this[TemplateRendererInterface::class],
                'error404.html.twig',
                'error.html.twig'
            );
        };
        $this[RouterInterface::class] = function () {
            return new FastRouteRouter();
        };
        $this[Application::class] = new ApplicationFactory();

        $this[EventDispatcher::class] = function () {
            $eventDispatcher = new ConfigurableEventDispatcher();

            $eventDispatcher->registerSpecificListener(
                UserHasRsvpd::class,
                function () {
                    $this[Session::class]->addSuccessFlash('You have successfully RSVP-ed to this meetup');
                }
            );

            return $eventDispatcher;
        };

        $this[MailerInterface::class] = function () {
            return new Mailer(
                Transport::fromDsn('smtp://mailhog:1025')
            );
        };

        /*
         * Templating
         */
        $this[TemplateRendererInterface::class] = new TwigRendererFactory();
        $this[ServerUrlHelper::class] = function () {
            return new ServerUrlHelper();
        };
        $this[UrlHelper::class] = function () {
            return new UrlHelper($this[RouterInterface::class]);
        };
        $this[UserExtension::class] = function () {
            return new UserExtension(
                $this[Session::class],
                $this[UserRepository::class]
            );
        };
        $this[FlashExtension::class] = function () {
            return new FlashExtension(
                $this[Session::class]
            );
        };
        /*
         * Persistence
         */
        $this[Connection::class] = function () {
            return DriverManager::getConnection(
                [
                    'driver' => 'pdo_sqlite',
                    'path' => $this['project_root_dir'] . '/var/app.sqlite'
                ]
            );
        };
        $this[SchemaManager::class] = function () {
            return new SchemaManager($this[Connection::class]);
        };

        $this[UserRepository::class] = function () {
            return new UserRepository();
        };
        $this[RsvpRepository::class] = function () {
            return new RsvpRepository(
                $this[Connection::class]
            );
        };

        /*
         * Controllers
         */
        $this[Session::class] = function () {
            return new Session(
                $this[UserRepository::class]
            );
        };

        $this[ScheduleMeetupController::class] = function () {
            return new ScheduleMeetupController(
                $this[Session::class],
                $this[TemplateRendererInterface::class],
                $this[RouterInterface::class],
                $this[Connection::class]
            );
        };
        $this[CancelMeetupController::class] = function () {
            return new CancelMeetupController(
                $this[Connection::class],
                $this[Session::class],
                $this[RouterInterface::class]
            );
        };
        $this[ListMeetupsController::class] = function () {
            return new ListMeetupsController(
                $this[Connection::class],
                $this[TemplateRendererInterface::class]
            );
        };
        $this[MeetupDetailsController::class] = function () {
            return new MeetupDetailsController(
                $this[Connection::class],
                $this[UserRepository::class],
                $this[RsvpRepository::class],
                $this[TemplateRendererInterface::class]
            );
        };
        $this[SwitchUserController::class] = function () {
            return new SwitchUserController(
                $this[UserRepository::class],
                $this[Session::class]
            );
        };
        $this[RsvpForMeetupController::class] = function () {
            return new RsvpForMeetupController(
                $this[Connection::class],
                $this[Session::class],
                $this[RsvpRepository::class],
                $this[RouterInterface::class],
                $this[EventDispatcher::class]
            );
        };

        /*
         * CLI
         */
        $this[ConsoleApplication::class] = function () {
            return new ConsoleApplication($this);
        };

        $this[ScheduleMeetupCommand::class] = function () {
            return new ScheduleMeetupCommand($this[Connection::class]);
        };

        $this->bootstrap();
    }

    private function bootstrap(): void
    {
        $this[SchemaManager::class]->updateSchema();
    }
}


text:
using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Net;
#endregion

namespace NetRumble
{
    /// <summary>
    /// Player input abstraction for ships.
    /// </summary>
    public struct ShipInput
    {
        #region Static Constants

        /// <summary>
        /// The empty version of this structure.
        /// </summary>
        private static ShipInput empty =
            new ShipInput(Vector2.Zero, Vector2.Zero, false);
        public static ShipInput Empty
        {
            get { return empty; }
        }

        #endregion

        #region Input Data

        /// <summary>
        /// The left-stick value of the ship input, used for movement.
        /// </summary>
        public Vector2 LeftStick;

        /// <summary>
        /// The right-stick value of the ship input, used for firing.
        /// </summary>
        public Vector2 RightStick;

        /// <summary>
        /// If true, the player is trying to fire a mine.
        /// </summary>
        public bool MineFired;

        #endregion

        #region Initialization Methods

        /// <summary>
        /// Constructs a new ShipInput object.
        /// </summary>
        /// <param name="leftStick">The left-stick value of the ship input.</param>
        /// <param name="rightStick">The right-stick value of the ship input.</param>
        /// <param name="mineFired">If true, the player is firing a mine.</param>
        public ShipInput(Vector2 leftStick, Vector2 rightStick, bool mineFired)
        {
            this.LeftStick = leftStick;
            this.RightStick = rightStick;
            this.MineFired = mineFired;
        }

        /// <summary>
        /// Create a new ShipInput object based on the data in the packet.
        /// </summary>
        /// <param name="packetReader">The packet with the data.</param>
        public ShipInput(PacketReader packetReader)
        {
            // safety-check the parameters, as they must be valid
            if (packetReader == null)
            {
                throw new ArgumentNullException("packetReader");
            }

            // read the data
            LeftStick = packetReader.ReadVector2();
            RightStick = packetReader.ReadVector2();
            MineFired = packetReader.ReadBoolean();
        }

        /// <summary>
        /// Create a new ShipInput object based on local input state.
        /// </summary>
        /// <param name="gamePadState">The local gamepad state.</param>
        /// <param name="keyboardState">The local keyboard state</param>
        public ShipInput(GamePadState gamePadState, KeyboardState keyboardState)
        {
            // check for movement action
            bool keyHit = false;
            LeftStick = Vector2.Zero;
            if (keyboardState.IsKeyDown(Keys.W))
            {
                LeftStick += Vector2.UnitY;
                keyHit = true;
            }
            if (keyboardState.IsKeyDown(Keys.A))
            {
                LeftStick += Vector2.Multiply(Vector2.UnitX, -1f);
                keyHit = true;
            }
            if (keyboardState.IsKeyDown(Keys.S))
            {
                LeftStick += Vector2.Multiply(Vector2.UnitY, -1f);
                keyHit = true;
            }
            if (keyboardState.IsKeyDown(Keys.D))
            {
                LeftStick += Vector2.UnitX;
                keyHit = true;
            }

            if (keyHit)
            {
                if (LeftStick.LengthSquared() > 0)
                {
                    LeftStick.Normalize();
                }
            }
            else
            {
                LeftStick = gamePadState.ThumbSticks.Left;
            }

            // check for firing action
            keyHit = false;
            RightStick = Vector2.Zero;
            if (keyboardState.IsKeyDown(Keys.Up))
            {
                RightStick += Vector2.UnitY;
                keyHit = true;
            }
            if (keyboardState.IsKeyDown(Keys.Left))
            {
                RightStick += Vector2.Multiply(Vector2.UnitX, -1f);
                keyHit = true;
            }
            if (keyboardState.IsKeyDown(Keys.Down))
            {
                RightStick += Vector2.Multiply(Vector2.UnitY, -1f);
                keyHit = true;
            }
            if (keyboardState.IsKeyDown(Keys.Right))
            {
                RightStick += Vector2.UnitX;
                keyHit = true;
            }

            if (keyHit)
            {
                if (RightStick.LengthSquared() > 0)
                {
                    RightStick.Normalize();
                }
            }
            else
            {
                RightStick = gamePadState.ThumbSticks.Right;
            }

            // check for firing a mine
            keyHit = false;
            MineFired = false;
            if (keyboardState.IsKeyDown(Keys.Space))
            {
                MineFired = true;
                keyHit = true;
            }

            if (!keyHit)
            {
                MineFired = gamePadState.Triggers.Right >= 0.9f;
            }
        }

        #endregion

        #region Networking Methods

        /// <summary>
        /// Serialize the object out to a packet.
        /// </summary>
        /// <param name="packetWriter">The packet to write to.</param>
        public void Serialize(PacketWriter packetWriter)
        {
            // safety-check the parameters, as they must be valid
            if (packetWriter == null)
            {
                throw new ArgumentNullException("packetWriter");
            }

            packetWriter.Write((int)World.PacketTypes.ShipInput);
            packetWriter.Write(LeftStick);
            packetWriter.Write(RightStick);
            packetWriter.Write(MineFired);
        }

        #endregion
    }
}