text:
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */

/*
 Copyright (C) 2009 StatPro Italia srl
 Copyright (C) 2009 Jose Aparicio

 This file is part of QuantLib, a free-software/open-source library
 for financial quantitative analysts and developers - http://quantlib.org/

 QuantLib is free software: you can redistribute it and/or modify it
 under the terms of the QuantLib license.  You should have received a
 copy of the license along with this program; if not, please email
 <quantlib-dev@lists.sf.net>. The license is also available online at
 <http://quantlib.org/license.shtml>.

 This program is distributed in the hope that it will be useful, but WITHOUT
 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 FOR A PARTICULAR PURPOSE.  See the license for more details.
*/

#include <ql/experimental/credit/defaultevent.hpp>
#include <ql/experimental/credit/recoveryratequote.hpp>
#include <ql/patterns/visitor.hpp>
#include <ql/settings.hpp>

namespace QuantLib {

    Date DefaultEvent::date() const {
        return defaultDate_;
    }

    void DefaultEvent::accept(AcyclicVisitor& v) {
        Visitor<DefaultEvent>* v1 =
            dynamic_cast<Visitor<DefaultEvent>*>(&v);
        if (v1 != 0)
            v1->visit(*this);
        else
            Event::accept(v);
    }

    // They will be sorted by settlement date
    Date DefaultEvent::DefaultSettlement::date() const {
        return settlementDate_;
    }

    void DefaultEvent::DefaultSettlement::accept(AcyclicVisitor& v) {
        Visitor<DefaultEvent::DefaultSettlement>* v1 =
            dynamic_cast<Visitor<DefaultEvent::DefaultSettlement>*>(&v);
        if (v1 != 0)
            v1->visit(*this);
        else
            Event::accept(v);
    }

    DefaultEvent::DefaultSettlement::DefaultSettlement(
        const Date& date,
        const std::map<Seniority, Real>& recoveryRates )
    : settlementDate_(date), recoveryRates_(recoveryRates) {
        QL_REQUIRE(recoveryRates.find(NoSeniority) ==
            recoveryRates.end(),
            "NoSeniority is not a valid realized seniority.");
    }

    DefaultEvent::DefaultSettlement::DefaultSettlement(
        const Date& date,
        Seniority seniority,
        const Real recoveryRate)
    : settlementDate_(date), recoveryRates_(makeIsdaConvMap()) {
        if (seniority == NoSeniority) {
            for (std::map<Seniority, Real>::iterator i=recoveryRates_.begin();
                 i != recoveryRates_.end(); ++i) {
                i->second = recoveryRate;
            }
        } else {
            recoveryRates_[seniority] = recoveryRate;
        }
    }

    Real DefaultEvent::DefaultSettlement::recoveryRate(
        Seniority sen) const {
        // expensive require cause called often...... fix me
        QL_REQUIRE(sen != NoSeniority,
            "NoSeniority is not valid for recovery rate request.");
        std::map<Seniority, Real>::const_iterator itmatch =
            recoveryRates_.find(sen);
        if(itmatch != recoveryRates_.end()) {
            return itmatch->second;
        }else{
            return Null<Real>();
        }
    }

    DefaultEvent::DefaultEvent(const Date& creditEventDate,
                               const DefaultType& atomicEvType,
                               const Currency& curr,
                               Seniority bondsSen,
                               // Settlement information:
                               const Date& settleDate,
                               const std::map<Seniority, Real>& recoveryRates)
    : bondsCurrency_(curr),
      defaultDate_(creditEventDate),
      eventType_(atomicEvType),
      bondsSeniority_(bondsSen),
      defSettlement_(settleDate,
                     recoveryRates.empty() ? makeIsdaConvMap()
                                           : recoveryRates) {
        if(settleDate != Null<Date>()) {// has settled
            QL_REQUIRE(settleDate >= creditEventDate,
              "Settlement date should be after default date.");
            QL_REQUIRE(recoveryRates.find(bondsSen) != recoveryRates.end(),
              "Settled events must contain the seniority of the default");
        }
    }

    DefaultEvent::DefaultEvent(const Date& creditEventDate,
                               const DefaultType& atomicEvType,
                               const Currency& curr,
                               Seniority bondsSen,
                               // Settlement information:
                               const Date& settleDate,
                               Real recoveryRate)
    : bondsCurrency_(curr),
      defaultDate_(creditEventDate),
      eventType_(atomicEvType),
      bondsSeniority_(bondsSen),
      defSettlement_(settleDate, bondsSen, recoveryRate) {
        if(settleDate != Null<Date>()) {
            QL_REQUIRE(settleDate >= creditEventDate,
            "Settlement date should be after default date.");
        }
    }

    bool DefaultEvent::matchesDefaultKey(
        const DefaultProbKey& contractKey) const {
        if(bondsCurrency_ != contractKey.currency()) return false;
        // a contract with NoSeniority matches all events
        if((bondsSeniority_ != contractKey.seniority())
            && (contractKey.seniority() != NoSeniority))
            return false;
        // loop on all event types in the contract and chek if we match any,
        //   calls derived types
        for(Size i=0; i<contractKey.size(); i++) {
            if(this->matchesEventType(contractKey.eventTypes()[i])) return true;
        }
        return false;
    }

    bool operator==(const DefaultEvent& lhs, const DefaultEvent& rhs) {
        return (lhs.currency() == rhs.currency()) &&
            (lhs.defaultType() == rhs.defaultType()) &&
            (lhs.date() == rhs.date()) &&
            (lhs.eventSeniority() == rhs.eventSeniority());
    }

    bool FailureToPayEvent::matchesEventType(
        const boost::shared_ptr<DefaultType>& contractEvType) const {
        boost::shared_ptr<FailureToPay> eveType =
            boost::dynamic_pointer_cast<FailureToPay>(contractEvType);
        // this chekcs the atomic types, no need to call parents method
        if(!eveType) return false;
        if(defaultedAmount_ < eveType->amountRequired()) return false;
        Date today = Settings::instance().evaluationDate();
        if(!this->hasOccurred(today - eveType->gracePeriod(), true))
            return false;
        return true;
    }

    FailureToPayEvent::FailureToPayEvent(const Date& creditEventDate,
                                         const Currency& curr,
                                         Seniority bondsSen,
                                         Real defaultedAmount,
                                         // Settlement information:
                                         const Date& settleDate,
                                         const std::map<Seniority, Real>&
                                            recoveryRates)
    : DefaultEvent(creditEventDate,
                   DefaultType(AtomicDefault::FailureToPay,
                               Restructuring::XR),
                   curr,
                   bondsSen,
                   settleDate,
                   recoveryRates),
      defaultedAmount_(defaultedAmount) { }

    FailureToPayEvent::FailureToPayEvent(const Date& creditEventDate,
                                         const Currency& curr,
                                         Seniority bondsSen,
                                         Real defaultedAmount,
                                         // Settlement information:
                                         const Date& settleDate,
                                         Real recoveryRates)
    : DefaultEvent(creditEventDate,
                   DefaultType(AtomicDefault::FailureToPay,
                               Restructuring::XR),
                   curr,
                   bondsSen,
                   settleDate,
                   recoveryRates),
      defaultedAmount_(defaultedAmount) { }

    BankruptcyEvent::BankruptcyEvent(const Date& creditEventDate,
                                     const Currency& curr,
                                     Seniority bondsSen,
                                     // Settlement information:
                                     const Date& settleDate,
                                     const std::map<Seniority, Real>&
                                        recoveryRates)
    : DefaultEvent(creditEventDate,
                   DefaultType(AtomicDefault::Bankruptcy,
                               Restructuring::XR),
                   curr,
                   bondsSen,
                   settleDate,
                   recoveryRates) {
        if(hasSettled()) {
            QL_REQUIRE(recoveryRates.size() == makeIsdaConvMap().size(),
              "Bankruptcy event should have settled for all seniorities.");
        }
    }

    BankruptcyEvent::BankruptcyEvent(const Date& creditEventDate,
                                     const Currency& curr,
                                     Seniority bondsSen,
                                     // Settlement information:
                                     const Date& settleDate,
                                     // means same for all
                                     Real recoveryRates)
    : DefaultEvent(creditEventDate,
                   DefaultType(AtomicDefault::Bankruptcy,
                               Restructuring::XR),
                   curr,
                   bondsSen,
                   settleDate,
                   recoveryRates) { }

}


text:
<?php

namespace Ivory\Tests\GoogleMap\Helper\Extension;

use Ivory\GoogleMap\Helper\Extension\InfoBoxExtensionHelper;

/**
 * InfoBox extension helper test.
 *
 * @author GeLo <geloen.eric@gmail.com>
 */
class InfoBoxExtensionHelperTest extends \PHPUnit_Framework_TestCase
{
    /** @var \Ivory\GoogleMap\Helper\Extension\InfoBoxExtensionHelper */
    protected $infoBoxExtensionHelper;

    /**
     * {@ineritdoc}
     */
    protected function setUp()
    {
        $this->infoBoxExtensionHelper = new InfoBoxExtensionHelper();
    }

    /**
     * {@ineritdoc}
     */
    protected function tearDown()
    {
        unset($this->infoBoxExtensionHelper);
    }

    public function testRenderLibraries()
    {
        $map = $this->getMock('Ivory\GoogleMap\Map');

        $expected = <<<EOF
<script type="text/javascript" src="//google-maps-utility-library-v3.googlecode.com/svn/trunk/infobox/src/infobox_packed.js"></script>

EOF;

        $this->assertSame($expected, $this->infoBoxExtensionHelper->renderLibraries($map));
    }

    public function testRenderBefore()
    {
        $map = $this->getMock('Ivory\GoogleMap\Map');

        $this->assertNull($this->infoBoxExtensionHelper->renderBefore($map));
    }

    public function testRenderAfterr()
    {
        $map = $this->getMock('Ivory\GoogleMap\Map');

        $this->assertNull($this->infoBoxExtensionHelper->renderAfter($map));
    }
}

redpajama_set_name: RedPajamaGithub


text:
/*
 * File:   Scene.cpp
 * Author: kdubovikov
 *
 * Created on November 1, 2014, 9:54 PM
 */

#include "Scene.h"
#include "StaticMesh.h"
#include "Text2D.h"

void Scene::addObject(Geometry& object) {
    objects.push_back(object);
}

void Scene::render() {
    static double lastTime = glfwGetTime();

    double currentTime = glfwGetTime();
    double deltaTime = currentTime - lastTime;

    inputManager.get()->processInputs(camera, deltaTime);
    camera.get()->applyTransformation();

    for (Geometry& object : objects) {
        object.prepare();
        object.applyUniforms(camera.get()->getViewMatrix(), camera.get()->getProjectionMatrix());

        StaticMesh* staticMesh = dynamic_cast<StaticMesh*>(&object);
        if (staticMesh != NULL) {
            staticMesh->prepareLightSource(light);
        }

        object.render();
    }

    lastTime = currentTime;
}

void Scene::setCamera(std::unique_ptr<Camera>& camera) {
    this->camera = std::move(camera);
}

void Scene::setInputManager(std::unique_ptr<InputManager>& inputManager) {
    this->inputManager = std::move(inputManager);
}

void Scene::setLightSource(std::unique_ptr<LightSource>& light) {
    this->light = std::move(light);
}


text:
package xyz.imxqd.course_assistant.activity;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.support.design.widget.TabLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

import android.widget.TextView;
import android.widget.Toast;

import org.jsoup.nodes.Document;

import java.io.IOException;
import java.util.HashMap;

import xyz.imxqd.course_assistant.R;
import xyz.imxqd.course_assistant.adapter.ConfirmListAdapter;
import xyz.imxqd.course_assistant.application.CourseAssistant;
import xyz.imxqd.course_assistant.fragment.CourseFragment;
import xyz.imxqd.course_assistant.fragment.NewSubmitFragment;
import xyz.imxqd.course_assistant.fragment.SelectedFragment;
import xyz.imxqd.course_assistant.model.Constants;
import xyz.imxqd.course_assistant.view.BadgeView;
import xyz.imxqd.course_assistant.view.LoginDialog;
import xyz.imxqd.course_assistant.view.MyToast;
import xyz.imxqd.course_assistant.web.CourseTool;

public class MainActivity extends AppCompatActivity implements LoginDialog.LoginCallBack, ViewPager.OnPageChangeListener {

    private SectionsPagerAdapter mSectionsPagerAdapter;
    private ViewPager mViewPager;
    private BadgeView badgeView = null;
    private TabLayout tabLayout;
    private FloatingActionButton fab;
    private Fragment selected, course, selecting;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        initViewPage();
        initFragments();
        initBadgeView();
        initFab();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (System.currentTimeMillis() - CourseAssistant.mLastLoginTime > Constants.LOGIN_SESSION_TIMEOUT) {
            login();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        if (id == R.id.action_help) {
            new AlertDialog.Builder(this)
                    .setTitle(R.string.help_dialog_title)
                    .setMessage(R.string.help_dialog_message)
                    .setPositiveButton(R.string.string_confirm, null)
                    .show();
            return true;
        } else if (id == R.id.action_switch_user) {
            SharedPreferences preferences = getSharedPreferences("user", Context.MODE_PRIVATE);
            preferences.edit()
                    .putBoolean("auto", false)
                    .apply();
            login();
        } else if (id == android.R.id.home) {
            onBackPressed();
        }

        return super.onOptionsItemSelected(item);
    }

    public void initViewPage() {
        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
        mViewPager = (ViewPager) findViewById(R.id.container);
        tabLayout = (TabLayout) findViewById(R.id.tabs);

        mViewPager.setOffscreenPageLimit(3);
        mViewPager.setAdapter(mSectionsPagerAdapter);
        mViewPager.addOnPageChangeListener(this);
        tabLayout.setupWithViewPager(mViewPager);
    }

    public void initFragments() {
        selected = SelectedFragment.newInstance();
        course = CourseFragment.newInstance();
        selecting = NewSubmitFragment.newInstance();
    }

    public void initFab() {
        fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                submit();
            }
        });
        fab.hide();
    }

    public void initBadgeView() {
        TabLayout.Tab tab = tabLayout.getTabAt(2);
        View view = LayoutInflater.from(this).inflate(R.layout.tab_title_layout, null);
        ((TextView) view.findViewById(R.id.tv_title)).setText(mSectionsPagerAdapter.getPageTitle(2));
        if (tab != null) {
            tab.setCustomView(view);
            if (badgeView == null) {
                badgeView = new BadgeView(this);
            }
            badgeView.setTargetView(view);
            CourseAssistant assistant = CourseAssistant.getInstance();
            setBadgeCount(assistant.getNewSubmitMap().size());
        }
    }

    int current_page = 0;

    @Override
    public void onBackPressed() {
        if (current_page == 0 || current_page == 2) {
            finish();
            return;
        }
        super.onBackPressed();
    }

    @Override
    public void onSuccess() {
        if (!CourseTool.isOpened) {
            Toast.makeText(this, "当前可能没有开放选课!", Toast.LENGTH_SHORT).show();
        }

        if ("2013214400".equals(CourseTool.studentNo)) {
            MyToast.myTosat(this, R.drawable.img2, 3000);
        } else if ("2013214407".equals(CourseTool.studentNo)) {
            MyToast.myTosat(this, R.drawable.img1, 3000);
        }
        ((SelectedFragment) selected).loadData();
        ((CourseFragment) course).loadData();
    }

    @Override
    public void oncCancel() {
        Snackbar.make(mViewPager, "你取消了登录,无法继续使用,请登录", Snackbar.LENGTH_INDEFINITE)
                .setAction("登录", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        login();
                    }
                })
                .show();
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        switch (position) {
            case 0:
                fab.hide();
                setHomeAsUp(false);
                break;
            case 1:
                fab.hide();
                break;
            case 2:
                setHomeAsUp(false);
                fab.show();
        }
        current_page = position;
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    /**
     * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
     * one of the sections/tabs/pages.
     */
    public class SectionsPagerAdapter extends FragmentPagerAdapter {

        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            switch (position) {
                case 0:
                    return selected;
                case 1:
                    return course;
                case 2:
                    return selecting;
            }
            return null;
        }

        @Override
        public int getCount() {
            return 3;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            switch (position) {
                case 0:
                    return getString(R.string.section_1);
                case 1:
                    return getString(R.string.section_2);
                case 2:
                    return getString(R.string.section_3);
            }
            return null;
        }
    }

    public void setHomeAsUp(boolean enable) {
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(enable);
        }

    }

    public void setBadgeCount(int count) {
        badgeView.setBadgeCount(count);
    }

    public void login() {
        LoginDialog dialog = new LoginDialog(this);
        dialog.setCallBack(this);
    }

    public void submit() {
        if (CourseTool.cookie != null && CourseTool.studentNo != null) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this)
                    .setTitle(R.string.submit_confirm_title)
                    .setNegativeButton(R.string.string_cancel, null)
                    .setPositiveButton(R.string.string_confirm, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            task = new SubmitTask();
                            task.execute();
                        }
                    });
            ConfirmListAdapter adapter = new ConfirmListAdapter();
            if (adapter.getCount() == 0) {
                builder.setMessage(R.string.empty_to_submit);
            } else {
                builder.setAdapter(adapter, null);
            }

            builder.show();
        }
    }

    SubmitTask task = null;

    class SubmitTask extends AsyncTask<Void, Void, Document> {
        ProgressDialog progressDialog;

        @Override
        protected void onPreExecute() {
            progressDialog = ProgressDialog.show(MainActivity.this, getString(R.string.loading_string),
                    getString(R.string.loading_string));
        }

        @Override
        protected Document doInBackground(Void... params) {
            HashMap<String, String> map = CourseAssistant.getInstance().getToSubmitMap();
            try {
                return CourseTool.submit(map);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Document html) {
            progressDialog.dismiss();
            if (html != null) {
                html.body().getElementsByTag("div").remove();
                html.body().getElementsByTag("center").remove();
                String text = html.body().html();
                text = text.replaceFirst("
", "");
                text = text.replaceFirst("
", "");
                //0500105X
//                ArrayList<String> list = new ArrayList<>();
//                for(int pos = 0; pos < text.length(); pos++){
//                    pos = text.indexOf(getString(R.string.string_course_code));
//                    String tmp = text.substring(pos + 5, 8);
//                    list.add(tmp);
//                }

                new AlertDialog.Builder(MainActivity.this)
                        .setTitle(R.string.submit_result_title)
                        .setMessage(Html.fromHtml(text + "
请根据结果选择以下操作:"))
                        .setPositiveButton(R.string.action_clear, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                CourseAssistant.getInstance().clear();
                                NewSubmitFragment n = (NewSubmitFragment) selecting;
                                n.updateUI();
                                setBadgeCount(0);
                                SelectedFragment s = (SelectedFragment) selected;
                                s.onRefresh();
                            }
                        })
                        .setNegativeButton(R.string.action_cancel, null)
                        .show();
            }
            task = null;
        }
    }
}


text:
extern int	debug;

static void	log_doit(int, int, const char *, va_list ap);
void		log_open(const char *i, int, int);
void		log_ret(const char *, ...);
void		log_syserr(const char *, ...);
void		log_msg(const char *, ...);
void		log_die(const char *, ...);


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

namespace SimpleClass2Test
{
    public class Program
    {
        static void Main(string[] args)
        {
            Class1 xObj = new Class2();
            xObj.MyMethod();
            Test2(xObj);
        }

        public static void Test2(object test)
        {
            test.ToString();
        }
    }

    public class Class1
    {
        public virtual string MyMethod()
        {
            return "Base(1)";
        }
    }

    public class Class2 : Class1
    {
        public override string MyMethod()
        {
            return "Class2";
        }
    }
}


text:
package com.duck8823.model.twitter;

import lombok.Data;
import twitter4j.Status;

import javax.persistence.*;
import javax.validation.constraints.NotNull;

/**
 * Created by maeda on 2016/01/11.
 */
@Entity
@Table(name = "twitter_filter")
@Data
public class Filter {

	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	@Column(name = "filter_id")
	private Long id;

	@NotNull
	@Enumerated(EnumType.STRING)
	@Column(name = "filter_type")
	private FilterType filterType;

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

	// for hibernate
	public Filter(){
	}

	public Filter(FilterType filterType, String keyword) {
		this.filterType = filterType;
		this.keyword = keyword;
	}

	public boolean find(Status status){
		return filterType.find(status, keyword);
	}

	@Override
	public boolean equals(Object object){
		if(!object.getClass().isAssignableFrom(Filter.class)){
			return false;
		}
		return getId().equals(Filter.class.cast(object).getId());
	}

	@Override
	public int hashCode() {
		return getId() != null ? getId().intValue() : 0;
	}
}


text:
'-----------------------------------------------------------------------------
' FramesetGameComponentAnimation.vb
'
' Microsoft XNA Community Game Platform
' Copyright (C) Microsoft Corporation. All rights reserved.
'-----------------------------------------------------------------------------
#End Region

#Region "Using Statements"
Imports System.Text
Imports Microsoft.Xna.Framework.Graphics
Imports Microsoft.Xna.Framework
#End Region

''' <summary>
''' A "typical" animation that consists of alternating between a set of frames.
''' </summary>
Public Class FramesetGameComponentAnimation
    Inherits AnimatedGameComponentAnimation
#Region "Fields"
    Private framesTexture As Texture2D
    Private numberOfFrames As Integer
    Private numberOfFramePerRow As Integer
    Private frameSize As Vector2

    Private percent As Double = 0
#End Region

#Region "Initializations"
    ''' <summary>
    ''' Creates a new instance of the class.
    ''' </summary>
    ''' <param name="framesTexture">The frames texture (animation sheet).</param>
    ''' <param name="numberOfFrames">The number of frames in the sheet.</param>
    ''' <param name="numberOfFramePerRow">The number of frame per row.</param>
    ''' <param name="frameSize">Size of the frame.</param>
    Public Sub New(ByVal framesTexture As Texture2D, ByVal numberOfFrames As Integer, ByVal numberOfFramePerRow As Integer, ByVal frameSize As Vector2)
        Me.framesTexture = framesTexture
        Me.numberOfFrames = numberOfFrames
        Me.numberOfFramePerRow = numberOfFramePerRow
        Me.frameSize = frameSize
    End Sub
#End Region

    ''' <summary>
    ''' Runs the frame set animation.
    ''' </summary>
    ''' <param name="gameTime">Game time information.</param>
    Public Overrides Sub Run(ByVal gameTime As GameTime)
        If IsStarted() Then
            ' Calculate the completion percent of the animation
            percent += (((gameTime.ElapsedGameTime.TotalMilliseconds / (Duration.TotalMilliseconds / AnimationCycles)) * 100))

            If percent >= 100 Then
                percent = 0
            End If

            ' Calculate the current frame index
            Dim animationIndex As Integer = CInt(Fix(numberOfFrames * percent / 100))
            Component.CurrentSegment = New Rectangle(CInt(Fix(frameSize.X)) * (animationIndex Mod numberOfFramePerRow), CInt(Fix(frameSize.Y)) * (animationIndex \ numberOfFramePerRow), CInt(Fix(frameSize.X)), CInt(Fix(frameSize.Y)))
            Component.CurrentFrame = framesTexture

        Else
            Component.CurrentFrame = Nothing
            Component.CurrentSegment = Nothing
        End If
        MyBase.Run(gameTime)
    End Sub
End Class


text:
require 'gherkin/native'
require 'gherkin/formatter/model'

module Gherkin
  module Listener
    # Adapter from the "raw" Gherkin <tt>Listener</tt> API
    # to the slightly more high-level <tt>Formatter</tt> API,
    # which is easier to implement (less state to keep track of).
    class FormatterListener
      native_impl('gherkin')

      def initialize(formatter)
        @formatter = formatter
        @comments = []
        @tags = []
        @table = nil
      end

      def comment(value, line)
        @comments << Formatter::Model::Comment.new(value, line)
      end

      def tag(name, line)
        @tags << Formatter::Model::Tag.new(name, line)
      end

      def feature(keyword, name, description, line)
        @formatter.feature(Formatter::Model::Feature.new(grab_comments!, grab_tags!, keyword, name, description, line))
      end

      def background(keyword, name, description, line)
        @formatter.background(Formatter::Model::Background.new(grab_comments!, keyword, name, description, line))
      end

      def scenario(keyword, name, description, line)
        replay_step_or_examples
        @formatter.scenario(Formatter::Model::Scenario.new(grab_comments!, grab_tags!, keyword, name, description, line))
      end

      def scenario_outline(keyword, name, description, line)
        replay_step_or_examples
        @formatter.scenario_outline(Formatter::Model::ScenarioOutline.new(grab_comments!, grab_tags!, keyword, name, description, line))
      end

      def examples(keyword, name, description, line)
        replay_step_or_examples
        @examples_statement = Formatter::Model::Examples.new(grab_comments!, grab_tags!, keyword, name, description, line)
      end

      def step(keyword, name, line)
        replay_step_or_examples
        @step_statement = Formatter::Model::Step.new(grab_comments!, keyword, name, line)
      end

      def row(cells, line)
        @table ||= []
        @table << Formatter::Model::Row.new(grab_comments!, cells, line)
      end

      def doc_string(string, line)
        @doc_string = Formatter::Model::DocString.new(string, line)
      end

      def eof
        replay_step_or_examples
        @formatter.eof
      end

      def syntax_error(state, ev, legal_events, uri, line)
        @formatter.syntax_error(state, ev, legal_events, uri, line)
      end

    private

      def grab_comments!
        comments = @comments
        @comments = []
        comments
      end

      def grab_tags!
        tags = @tags
        @tags = []
        tags
      end

      def grab_rows!
        table = @table
        @table = nil
        table
      end

      def grab_doc_string!
        doc_string = @doc_string
        @doc_string = nil
        doc_string
      end

      def replay_step_or_examples
        if(@step_statement)
          @step_statement.multiline_arg = grab_doc_string! || grab_rows!
          @formatter.step(@step_statement)
          @step_statement = nil
        end
        if(@examples_statement)
          @examples_statement.rows = grab_rows!
          @formatter.examples(@examples_statement)
          @examples_statement = nil
        end
      end
    end
  end
end


text:
<?php

namespace Predis\Command;

/**
 * @link http://redis.io/commands/info
 *
 * @author Daniele Alessandri <suppakilla@gmail.com>
 */
class ServerInfo extends Command
{
    /**
     * {@inheritdoc}
     */
    public function getId()
    {
        return 'INFO';
    }

    /**
     * {@inheritdoc}
     */
    public function parseResponse($data)
    {
        $info = [];
        $infoLines = preg_split('/\r?\n/', $data);

        foreach ($infoLines as $row) {
            if (strpos($row, ':') === FALSE) {
                continue;
            }

            list($k, $v) = $this->parseRow($row);
            $info[$k] = $v;
        }

        return $info;
    }

    /**
     * Parses a single row of the response and returns the key-value pair.
     *
     * @param string $row Single row of the response.
     *
     * @return array
     */
    protected function parseRow($row)
    {
        list($k, $v) = explode(':', $row, 2);

        if (preg_match('/^db\d+$/', $k)) {
            $v = $this->parseDatabaseStats($v);
        }

        return array($k, $v);
    }

    /**
     * Extracts the statistics of each logical DB from the string buffer.
     *
     * @param string $str Response buffer.
     *
     * @return array
     */
    protected function parseDatabaseStats($str)
    {
        $db = [];

        foreach (explode(',', $str) as $dbvar) {
            list($dbvk, $dbvv) = explode('=', $dbvar);
            $db[trim($dbvk)] = $dbvv;
        }

        return $db;
    }

    /**
     * Parses the response and extracts the allocation statistics.
     *
     * @param string $str Response buffer.
     *
     * @return array
     */
    protected function parseAllocationStats($str)
    {
        $stats = [];

        foreach (explode(',', $str) as $kv) {
            @list($size, $objects, $extra) = explode('=', $kv);

            // hack to prevent incorrect values when parsing the >=256 key
            if (isset($extra)) {
                $size = ">=$objects";
                $objects = $extra;
            }

            $stats[$size] = $objects;
        }

        return $stats;
    }
}


text:
<?php

namespace Backend\Modules\Immo\Actions;

use Backend\Core\Engine\Base\ActionIndex as BackendBaseActionIndex;
use Backend\Core\Engine\Language as BL;
use Backend\Core\Engine\Authentication as BackendAuthentication;
use Backend\Core\Engine\Model as BackendModel;
use Backend\Core\Engine\DataGridDB as BackendDataGridDB;
use Backend\Core\Engine\DataGridFunctions as BackendDataGridFunctions;
use Backend\Modules\Immo\Engine\Model as BackendImmoModel;

/**
 * This is the media action, it will display the overview of media for a specific immo.
 *
 * @author Bart De Clercq <info@lexxweb.be>
 * @author Tim van Wolfswinkel <tim@webleads.nl>
 */
class Media extends BackendBaseActionIndex
{
	/**
	 * The immo record
	 *
	 * @var	array
	 */
	private $immo = array();

	/**
	 * Datagrid with published items
	 *
	 * @var	SpoonDataGrid
	 */
	private $dgImages, $dgFiles, $dgVideos;

	/**
	 * Execute the action
	 */
	public function execute()
	{
		$this->id = $this->getParameter('immo_id', 'int');

		if($this->id !== null && BackendImmoModel::exists($this->id))
		{
			parent::execute();

			$this->getData();
			$this->loadDataGridImages();
			$this->loadDataGridFiles();
			$this->loadDataGridVideos();
			$this->parse();
			$this->display();
		}

		// the immo does not exist
		else $this->redirect(BackendModel::createURLForAction('index') . '&error=non-existing');
	}

	/**
	 * Gets all necessary data
	 */
	protected function getData()
	{
		$this->immo = BackendImmoModel::get($this->id);
	}

	/**
	 * Loads the datagrid of the images
	 */
	protected function loadDataGridImages()
	{
		// set image link
		$imageLink = FRONTEND_FILES_URL . '/' . $this->module . '/[immo_id]/64x64';

		// create images datagrid
		$this->dgImages = new BackendDataGridDB(BackendImmoModel::QRY_DATAGRID_BROWSE_IMAGES, $this->id);
		$this->dgImages->setAttributes(array('class' => 'dataGrid sequenceByDragAndDrop'));
		$this->dgImages->setAttributes(array('id' => 'immo_images_dg'));
		$this->dgImages->setAttributes(array('data-action' => 'sequence_images'));

		$this->dgImages->setColumnHidden('sequence');
		$this->dgImages->setColumnHidden('immo_id');

		$this->dgImages->addColumn('dragAndDropHandle', null, '' . BL::lbl('Move') . '');
		$this->dgImages->setColumnsSequence('dragAndDropHandle');
		$this->dgImages->setColumnAttributes('dragAndDropHandle', array('class' => 'dragAndDropHandle'));

		$this->dgImages->setRowAttributes(array('data-id' => '[id]'));
		$this->dgImages->setSortingColumns(array('title', 'sequence'), 'sequence');
		$this->dgImages->setSortParameter('asc');
		$this->dgImages->addColumn('edit', null, BL::lbl('Edit'), BackendModel::createURLForAction('edit_image') . '&id=[id]&immo_id=[immo_id]', BL::lbl('Edit'));

		$this->dgImages->setColumnFunction(array(new BackendDataGridFunctions(), 'showImage'), array($imageLink, '[filename]'), 'filename' );
		$this->dgImages->setColumnAttributes('filename', array('class' => 'thumbnail'));
		$this->dgImages->addColumn('checkbox', '<input type="checkbox" name="toggleChecks" value="toggleChecks" />', '<input type="checkbox" name="id[]" value="[id]" class="inputCheckbox" />');
		$this->dgImages->setColumnsSequence('checkbox');

		$ddmMassAction = new \SpoonFormDropdown('action', array('deleteImages' => BL::lbl('Delete')), 'deleteImages');
		$this->dgImages->setMassAction($ddmMassAction);
		$this->dgImages->setColumnAttributes('title', array('data-id' => '{id:[id]}'));
	}

	/**
	 * Loads the datagrid of the files
	 */
	protected function loadDataGridFiles()
	{
		// create files datagrid
		$this->dgFiles = new BackendDataGridDB(BackendImmoModel::QRY_DATAGRID_BROWSE_FILES, $this->id);

		$this->dgFiles->setAttributes(array('class' => 'dataGrid sequenceByDragAndDrop'));
		$this->dgFiles->setAttributes(array('id' => 'immo_files_dg'));
		$this->dgFiles->setAttributes(array('data-action' => 'sequence_files'));

		$this->dgFiles->setColumnHidden('sequence');
		$this->dgFiles->setColumnHidden('immo_id');

		$this->dgFiles->addColumn('dragAndDropHandle', null, '' . BL::lbl('Move') . '');
		$this->dgFiles->setColumnsSequence('dragAndDropHandle');
		$this->dgFiles->setColumnAttributes('dragAndDropHandle', array('class' => 'dragAndDropHandle'));

		$this->dgFiles->setRowAttributes(array('data-id' => '[id]'));

		$this->dgFiles->setSortingColumns(array('title', 'sequence'), 'sequence');
		$this->dgFiles->setSortParameter('asc');

		$this->dgFiles->addColumn('edit', null, BL::lbl('Edit'), BackendModel::createURLForAction('edit_file') . '&id=[id]&immo_id=[immo_id]', BL::lbl('Edit'));
		$this->dgFiles->addColumn('checkbox', '<input type="checkbox" name="toggleChecks" value="toggleChecks" />', '<input type="checkbox" name="id[]" value="[id]" class="inputCheckbox" />');
		$this->dgFiles->setColumnsSequence('checkbox');

		$ddmMassAction = new \SpoonFormDropdown('action', array('deleteFiles' => BL::lbl('Delete')), 'deleteFiles');
		$this->dgFiles->setMassAction($ddmMassAction);
		$this->dgFiles->setColumnAttributes('title', array('data-id' => '{id:[id]}'));
	}

	/**
	 * Loads the datagrid of the videos
	 */
	protected function loadDataGridVideos()
	{
		// create videos datagrid
		$this->dgVideos = new BackendDataGridDB(BackendImmoModel::QRY_DATAGRID_BROWSE_VIDEOS, $this->id);

		$this->dgVideos->setAttributes(array('class' => 'dataGrid sequenceByDragAndDrop'));
		$this->dgVideos->setAttributes(array('id' => 'immo_videos_dg'));
		$this->dgVideos->setAttributes(array('data-action' => 'sequence_videos'));

		$this->dgVideos->setColumnHidden('immo_id');

		$this->dgVideos->addColumn('dragAndDropHandle', null, '' . BL::lbl('Move') . '');
		$this->dgVideos->setColumnsSequence('dragAndDropHandle');
		$this->dgVideos->setColumnAttributes('dragAndDropHandle', array('class' => 'dragAndDropHandle'));

		$this->dgVideos->setRowAttributes(array('data-id' => '[id]'));

		$this->dgVideos->setSortingColumns(array('title', 'sequence'), 'sequence');
		$this->dgVideos->setSortParameter('asc');

		$this->dgVideos->addColumn('edit', null, BL::lbl('Edit'), BackendModel::createURLForAction('edit_video') . '&id=[id]&immo_id=[immo_id]', BL::lbl('Edit'));
		$this->dgVideos->addColumn('checkbox', '<input type="checkbox" name="toggleChecks" value="toggleChecks" />', '<input type="checkbox" name="id[]" value="[id]" class="inputCheckbox" />');
		$this->dgVideos->setColumnsSequence('checkbox');

		$ddmMassAction = new \SpoonFormDropdown('action', array('deleteVideos' => BL::lbl('Delete')), 'deleteVideos');
		$this->dgVideos->setMassAction($ddmMassAction);
		$this->dgVideos->setColumnAttributes('title', array('data-id' => '{id:[id]}'));
	}

	/**
	 * Parse & display the page
	 */
	protected function parse()
	{
		$this->tpl->assign('dataGridImages', ($this->dgImages->getNumResults() != 0) ? $this->dgImages->getContent() : false);
		$this->tpl->assign('dataGridFiles', ($this->dgFiles->getNumResults() != 0) ? $this->dgFiles->getContent() : false);
		$this->tpl->assign('dataGridVideos', ($this->dgVideos->getNumResults() != 0) ? $this->dgVideos->getContent() : false);

		$this->tpl->assign('immo', $this->immo);
	}
}


text:
set -Eeuo pipefail

if [ "${1:0:1}" = '-' ]; then
	set -- mongod "$@"
fi

originalArgOne="$1"

# allow the container to be started with `--user`
# all mongo* commands should be dropped to the correct user
if [[ "$originalArgOne" == mongo* ]] && [ "$(id -u)" = '0' ]; then
	if [ "$originalArgOne" = 'mongod' ]; then
		find /data/configdb /data/db \! -user mongodb -exec chown mongodb '{}' +
	fi

	# make sure we can write to stdout and stderr as "mongodb"
	# (for our "initdb" code later; see "--logpath" below)
	chown --dereference mongodb "/proc/$$/fd/1" "/proc/$$/fd/2" || :
	# ignore errors thanks to https://github.com/docker-library/mongo/issues/149

	exec gosu mongodb "$BASH_SOURCE" "$@"
fi

dpkgArch="$(dpkg --print-architecture)"
case "$dpkgArch" in
	amd64) # https://github.com/docker-library/mongo/issues/485#issuecomment-891991814
		if ! grep -qE '^flags.* avx( .*|$)' /proc/cpuinfo; then
			{
				echo
				echo 'WARNING: MongoDB 5.0+ requires a CPU with AVX support, and your current system does not appear to have that!'
				echo '  see https://jira.mongodb.org/browse/SERVER-54407'
				echo '  see also https://www.mongodb.com/community/forums/t/mongodb-5-0-cpu-intel-g4650-compatibility/116610/2'
				echo '  see also https://github.com/docker-library/mongo/issues/485#issuecomment-891991814'
				echo
			} >&2
		fi
		;;

	arm64) # https://github.com/docker-library/mongo/issues/485#issuecomment-970864306
		# https://en.wikichip.org/wiki/arm/armv8#ARMv8_Extensions_and_Processor_Features
		# http://javathunderx.blogspot.com/2018/11/cheat-sheet-for-cpuinfo-features-on.html
		if ! grep -qE '^Features.* (fphp|dcpop|sha3|sm3|sm4|asimddp|sha512|sve)( .*|$)' /proc/cpuinfo; then
			{
				echo
				echo 'WARNING: MongoDB 5.0+ requires ARMv8.2-A or higher, and your current system does not appear to implement any of the common features for that!'
				echo '  see https://jira.mongodb.org/browse/SERVER-55178'
				echo '  see also https://en.wikichip.org/wiki/arm/armv8#ARMv8_Extensions_and_Processor_Features'
				echo '  see also https://github.com/docker-library/mongo/issues/485#issuecomment-970864306'
				echo
			} >&2
		fi
		;;
esac

# you should use numactl to start your mongod instances, including the config servers, mongos instances, and any clients.
# https://docs.mongodb.com/manual/administration/production-notes/#configuring-numa-on-linux
if [[ "$originalArgOne" == mongo* ]]; then
	numa='numactl --interleave=all'
	if $numa true &> /dev/null; then
		set -- $numa "$@"
	fi
fi

# usage: file_env VAR [DEFAULT]
#    ie: file_env 'XYZ_DB_PASSWORD' 'example'
# (will allow for "$XYZ_DB_PASSWORD_FILE" to fill in the value of
#  "$XYZ_DB_PASSWORD" from a file, especially for Docker's secrets feature)
file_env() {
	local var="$1"
	local fileVar="${var}_FILE"
	local def="${2:-}"
	if [ "${!var:-}" ] && [ "${!fileVar:-}" ]; then
		echo >&2 "error: both $var and $fileVar are set (but are exclusive)"
		exit 1
	fi
	local val="$def"
	if [ "${!var:-}" ]; then
		val="${!var}"
	elif [ "${!fileVar:-}" ]; then
		val="$(< "${!fileVar}")"
	fi
	export "$var"="$val"
	unset "$fileVar"
}

# see https://github.com/docker-library/mongo/issues/147 (mongod is picky about duplicated arguments)
_mongod_hack_have_arg() {
	local checkArg="$1"; shift
	local arg
	for arg; do
		case "$arg" in
			"$checkArg"|"$checkArg"=*)
				return 0
				;;
		esac
	done
	return 1
}
# _mongod_hack_get_arg_val '--some-arg' "$@"
_mongod_hack_get_arg_val() {
	local checkArg="$1"; shift
	while [ "$#" -gt 0 ]; do
		local arg="$1"; shift
		case "$arg" in
			"$checkArg")
				echo "$1"
				return 0
				;;
			"$checkArg"=*)
				echo "${arg#$checkArg=}"
				return 0
				;;
		esac
	done
	return 1
}
declare -a mongodHackedArgs
# _mongod_hack_ensure_arg '--some-arg' "$@"
# set -- "${mongodHackedArgs[@]}"
_mongod_hack_ensure_arg() {
	local ensureArg="$1"; shift
	mongodHackedArgs=( "$@" )
	if ! _mongod_hack_have_arg "$ensureArg" "$@"; then
		mongodHackedArgs+=( "$ensureArg" )
	fi
}
# _mongod_hack_ensure_no_arg '--some-unwanted-arg' "$@"
# set -- "${mongodHackedArgs[@]}"
_mongod_hack_ensure_no_arg() {
	local ensureNoArg="$1"; shift
	mongodHackedArgs=()
	while [ "$#" -gt 0 ]; do
		local arg="$1"; shift
		if [ "$arg" = "$ensureNoArg" ]; then
			continue
		fi
		mongodHackedArgs+=( "$arg" )
	done
}
# _mongod_hack_ensure_no_arg '--some-unwanted-arg' "$@"
# set -- "${mongodHackedArgs[@]}"
_mongod_hack_ensure_no_arg_val() {
	local ensureNoArg="$1"; shift
	mongodHackedArgs=()
	while [ "$#" -gt 0 ]; do
		local arg="$1"; shift
		case "$arg" in
			"$ensureNoArg")
				shift # also skip the value
				continue
				;;
			"$ensureNoArg"=*)
				# value is already included
				continue
				;;
		esac
		mongodHackedArgs+=( "$arg" )
	done
}
# _mongod_hack_ensure_arg_val '--some-arg' 'some-val' "$@"
# set -- "${mongodHackedArgs[@]}"
_mongod_hack_ensure_arg_val() {
	local ensureArg="$1"; shift
	local ensureVal="$1"; shift
	_mongod_hack_ensure_no_arg_val "$ensureArg" "$@"
	mongodHackedArgs+=( "$ensureArg" "$ensureVal" )
}

# _js_escape 'some "string" value'
_js_escape() {
	jq --null-input --arg 'str' "$1" '$str'
}

: "${TMPDIR:=/tmp}"
jsonConfigFile="$TMPDIR/docker-entrypoint-config.json"
tempConfigFile="$TMPDIR/docker-entrypoint-temp-config.json"
_parse_config() {
	if [ -s "$tempConfigFile" ]; then
		return 0
	fi

	local configPath
	if configPath="$(_mongod_hack_get_arg_val --config "$@")" && [ -s "$configPath" ]; then
		# if --config is specified, parse it into a JSON file so we can remove a few problematic keys (especially SSL-related keys)
		# see https://docs.mongodb.com/manual/reference/configuration-options/
		if grep -vEm1 '^[[:space:]]*(#|$)' "$configPath" | grep -qE '^[[:space:]]*[^=:]+[[:space:]]*='; then
			# if the first non-comment/non-blank line of the config file looks like "foo = ...", this is probably the 2.4 and older "ini-style config format"
			# https://docs.mongodb.com/v2.4/reference/configuration-options/
			# https://docs.mongodb.com/v2.6/reference/configuration-options/
			# https://github.com/mongodb/mongo/blob/r4.4.2/src/mongo/util/options_parser/options_parser.cpp#L1359-L1375
			# https://stackoverflow.com/a/25518018/433558
			echo >&2
			echo >&2 "WARNING: it appears that '$configPath' is in the older INI-style format (replaced by YAML in MongoDB 2.6)"
			echo >&2 '  This script does not parse the older INI-style format, and thus will ignore it.'
			echo >&2
			return 1
		fi
		if [ "$mongoShell" = 'mongo' ]; then
			"$mongoShell" --norc --nodb --quiet --eval "load('/js-yaml.js'); printjson(jsyaml.load(cat($(_js_escape "$configPath"))))" > "$jsonConfigFile"
		else
			# https://www.mongodb.com/docs/manual/reference/method/js-native/#std-label-native-in-mongosh
			"$mongoShell" --norc --nodb --quiet --eval "load('/js-yaml.js'); JSON.stringify(jsyaml.load(fs.readFileSync($(_js_escape "$configPath"), 'utf8')))" > "$jsonConfigFile"
		fi
		if [ "$(head -c1 "$jsonConfigFile")" != '{' ] || [ "$(tail -c2 "$jsonConfigFile")" != '}' ]; then
			# if the file doesn't start with "{" and end with "}", it's *probably* an error ("uncaught exception: YAMLException: foo" for example), so we should print it out
			echo >&2 'error: unexpected "js-yaml.js" output while parsing config:'
			cat >&2 "$jsonConfigFile"
			exit 1
		fi
		jq 'del(.systemLog, .processManagement, .net, .security, .replication)' "$jsonConfigFile" > "$tempConfigFile"
		return 0
	fi

	return 1
}
dbPath=
_dbPath() {
	if [ -n "$dbPath" ]; then
		echo "$dbPath"
		return
	fi

	if ! dbPath="$(_mongod_hack_get_arg_val --dbpath "$@")"; then
		if _parse_config "$@"; then
			dbPath="$(jq -r '.storage.dbPath // empty' "$jsonConfigFile")"
		fi
	fi

	if [ -z "$dbPath" ]; then
		if _mongod_hack_have_arg --configsvr "$@" || {
			_parse_config "$@" \
			&& clusterRole="$(jq -r '.sharding.clusterRole // empty' "$jsonConfigFile")" \
			&& [ "$clusterRole" = 'configsvr' ]
		}; then
			# if running as config server, then the default dbpath is /data/configdb
			# https://docs.mongodb.com/manual/reference/program/mongod/#cmdoption-mongod-configsvr
			dbPath=/data/configdb
		fi
	fi

	: "${dbPath:=/data/db}"

	echo "$dbPath"
}

if [ "$originalArgOne" = 'mongod' ]; then
	file_env 'MONGO_INITDB_ROOT_USERNAME'
	file_env 'MONGO_INITDB_ROOT_PASSWORD'

	mongoShell='mongo'
	if ! command -v "$mongoShell" > /dev/null; then
		mongoShell='mongosh'
	fi

	# pre-check a few factors to see if it's even worth bothering with initdb
	shouldPerformInitdb=
	if [ "$MONGO_INITDB_ROOT_USERNAME" ] && [ "$MONGO_INITDB_ROOT_PASSWORD" ]; then
		# if we have a username/password, let's set "--auth"
		_mongod_hack_ensure_arg '--auth' "$@"
		set -- "${mongodHackedArgs[@]}"
		shouldPerformInitdb='true'
	elif [ "$MONGO_INITDB_ROOT_USERNAME" ] || [ "$MONGO_INITDB_ROOT_PASSWORD" ]; then
		cat >&2 <<-'EOF'

			error: missing 'MONGO_INITDB_ROOT_USERNAME' or 'MONGO_INITDB_ROOT_PASSWORD'
			       both must be specified for a user to be created

		EOF
		exit 1
	fi

	if [ -z "$shouldPerformInitdb" ]; then
		# if we've got any /docker-entrypoint-initdb.d/* files to parse later, we should initdb
		for f in /docker-entrypoint-initdb.d/*; do
			case "$f" in
				*.sh|*.js) # this should match the set of files we check for below
					shouldPerformInitdb="$f"
					break
					;;
			esac
		done
	fi

	# check for a few known paths (to determine whether we've already initialized and should thus skip our initdb scripts)
	if [ -n "$shouldPerformInitdb" ]; then
		dbPath="$(_dbPath "$@")"
		for path in \
			"$dbPath/WiredTiger" \
			"$dbPath/journal" \
			"$dbPath/local.0" \
			"$dbPath/storage.bson" \
		; do
			if [ -e "$path" ]; then
				shouldPerformInitdb=
				break
			fi
		done
	fi

	if [ -n "$shouldPerformInitdb" ]; then
		mongodHackedArgs=( "$@" )
		if _parse_config "$@"; then
			_mongod_hack_ensure_arg_val --config "$tempConfigFile" "${mongodHackedArgs[@]}"
		fi
		_mongod_hack_ensure_arg_val --bind_ip 127.0.0.1 "${mongodHackedArgs[@]}"
		_mongod_hack_ensure_arg_val --port 27017 "${mongodHackedArgs[@]}"
		_mongod_hack_ensure_no_arg --bind_ip_all "${mongodHackedArgs[@]}"

		# remove "--auth" and "--replSet" for our initial startup (see https://docs.mongodb.com/manual/tutorial/enable-authentication/#start-mongodb-without-access-control)
		# https://github.com/docker-library/mongo/issues/211
		_mongod_hack_ensure_no_arg --auth "${mongodHackedArgs[@]}"
		# "keyFile implies security.authorization"
		# https://docs.mongodb.com/manual/reference/configuration-options/#mongodb-setting-security.keyFile
		_mongod_hack_ensure_no_arg_val --keyFile "${mongodHackedArgs[@]}"
		if [ "$MONGO_INITDB_ROOT_USERNAME" ] && [ "$MONGO_INITDB_ROOT_PASSWORD" ]; then
			_mongod_hack_ensure_no_arg_val --replSet "${mongodHackedArgs[@]}"
		fi

		# "BadValue: need sslPEMKeyFile when SSL is enabled" vs "BadValue: need to enable SSL via the sslMode flag when using SSL configuration parameters"
		tlsMode='disabled'
		if _mongod_hack_have_arg '--tlsCertificateKeyFile' "$@"; then
			tlsMode='allowTLS'
		elif _mongod_hack_have_arg '--sslPEMKeyFile' "$@"; then
			tlsMode='allowSSL'
		fi
		# 4.2 switched all configuration/flag names from "SSL" to "TLS"
		if [ "$tlsMode" = 'allowTLS' ] || mongod --help 2>&1 | grep -q -- ' --tlsMode '; then
			_mongod_hack_ensure_arg_val --tlsMode "$tlsMode" "${mongodHackedArgs[@]}"
		else
			_mongod_hack_ensure_arg_val --sslMode "$tlsMode" "${mongodHackedArgs[@]}"
		fi

		if stat "/proc/$$/fd/1" > /dev/null && [ -w "/proc/$$/fd/1" ]; then
			# https://github.com/mongodb/mongo/blob/38c0eb538d0fd390c6cb9ce9ae9894153f6e8ef5/src/mongo/db/initialize_server_global_state.cpp#L237-L251
			# https://github.com/docker-library/mongo/issues/164#issuecomment-293965668
			_mongod_hack_ensure_arg_val --logpath "/proc/$$/fd/1" "${mongodHackedArgs[@]}"
		else
			initdbLogPath="$(_dbPath "$@")/docker-initdb.log"
			echo >&2 "warning: initdb logs cannot write to '/proc/$$/fd/1', so they are in '$initdbLogPath' instead"
			_mongod_hack_ensure_arg_val --logpath "$initdbLogPath" "${mongodHackedArgs[@]}"
		fi
		_mongod_hack_ensure_arg --logappend "${mongodHackedArgs[@]}"

		pidfile="$TMPDIR/docker-entrypoint-temp-mongod.pid"
		rm -f "$pidfile"
		_mongod_hack_ensure_arg_val --pidfilepath "$pidfile" "${mongodHackedArgs[@]}"

		"${mongodHackedArgs[@]}" --fork

		mongo=( "$mongoShell" --host 127.0.0.1 --port 27017 --quiet )

		# check to see that our "mongod" actually did start up (catches "--help", "--version", MongoDB 3.2 being silly, slow prealloc, etc)
		# https://jira.mongodb.org/browse/SERVER-16292
		tries=30
		while true; do
			if ! { [ -s "$pidfile" ] && ps "$(< "$pidfile")" &> /dev/null; }; then
				# bail ASAP if "mongod" isn't even running
				echo >&2
				echo >&2 "error: $originalArgOne does not appear to have stayed running -- perhaps it had an error?"
				echo >&2
				exit 1
			fi
			if "${mongo[@]}" 'admin' --eval 'quit(0)' &> /dev/null; then
				# success!
				break
			fi
			(( tries-- ))
			if [ "$tries" -le 0 ]; then
				echo >&2
				echo >&2 "error: $originalArgOne does not appear to have accepted connections quickly enough -- perhaps it had an error?"
				echo >&2
				exit 1
			fi
			sleep 1
		done

		if [ "$MONGO_INITDB_ROOT_USERNAME" ] && [ "$MONGO_INITDB_ROOT_PASSWORD" ]; then
			rootAuthDatabase='admin'

			"${mongo[@]}" "$rootAuthDatabase" <<-EOJS
				db.createUser({
					user: $(_js_escape "$MONGO_INITDB_ROOT_USERNAME"),
					pwd: $(_js_escape "$MONGO_INITDB_ROOT_PASSWORD"),
					roles: [ { role: 'root', db: $(_js_escape "$rootAuthDatabase") } ]
				})
			EOJS
		fi

		export MONGO_INITDB_DATABASE="${MONGO_INITDB_DATABASE:-test}"

		echo
		for f in /docker-entrypoint-initdb.d/*; do
			case "$f" in
				*.sh) echo "$0: running $f"; . "$f" ;;
				*.js) echo "$0: running $f"; "${mongo[@]}" "$MONGO_INITDB_DATABASE" "$f"; echo ;;
				*)    echo "$0: ignoring $f" ;;
			esac
			echo
		done

		"${mongodHackedArgs[@]}" --shutdown
		rm -f "$pidfile"

		echo
		echo 'MongoDB init process complete; ready for start up.'
		echo
	fi

	# MongoDB 3.6+ defaults to localhost-only binding
	haveBindIp=
	if _mongod_hack_have_arg --bind_ip "$@" || _mongod_hack_have_arg --bind_ip_all "$@"; then
		haveBindIp=1
	elif _parse_config "$@" && jq --exit-status '.net.bindIp // .net.bindIpAll' "$jsonConfigFile" > /dev/null; then
		haveBindIp=1
	fi
	if [ -z "$haveBindIp" ]; then
		# so if no "--bind_ip" is specified, let's add "--bind_ip_all"
		set -- "$@" --bind_ip_all
	fi

	unset "${!MONGO_INITDB_@}"
fi

rm -f "$jsonConfigFile" "$tempConfigFile"

exec "$@"


text:
package com.team09.qanda.esearch;

/**
 *
 * This class is used to obtain information from the elasticsearch server.
 * It is not used in the context of the application other than to store
 * the result of queries to the server.
 *
 */
public class ESResults {
	private int took;
	private boolean timed_out;
	private Shards _shards;
	private ESResultList hits;

	public void setTook(int took) {
		this.took = took;
	}
	public void setHits(ESResultList hits) {
		this.hits = hits;
	}

	public int getTook() {
		return took;
	}
	public ESResultList getHits() {
		return hits;
	}
}


text:
package nuxt;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.*;

public class app {
    private ApplicationContext ctx = null;
    private JdbcTemplate template = null;
    {
        ctx = new ClassPathXmlApplicationContext("nuxt.xml");
        template = ctx.getBean(JdbcTemplate.class);
    }

    @Test
    public void testArticles () {

        List<Object[]> data = new ArrayList<>();
        Date date = new Date();
        for (int i = 0; i < 500; i++) {
            String uuid = UUID.randomUUID().toString();
            Object[] objects = new Object[]{uuid.substring(0, 10), uuid, date, i % 2 == 0 ? 1 : 2};
            data.add(objects);
        }
        String sql = "insert into article (title, content, date, userId) values (?, ?, ?, ?)";
        template.batchUpdate(sql, data);
//        System.out.println(template.getDataSource());
    }

    @Test
    public void testUpdateDate () {
        String sql = "update article set date = ?";
        List<Object[]> data = new ArrayList<>();
        for (int i = 0; i < 500; i++) {
            data.add(new Object[]{new Date()});
        }
        template.batchUpdate(sql, data);
    }
}


text:
@interface LEOCameraPickerController ()
{
    LEOUploadToolBar *_uploadToolBar;
    NSString *_uploadPath;
    UIImageView *_previewImageView;
    NSDictionary *_info;
    UIImageView *_navImage;

    BOOL isLoad;
    MBProgressHUD *_hub;
}
@end

@implementation LEOCameraPickerController
@synthesize delegate;
@synthesize uploadPath=_uploadPath;
//-(id)init
//{
//    self=[super init];
//    if (self) {
//
//    }
//    return self;
//}

- (void)viewDidLoad
{
    [super viewDidLoad];
    UIImage *stretchImage=[UIImage imageNamed:kNavigationBg];
    stretchImage=[stretchImage stretchableImageWithLeftCapWidth:1 topCapHeight:0];
	[self.navigationController.navigationBar setBackgroundImage:stretchImage forBarMetrics:UIBarMetricsDefault];

    self.view.backgroundColor=[UIColor colorWithRed:kBackgroundColorR green:kBackgroundColorG blue:kBackgroundColorB alpha:kBackgroundColorA];

    CGRect rect=self.view.frame;
//    UIImage *stretchImage=[UIImage imageNamed:kNavigationBg];
//    stretchImage=[stretchImage stretchableImageWithLeftCapWidth:1 topCapHeight:0];
//    rect.size.height=kLEONavBarHeight;
//    rect.origin.y=0;
//    _navImage=[[UIImageView alloc] initWithFrame:rect];
//    [_navImage setImage:stretchImage];
//    [self.view addSubview:_navImage];

    UIButton *cancelButtonView=[UIButton buttonWithType:UIButtonTypeCustom];
    cancelButtonView.frame=CGRectMake(0,kLEONavBarBtnTopY,kDefalutNavItemWidth,kLEONavBarBtnHeight);
    [cancelButtonView setTitle:NSLocalizedString(@"Cancel", @"") forState:UIControlStateNormal];
    [cancelButtonView setBackgroundImage:[UIImage imageNamed:kNavigationEditBg] forState:UIControlStateNormal];
    [cancelButtonView setBackgroundImage:[UIImage imageNamed:kNavigationEditBgHighlight] forState:UIControlStateHighlighted];
    [cancelButtonView.titleLabel setFont:[UIFont systemFontOfSize:kLEONavBarFontSz]];
    [cancelButtonView addTarget:self action:@selector(cancelChoose) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightButton=[[[UIBarButtonItem alloc] initWithCustomView:cancelButtonView] autorelease];
    self.navigationItem.rightBarButtonItem=rightButton;
//    [self.view addSubview:cancelButtonView];

    rect.size.height-=kLEOTabBarHeight+kLEONavBarHeight;
    rect.origin.y=0;
    _previewImageView=[[UIImageView alloc] initWithFrame:rect];
    _previewImageView.contentMode=UIViewContentModeScaleAspectFit;
    [self.view addSubview:_previewImageView];

    _uploadToolBar=[[LEOUploadToolBar alloc] init];
    _uploadToolBar.delegate=self;
    rect=_uploadToolBar.frame;
    rect.origin.y-=kLEONavBarHeight+kLEOStatusBarHeight;
    _uploadToolBar.frame=rect;
    [self.view addSubview:_uploadToolBar];
    [self setUploadPath:@"/"];

    isLoad=NO;
}

-(void)viewDidAppear:(BOOL)animated
{
    if (isLoad==NO) {
        // 载入
        [self showCameraPreview];
        isLoad=YES;
    }else{
        // do nothing
    }
}

-(void)dealloc
{
    [_uploadToolBar release];
    if (_uploadPath!=nil) {
        [_uploadPath release];
        _uploadPath=nil;
    }
    [super dealloc];
}

-(void)setPreviewImage:(UIImage *)image
{
    [_previewImageView setImage:image];
}

#pragma mark - Private
-(void)cancelChoose
{
    if (self.delegate!=nil && [self.delegate respondsToSelector:@selector(leoCameraPickerControllerDidCancel:)]) {
        [self.delegate leoCameraPickerControllerDidCancel:self];
    }
}

-(void)showCameraPreview
{
    UIImagePickerController *picker=[[UIImagePickerController alloc] init];
    picker.delegate=self;
    picker.navigationBarHidden=YES;
    picker.wantsFullScreenLayout=NO;
    picker.sourceType=UIImagePickerControllerSourceTypeCamera;
    [self presentModalViewController:picker animated:YES];
    [picker release];
}

-(void)setupProgressHD:(NSString *)text isDone:(BOOL)done
{
    if (_hub) {
        [_hub hide:NO];
        [_hub release];
        _hub=nil;
    }
    _hub=[[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:_hub];
    _hub.delegate=self;
    _hub.labelText=text;
    _hub.customView=[[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"/res/Checkmark.png"]] autorelease];
    _hub.mode=done?MBProgressHUDModeCustomView:MBProgressHUDModeIndeterminate;
    _hub.removeFromSuperViewOnHide=YES;
    [_hub show:NO];
    if (done) {
        [_hub hide:NO afterDelay:1.5];
    }
}

#pragma mark - UploadToolBar delegate
-(void)chooseButton:(id)sender
{
    LEOChoosePathViewController *chooseVC=[[LEOChoosePathViewController alloc] initWithPath:nil];
    chooseVC.parent=self;
    UINavigationController *navChooseVC=[[UINavigationController alloc] initWithRootViewController:chooseVC];
    [self presentViewController:navChooseVC animated:YES completion:nil];
    [chooseVC release];
    [navChooseVC release];
}

-(void)uploadButton:(id)sender
{
//    [self setupProgressHD:NSLocalizedString(@"Progressing...", @"") isDone:NO];
    if (self.delegate!=nil && [self.delegate respondsToSelector:@selector(leoCameraPickerController:didFinishPickingPictureWithInfo:andPath:)]) {
//        [self.delegate performSelector:@selector(leoCameraPickerController:didFinishPickingPictureWithInfo:andPath:) withObject:_info withObject:_uploadPath];
        [self.delegate leoCameraPickerController:self didFinishPickingPictureWithInfo:_info andPath:_uploadPath];
    }
//    if(_hub!=nil) {
//        [_hub hide:NO];
//        [_hub release];
//        _hub=nil;
//    }
}

-(void)setUploadPath:(NSString *)path
{
    if (_uploadPath) {
        [_uploadPath release];
        _uploadPath=nil;
    }
    _uploadPath=[[NSString alloc] initWithFormat:@"%@",path];
    [_uploadToolBar setDisplayPath:_uploadPath];
    NSLog(@"_uploadPath:%@",_uploadPath);
}

#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [picker dismissModalViewControllerAnimated:NO];
    _info=[info copy];
    _previewImageView.image=[info objectForKey:UIImagePickerControllerOriginalImage];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissModalViewControllerAnimated:NO];
    if (self.delegate!=nil && [self.delegate respondsToSelector:@selector(leoCameraPickerControllerDidCancel:)]) {
        [self.delegate leoCameraPickerControllerDidCancel:self];
    }
}
@end


text:
package net.ymate.platform.webmvc.context;

import net.ymate.platform.webmvc.base.Type;

import javax.servlet.jsp.PageContext;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.Set;

/**
 * @author 刘镇 (suninformation@163.com) on 2011-7-24 下午10:31:48
 */
@SuppressWarnings("rawtypes")
public class AttributeMap implements Map {

    private static final String UNSUPPORTED = "method makes no sense for a simplified map";

    private final Map context;

    public AttributeMap(Map context) {
        this.context = context;
    }

    @Override
    public boolean isEmpty() {
        throw new UnsupportedOperationException(UNSUPPORTED);
    }

    @Override
    public void clear() {
        throw new UnsupportedOperationException(UNSUPPORTED);
    }

    @Override
    public boolean containsKey(Object key) {
        return (get(key) != null);
    }

    @Override
    public boolean containsValue(Object value) {
        throw new UnsupportedOperationException(UNSUPPORTED);
    }

    @Override
    public Set entrySet() {
        return Collections.emptySet();
    }

    @Override
    public Object get(Object key) {
        PageContext pc = getPageContext();
        if (pc == null) {
            Map request = (Map) context.get("request");
            Map session = (Map) context.get("session");
            Map application = (Map) context.get("application");
            if ((request != null) && (request.get(key) != null)) {
                return request.get(key);
            } else if ((session != null) && (session.get(key) != null)) {
                return session.get(key);
            } else if ((application != null) && (application.get(key) != null)) {
                return application.get(key);
            }
        } else {
            try {
                return pc.findAttribute(key.toString());
            } catch (NullPointerException npe) {
                return null;
            }
        }
        return null;
    }

    @Override
    public Set keySet() {
        return Collections.EMPTY_SET;
    }

    @Override
    public Object put(Object key, Object value) {
        PageContext pc = getPageContext();
        if (pc != null) {
            pc.setAttribute(key.toString(), value);
        }
        return null;
    }

    @Override
    public void putAll(Map t) {
        throw new UnsupportedOperationException(UNSUPPORTED);
    }

    @Override
    public Object remove(Object key) {
        throw new UnsupportedOperationException(UNSUPPORTED);
    }

    @Override
    public int size() {
        throw new UnsupportedOperationException(UNSUPPORTED);
    }

    @Override
    public Collection values() {
        return Collections.EMPTY_SET;
    }

    private PageContext getPageContext() {
        return (PageContext) context.get(Type.Context.PAGE_CONTEXT);
    }
}


text:
import Ember from 'ember';
import ModalMixin from '../../utils/modal-mixin';

export default Ember.Component.extend(ModalMixin, {
  // To be injected.
  themes: [],
  themeName: null,
  titleTranslation: null,

  classNames: ['theme-modal'],

  displayedThemes: Ember.computed('themes', 'themeName', function() {
    var themeName = this.get('themeName');
    return this.get('themes').map(function(theme) {
      return {
        name: theme.name,
        value: theme.value,
        isSelected: theme.name === themeName
      };
    });
  }),

  actions: {
    setTheme(themeName) {
      this.set('themeName', themeName);
      console.log('Set theme to: %s', this.get('themeName'));
    }
  }
});


text:
@interface SMCLocationDemoTests : XCTestCase

@end

@implementation SMCLocationDemoTests

- (void)setUp {
    [super setUp];
    // Put setup code here. This method is called before the invocation of each test method in the class.
}

- (void)tearDown {
    // Put teardown code here. This method is called after the invocation of each test method in the class.
    [super tearDown];
}

- (void)testExample {
    // This is an example of a functional test case.
    // Use XCTAssert and related functions to verify your tests produce the correct results.

}

- (void)testAddMLogRun {
    RLMRealm *realm = [RLMRealm defaultRealm];

    MLogRun* log = [MLogRun new];
    [realm transactionWithBlock:^{
        [realm addObject:log];
    }];
}

- (void)testReadMLogRun {
    RLMResults *logs = [MLogRun allObjects];
    NSLog(@"count = %ld", logs.count);
}

- (void)testPerformanceExample {
    // This is an example of a performance test case.
    [self measureBlock:^{
        // Put the code you want to measure the time of here.
    }];
}

@end


text:
import cherrypy
import types

from server.utils import negotiateFormat, listutils

htmlHead = "<!DOCTYPE html>"

# Return format map.  Browsers don't understand some of the fancier types
return_map = {'txt': 'text/plain',
              'html': 'text/html',
              'htm': 'text/html',
              'xhtml': 'application/xhtml+xml',
              'xml': 'application/rdf+xml',
              'pretty-xml': 'application/rdf+xml',
              'json': 'application/rdf+xml',
              'trix': 'application/rdf+xml',
              'n3': 'text/plain',
              'nquads': 'text/plain',
              'turtle': 'text/plain',
              'nt': 'text/plain',}

def expose(arg1=None, arg2=None):
    """ Expose the wrapped function as a web service
    :param arg1: Either a function or the "self" parameter for a class method or a set of allowable methods
    :param arg2: allowable methods if arg1 is "self"
    :return: normalized function wrapper
    """

    def expose_(func_):

        @cherrypy.tools.allow(methods=arg2)
        @cherrypy.expose
        def wrapped_f(self, *args, format=None, **kwargs):

            if not format:
                format = negotiateFormat.negotiate_format(self.formats, cherrypy.request.headers)

            # Function can return one of:
            # formatted string           - to be returned directly to the caller, unformatted
            # class                      - assumed to have a toxml() function
            # tuple                      - tuple of (rval, (error code, error message))
            #                               rval is string or class as above
            rtn = func_(self, *args, format=format, **kwargs)

            rval, (err, msg) = rtn if isinstance(rtn, (list, tuple)) else (rtn, (500, 'Internal Server Error'))
            if not rval:
                raise cherrypy.HTTPError(err, str(msg))
            if rval.startswith(htmlHead):
                return rval
            cherrypy.response.headers['Content-type'] = return_map.get(format, 'text/plain') + ';charset=UTF-8'
            return rval

        return wrapped_f

    # This can be invoked within a class, meaning that the first argument (
    if isinstance(arg1, (types.FunctionType, types.MethodType)):
        return expose_(arg1)
    elif arg1 is not None:
        arg2 = arg1
    return expose_


text:
import sbt._
import Keys._

object MustacheBuild extends Build {

  override lazy val settings = super.settings :+
    (shellPrompt := { s => Project.extract(s).currentProject.id + "> " })

  lazy val stdSettings = Defaults.defaultSettings ++ Seq(
    scalaVersion := "2.10.1",
    exportJars := true,
    libraryDependencies ++= Dependencies.deps,
    resolvers ++= Resolvers.res,
    scalacOptions ++= Seq("-unchecked", "-deprecation", "-language:postfixOps", "-language:implicitConversions")
  )

  lazy val main = Project(
    id          = "placeHldr",
    base  	= file("."),
    settings    = stdSettings ++ Seq(MustacheTasks.distTask)
  )

  object Dependencies {
    lazy val deps = Seq(play, scalate, commonsIO)
    lazy val play      = "play" %% "play" % "2.1.1"
    lazy val scalate   = "org.fusesource.scalate" %% "scalate-core" % "1.6.1"
    lazy val commonsIO = "org.apache.commons" % "commons-io" % "1.3.2"
  }

  object Resolvers {
    lazy val res = Seq(typesafeRepo)
    lazy val typesafeRepo = "TypeSafe Repo" at "http://repo.typesafe.com/typesafe/releases"
  }

}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="generator" content="rustdoc">
    <meta name="description" content="API documentation for the Rust `RustcOptGroup` struct in crate `rustc_trans`.">
    <meta name="keywords" content="rust, rustlang, rust-lang, RustcOptGroup">

    <title>rustc_trans::session::config::RustcOptGroup - Rust</title>

    <link rel="stylesheet" type="text/css" href="../../../main.css">

    <link rel="shortcut icon" href="http://www.rust-lang.org/favicon.ico">

rustc_trans::<wbr>session::<wbr>config

        <form class="search-form js-only">

                <input class="search-input" name="search"
                       autocomplete="off"
                       placeholder="Click or press 'S' to search, '?' for more options..."
                       type="search">

        </form>

Struct rustc_trans::<wbr>session::<wbr>config::<wbr>RustcOptGroup<wbr>Unstable
            [-] [+]
        [src]

pub struct RustcOptGroup {
    pub opt_group: OptGroup,
    pub stability: OptionStability,
}

Fields

opt_group

stability

Methods

impl RustcOptGroup

fn is_stable(&self) -> bool

Trait Implementations

Derived Implementations

impl Eq for RustcOptGroup

fn assert_receiver_is_total_eq(&self)

impl PartialEq<RustcOptGroup> for RustcOptGroup

fn eq(&self, __arg_0: &RustcOptGroup) -> bool

fn ne(&self, __arg_0: &RustcOptGroup) -> bool

impl Clone for RustcOptGroup

fn clone(&self) -> RustcOptGroup

fn clone_from(&mut self, source: &Self)

Keyboard shortcuts

?

Show this help dialog

S

Focus the search field

⇤

Move up in search results

⇥

Move down in search results

⏎

Go to active search result

Search tricks

                Prefix searches with a type followed by a colon (e.g.
                fn:) to restrict the search to a given type.

                Accepted types are: fn, mod,
                struct, enum,
                trait, typedef (or
                tdef).


text:
package engine

import (
	"context"
	"fmt"
	"sort"

	"vitess.io/vitess/go/vt/vtgate/evalengine"

	topodatapb "vitess.io/vitess/go/vt/proto/topodata"

	"vitess.io/vitess/go/sqltypes"
	"vitess.io/vitess/go/vt/srvtopo"
	"vitess.io/vitess/go/vt/vtgate/vindexes"

	querypb "vitess.io/vitess/go/vt/proto/query"
)

var _ Primitive = (*Update)(nil)

// VindexValues contains changed values for a vindex.
type VindexValues struct {
	PvMap  map[string]evalengine.Expr
	Offset int // Offset from ownedVindexQuery to provide input decision for vindex update.
}

// Update represents the instructions to perform an update.
type Update struct {
	*DML

	// ChangedVindexValues contains values for updated Vindexes during an update statement.
	ChangedVindexValues map[string]*VindexValues

	// Update does not take inputs
	noInputs
}

// TryExecute performs a non-streaming exec.
func (upd *Update) TryExecute(ctx context.Context, vcursor VCursor, bindVars map[string]*querypb.BindVariable, wantfields bool) (*sqltypes.Result, error) {
	ctx, cancelFunc := addQueryTimeout(ctx, vcursor, upd.QueryTimeout)
	defer cancelFunc()

	rss, _, err := upd.findRoute(ctx, vcursor, bindVars)
	if err != nil {
		return nil, err
	}
	err = allowOnlyPrimary(rss...)
	if err != nil {
		return nil, err
	}

	switch upd.Opcode {
	case Unsharded:
		return upd.execUnsharded(ctx, vcursor, bindVars, rss)
	case Equal, EqualUnique, IN, Scatter, ByDestination, SubShard, MultiEqual:
		return upd.execMultiDestination(ctx, vcursor, bindVars, rss, upd.updateVindexEntries)
	default:
		// Unreachable.
		return nil, fmt.Errorf("unsupported opcode: %v", upd.Opcode)
	}
}

// TryStreamExecute performs a streaming exec.
func (upd *Update) TryStreamExecute(ctx context.Context, vcursor VCursor, bindVars map[string]*querypb.BindVariable, wantfields bool, callback func(*sqltypes.Result) error) error {
	res, err := upd.TryExecute(ctx, vcursor, bindVars, wantfields)
	if err != nil {
		return err
	}
	return callback(res)

}

// GetFields fetches the field info.
func (upd *Update) GetFields(ctx context.Context, vcursor VCursor, bindVars map[string]*querypb.BindVariable) (*sqltypes.Result, error) {
	return nil, fmt.Errorf("BUG: unreachable code for %q", upd.Query)
}

// updateVindexEntries performs an update when a vindex is being modified
// by the statement.
// Note: the commit order may be different from the DML order because it's possible
// for DMLs to reuse existing transactions.
// Note 2: While changes are being committed, the changing row could be
// unreachable by either the new or old column values.
func (upd *Update) updateVindexEntries(ctx context.Context, vcursor VCursor, bindVars map[string]*querypb.BindVariable, rss []*srvtopo.ResolvedShard) error {
	if len(upd.ChangedVindexValues) == 0 {
		return nil
	}
	queries := make([]*querypb.BoundQuery, len(rss))
	for i := range rss {
		queries[i] = &querypb.BoundQuery{Sql: upd.OwnedVindexQuery, BindVariables: bindVars}
	}
	subQueryResult, errors := vcursor.ExecuteMultiShard(ctx, rss, queries, false /* rollbackOnError */, false /* canAutocommit */)
	for _, err := range errors {
		if err != nil {
			return err
		}
	}

	if len(subQueryResult.Rows) == 0 {
		return nil
	}

	fieldColNumMap := make(map[string]int)
	for colNum, field := range subQueryResult.Fields {
		fieldColNumMap[field.Name] = colNum
	}
	env := evalengine.EnvWithBindVars(bindVars, vcursor.ConnCollation())

	for _, row := range subQueryResult.Rows {
		ksid, err := resolveKeyspaceID(ctx, vcursor, upd.KsidVindex, row[0:upd.KsidLength])
		if err != nil {
			return err
		}

		vindexTable, err := upd.GetSingleTable()
		if err != nil {
			return err
		}
		for _, colVindex := range vindexTable.ColumnVindexes {
			// Skip this vindex if no rows are being changed
			updColValues, ok := upd.ChangedVindexValues[colVindex.Name]
			if !ok {
				continue
			}

			offset := updColValues.Offset
			if !row[offset].IsNull() {
				val, err := evalengine.ToInt64(row[offset])
				if err != nil {
					return err
				}
				if val == int64(1) { // 1 means that the old and new value are same and vindex update is not required.
					continue
				}
			}

			fromIds := make([]sqltypes.Value, 0, len(colVindex.Columns))
			var vindexColumnKeys []sqltypes.Value
			for _, vCol := range colVindex.Columns {
				// Fetch the column values.
				origColValue := row[fieldColNumMap[vCol.String()]]
				fromIds = append(fromIds, origColValue)
				if colValue, exists := updColValues.PvMap[vCol.String()]; exists {
					resolvedVal, err := env.Evaluate(colValue)
					if err != nil {
						return err
					}
					vindexColumnKeys = append(vindexColumnKeys, resolvedVal.Value())
				} else {
					// Set the column value to original as this column in vindex is not updated.
					vindexColumnKeys = append(vindexColumnKeys, origColValue)
				}
			}

			if colVindex.Owned {
				if err := colVindex.Vindex.(vindexes.Lookup).Update(ctx, vcursor, fromIds, ksid, vindexColumnKeys); err != nil {
					return err
				}
			} else {
				allNulls := true
				for _, key := range vindexColumnKeys {
					allNulls = key.IsNull()
					if !allNulls {
						break
					}
				}

				// All columns for this Vindex are set to null, so we can skip verification
				if allNulls {
					continue
				}

				// If values were supplied, we validate against keyspace id.
				verified, err := vindexes.Verify(ctx, colVindex.Vindex, vcursor, [][]sqltypes.Value{vindexColumnKeys}, [][]byte{ksid})
				if err != nil {
					return err
				}

				if !verified[0] {
					return fmt.Errorf("values %v for column %v does not map to keyspace ids", vindexColumnKeys, colVindex.Columns)
				}
			}
		}
	}
	return nil
}

func (upd *Update) description() PrimitiveDescription {
	other := map[string]any{
		"Query":                upd.Query,
		"Table":                upd.GetTableName(),
		"OwnedVindexQuery":     upd.OwnedVindexQuery,
		"MultiShardAutocommit": upd.MultiShardAutocommit,
		"QueryTimeout":         upd.QueryTimeout,
	}

	addFieldsIfNotEmpty(upd.DML, other)

	var changedVindexes []string
	for k, v := range upd.ChangedVindexValues {
		changedVindexes = append(changedVindexes, fmt.Sprintf("%s:%d", k, v.Offset))
	}
	sort.Strings(changedVindexes) // We sort these so random changes in the map order does not affect output
	if len(changedVindexes) > 0 {
		other["ChangedVindexValues"] = changedVindexes
	}

	return PrimitiveDescription{
		OperatorType:     "Update",
		Keyspace:         upd.Keyspace,
		Variant:          upd.Opcode.String(),
		TargetTabletType: topodatapb.TabletType_PRIMARY,
		Other:            other,
	}
}


text:
package org.drools.scenariosimulation.backend.util;

import java.util.List;
import java.util.Map;
import java.util.Objects;

import org.drools.scenariosimulation.backend.interfaces.ThrowingConsumer;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;

import static org.drools.scenariosimulation.api.utils.ConstantsHolder.BACKGROUND_DATA_NODE;
import static org.drools.scenariosimulation.api.utils.ConstantsHolder.BACKGROUND_NODE;
import static org.drools.scenariosimulation.api.utils.ConstantsHolder.DMO_SESSION_NODE;
import static org.drools.scenariosimulation.api.utils.ConstantsHolder.EXPRESSION_ELEMENTS_NODE;
import static org.drools.scenariosimulation.api.utils.ConstantsHolder.EXPRESSION_IDENTIFIER_NODE;
import static org.drools.scenariosimulation.api.utils.ConstantsHolder.FACT_IDENTIFIER_NODE;
import static org.drools.scenariosimulation.api.utils.ConstantsHolder.FACT_MAPPINGS_NODE;
import static org.drools.scenariosimulation.api.utils.ConstantsHolder.FACT_MAPPING_NODE;
import static org.drools.scenariosimulation.api.utils.ConstantsHolder.FACT_MAPPING_VALUES_NODE;
import static org.drools.scenariosimulation.api.utils.ConstantsHolder.FACT_MAPPING_VALUE_NODE;
import static org.drools.scenariosimulation.api.utils.ConstantsHolder.FACT_MAPPING_VALUE_TYPE_NODE;
import static org.drools.scenariosimulation.api.utils.ConstantsHolder.NOT_EXPRESSION;
import static org.drools.scenariosimulation.api.utils.ConstantsHolder.SCENARIO_SIMULATION_MODEL_NODE;
import static org.drools.scenariosimulation.api.utils.ConstantsHolder.SETTINGS;
import static org.drools.scenariosimulation.api.utils.ConstantsHolder.SETTINGS_NODE;
import static org.drools.scenariosimulation.api.utils.ConstantsHolder.SIMULATION_DESCRIPTOR_NODE;
import static org.drools.scenariosimulation.api.utils.ConstantsHolder.SIMULATION_NODE;
import static org.drools.scenariosimulation.backend.util.ScenarioSimulationXMLPersistence.getColumnWidth;

public class InMemoryMigrationStrategy implements MigrationStrategy {

    @Override
    public ThrowingConsumer<Document> from1_0to1_1() {
        return document -> {
            DOMParserUtil.replaceNodeText(document, EXPRESSION_IDENTIFIER_NODE, "type", "EXPECTED", "EXPECT");
            updateVersion(document, "1.1");
        };
    }

    @Override
    public ThrowingConsumer<Document> from1_1to1_2() {
        return document -> {
            Map<Node, List<Node>> dmoSessionNodesMap = DOMParserUtil.getNestedChildrenNodesMap(document, SIMULATION_NODE, SIMULATION_DESCRIPTOR_NODE, DMO_SESSION_NODE);
            Map<Node, List<Node>> dmnFilePathNodesMap = DOMParserUtil.getNestedChildrenNodesMap(document, SIMULATION_NODE, SIMULATION_DESCRIPTOR_NODE, "dmnFilePath");
            Map<Node, List<Node>> typeNodesMap = DOMParserUtil.getNestedChildrenNodesMap(document, SIMULATION_NODE, SIMULATION_DESCRIPTOR_NODE, "type");
            List<Node> dmoSessionNodes = dmoSessionNodesMap.values().iterator().next();
            List<Node> dmnFilePathNodes = dmnFilePathNodesMap.values().iterator().next();
            List<Node> typeNodes = typeNodesMap.values().iterator().next();
            if (!dmoSessionNodes.isEmpty() || (!dmnFilePathNodes.isEmpty() && !typeNodes.isEmpty())) {
                //
            } else {
                DOMParserUtil.createNestedNodes(document, SIMULATION_NODE, SIMULATION_DESCRIPTOR_NODE, DMO_SESSION_NODE, null);
                DOMParserUtil.createNestedNodes(document, SIMULATION_NODE, SIMULATION_DESCRIPTOR_NODE, "type", "RULE");
            }
            updateVersion(document, "1.2");
        };
    }

    @Override
    public ThrowingConsumer<Document> from1_2to1_3() {
        return document -> {
            List<Node> factMappingsNodes = DOMParserUtil.getNestedChildrenNodesList(document, SIMULATION_NODE, SIMULATION_DESCRIPTOR_NODE, FACT_MAPPINGS_NODE);
            Node factMappingsNode = factMappingsNodes.get(0);
            final List<Node> factIdentifierNodeList = DOMParserUtil.getNestedChildrenNodesList(factMappingsNode, FACT_MAPPING_NODE, FACT_IDENTIFIER_NODE);
            factIdentifierNodeList.forEach(factIdentifierNode -> {
                List<Node> factIdentifierNameList = DOMParserUtil.getChildrenNodesList(factIdentifierNode, "name");
                if (!factIdentifierNameList.isEmpty()) {
                    String factIdentifierName = factIdentifierNameList.get(0).getTextContent();
                    Node factMappingNode = factIdentifierNode.getParentNode();
                    List<Node> expressionElementsNodeList = DOMParserUtil.getChildrenNodesList(factMappingNode, "expressionElements");
                    Node expressionElementsNode;
                    if (expressionElementsNodeList.isEmpty()) {
                        expressionElementsNode = DOMParserUtil.createNodeAtPosition(factMappingNode, "expressionElements", null, 0);
                    } else {
                        expressionElementsNode = expressionElementsNodeList.get(0);
                    }
                    Node expressionElementNode = DOMParserUtil.createNodeAtPosition(expressionElementsNode, "ExpressionElement", null, 0);
                    DOMParserUtil.createNodeAtPosition(expressionElementNode, "step", factIdentifierName, 0);
                }
            });
            updateVersion(document, "1.3");
        };
    }

    @Override
    public ThrowingConsumer<Document> from1_3to1_4() {
        return document -> {
            List<Node> typeNodes = DOMParserUtil.getNestedChildrenNodesList(document, SIMULATION_NODE, SIMULATION_DESCRIPTOR_NODE, "type");
            if (!typeNodes.isEmpty()) {
                Node typeNode = typeNodes.get(0);
                Node simulationDescriptorNode = typeNode.getParentNode();
                String defaultContent = "default";
                switch (typeNode.getTextContent()) {
                    case "RULE":
                        if (DOMParserUtil.getChildrenNodesList(simulationDescriptorNode, "kieSession").isEmpty()) {
                            DOMParserUtil.createNodeAtPosition(simulationDescriptorNode, "kieSession", defaultContent, null);
                        }
                        if (DOMParserUtil.getChildrenNodesList(simulationDescriptorNode, "kieBase").isEmpty()) {
                            DOMParserUtil.createNodeAtPosition(simulationDescriptorNode, "kieBase", defaultContent, null);
                        }
                        if (DOMParserUtil.getChildrenNodesList(simulationDescriptorNode, "ruleFlowGroup").isEmpty()) {
                            DOMParserUtil.createNodeAtPosition(simulationDescriptorNode, "ruleFlowGroup", defaultContent, null);
                        }
                        break;
                    case "DMN":
                        if (DOMParserUtil.getChildrenNodesList(simulationDescriptorNode, "dmnNamespace").isEmpty()) {
                            DOMParserUtil.createNodeAtPosition(simulationDescriptorNode, "dmnNamespace", null, null);
                        }
                        if (DOMParserUtil.getChildrenNodesList(simulationDescriptorNode, "dmnName").isEmpty()) {
                            DOMParserUtil.createNodeAtPosition(simulationDescriptorNode, "dmnName", null, null);
                        }
                        break;
                    default:
                }
                if (DOMParserUtil.getChildrenNodesList(simulationDescriptorNode, "skipFromBuild").isEmpty()) {
                    DOMParserUtil.createNodeAtPosition(simulationDescriptorNode, "skipFromBuild", "false", null);
                }
                if (DOMParserUtil.getChildrenNodesList(simulationDescriptorNode, "fileName").isEmpty()) {
                    DOMParserUtil.createNodeAtPosition(simulationDescriptorNode, "fileName", null, null);
                }
            }
            updateVersion(document, "1.4");
        };
    }

    @Override
    public ThrowingConsumer<Document> from1_4to1_5() {
        return document -> {
            Node simulationDescriptorNode = DOMParserUtil.getNestedChildrenNodesList(document, "ScenarioSimulationModel", SIMULATION_NODE, SIMULATION_DESCRIPTOR_NODE).get(0);
            List<Node> dmoSessionNodesList = DOMParserUtil.getChildrenNodesList(simulationDescriptorNode, DMO_SESSION_NODE);
            if (dmoSessionNodesList.isEmpty()) {
                DOMParserUtil.createNodeAtPosition(simulationDescriptorNode, DMO_SESSION_NODE, null, null);
            } else {
                Node dmoSessionNode = dmoSessionNodesList.get(0);
                if (Objects.equals("default", dmoSessionNode.getTextContent()) || Objects.equals("", dmoSessionNode.getTextContent())) {
                    simulationDescriptorNode.removeChild(dmoSessionNode);
                }
            }
            updateVersion(document, "1.5");
        };
    }

    @Override
    public ThrowingConsumer<Document> from1_5to1_6() {
        return document -> {
            DOMParserUtil.cleanupNodes(document, "Scenario", SIMULATION_DESCRIPTOR_NODE);
            List<Node> simulationFactMappingNodeList = DOMParserUtil.getNestedChildrenNodesList(document, SIMULATION_DESCRIPTOR_NODE, FACT_MAPPINGS_NODE, FACT_MAPPING_NODE);
            for (Node simulationFactMapping : simulationFactMappingNodeList) {
                replaceReference(simulationFactMappingNodeList, simulationFactMapping, FACT_IDENTIFIER_NODE);
            }
            List<Node> scenarioFactMappingValueNodeList = DOMParserUtil.getNestedChildrenNodesList(document, "Scenario", "factMappingValues", "FactMappingValue");
            scenarioFactMappingValueNodeList.forEach(scenarioFactMappingValue -> {
                replaceReference(simulationFactMappingNodeList, scenarioFactMappingValue, FACT_IDENTIFIER_NODE);
                replaceReference(simulationFactMappingNodeList, scenarioFactMappingValue, EXPRESSION_IDENTIFIER_NODE);
            });
            updateVersion(document, "1.6");
        };
    }

    @Override
    public ThrowingConsumer<Document> from1_6to1_7() {
        return document -> {
            final List<Node> factMappingNodeList = DOMParserUtil.getNestedChildrenNodesList(document, SIMULATION_DESCRIPTOR_NODE, FACT_MAPPINGS_NODE, FACT_MAPPING_NODE);
            factMappingNodeList.forEach(factMappingNode -> {
                List<Node> expressionIdentifierNamesNodes = DOMParserUtil.getNestedChildrenNodesList(factMappingNode, EXPRESSION_IDENTIFIER_NODE, "name");
                String expressionIdentifierName = expressionIdentifierNamesNodes.get(0).getTextContent();
                DOMParserUtil.createNodeAtPosition(factMappingNode, "columnWidth", Double.toString(getColumnWidth(expressionIdentifierName)), null);
            });
            updateVersion(document, "1.7");
        };
    }

    @Override
    public ThrowingConsumer<Document> from1_7to1_8() {
        return document -> {
            final Node settingsNode = DOMParserUtil.createNodeAtPosition(document.getElementsByTagName(SCENARIO_SIMULATION_MODEL_NODE).item(0), SETTINGS_NODE, null, null);
            for (String setting : SETTINGS) {
                final Map<Node, List<Node>> childrenNodesMap = DOMParserUtil.getChildrenNodesMap(document, SIMULATION_DESCRIPTOR_NODE, setting);
                childrenNodesMap.values().stream()
                        .filter(childNodeList -> !childNodeList.isEmpty())
                        .findFirst()
                        .ifPresent(childNodeList -> {
                            final Node node = childNodeList.get(0);
                            DOMParserUtil.createNodeAtPosition(settingsNode, node.getNodeName(), node.getTextContent(), null);
                            node.getParentNode().removeChild(node);
                        });
            }
            final List<Node> factMappingNodesList = DOMParserUtil.getNestedChildrenNodesList(document, SIMULATION_DESCRIPTOR_NODE, FACT_MAPPINGS_NODE, FACT_MAPPING_NODE);
            factMappingNodesList.forEach(factMappingNode -> DOMParserUtil.createNodeAtPosition(factMappingNode, FACT_MAPPING_VALUE_TYPE_NODE, NOT_EXPRESSION, null));
            final Node backgroundNode = DOMParserUtil.createNodeAtPosition(document.getElementsByTagName(SCENARIO_SIMULATION_MODEL_NODE).item(0), BACKGROUND_NODE, null, null);
            final Node simulationDescriptorNode = DOMParserUtil.createNodeAtPosition(backgroundNode, SIMULATION_DESCRIPTOR_NODE, null, null);
            final Node factMappingsNode = DOMParserUtil.createNodeAtPosition(simulationDescriptorNode, FACT_MAPPINGS_NODE, null, null);
            final Node factMappingNode = DOMParserUtil.createNodeAtPosition(factMappingsNode, FACT_MAPPING_NODE, null, null);
            DOMParserUtil.createNodeAtPosition(factMappingNode, FACT_MAPPING_VALUE_TYPE_NODE, NOT_EXPRESSION, null);
            final Node expressionElementsNode = DOMParserUtil.createNodeAtPosition(factMappingNode, EXPRESSION_ELEMENTS_NODE, null, null);
            ((Element) expressionElementsNode).setAttribute("class", "linked-list");
            final Node expressionIdentifierNode = DOMParserUtil.createNodeAtPosition(factMappingNode, EXPRESSION_IDENTIFIER_NODE, null, null);
            DOMParserUtil.createNodeAtPosition(expressionIdentifierNode, "name", "1|1", null);
            DOMParserUtil.createNodeAtPosition(expressionIdentifierNode, "type", "GIVEN", null);
            final Node factIdentifierNode = DOMParserUtil.createNodeAtPosition(factMappingNode, FACT_IDENTIFIER_NODE, null, null);
            DOMParserUtil.createNodeAtPosition(factIdentifierNode, "name", "Empty", null);
            DOMParserUtil.createNodeAtPosition(factIdentifierNode, "className", Void.class.getCanonicalName(), null);
            DOMParserUtil.createNodeAtPosition(factMappingNode, "className", Void.class.getCanonicalName(), null);
            DOMParserUtil.createNodeAtPosition(factMappingNode, "factAlias", "Instance 1", null);
            DOMParserUtil.createNodeAtPosition(factMappingNode, "expressionAlias", "PROPERTY 1", null);
            final Node scesimData = DOMParserUtil.createNodeAtPosition(backgroundNode, "scesimData", null, null);
            ((Element)scesimData).setAttribute("class", "linked-list");
            final Node backgroundData = DOMParserUtil.createNodeAtPosition(scesimData, BACKGROUND_DATA_NODE, null, null);
            final Node factMappingValues = DOMParserUtil.createNodeAtPosition(backgroundData, FACT_MAPPING_VALUES_NODE, null, null);
            final Node factMappingValue = DOMParserUtil.createNodeAtPosition(factMappingValues, FACT_MAPPING_VALUE_NODE, null, null);
            final Node factIdentifier = DOMParserUtil.createNodeAtPosition(factMappingValue, FACT_IDENTIFIER_NODE, null, null);
            DOMParserUtil.createNodeAtPosition(factIdentifier, "name", "Empty", null);
            DOMParserUtil.createNodeAtPosition(factIdentifier, "className", Void.class.getCanonicalName(), null);
            final Node expressionIdentifier = DOMParserUtil.createNodeAtPosition(factMappingValue, EXPRESSION_IDENTIFIER_NODE, null, null);
            DOMParserUtil.createNodeAtPosition(expressionIdentifier, "name", "1|1", null);
            DOMParserUtil.createNodeAtPosition(expressionIdentifier, "type", "GIVEN", null);
            updateVersion(document, "1.8");
        };
    }

    private void replaceReference(List<Node> simulationFactMappingNodeList, Node containerNode, String referredNodeName) {
        final List<Node> referredNodesList = DOMParserUtil.getChildrenNodesList(containerNode, referredNodeName);
        if (!referredNodesList.isEmpty()) {
            Node referringNode = referredNodesList.get(0);
            String referenceAttribute = DOMParserUtil.getAttributeValue(referringNode, "reference");
            if (referenceAttribute != null) {
                String referredIndex = "1";
                if (referenceAttribute.contains("[") && referenceAttribute.contains("]")) {
                    referredIndex = referenceAttribute.substring(referenceAttribute.indexOf('[') + 1, referenceAttribute.indexOf(']'));
                }
                int index = Integer.parseInt(referredIndex) - 1;
                Node referredFactMapping = simulationFactMappingNodeList.get(index);
                Node referredNode = DOMParserUtil.getChildrenNodesList(referredFactMapping, referredNodeName).get(0);
                Node clonedNode = referredNode.cloneNode(true);
                containerNode.replaceChild(clonedNode, referringNode);
            }
        }
    }
}


text:
<?php
/**
 * Created by PhpStorm.
 * User: Neofox
 * Date: 21/04/2016
 * Time: 20:18
 */
namespace GuildWars2\Wrapper;

/**
 * Interface WrapperInterface
 * @package GuildWars2\Wrapper
 */
interface WrapperInterface
{
    /**
     * @param string $params
     * @param array  $query
     *
     * @return mixed
     */
    public function callApi(string $params, array $query);

    /**
     * @param string $lang
     *
     * @return mixed
     */
    public function validateLanguage(string $lang);
}


text:
@implementation Registration

NSString* const myFormat = @"<entry xmlns=\"http://www.w3.org/2005/Atom\"><content type=\"text/xml\"><AppleRegistrationDescription xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"http://schemas.microsoft.com/netservices/2010/10/servicebus/connect\">%@<DeviceToken>%@</DeviceToken></AppleRegistrationDescription></content></entry>";

@synthesize ETag, expiresAt, tags, deviceToken, registrationId;

+ (NSString*) Name
{
    return @"$Default";
}

+ (NSString*) payloadWithDeviceToken:(NSString*)deviceToken tags:(NSSet*)tags
{
    NSString* tagNode = @"";
    NSString* tagString = [TestHelper convertTagSetToString:tags];
    if( [tagString length]>0)
    {
        tagNode = [NSString stringWithFormat:@"<Tags>%@</Tags>", tagString];
    }

    return [NSString stringWithFormat:myFormat, tagNode, deviceToken];
}

@end


text:
using System.Collections.Generic;

namespace OrchardCore.Indexing.Settings
{
    /// <summary>
    /// Represents the indexing settings for a content type.
    /// </summary>
    public class TypeIndexSettings
    {
        /// <summary>
        /// The list of indexes that this type should be included into.
        /// </summary>
        public List<TypeIndexEntry> Indexes { get; set; }
    }

    public class TypeIndexEntry
    {
        public const string Published = "published";
        public const string Latest = "latest";

        public string Name { get; set; }
        public string Version { get; set; }
    }
}