text:
package org.garywzh.quumiibox.ui.fragment;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.view.ActionMode;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.FrameLayout;

import com.bignerdranch.android.multiselector.ModalMultiSelectorCallback;
import com.bignerdranch.android.multiselector.MultiSelector;
import com.google.common.eventbus.Subscribe;
import com.umeng.analytics.MobclickAgent;

import org.garywzh.quumiibox.AppContext;
import org.garywzh.quumiibox.R;
import org.garywzh.quumiibox.common.UserState;
import org.garywzh.quumiibox.eventbus.CatagoryChangedEvent;
import org.garywzh.quumiibox.ui.MainActivity;
import org.garywzh.quumiibox.ui.adapter.CategoryAdapter;
import org.garywzh.quumiibox.util.ExecutorUtils;

import java.util.List;

public class CategoryFragment extends Fragment implements CategoryAdapter.OnStartActionModeListener {
    private static final String TAG = CategoryFragment.class.getSimpleName();

    private CategoryAdapter.OnCateItemClickListener mOnItemClickListener;
    private CategoryAdapter mCategoryAdapter;

    public CategoryFragment() {
        // Required empty public constructor
    }

    public static CategoryFragment newInstance() {
        return new CategoryFragment();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        RecyclerView recyclerView = (RecyclerView) inflater.inflate(R.layout.fragment_category, container, false);
        recyclerView.setLayoutManager(new LinearLayoutManager(recyclerView.getContext()));

        mCategoryAdapter = new CategoryAdapter(mOnItemClickListener, this);
        recyclerView.setAdapter(mCategoryAdapter);

        return recyclerView;
    }

    @Override
    public void onStart() {
        super.onStart();
        AppContext.getEventBus().register(this);
    }

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(getActivity());
    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(getActivity());
    }

    @Override
    public void onStop() {
        super.onStop();
        AppContext.getEventBus().unregister(this);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        final MainActivity activity = ((MainActivity) getActivity());
        activity.setTitle(getString(R.string.drawer_tag));
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        try {
            mOnItemClickListener = (CategoryAdapter.OnCateItemClickListener) context;
        } catch (ClassCastException e) {
            throw new ClassCastException(context.toString()
                    + " must implement OnItemActionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mOnItemClickListener = null;
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.menu_cateitem_list, menu);
        super.onCreateOptionsMenu(menu, inflater);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_add) {
            showAddItemDialog();
            return true;
        } else if (id == R.id.action_reset) {
            showResetDialog();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onStartActionMode(final MultiSelector multiSelector) {
        ((AppCompatActivity) getActivity()).startSupportActionMode(new ModalMultiSelectorCallback(multiSelector) {

            @Override
            public boolean onCreateActionMode(ActionMode actionMode, Menu menu) {
                super.onCreateActionMode(actionMode, menu);
                getActivity().getMenuInflater().inflate(R.menu.menu_action_mode, menu);
                return true;
            }

            @Override
            public boolean onActionItemClicked(ActionMode actionMode, MenuItem menuItem) {
                if (menuItem.getItemId() == R.id.action_delete) {
                    actionMode.finish();

                    List<String> items = UserState.getInstance().getCategoryItems();
                    for (int i = items.size() - 1; i >= 0; i--) {
                        if (multiSelector.isSelected(i, 0)) {
                            items.remove(items.get(i));
                        }
                    }
                    mCategoryAdapter.notifyDataSetChanged();
                    UserState.getInstance().updateCategoryItemsPrefs();
                    multiSelector.clearSelections();
                    return true;
                }
                return false;
            }
        });
    }

    private void showAddItemDialog() {
        AddItemAlertDialogFragment dialogFragment = AddItemAlertDialogFragment.newInstance();
        dialogFragment.show(getFragmentManager(), "additemdialog");
    }

    private void showResetDialog() {
        ResetAlertDialogFragment dialogFragment = ResetAlertDialogFragment.newInstance();
        dialogFragment.show(getFragmentManager(), "resetdialog");
    }

    @Subscribe
    public void onCatagoryChangedEvent(CatagoryChangedEvent e) {
        mCategoryAdapter.notifyDataSetChanged();
    }

    public static class ResetAlertDialogFragment extends DialogFragment {
        public static ResetAlertDialogFragment newInstance() {
            return new ResetAlertDialogFragment();
        }

        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            OnResetDialogClickListener onResetDialogClickListener = new OnResetDialogClickListener();
            return new AlertDialog.Builder(getActivity())
                    .setMessage("将丢失修改的自定义内容")
                    .setTitle("重置")
                    .setPositiveButton(R.string.alert_dialog_ok, onResetDialogClickListener)
                    .setNegativeButton(R.string.alert_dialog_cancel, onResetDialogClickListener)
                    .create();
        }

        static class OnResetDialogClickListener implements DialogInterface.OnClickListener {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                switch (which) {
                    case Dialog.BUTTON_NEGATIVE:
                        break;
                    case Dialog.BUTTON_POSITIVE:
                        ExecutorUtils.execute(new Runnable() {
                            @Override
                            public void run() {
                                UserState.getInstance().resetCateItemPrefs();
                                AppContext.getEventBus().post(new CatagoryChangedEvent());
                            }
                        });
                        break;
                }
            }
        }
    }

    public static class AddItemAlertDialogFragment extends DialogFragment {

        public static AddItemAlertDialogFragment newInstance() {
            return new AddItemAlertDialogFragment();
        }

        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            Activity activity = getActivity();
            int margin_in_dp = 24;
            final float scale = getResources().getDisplayMetrics().density;
            int margin_in_px = (int) (margin_in_dp * scale + 0.5f);
            FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            params.leftMargin = margin_in_px;
            params.rightMargin = margin_in_px;
            final EditText input = new EditText(activity);
            input.setSingleLine(true);
            input.setLayoutParams(params);
            FrameLayout container = new FrameLayout(activity);
            container.addView(input);
            OnAddItemDialogClickListener onDialogClickListener = new OnAddItemDialogClickListener(input);

            return new AlertDialog.Builder(getActivity())
                    .setTitle("添加一个标签")
                    .setView(container)
                    .setPositiveButton(R.string.alert_dialog_ok, onDialogClickListener)
                    .setNegativeButton(R.string.alert_dialog_cancel, onDialogClickListener)
                    .create();
        }

        @Override
        public void onActivityCreated(Bundle savedInstanceState) {
            super.onActivityCreated(savedInstanceState);
            getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
        }

        static class OnAddItemDialogClickListener implements DialogInterface.OnClickListener {
            private EditText mEditText;

            public OnAddItemDialogClickListener(EditText editText) {
                super();
                mEditText = editText;
            }

            @Override
            public void onClick(DialogInterface dialog, int which) {
                switch (which) {
                    case Dialog.BUTTON_NEGATIVE:
                        break;
                    case Dialog.BUTTON_POSITIVE:
                        if (mEditText.getText().toString().trim().length() == 0) {
                            return;
                        }
                        ExecutorUtils.execute(new Runnable() {
                            @Override
                            public void run() {
                                UserState.getInstance().addCateoryItem(mEditText.getText().toString());
                                AppContext.getEventBus().post(new CatagoryChangedEvent());
                            }
                        });
                        break;
                }
            }
        }
    }
}


text:
<?php

namespace app\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\models\Type;

class TypeSearch extends Type
{

    public function rules()
    {
        return [
            [['id_type'], 'integer'],
            [['desc_type', 'hexcolor_type', 'icon_type'], 'safe'],
        ];
    }

    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    public function search($params)
    {
        $query = Type::find();

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        $query->andFilterWhere([
            'id_type' => $this->id_type,
        ]);

        $query->andFilterWhere(['like', 'desc_type', $this->desc_type])
            ->andFilterWhere(['like', 'hexcolor_type', $this->hexcolor_type])
            ->andFilterWhere(['like', 'icon_type', $this->icon_type]);

        return $dataProvider;
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8"?>
<sem:triples uri="http://www.lds.org/vrl/concepts/general-subjects/explosions" xmlns:sem="http://marklogic.com/semantics">
  <sem:triple>
    <sem:subject>http://www.lds.org/vrl/concepts/general-subjects/explosions</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#prefLabel</sem:predicate>
    <sem:object datatype="xsd:string" xml:lang="eng">Explosions</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/vrl/concepts/general-subjects/explosions</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#inScheme</sem:predicate>
    <sem:object datatype="sem:iri">http://www.lds.org/concept-scheme/vrl</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/vrl/concepts/general-subjects/explosions</sem:subject>
    <sem:predicate>http://www.lds.org/core#entityType</sem:predicate>
    <sem:object datatype="sem:iri">http://www.lds.org/Topic</sem:object>
  </sem:triple>
</sem:triples>


text:
#ifndef __CGD3D11_H__
#define __CGD3D11_H__

#ifdef _WIN32

#pragma once

#include <windows.h>
#include <d3d11.h>

#include "Cg/cg.h"

/* Set up for either Win32 import/export/lib. */

#ifdef CGD3D11DLL_EXPORTS
# define CGD3D11DLL_API __declspec(dllexport)
#elif defined(CG_LIB)
# define CGD3D11DLL_API
#else
# define CGD3D11DLL_API __declspec(dllimport)
#endif

#ifndef CGD3D11ENTRY
# ifdef _WIN32
#  define CGD3D11ENTRY __cdecl
# else
#  define CGD3D11ENTRY
# endif
#endif

#ifdef __cplusplus
extern "C"
{
#endif

#ifndef CGD3D11_EXPLICIT

CGD3D11DLL_API ID3D11Device * CGD3D11ENTRY cgD3D11GetDevice(CGcontext Context);
CGD3D11DLL_API HRESULT CGD3D11ENTRY cgD3D11SetDevice(CGcontext Context, ID3D11Device *pDevice);
CGD3D11DLL_API void CGD3D11ENTRY cgD3D11SetTextureParameter(CGparameter Parameter, ID3D11Resource *pTexture);
CGD3D11DLL_API void CGD3D11ENTRY cgD3D11SetSamplerStateParameter(CGparameter Parameter, ID3D11SamplerState *pSamplerState);
CGD3D11DLL_API void CGD3D11ENTRY cgD3D11SetTextureSamplerStateParameter(CGparameter Parameter, ID3D11Resource *pTexture, ID3D11SamplerState *pSamplerState);
CGD3D11DLL_API HRESULT CGD3D11ENTRY cgD3D11LoadProgram(CGprogram Program, UINT Flags);
CGD3D11DLL_API ID3D10Blob * CGD3D11ENTRY cgD3D11GetCompiledProgram(CGprogram Program);
CGD3D11DLL_API ID3D10Blob * CGD3D11ENTRY cgD3D11GetProgramErrors(CGprogram Program);
CGD3D11DLL_API CGbool CGD3D11ENTRY cgD3D11IsProgramLoaded(CGprogram Program);
CGD3D11DLL_API HRESULT CGD3D11ENTRY cgD3D11BindProgram(CGprogram Program);
CGD3D11DLL_API void CGD3D11ENTRY cgD3D11UnloadProgram(CGprogram Program);
CGD3D11DLL_API ID3D11Buffer * CGD3D11ENTRY cgD3D11GetBufferByIndex(CGprogram Program, UINT Index);
CGD3D11DLL_API void CGD3D11ENTRY cgD3D11RegisterStates(CGcontext Context);
CGD3D11DLL_API void CGD3D11ENTRY cgD3D11SetManageTextureParameters(CGcontext Context, CGbool Flag);
CGD3D11DLL_API CGbool CGD3D11ENTRY cgD3D11GetManageTextureParameters(CGcontext Context);
CGD3D11DLL_API ID3D10Blob * CGD3D11ENTRY cgD3D11GetIASignatureByPass(CGpass Pass);
CGD3D11DLL_API CGprofile CGD3D11ENTRY cgD3D11GetLatestVertexProfile(void);
CGD3D11DLL_API CGprofile CGD3D11ENTRY cgD3D11GetLatestGeometryProfile(void);
CGD3D11DLL_API CGprofile CGD3D11ENTRY cgD3D11GetLatestPixelProfile(void);
CGD3D11DLL_API CGprofile CGD3D11ENTRY cgD3D11GetLatestHullProfile(void);
CGD3D11DLL_API CGprofile CGD3D11ENTRY cgD3D11GetLatestDomainProfile(void);
CGD3D11DLL_API CGbool CGD3D11ENTRY cgD3D11IsProfileSupported(CGprofile Profile);
CGD3D11DLL_API DWORD CGD3D11ENTRY cgD3D11TypeToSize(CGtype Type);
CGD3D11DLL_API HRESULT CGD3D11ENTRY cgD3D11GetLastError(void);
CGD3D11DLL_API const char ** CGD3D11ENTRY cgD3D11GetOptimalOptions(CGprofile Profile);
CGD3D11DLL_API const char * CGD3D11ENTRY cgD3D11TranslateCGerror(CGerror Error);
CGD3D11DLL_API const char * CGD3D11ENTRY cgD3D11TranslateHRESULT(HRESULT hr);
CGD3D11DLL_API void CGD3D11ENTRY cgD3D11UnbindProgram(CGprogram Program);

#endif /* CGD3D11_EXPLICIT */

#ifdef __cplusplus
}
#endif

#endif /* _WIN32 */

#endif


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE ui:UiBinder SYSTEM "http://dl.google.com/gwt/DTD/xhtml.ent">
<ui:UiBinder xmlns:ui="urn:ui:com.google.gwt.uibinder" xmlns:g="urn:import:com.google.gwt.user.client.ui"
	xmlns:d="urn:import:org.ovirt.engine.ui.common.widget.dialog" xmlns:e="urn:import:org.ovirt.engine.ui.common.widget.editor"
    xmlns:ge="urn:import:org.ovirt.engine.ui.common.widget.editor.generic">

	<ui:style type="org.ovirt.engine.ui.webadmin.section.main.view.popup.datacenter.DataCenterPopupView.Style">
		.contentStyle {
		}
	</ui:style>

	<d:SimpleDialogPanel width="450px" height="320px">
		<d:content>
			<g:FlowPanel>
				<ge:StringEntityModelTextBoxEditor ui:field="nameEditor" />
				<ge:StringEntityModelTextBoxEditor ui:field="descriptionEditor" />
				<e:ListModelListBoxEditor ui:field="storagePoolTypeEditor" />
				<e:ListModelListBoxEditor ui:field="versionEditor" />
				<e:ListModelListBoxEditor ui:field="quotaEnforceTypeEditor" />
				<ge:StringEntityModelTextBoxEditor ui:field="commentEditor" />
			</g:FlowPanel>
		</d:content>
	</d:SimpleDialogPanel>

</ui:UiBinder>


text:
package org.elasticlib.console.command.node;

import java.util.List;
import org.elasticlib.common.model.NodeInfo;
import org.elasticlib.console.command.AbstractCommand;
import org.elasticlib.console.command.Category;
import org.elasticlib.console.config.ConsoleConfig;
import org.elasticlib.console.display.Display;
import org.elasticlib.console.http.Session;

/**
 * The node command.
 */
public class Node extends AbstractCommand {

    /**
     * Constructor.
     */
    public Node() {
        super(Category.NODE);
    }

    @Override
    public void execute(Display display, Session session, ConsoleConfig config, List<String> params) {
        NodeInfo info = session.getClient()
                .node()
                .getInfo();

        display.print(info);
    }
}


text:
import { Injectable } from '@angular/core';
import { Action } from '@ngrx/store';

export interface AudienceAction extends Action {
  type: string;
  payload?: any;
}

@Injectable()
export class AudienceActions {
  static SET_EDIT_AUDIENCE_INDEX   = '[audience] Edit Audience';
  static SET_UPDATE_AUDIENCE_INDEX = '[audience] Update Audience';

  setEditAudienceIndex (index: number): AudienceAction {
    return {
      type:    AudienceActions.SET_EDIT_AUDIENCE_INDEX,
      payload: {index}
    };
  }

  setUpdateAudienceIndex (index: number): AudienceAction {
    return {
      type:    AudienceActions.SET_UPDATE_AUDIENCE_INDEX,
      payload: {index}
    };
  }
}


text:
package org.apache.geode.cache.util;

import static org.apache.geode.distributed.ConfigurationProperties.MCAST_PORT;
import static org.apache.geode.test.awaitility.GeodeAwaitility.await;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

import java.io.ByteArrayInputStream;
import java.util.Properties;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import org.apache.geode.GemFireConfigException;
import org.apache.geode.cache.CacheFactory;
import org.apache.geode.cache.util.AutoBalancer.CacheOperationFacade;
import org.apache.geode.cache.util.AutoBalancer.GeodeCacheFacade;
import org.apache.geode.distributed.DistributedLockService;
import org.apache.geode.distributed.internal.InternalDistributedSystem;
import org.apache.geode.distributed.internal.locks.DLockService;
import org.apache.geode.internal.cache.GemFireCacheImpl;
import org.apache.geode.internal.statistics.HostStatSampler;

/**
 * IntegrationTests for AutoBalancer that include usage of Cache, StatSampler and
 * DistributedLockService.
 */
public class AutoBalancerIntegrationJUnitTest {

  private static final int TIMEOUT_SECONDS = 5;

  private GemFireCacheImpl cache;

  @Before
  public void setUpCacheAndDLS() {
    cache = createBasicCache();
  }

  @After
  public void destroyCacheAndDLS() {
    if (DLockService.getServiceNamed(AutoBalancer.AUTO_BALANCER_LOCK_SERVICE_NAME) != null) {
      DLockService.destroy(AutoBalancer.AUTO_BALANCER_LOCK_SERVICE_NAME);
    }

    AutoBalancer autoBalancer = (AutoBalancer) cache.getInitializer();
    if (autoBalancer != null) {
      autoBalancer.destroy();
    }

    if (cache != null && !cache.isClosed()) {
      try {
        final HostStatSampler statSampler =
            ((InternalDistributedSystem) cache.getDistributedSystem()).getStatSampler();
        cache.close();
        // wait for the stat sampler to stand down
        await().until(isAlive(statSampler), equalTo(false));
      } finally {
        cache = null;
      }
    }
  }

  @Test
  public void testAutoRebalaceStatsOnLockSuccess() throws InterruptedException {
    assertEquals(0, cache.getInternalResourceManager().getStats().getAutoRebalanceAttempts());
    AutoBalancer balancer = new AutoBalancer();
    final String someSchedule = "1 * * * 1 *";
    final Properties props = new Properties();
    props.put(AutoBalancer.SCHEDULE, someSchedule);
    balancer.initialize(cache, props);
    balancer.getOOBAuditor().execute();
    assertEquals(1, cache.getInternalResourceManager().getStats().getAutoRebalanceAttempts());
  }

  @Test
  public void testAutoRebalaceStatsOnLockFailure() throws InterruptedException {
    acquireLockInDifferentThread(1);
    assertEquals(0, cache.getInternalResourceManager().getStats().getAutoRebalanceAttempts());
    AutoBalancer balancer = new AutoBalancer();
    final String someSchedule = "1 * * * 1 *";
    final Properties props = new Properties();
    props.put(AutoBalancer.SCHEDULE, someSchedule);
    balancer.initialize(cache, props);
    balancer.getOOBAuditor().execute();
    assertEquals(0, cache.getInternalResourceManager().getStats().getAutoRebalanceAttempts());
  }

  @Test
  public void testAutoBalanceStatUpdate() {
    assertEquals(0, cache.getInternalResourceManager().getStats().getAutoRebalanceAttempts());
    new GeodeCacheFacade(cache).incrementAttemptCounter();
    assertEquals(1, cache.getInternalResourceManager().getStats().getAutoRebalanceAttempts());
  }

  @Test
  public void testLockSuccess() throws InterruptedException {
    acquireLockInDifferentThread(1);
    DistributedLockService dls = new GeodeCacheFacade(cache).getDLS();
    assertFalse(dls.lock(AutoBalancer.AUTO_BALANCER_LOCK, 0, -1));
  }

  @Test
  public void canReacquireLock() throws InterruptedException {
    acquireLockInDifferentThread(2);
    DistributedLockService dls = new GeodeCacheFacade(cache).getDLS();
    assertFalse(dls.lock(AutoBalancer.AUTO_BALANCER_LOCK, 0, -1));
  }

  @Test
  public void testLockAlreadyTakenElsewhere() throws InterruptedException {
    DistributedLockService dls = new GeodeCacheFacade(cache).getDLS();
    assertTrue(dls.lock(AutoBalancer.AUTO_BALANCER_LOCK, 0, -1));

    final AtomicBoolean success = new AtomicBoolean(true);

    Thread thread = new Thread(new Runnable() {
      @Override
      public void run() {
        CacheOperationFacade cacheFacade = new GeodeCacheFacade(cache);
        success.set(cacheFacade.acquireAutoBalanceLock());
      }
    });
    thread.start();
    thread.join();

    assertFalse(success.get());
  }

  @Test
  public void testInitializerCacheXML() {
    String configStr =
        "<cache xmlns=\"http://geode.apache.org/schema/cache\"                          "
            + " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"                                      "
            + " xsi:schemaLocation=\"http://geode.apache.org/schema/cache http://geode.apache.org/schema/cache/cache-1.0.xsd\""
            + " version=\"1.0\">                                                                             "
            + "   <initializer>                                                                              "
            + "     <class-name>org.apache.geode.cache.util.AutoBalancer</class-name>                    "
            + "     <parameter name=\"schedule\">                                                            "
            + "       <string>* * * * * ? </string>                                                          "
            + "     </parameter>                                                                             "
            + "   </initializer>                                                                             "
            + " </cache>";

    cache.loadCacheXml(new ByteArrayInputStream(configStr.getBytes()));
  }

  @Test(expected = GemFireConfigException.class)
  public void testInitFailOnMissingScheduleConf() {
    String configStr =
        "<cache xmlns=\"http://geode.apache.org/schema/cache\"                          "
            + " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"                                      "
            + " xsi:schemaLocation=\"http://geode.apache.org/schema/cache http://geode.apache.org/schema/cache/cache-1.0.xsd\""
            + " version=\"1.0\">                                                                             "
            + "   <initializer>                                                                              "
            + "     <class-name>org.apache.geode.cache.util.AutoBalancer</class-name>                    "
            + "   </initializer>                                                                             "
            + " </cache>";

    cache.loadCacheXml(new ByteArrayInputStream(configStr.getBytes()));
  }

  private GemFireCacheImpl createBasicCache() {
    return (GemFireCacheImpl) new CacheFactory().set(MCAST_PORT, "0").create();
  }

  private Callable<Boolean> isAlive(final HostStatSampler statSampler) {
    return new Callable<Boolean>() {
      @Override
      public Boolean call() throws Exception {
        return statSampler.isAlive();
      }
    };
  }

  private void acquireLockInDifferentThread(final int num) throws InterruptedException {
    final CountDownLatch latch = new CountDownLatch(num);
    Thread thread = new Thread(new Runnable() {
      @Override
      public void run() {
        CacheOperationFacade cacheFacade = new GeodeCacheFacade(cache);
        for (int i = 0; i < num; i++) {
          boolean result = cacheFacade.acquireAutoBalanceLock();
          if (result) {
            latch.countDown();
          }
        }
      }
    });
    thread.start();
    assertTrue(latch.await(TIMEOUT_SECONDS, TimeUnit.SECONDS));
  }
}


text:
<?php
namespace Bakgat\Notos\Test\Domain\Model\Location;

use Bakgat\Notos\Domain\Model\Location\URL;
use Orchestra\Testbench\TestCase;

/**
 * Created by PhpStorm.
 * User: karlvaniseghem
 * Date: 19/10/15
 * Time: 15:44
 */
class URLTest extends TestCase
{
    /**
     * @test
     * @group url
     */
    public function should_require_valid_url() {
        $this->setExpectedException('Bakgat\Notos\Domain\Model\Location\Exceptions\URLNotValidException');
        $url  = new URL('@');
    }

    /**
     * @test
     * @group url
     */
    public function should_accept_valid_url() {
        $url = new URL('klimtoren.be');

        $this->assertInstanceOf('Bakgat\Notos\Domain\Model\Location\URL', $url);
    }

    /**
     * @test
     * @group url
     */
    public function should_test_equality() {
        $one = new URL('www.klimtoren.be');
        $two = new URL('http://www.klimtoren.be');
        $three = new URL('ww.klimtoren.be/'); //ww instead of www

        $this->assertTrue($one->equals($two));
        $this->assertFalse($three->equals($one));
    }

    /**
     * @test
     * @group url
     */
    public function should_return_as_string() {
        $klimtoren = new URL('www.klimtoren.be');

        $this->assertEquals('http://www.klimtoren.be/', $klimtoren->toString());
        $this->assertEquals('http://www.klimtoren.be/', (string)$klimtoren);
    }
}


text:
(function(){
	"use strict";

	KC3StrategyTabs.crafts = new KC3StrategyTab("crafts");

	KC3StrategyTabs.crafts.definition = {
		tabSelf: KC3StrategyTabs.crafts,

		/* INIT
		Prepares all data needed
		---------------------------------*/
		init :function(){

		},

		/* EXECUTE
		Places data onto the interface
		---------------------------------*/
		execute :function(){
			var self = this;
			// Get pagination
			KC3Database.count_devmt(function(NumRecords){
				var itemsPerPage = 25;
				var numPages = Math.ceil(NumRecords/itemsPerPage);

				if(numPages > 0){
					$('.pagination').twbsPagination({
						totalPages: numPages,
						visiblePages: 9,
						onPageClick: function (event, page) {
							self.tabSelf.definition.showPage( page );
						}
					});
				}else{
					$('.pagination').hide();
				}

				self.tabSelf.definition.showPage(1);
			});
		},

		showPage :function(pageNumber){
			KC3Database.get_devmt(pageNumber, function(response){
				$(".tab_crafts .build_list").html("");

				var ctr, thisBuild, buildbox, MasterItem;
				var shipClickFunc = function(e){
					KC3StrategyTabs.gotoTab("mstship", $(this).attr("alt"));
				};
				var gearClickFunc = function(e){
					KC3StrategyTabs.gotoTab("mstgear", $(this).attr("alt"));
				};
				for(ctr in response){
					thisBuild = response[ctr];

					buildbox = $(".tab_crafts .factory .build_item").clone().appendTo(".tab_crafts .build_list");

					$(".build_id", buildbox).text( thisBuild.id );
					$(".build_ficon img", buildbox).attr("src", KC3Meta.shipIcon(thisBuild.flag) );
					$(".build_ficon img", buildbox).attr("alt", thisBuild.flag);
					$(".build_ficon img", buildbox).click(shipClickFunc);
					$(".build_flag", buildbox).text( KC3Meta.shipName( KC3Master.ship(thisBuild.flag).api_name ) );

					$(".build_rsc1", buildbox).text( thisBuild.rsc1 );
					$(".build_rsc2", buildbox).text( thisBuild.rsc2 );
					$(".build_rsc3", buildbox).text( thisBuild.rsc3 );
					$(".build_rsc4", buildbox).text( thisBuild.rsc4 );

					if(thisBuild.result > -1){
						MasterItem = KC3Master.slotitem(thisBuild.result);
						$(".build_ricon img", buildbox).attr("src", "../../assets/img/items/"+MasterItem.api_type[3]+".png");
						$(".build_ricon img", buildbox).attr("alt", thisBuild.result);
						$(".build_ricon img", buildbox).click(gearClickFunc);
						$(".build_ricon", buildbox).addClass("hover");
						$(".build_result", buildbox).text( KC3Meta.gearName( MasterItem.api_name ) );
					}else{
						$(".build_ricon img", buildbox).attr("src", "../../assets/img/client/penguin.png");
						$(".build_result", buildbox).text( "Penguin" );
					}

					$(".build_time", buildbox).text( new Date(thisBuild.time*1000).format("mmm dd, yy - hh:MM tt") );

				}
			});
		}

	};

})();


text:
import { Directive, Input, forwardRef, OnInit, OnChanges, SimpleChanges } from '@angular/core';
import { NG_VALIDATORS, Validator, ValidatorFn, AbstractControl } from '@angular/forms';

import { minDate } from './';

const MIN_DATE_VALIDATOR: any = {
  provide: NG_VALIDATORS,
  useExisting: forwardRef(() => MinDateValidator),
  multi: true
};

@Directive({
  selector: '[minDate][formControlName],[minDate][formControl],[minDate][ngModel]',
  providers: [MIN_DATE_VALIDATOR]
})
export class MinDateValidator implements Validator, OnInit, OnChanges {
  @Input() minDate;

  private validator: ValidatorFn;
  private onChange: () => void;

  ngOnInit() {
    this.validator = minDate(this.minDate);
  }

  ngOnChanges(changes: SimpleChanges) {
    for (let key in changes) {
      if (key === 'minDate') {
        this.validator = minDate(changes[key].currentValue);
        if (this.onChange) this.onChange();
      }
    }
  }

  validate(c: AbstractControl): {[key: string]: any} {
    return this.validator(c);
  }

  registerOnValidatorChange(fn: () => void): void {
    this.onChange = fn;
  }
}


text:
O [Tutorial - Guia de Usuário](../tutorial/){.internal-link target=_blank} deve ser o suficiente para dar a você um tour por todos os principais recursos do **FastAPI**.

Na próxima seção você verá outras opções, configurações, e recursos adicionais.

!!! tip "Dica"
    As próximas seções **não são necessáriamente "avançadas"**

    E é possível que para seu caso de uso, a solução esteja em uma delas.

## Leia o Tutorial primeiro

Você ainda pode usar a maior parte dos recursos no **FastAPI** com o conhecimento do [Tutorial - Guia de Usuário](../tutorial/){.internal-link target=_blank}.

E as próximas seções assumem que você já leu ele, e que você conhece suas ideias principais.

## Curso TestDriven.io

Se você gostaria de fazer um curso avançado-iniciante para complementar essa seção da documentação, você pode querer conferir: Test-Driven Development com FastAPI e Docker por **TestDriven.io**.

Eles estão atualmente doando 10% de todos os lucros para o desenvolvimento do **FastAPI**. 🎉 😄


text:
require("should");
var validateTransferOutItem = require("./transfer-out-item-validator");

module.exports = function(data) {
    data.should.not.equal(null);
    data.should.instanceof(Object);

    data.should.have.property('code');
    data.code.should.instanceof(String);

    data.should.have.property('date');
    data.date.should.instanceof(Date);

    data.should.have.property('reference');
    data.reference.should.instanceof(String);

    data.should.have.property('sourceId');
    data.sourceId.should.instanceof(Object);

    data.should.have.property('source');
    data.source.should.instanceof(Object);

    data.should.have.property('destinationId');
    data.destinationId.should.instanceof(Object);

    data.should.have.property('destination');
    data.destination.should.instanceof(Object);

    data.should.have.property('items');
    data.items.should.instanceof(Array);

    for (var item of data.items) {
        validateTransferOutItem(item);
    }

    data.should.have.property('remark');
    data.remark.should.instanceof(String);
};


text:
  class LocationsController < ApplicationController
  before_action :current_user

  #NEED TO NEST UNDER GROUPS
  #controller to add location, triggered by adding review to searched location
  def create
    group_id = params[:group_id]

    # add the location if it doesn't already exist
    location = location_params()
    new_location = Location.create_with(location).find_or_create_by(place_id: location[:place_id])
    new_location.groups << Group.find(group_id)
    new_location.save

    group_location = GroupLocation.where(group_id: group_id, location_id: new_location.id).last
    # binding.pry

    # add review that triggered location
    # add review that triggered location creation
    review = params.permit(:review, :rating )

    @new_review = Review.create(rating: review[:rating], review: review[:review], group_location_id: group_location.id, user_id: @current_user.id)
    # binding.pry

    redirect_to("/groups/#{group_id}/map")

  end

  #show reviews
  #GroupLocation.find_by_group_id_and_location_id(g.id, l.id).reviews
  def show
    g_id = params[:group_id]
    l_id = params[:id]
    @reviews = GroupLocation.find_by_group_id_and_location_id(g_id, l_id).reviews

    #response for AJAX call
    respond_to do |format|
      format.html # map.html.erb
      format.json { render json: @reviews}
    end

  end

  private
  def location_params
    params.permit(:title, :lat, :lng, :address, :place_id, :website, :phone_number)
  end

end


text:
<?php

function bailout($message)
{
    exit($message."\n");
}

function check_dir($source)
{
    if (!file_exists($source)) {
        bailout('The directory '.$source.' does not exist');
    }

    if (!is_dir($source)) {
        bailout('The file '.$source.' is not a directory');
    }
}

function check_command($command)
{
    exec('which '.$command, $output, $result);

    if ($result !== 0) {
        bailout('The command "'.$command.'" is not installed');
    }
}

function clear_directory($directory)
{
    $iterator = new \DirectoryIterator($directory);

    foreach ($iterator as $file) {
        if (!$file->isDot()) {
            if ($file->isDir()) {
                clear_directory($file->getPathname());
            } else {
                unlink($file->getPathname());
            }
        }
    }
}

function make_directory($directory)
{
    if (!file_exists($directory)) {
        mkdir($directory);
    }

    if (!is_dir($directory)) {
        bailout('The file '.$directory.' already exists but is no directory');
    }
}

function list_files($directory, $extension)
{
    $files = array();
    $iterator = new \DirectoryIterator($directory);

    foreach ($iterator as $file) {
        if (!$file->isDot() && substr($file->getFilename(), -strlen($extension)) === $extension) {
            $files[] = substr($file->getFilename(), 0, -strlen($extension));
        }
    }

    return $files;
}

function genrb($source, $target, $icuBinPath = '', $params = '')
{
    exec($icuBinPath.'genrb --quiet '.$params.' -d '.$target.' '.$source.DIRECTORY_SEPARATOR.'*.txt', $output, $result);

    if ($result !== 0) {
        bailout('genrb failed');
    }
}

function genrb_file($target, $source, $locale, $icuBinPath = '')
{
    exec($icuBinPath.'genrb --quiet -d '.$target.' '.$source.DIRECTORY_SEPARATOR.$locale.'.txt', $output, $result);

    if ($result !== 0) {
        bailout('genrb failed');
    }
}

function load_resource_bundle($locale, $directory)
{
    $bundle = \ResourceBundle::create($locale, $directory);

    if (null === $bundle) {
        bailout('The resource bundle for locale '.$locale.' could not be loaded from directory '.$directory);
    }

    return $bundle;
}

function get_data($index, $dataDir, $locale = 'en', $constraint = null)
{
    $data = array();
    $bundle = load_resource_bundle($locale, $dataDir);

    foreach ($bundle->get($index) as $code => $name) {
        if (null !== $constraint) {
            if ($constraint($code)) {
                $data[$code] = $name;
            }
            continue;
        }

        $data[$code] = $name;
    }

    $collator = new \Collator($locale);
    $collator->asort($data);

    return $data;
}

function icu_version() {
    exec('icu-config --version', $output, $result);

    if ($result !== 0 || !isset($output[0])) {
        bailout('icu-config failed');
    }

    return $output[0];
}

function normalize_icu_version($version) {
    preg_match('/^(?P<version>[0-9]\.[0-9]|[0-9]{2,})/', $version, $matches);

    return $matches['version'];
}

function download_icu_data($version) {
    $icu = parse_ini_file(__DIR__.'/icu.ini');

    if (!isset($icu[$version])) {
        bailout('The version '.$version.' is not available in the datasource.ini file.');
    }

    $checkoutPath = sys_get_temp_dir().DIRECTORY_SEPARATOR.'data-'.$version;

    exec('svn checkout '.$icu[$version].' '.$checkoutPath, $output, $result);

    if ($result !== 0) {
        bailout('svn failed');
    }

    return $checkoutPath;
}

function is_icu_version_42_or_earlier($version)
{
    return version_compare($version, '4.4', '<');
}

function create_stub_datafile($locale, $target, $data)
{
    $template = <<<TEMPLATE
<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

return %s;

TEMPLATE;

    ksort($data);
    $data = var_export($data, true);
    $data = preg_replace('/array \(/', 'array(', $data);
    $data = preg_replace('/\n {1,10}array\(/', 'array(', $data);
    $data = preg_replace('/  /', '    ', $data);
    $data = sprintf($template, $data);

    file_put_contents($target.DIRECTORY_SEPARATOR.$locale.'.php', $data);
}

function create_svn_info_file($source, $target)
{
    exec('svn info --xml '.$source, $output, $result);

    $xml = simplexml_load_string(implode("\n", $output));

    if ($result !== 0) {
        bailout('svn info failed');
    }

    $url = (string) $xml->entry->url;
    $revision = (string) $xml->entry->commit['revision'];
    $author = (string) $xml->entry->commit->author;
    $date = (string) $xml->entry->commit->date;

    $data = <<<SVN_INFO_DATA
SVN info data
=============

URL: $url
Revision: $revision
Author: $author
Date: $date

SVN_INFO_DATA;

    file_put_contents($target.DIRECTORY_SEPARATOR.'svn-info.txt', $data);
}

if ($GLOBALS['argc'] < 1) {
    bailout(<<<MESSAGE
Usage: php build-data.php [icu-version] [icu-binaries-path]

Builds or update the ICU data in Symfony2 for a specific ICU version. If the
ICU version or the path to the binaries are not provided, it will build the
latest version released using the genrb found in the environment path.

Examples:

    php build-data.php 4.2
    It will build the ICU data using the 49 version data

    php build-data.php 4.2 /path/to/icu/bin
    It will build the ICU data using the 49 version data and the genrb and
    icu-config binaries found in the environment path

It is recommended to use the ICU binaries in the same version of the desired
version to build the data files.

Read the UPDATE.txt file for more info.

MESSAGE
    );
}

check_command('svn');
check_command('icu-config');

// Script options
$version = isset($GLOBALS['argv'][1]) ? $GLOBALS['argv'][1] : icu_version();
$icuBinPath = isset($GLOBALS['argv'][2]) ? $GLOBALS['argv'][2] : '';

// Slash the path
if ('' != $icuBinPath && (strrpos($icuBinPath, DIRECTORY_SEPARATOR) + 1 != strlen($icuBinPath))) {
    $icuBinPath .= DIRECTORY_SEPARATOR;
}

check_command($icuBinPath.'genrb');

$version = normalize_icu_version($version);
$source = download_icu_data($version);

// Verify that all required directories exist
check_dir($source);
check_dir($source.DIRECTORY_SEPARATOR.'.svn');

$source = realpath($source);

// Currency, language and region data are bundled in the locales directory in ICU <= 4.2
if (!is_icu_version_42_or_earlier($version)) {
    check_dir($source.DIRECTORY_SEPARATOR.'curr');
    check_dir($source.DIRECTORY_SEPARATOR.'lang');
    check_dir($source.DIRECTORY_SEPARATOR.'region');
}

check_dir($source.DIRECTORY_SEPARATOR.'locales');

// Convert the *.txt resource bundles to *.res files
$target = $version;
$target = __DIR__.DIRECTORY_SEPARATOR.$target;
$currDir = $target.DIRECTORY_SEPARATOR.'curr';
$langDir = $target.DIRECTORY_SEPARATOR.'lang';
$localesDir = $target.DIRECTORY_SEPARATOR.'locales';
$namesDir = $target.DIRECTORY_SEPARATOR.'names';
$namesGeneratedDir = $namesDir.DIRECTORY_SEPARATOR.'generated';
$regionDir = $target.DIRECTORY_SEPARATOR.'region';

make_directory($target);
clear_directory($target);
create_svn_info_file($source, $target);

make_directory($currDir);
clear_directory($currDir);

// Currency data is available at the locales data files in ICU <= 4.2 and the supplementalData file is available at the
// misc directory
if (is_icu_version_42_or_earlier($version)) {
    genrb_file($currDir, $source.DIRECTORY_SEPARATOR.'locales', 'en', $icuBinPath);
    genrb_file($currDir, $source.DIRECTORY_SEPARATOR.'misc', 'supplementalData', $icuBinPath);
} else {
    genrb_file($currDir, $source.DIRECTORY_SEPARATOR.'curr', 'en', $icuBinPath);
    genrb_file($currDir, $source.DIRECTORY_SEPARATOR.'curr', 'supplementalData', $icuBinPath);
}

// It seems \ResourceBundle does not like locale names with uppercase chars then we rename the binary file
// See: http://bugs.php.net/bug.php?id=54025
$filename_from = $currDir.DIRECTORY_SEPARATOR.'supplementalData.res';
$filename_to   = $currDir.DIRECTORY_SEPARATOR.'supplementaldata.res';

if (!rename($filename_from, $filename_to)) {
    bailout('The file '.$filename_from.' could not be renamed');
}

make_directory($langDir);
clear_directory($langDir);

// Language data is available at the locales data files in ICU <= 4.2
if (is_icu_version_42_or_earlier($version)) {
    genrb($source.DIRECTORY_SEPARATOR.'locales', $langDir, $icuBinPath);
} else {
    genrb($source.DIRECTORY_SEPARATOR.'lang', $langDir, $icuBinPath);
}

make_directory($localesDir);
clear_directory($localesDir);
genrb($source.DIRECTORY_SEPARATOR.'locales', $localesDir, $icuBinPath);

make_directory($regionDir);
clear_directory($regionDir);

// Region data is available at the locales data files in ICU <= 4.2
if (is_icu_version_42_or_earlier($version)) {
    genrb($source.DIRECTORY_SEPARATOR.'locales', $regionDir, $icuBinPath);
} else {
    genrb($source.DIRECTORY_SEPARATOR.'region', $regionDir, $icuBinPath);
}

make_directory($namesDir);
clear_directory($namesDir);

make_directory($namesGeneratedDir);
clear_directory($namesGeneratedDir);

// Discover the list of supported locales, which are the names of the resource
// bundles in the "locales" directory
$supportedLocales = list_files($localesDir, '.res');

sort($supportedLocales);

// Delete unneeded locales
foreach ($supportedLocales as $key => $supportedLocale) {
    // Delete all aliases from the list
    // i.e., "az_AZ" is an alias for "az_Latn_AZ"
    $localeBundleOrig = file_get_contents($source.DIRECTORY_SEPARATOR.'locales'.DIRECTORY_SEPARATOR.$supportedLocale.'.txt');

    // The key "%%ALIAS" is not accessible through the \ResourceBundle class
    if (strpos($localeBundleOrig, '%%ALIAS') !== false) {
        unset($supportedLocales[$key]);
    }

    // Delete locales that have no content (i.e. only "Version" key)
    $localeBundle = load_resource_bundle($supportedLocale, $localesDir);

    // There seems to be no other way for identifying all keys in this specific
    // resource bundle
    $bundleKeys = array();

    foreach ($localeBundle as $bundleKey => $_) {
        $bundleKeys[] = $bundleKey;
    }

    if ($bundleKeys === array('Version')) {
        unset($supportedLocales[$key]);
    }
}

// Discover the list of locales for which individual language/region names
// exist. This list contains for example "de" and "de_CH", but not "de_DE" which
// is equal to "de"
$translatedLocales = array_unique(array_merge(
    list_files($langDir, '.res'),
    list_files($regionDir, '.res')
));

sort($translatedLocales);

// For each translated locale, generate a list of locale names
// Each locale name has the form: "Language (Script, Region, Variant1, ...)
// Script, Region and Variants are optional. If none of them is available,
// the braces are not printed.
foreach ($translatedLocales as $translatedLocale) {
    // Don't include ICU's root resource bundle
    if ($translatedLocale === 'root') {
        continue;
    }

    $langBundle = load_resource_bundle($translatedLocale, $langDir);
    $regionBundle = load_resource_bundle($translatedLocale, $regionDir);
    $localeNames = array();

    foreach ($supportedLocales as $supportedLocale) {
        // Don't include ICU's root resource bundle
        if ($supportedLocale === 'root') {
            continue;
        }

        $lang = \Locale::getPrimaryLanguage($supportedLocale);
        $script = \Locale::getScript($supportedLocale);
        $region = \Locale::getRegion($supportedLocale);
        $variants = \Locale::getAllVariants($supportedLocale);

        // Currently the only available variant is POSIX, which we don't want
        // to include in the list
        if (count($variants) > 0) {
            continue;
        }

        $langName = $langBundle->get('Languages')->get($lang);
        $extras = array();

        // Some languages are simply not translated
        // Example: "az" (Azerbaijani) has no translation in "af" (Afrikaans)
        if (!$langName) {
            continue;
        }

        // "af" (Afrikaans) has no "Scripts" block
        if (!$langBundle->get('Scripts')) {
            continue;
        }

        // "as" (Assamese) has no "Variants" block
        if (!$langBundle->get('Variants')) {
            continue;
        }

        // Discover the name of the script part of the locale
        // i.e. in zh_Hans_MO, "Hans" is the script
        if ($script) {
            // Some languages are translated together with their script,
            // i.e. "zh_Hans" is translated as "Simplified Chinese"
            if ($langBundle->get('Languages')->get($lang.'_'.$script)) {
                $langName = $langBundle->get('Languages')->get($lang.'_'.$script);

                // If the script is appended in braces, extract it
                // i.e. "zh_Hans" is translated as "Chinesisch (vereinfacht)"
                // in "de"
                if (strpos($langName, '(') !== false) {
                    list($langName, $scriptName) = preg_split('/[\s()]/', $langName, null, PREG_SPLIT_NO_EMPTY);

                    $extras[] = $scriptName;
                }
            } else {
                $scriptName = $langBundle->get('Scripts')->get($script);

                // Some scripts are not translated into every language
                if (!$scriptName) {
                    continue;
                }

                $extras[] = $scriptName;
            }
        }

        // Discover the name of the region part of the locale
        // i.e. in de_AT, "AT" is the region
        if ($region) {
            // Some languages are translated together with their region,
            // i.e. "en_GB" is translated as "British English"
            // we don't include these languages though because they mess up
            // the locale sorting
            // if ($langBundle->get('Languages')->get($lang.'_'.$region)) {
            //     $langName = $langBundle->get('Languages')->get($lang.'_'.$region);
            // } else {
            $regionName = $regionBundle->get('Countries')->get($region);

            // Some regions are not translated into every language
            if (!$regionName) {
                continue;
            }

            $extras[] = $regionName;
            // }
        }

        if (count($extras) > 0) {
            $langName .= ' ('.implode(', ', $extras).')';
        }

        $localeNames[$supportedLocale] = $langName;
    }

    // If no names could be generated for the current locale, skip it
    if (count($localeNames) === 0) {
        continue;
    }

    $file = fopen($namesGeneratedDir.DIRECTORY_SEPARATOR.$translatedLocale.'.txt', 'w');

    fwrite($file, "$translatedLocale{\n");
    fwrite($file, "    Locales{\n");

    foreach ($localeNames as $supportedLocale => $langName) {
        fwrite($file, "        $supportedLocale{\"$langName\"}\n");
    }

    fwrite($file, "    }\n");
    fwrite($file, "}\n");

    fclose($file);
}

// Convert generated files to binary format
// Even if the source and generated file are UTF-8 encoded, for some reason the data seems not correctly encoded, leading to
// a parse error in genrb (Stopped parsing resource with U_ILLEGAL_CHAR_FOUND). So we call the genrb passing that the source
// files are UTF-8 encoded.
if (is_icu_version_42_or_earlier($version)) {
    genrb($namesGeneratedDir, $namesDir, $icuBinPath, '-e UTF-8');
} else {
    genrb($namesGeneratedDir, $namesDir, $icuBinPath);
}

// Clean up
clear_directory($namesGeneratedDir);
rmdir($namesGeneratedDir);

// Generate the data to the stubbed intl classes We only extract data for the 'en' locale
// The extracted data is used only by the stub classes
$defaultLocale = 'en';

$currencies = array();
$currenciesMeta = array();
$defaultMeta = array();

$bundle = load_resource_bundle('supplementaldata', $currDir);

foreach ($bundle->get('CurrencyMeta') as $code => $data) {
    // The 'DEFAULT' key contains the fraction digits and the rounding increment that are common for a lot of currencies
    // Only currencies with different values are added to the icu-data (e.g: CHF and JPY)
    if ('DEFAULT' == $code) {
        $defaultMeta = array(
            'fractionDigits'    => $data[0],
            'roundingIncrement' => $data[1],
        );

        continue;
    }

    $currenciesMeta[$code]['fractionDigits'] = $data[0];
    $currenciesMeta[$code]['roundingIncrement'] = $data[1];
}

$bundle = load_resource_bundle('en', $currDir);

foreach ($bundle->get('Currencies') as $code => $data) {
    $currencies[$code]['symbol'] = $data[0];
    $currencies[$code]['name']   = $data[1];

    if (!isset($currenciesMeta[$code])) {
        $currencies[$code]['fractionDigits'] = $defaultMeta['fractionDigits'];
        $currencies[$code]['roundingIncrement'] = $defaultMeta['roundingIncrement'];
        continue;
    }

    $currencies[$code]['fractionDigits'] = $currenciesMeta[$code]['fractionDigits'];
    $currencies[$code]['roundingIncrement'] = $currenciesMeta[$code]['roundingIncrement'];
}

// Countries.
$countriesConstraint = function($code) {
    // Global countries (f.i. "America") have numeric codes
    // Countries have alphabetic codes
    // "ZZ" is the code for unknown country
    if (ctype_alpha($code) && 'ZZ' !== $code) {
        return true;
    }

    return false;
};

$countries = get_data('Countries', $regionDir, $defaultLocale, $countriesConstraint);

// Languages
$languagesConstraint = function($code) {
    // "mul" is the code for multiple languages
    if ('mul' !== $code) {
        return true;
    }

    return false;
};

$languages = get_data('Languages', $langDir, $defaultLocale, $languagesConstraint);

// Display locales
$displayLocales = get_data('Locales', $namesDir, $defaultLocale);

// Create the stubs datafiles
$stubDir = $target.DIRECTORY_SEPARATOR.'stub';
$stubCurrDir = $stubDir.DIRECTORY_SEPARATOR.'curr';
$stubLangDir = $stubDir.DIRECTORY_SEPARATOR.'lang';
$stubNamesDir = $stubDir.DIRECTORY_SEPARATOR.'names';
$stubRegionDir = $stubDir.DIRECTORY_SEPARATOR.'region';

// Create the directories
make_directory($stubDir);
make_directory($stubCurrDir);
make_directory($stubLangDir);
make_directory($stubNamesDir);
make_directory($stubRegionDir);

clear_directory($stubCurrDir);
clear_directory($stubLangDir);
clear_directory($stubNamesDir);
clear_directory($stubRegionDir);

create_stub_datafile($defaultLocale, $stubCurrDir, $currencies);
create_stub_datafile($defaultLocale, $stubLangDir, $languages);
create_stub_datafile($defaultLocale, $stubNamesDir, $displayLocales);
create_stub_datafile($defaultLocale, $stubRegionDir, $countries);

// Clean up
clear_directory($currDir);
rmdir($currDir);


text:
package com.akira.mis.common.mapper;

import org.apache.ibatis.annotations.InsertProvider;

/**
 * Created by liuchang on 2017/7/4.
 */
public interface UpdateRelationMapper {
    @InsertProvider(type = RelationProvider.class, method = "dynamicSQL")
    void insertRelation(Relation relation);
    @InsertProvider(type = RelationProvider.class, method = "dynamicSQL")
    void deleteRelation(Relation relation);

}


text:
module app.dialogs.dataschemaimport {

    import IDialogService = angular.material.IDialogService;
    import IDialogOptions = angular.material.IDialogOptions;
    import IHttpService = angular.IHttpService;

    export class FromUrlHookService implements ImportHook {

        static $inject = ['DataschemaImportService', '$http'];

        constructor(importService:DataschemaImportService, private $http:IHttpService){
            importService.registerImportHook(this);
        }

        getTitle():string {
            return "URL";
        }

        getIconFont():string {
            return "language";
        }

        openDialog(wizard:AbstractWizard):void {
            wizard.addSteps([new FromUrlHookController(wizard, this.$http)]);
            wizard.next();
        }
    }

    angular.module('app.dialogs.url').service('FromUrlHookService', FromUrlHookService);
}


text:
<html>
<head>
<script type="text/javascript">
function runTest() {
  var canvas = document.getElementById("canvas1");
  if (!canvas)
    return false;
  var gl = canvas.getContext("experimental-webgl");
  if (!gl)
    gl = canvas.getContext("webgl");
  if (!gl)
    return false;
  var extension = gl.getExtension("WEBGL_debug_renderer_info") != null;

  var query = /query=(.*)/.exec(window.location.href);
  if (!query)
    return false;
  if (query[1] != "enabled" && query[1] != "disabled" &&
      query[1] != "bypassed")
    return false;
  var enabled = query[1] == "enabled";
  return extension == enabled;
}

function onLoad() {
  if (runTest())
    window.domAutomationController.send("SUCCESS");
  else
    window.domAutomationController.send("FAILURE");
}
</script>
</head>
<body onload="onLoad()">
<canvas id="canvas1" width="16px" height="16px">
</canvas>
</body>
</html>


text:
<?php
defined('C5_EXECUTE') or die("Access Denied.");

use Concrete\Core\Application\Service\FileManager;

$section = 'groups';

$app = Concrete\Core\Support\Facade\Application::getFacadeApplication();

$ih = $app->make('helper/concrete/ui');
$valt = $app->make('helper/validation/token');

$date = $app->make('helper/form/date_time');
$form = $app->make('helper/form');
/** @var FileManager $af */
$af = $app->make(FileManager::class);

$rootNode = $tree->getRootTreeNodeObject();

$guestGroupNode = GroupTreeNode::getTreeNodeByGroupID(GUEST_GROUP_ID);
$registeredGroupNode = GroupTreeNode::getTreeNodeByGroupID(REGISTERED_GROUP_ID);

$request = Request::getInstance();

use Concrete\Core\Support\Facade\Url;
use Concrete\Core\User\Group\GroupType; ?>

<form class="form-stacked" method="post" id="add-group-form" action="<?=$view->url('/dashboard/users/add_group/', 'do_add')?>">
    <?=$valt->output('add_or_update_group')?>
    <fieldset>
        <legend><?=t('Group Details')?></legend>

            <?=$form->label('gName', t('Name'))?>
            <input type="text" class="form-control" name="gName" value="<?=h($request->post('gName'))?>" />

            <?=$form->label('gDescription', t('Description'))?>

                <?=$form->textarea('gDescription', ['rows' => 6, 'class' => 'span6'])?>

            <?php echo $form->label('gtID', t('Group Type')); ?>
            <?php echo $form->select('gtID', GroupType::getSelectList()); ?>

                <?php echo t("Click %s to manage the group types.", sprintf(
                    "%s",
                    (string)Url::to("/dashboard/users/group_types"),
                    t("here")
                )); ?>

            <?php echo $form->label('gOverrideGroupTypeSettings', t('Type Settings')); ?>
            <?php echo $form->select('gOverrideGroupTypeSettings', [
                0 => t("Inherit settings from group type"),
                1 => t("Override settings from group type"),
            ]); ?>

                <?php echo $form->checkbox('gtPetitionForPublicEntry', 1, false, ["class" => "form-check-input"]); ?>
                <?php echo $form->label('gtPetitionForPublicEntry', t('Petition For Public Entry'), ["class" => "form-check-label"]); ?>

            <?php echo $form->label('gThumbnailFID', t('Thumbnail Image')); ?>
            <?php echo  $af->image('gThumbnailFID','gThumbnailFID', t("Please select")); ?>

            <?=t('Create Group Beneath')?>

                <div class="groups-tree" style="width: 460px" data-groups-tree="<?=$tree->getTreeID()?>">

                <?=$form->hidden('gParentNodeID')?>

    </fieldset>

    <fieldset class="override-group-type-setting">
        <legend>
            <?php echo t("Roles"); ?>
        </legend>

        <?php /** @noinspection PhpUnhandledExceptionInspection */
        echo View::element("groups/roles_list", ["roles" => [], "defaultRole" => null]); ?>
    </fieldset>

    <fieldset>

                <?=t('Image')?>

                    <?php
                    $af = $app->make('helper/concrete/asset_library');
                    echo $af->image('gBadgeFID', 'gBadgeFID', t('Choose Badge Image'), isset($badgeImage) ? $badgeImage : null);
                    ?>

                <?=$form->label('gBadgeDescription', t('Badge Description'))?>

                    <?=$form->textarea('gBadgeDescription', ['rows' => 6, 'class' => 'span6'])?>

                <?=$form->label('gBadgeCommunityPointValue', t('Community Points'))?>

                    <?=$form->text('gBadgeCommunityPointValue', $app->make('config')->get('concrete.user.group.badge.default_point_value'), ['class' => 'span1'])?>

    </fieldset>

    <fieldset>
        <legend><?=t('Automation')?></legend>

                    <?=$form->checkbox('gIsAutomated', 1, false)?>
                    <?=t('This group is automatically entered.')?> <i class="fa fa-question-circle launch-tooltip" title="<?=t("Automated Groups aren't assigned by administrators. They are checked against code at certain times that determines whether users should enter them.")?>">

                <?=t('Check Group')?>

                        <?=$form->checkbox('gCheckAutomationOnRegister', 1)?>
                        <?=t('When a user registers.')?>

                        <?=$form->checkbox('gCheckAutomationOnLogin', 1)?>
                        <?=t('When a user signs in.')?>

                        <?=$form->checkbox('gCheckAutomationOnJobRun', 1)?>
                        <?=t('When the "Check Automated Groups" Job runs.')?>

                    <?php
                    echo t('For custom automated group actions, make sure an automation group controller exists.');
                    ?>

                    <?=$form->checkbox('gUserExpirationIsEnabled', 1, false)?>
                    <?=t('Automatically remove users from this group.')?>

                <?=$form->select(
                    "gUserExpirationMethod",
                    [
                        'SET_TIME' => t('at a specific date and time'),
                        'INTERVAL' => t('once a certain amount of time has passed'),
                    ],
                    [
                        'disabled' => true,
                        'class' => 'form-control',
                    ]
                );?>

                <?=t('Expiration Date')?>
                <?=$date->datetime('gUserExpirationSetDateTime')?>

                <?=t('Accounts expire after')?>

                            <?=t('Days')?>
                            <?=t('Hours')?>
                            <?=t('Minutes')?>

                            <?=$form->text('gUserExpirationIntervalDays', ['style' => isset($style) ? $style : null, 'class' => 'span1'])?>
                            <?=$form->text('gUserExpirationIntervalHours', ['style' => isset($style) ? $style : null, 'class' => 'span1'])?>
                            <?=$form->text('gUserExpirationIntervalMinutes', ['style' => isset($style) ? $style : null, 'class' => 'span1'])?>

                <?=$form->label('gUserExpirationAction', t('Expiration Action'))?>

                    <?=$form->select(
                        "gUserExpirationAction",
                        [
                            'REMOVE' => t('Remove the user from this group'),
                            'DEACTIVATE' => t('Deactivate the user account'),
                            'REMOVE_DEACTIVATE' => t('Remove the user from the group and deactivate the account'),
                        ]
                    );?>

    </fieldset>

            <a href="<?=$app->make('url/manager')->resolve(['/dashboard/users/groups'])?>" class="btn btn-secondary float-left"><?=t('Cancel')?>
            <?=$form->submit('add', t('Add Group'), ['class' => 'btn btn-primary float-right'])?>

</form>


text:
package hmi.physics;

import hmi.animation.VJoint;
import hmi.math.Mat4f;
import hmi.math.Quat4f;
import hmi.math.Vec3f;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

public abstract class PhysicalHumanoid
{
    private ArrayList<PhysicalHumanoidListener> phListeners = new ArrayList<PhysicalHumanoidListener>();

    private boolean bIsEnabled = true;
    private float[] COM = new float[3];
    private float[] COMDiff = new float[3];

    private float[] COMNoContacts = new float[3];
    private float[] COMNoContactsDiff = new float[3];
    private float[] COMOffset = new float[3];
    private float[] COMOffsetDiff = new float[3];

    private float[] vecTemp = new float[3];
    private float[] qTemp = new float[4];

    // all physical segments besides the root segment
    private List<PhysicalSegment> segments = new ArrayList<PhysicalSegment>();
    protected List<PhysicalJoint> joints = new ArrayList<PhysicalJoint>();
    private PhysicalSegment rootSegment;

    // maps for quick access to physical joints and segments, segment maps include the root segment
    protected HashMap<String, PhysicalSegment> nameSegmentMap = new HashMap<String, PhysicalSegment>();
    protected HashMap<String, PhysicalJoint> namePhysicalJointMap = new HashMap<String, PhysicalJoint>();

    // simulation data to set on the humanoid
    protected float[] rootTranslationBuffer;
    protected float[] rootRotationBuffer;
    protected float[] COMBuffer = new float[3];
    protected float[] COMDiffBuffer = new float[3];
    protected float[] COMOffsetBuffer = new float[3];
    protected float[] COMOffsetDiffBuffer = new float[3];

    private float offsetMass = 0;
    private String id = "";

    // temp vars
    float m[] = new float[16];

    public void removeSegment(PhysicalSegment segment)
    {
        segments.remove(segment);
    }

    /**
     * Constructor
     */
    public PhysicalHumanoid(String id)
    {
        this.id = id;
        for (int i = 0; i < 3; i++)
        {
            COM[i] = 0;
            COMDiff[i] = 0;
            COMNoContacts[i] = 0;
            COMNoContactsDiff[i] = 0;
        }
    }

    public void addSegment(PhysicalSegment segment)
    {
        segments.add(segment);
        setupHashMaps(segment);
    }

    public void addRootSegment(PhysicalSegment segment)
    {
        rootSegment = segment;
        setupHashMaps(segment);
    }

    /**
     * Sets the CoM and derivates + all segments with the matching names to the state of ph COMOffset is set to 0
     *
     * @param ph
     */
    public void set(PhysicalHumanoid ph)
    {
        Vec3f.set(COM, ph.COM);
        Vec3f.set(COMDiff, ph.COMDiff);
        Vec3f.set(COMNoContacts, ph.COMNoContacts);
        Vec3f.set(COMNoContactsDiff, ph.COMNoContactsDiff);
        Vec3f.set(COMOffset, 0, 0, 0);
        if (rootSegment != null && ph.rootSegment != null)
        {
            rootSegment.box.setTorque(0, 0, 0);
            rootSegment.box.setForce(0, 0, 0);
            if (rootSegment.getSid().equals(ph.rootSegment.getSid()))
            {
                ph.rootSegment.getRotation(qTemp);
                rootSegment.setRotation(qTemp);
                ph.rootSegment.getAngularVelocity(vecTemp);
                rootSegment.setAngularVelocity(vecTemp);
                ph.rootSegment.getTranslation(vecTemp);
                rootSegment.setTranslation(vecTemp);
                ph.rootSegment.getVelocity(vecTemp);
                rootSegment.setVelocity(vecTemp);

                ph.rootSegment.box.getForce(vecTemp);
                rootSegment.box.addForce(vecTemp);
                ph.rootSegment.box.getTorque(vecTemp);
                rootSegment.box.addTorque(vecTemp);
            }
        }
        for (PhysicalSegment ps : segments)
        {
            ps.box.setTorque(0, 0, 0);
            ps.box.setForce(0, 0, 0);
            for (PhysicalSegment srcPs : ph.segments)
            {
                if (ps.getSid().equals(srcPs.getSid()))
                {
                    // System.out.println("Copying "+ps.getSid());

                    srcPs.getRotation(qTemp);
                    ps.setRotation(qTemp);
                    srcPs.getAngularVelocity(vecTemp);
                    ps.setAngularVelocity(vecTemp);
                    srcPs.getTranslation(vecTemp);
                    ps.setTranslation(vecTemp);
                    srcPs.getVelocity(vecTemp);
                    ps.setVelocity(vecTemp);
                    srcPs.box.getTorque(vecTemp);
                    ps.box.addTorque(vecTemp);
                    srcPs.box.getForce(vecTemp);
                    ps.box.addForce(vecTemp);
                }
            }
        }
    }

    /**
     * Creates a PhysicalJoint
     *
     * @param name joint name
     * @param seg1 corresponds with visual parent segment
     * @param seg2 corresponds with visual segment that rotates with the joint
     * @param anchor world position of the joint anchor
     * @return the created joint
     */
    public abstract PhysicalJoint setupJoint(String name, PhysicalSegment seg1, PhysicalSegment seg2, float[] anchor);

    /**
     * Creates a PhysicalSegment of the correct type for this PhysicalHumanoid subclass and makes sure its rigid body exists
     *
     * @return the created segment
     */
    public abstract PhysicalSegment createSegment(String segmentId, String segmentSid);

    /**
     * Create a new PhysicalHumanoid of the same type
     */
    public abstract PhysicalHumanoid createNew(String id);

    /**
     * Gets an array of segments, including the root segment. This is a copy of the actual arraylist containing the segments, so changes to the array
     * itself do not affect the PhysicalHumanoid.
     */
    public PhysicalSegment[] getSegments()
    {
        PhysicalSegment[] ps;
        if (rootSegment != null)
        {
            ps = new PhysicalSegment[segments.size() + 1];
            ps[0] = rootSegment;
            int i = 1;
            for (PhysicalSegment p : segments)
            {
                ps[i] = p;
                i++;
            }
        }
        else
        {
            ps = new PhysicalSegment[0];
        }
        return ps;
    }

    /**
     * Get the PhysicalJoint with this name in the Humanoid
     *
     * @param name joint name
     * @return the PhysicalJoint
     */
    public PhysicalJoint getJoint(String name)
    {
        PhysicalJoint pj = namePhysicalJointMap.get(name);
        if (pj == null)
        {
            pj = namePhysicalJointMap.get(name + "_joint");
        }
        if (pj == null)
        {
            // System.out.println("No joint named \"" + name+"\" or \"" + name+"_joint\" found in the following map:");
            // System.out.println(namePhysicalJointMap);
        }
        return pj;
    }

    /**
     * Get the PhysicalSegment with this start joint
     *
     * @param name name of the startJoint
     * @return the PhysicalSegment
     */
    public PhysicalSegment getSegment(String name)
    {
        // System.out.println(nameSegmentMap);
        PhysicalSegment seg = nameSegmentMap.get(name);
        if (seg == null)
        {
            seg = nameSegmentMap.get(name + "_segment");
        }
        if (seg == null)
        {
            // System.out.println("No segment named \"" + name+"\" or \"" + name+"_segment\" found in the following map:");
            // System.out.println(nameSegmentMap);
            // throw new RuntimeException();
        }
        return seg;
    }

    /**
     * Removes a physical segment from the name->segment hashmap
     *
     * @param ps the segment to remove
     */
    public void removeFromHashMap(PhysicalSegment ps)
    {
        nameSegmentMap.remove(ps.getSid());
    }

    /**
     * Add a PhysicalSegment to the name->segment HashMap
     *
     * @param ps the segment
     */
    public void setupHashMaps(PhysicalSegment ps)
    {
        if (ps.getSid() != null)
        {
            nameSegmentMap.put(ps.getSid(), ps);
        }
    }

    /*
     * public ConfigList getCurrentConfig() { ConfigList list = new ConfigList(1);
     *
     * return list; }
     */

    /**
     * Gets the current config, that is, position, rotation + derivates for all rigid bodies,
     */
    /*
     * public PhysicalHumanoidConfig getCurrentConfig() { ArrayList<SegmentConfiguration> segmentConfig = new ArrayList<SegmentConfiguration>();
     *
     * SegmentConfiguration sc = new SegmentConfiguration(); sc.segmentName = rootSegment.getName(); sc.config = rootSegment.getCurrentConfig();
     * segmentConfig.add(sc);
     *
     * for (PhysicalSegment ps:segments) { sc = new SegmentConfiguration(); sc.segmentName = ps.getName(); sc.config = ps.getCurrentConfig();
     * segmentConfig.add(sc); } PhysicalHumanoidConfig phc = new PhysicalHumanoidConfig(); phc.segConfigs = segmentConfig; return phc; }
     */
    /**
     * Sets a physicalhumanoid config, that is, position, rotation + derivates for all rigid bodies, sets all forces and torques to zero
     */
    /*
     * public void setConfig(PhysicalHumanoidConfig phc) { for (SegmentConfiguration sc:phc.segConfigs) { PhysicalSegment ps =
     * getSegment(sc.segmentName); ps.setConfig(sc.config); } for (PhysicalJoint pj: joints) { //disable motors pj.setMaximumForce(0, 0);
     * pj.setMaximumForce(1, 0); pj.setMaximumForce(2, 0); } }
     */

    /**
     * copy the simulation info to the root and joint local translation and rotation buffers
     */
    public void copy()
    {
        setRootSimInfo();

        for (PhysicalJoint pj : joints)
        {
            float[] buffer = pj.getRotationBuffer();
            if (buffer != null)
            {
                pj.getRotation(buffer);
            }
        }
        if (rootSegment != null)
        {
            rootSegment.box.copy();
        }
        for (PhysicalSegment seg : segments)
        {
            seg.box.copy();
        }
        Vec3f.set(COMBuffer, COM);
        Vec3f.set(COMDiffBuffer, COMDiff);
        Vec3f.set(COMOffsetBuffer, COMOffset);
        Vec3f.set(COMOffsetDiffBuffer, COMOffsetDiff);
        if (getCOMOffsetMass() > 0)
        {
            Vec3f.scale(1f / getCOMOffsetMass(), COMOffsetDiffBuffer);
            Vec3f.scale(1f / getCOMOffsetMass(), COMOffsetBuffer);
        }
    }

    /**
     * Checks if segments touch the ground and updates their onGrounds accordingly. The default implementation sets all onGrounds to false, subclasses
     * have to implement the handleCollisions function to detect ground collision.
     */
    public void updateCollision()
    {
        // clear ground contacts
        for (PhysicalSegment ps : segments)
        {
            ps.onGround = false;
        }
        rootSegment.onGround = false;

        handleCollisions();
    }

    /**
     * Disables or enables the PhysicalHumanoid. Disabled Humanoids are not updated with the physical simulation step and do not collide with other
     * bodies.
     *
     * @param enabled
     */
    public void setEnabled(boolean enabled)
    {
        bIsEnabled = enabled;
        if (rootSegment != null)
        {
            rootSegment.setEnabled(enabled);
        }
        for (PhysicalSegment ps : segments)
        {
            ps.setEnabled(enabled);
        }
        notifyPhysicalHumanListeners();
    }

    public boolean isEnabled()
    {
        return bIsEnabled;
    }

    public void addPhysicalHumanoidListener(PhysicalHumanoidListener phl)
    {
        synchronized (phListeners)
        {
            phListeners.add(phl);
        }
    }

    public void removePhysicalHumanoidListener(PhysicalHumanoidListener phl)
    {
        synchronized (phListeners)
        {
            phListeners.remove(phl);
        }
    }

    private void notifyPhysicalHumanListeners()
    {
        synchronized (phListeners)
        {
            for (PhysicalHumanoidListener phl : phListeners)
            {
                phl.physicalHumanEnabled(this, bIsEnabled);
            }
        }
    }

    /**
     * Gets the total mass of the humanoid
     *
     * @return the total mass
     */
    public float getTotalMass()
    {
        float totalMass = rootSegment.box.getMass();
        for (PhysicalSegment ps : segments)
        {
            totalMass += ps.box.getMass();
        }
        return totalMass;
    }

    /**
     * Offsets the COM
     *
     * @param offset offset, scaled by mass
     * @param mass mass of the offset
     */
    public void setCOMOffset(float offset[], float mass)
    {
        Vec3f.set(COMOffsetDiff, offset);
        Vec3f.sub(COMOffsetDiff, COMOffset);
        Vec3f.set(COMOffset, offset);
        offsetMass = mass;
    }

    public float getCOMOffsetMass()
    {
        return offsetMass;
    }

    @edu.umd.cs.findbugs.annotations.SuppressWarnings(value = "EI_EXPOSE_REP", justification = "Representations are exposed for efficiency reasons")
    public float[] getCOMOffset()
    {
        return COMOffset;
    }

    /**
     * Calculates the new Center Of Mass COM and COMDiff (=dCOM/dt)
     *
     * @param timeStep time since last update
     */
    public void updateCOM(float timeStep)
    {
        for (int i = 0; i < 3; i++)
        {
            v1[i] = 0;
            v3[i] = 0;
        }

        float totalMass = 0;
        float noContactMass = 0;
        if (rootSegment != null)
        {
            rootSegment.box.getTranslation(v2);
            Vec3f.scale(rootSegment.box.getMass(), v2);
            Vec3f.add(v1, v2);
            Vec3f.add(v3, v2);

            noContactMass = rootSegment.box.getMass();
            totalMass = rootSegment.box.getMass();
        }

        totalMass += offsetMass;
        Vec3f.add(v1, COMOffset);
        Vec3f.add(v3, COMOffset);

        for (PhysicalSegment ps : segments)
        {
            ps.box.getTranslation(v2);
            Vec3f.scale(ps.box.getMass(), v2);
            Vec3f.add(v1, v2);
            totalMass += ps.box.getMass();
            if (!ps.onGround)
            {
                Vec3f.add(v3, v2);
                noContactMass += ps.box.getMass();
            }
        }
        Vec3f.scale(1.0f / totalMass, v1);
        Vec3f.scale(1.0f / noContactMass, v3);

        if (timeStep == 0.0)
        {
            for (int i = 0; i < 3; i++)
            {
                COMDiff[i] = 0;
                COMOffsetDiff[i] = 0;
                COMNoContactsDiff[i] = 0;
            }
        }
        else
        {

            Vec3f.scale(1f / timeStep, COMOffsetDiff);

            Vec3f.set(v2, v1);
            Vec3f.sub(v2, COM);
            Vec3f.scale(1f / timeStep, v2);
            Vec3f.set(COMDiff, v2);

            Vec3f.set(v2, v3);
            Vec3f.sub(v2, COMNoContacts);
            Vec3f.scale(1f / timeStep, v2);
            Vec3f.set(COMNoContactsDiff, v2);
        }
        Vec3f.set(COM, v1);
        Vec3f.set(COMNoContacts, v3);

        if (Vec3f.length(COMDiff) > 1)
        {
            // System.out.println("com offset ("+timeStep+")"+Vec3f.toString(COMOffset));
            // System.out.println("com diff   ("+timeStep+")"+Vec3f.toString(COMDiff));
        }

    }

    /**
     * Get String representation
     */
    @Override
    public String toString()
    {
        return "Segments: " + segments.toString() + "\n" + "Joints: " + joints.toString();
    }

    /**
     * @return the last calculated COM, use updateCOM to calculate the current COM
     */
    @edu.umd.cs.findbugs.annotations.SuppressWarnings(value = "EI_EXPOSE_REP", justification = "Representations are exposed for efficiency reasons")
    public float[] getCOM()
    {
        return COM;
    }

    /**
     * @return the last calculated COMDiff, use updateCOM to calculate the current COMDiff
     */
    @edu.umd.cs.findbugs.annotations.SuppressWarnings(value = "EI_EXPOSE_REP", justification = "Representations are exposed for efficiency reasons")
    public float[] getCOMDiff()
    {
        return COMDiff;
    }

    /**
     * Get the COM excluding feet weights
     *
     * @return the COMNoFeet
     */
    @edu.umd.cs.findbugs.annotations.SuppressWarnings(value = "EI_EXPOSE_REP", justification = "Representations are exposed for efficiency reasons")
    public float[] getCOMNoContacts()
    {
        return COMNoContacts;
    }

    /**
     * Get the dCOM/dt excluding feet weights
     *
     * @return the COMNoFeetDiff
     */
    @edu.umd.cs.findbugs.annotations.SuppressWarnings(value = "EI_EXPOSE_REP", justification = "Representations are exposed for efficiency reasons")
    public float[] getCOMNoContactsDiff()
    {
        return COMNoContactsDiff;
    }

    /**
     * @param rootRotationBuffer the rootRotationBuffer to set
     */
    @edu.umd.cs.findbugs.annotations.SuppressWarnings(value = "EI_EXPOSE_REP2", justification = "Representations are exposed for efficiency reasons")
    public void setRootRotationBuffer(float[] rootRotationBuffer)
    {
        this.rootRotationBuffer = rootRotationBuffer;
    }

    /**
     * @param rootTranslationBuffer the rootTranslationBuffer to set
     */
    @edu.umd.cs.findbugs.annotations.SuppressWarnings(value = "EI_EXPOSE_REP2", justification = "Representations are exposed for efficiency reasons")
    public void setRootTranslationBuffer(float[] rootTranslationBuffer)
    {
        this.rootTranslationBuffer = rootTranslationBuffer;
    }

    @edu.umd.cs.findbugs.annotations.SuppressWarnings(value = "EI_EXPOSE_REP2", justification = "Representations are exposed for efficiency reasons")
    public void setCOMBuffer(float[] COMBuffer)
    {
        this.COMBuffer = COMBuffer;
    }

    @edu.umd.cs.findbugs.annotations.SuppressWarnings(value = "EI_EXPOSE_REP2", justification = "Representations are exposed for efficiency reasons")
    public void setCOMDiffBuffer(float[] COMDiffBuffer)
    {
        this.COMDiffBuffer = COMDiffBuffer;
    }

    @edu.umd.cs.findbugs.annotations.SuppressWarnings(value = "EI_EXPOSE_REP2", justification = "Representations are exposed for efficiency reasons")
    public void setCOMOffsetDiffBuffer(float[] COMOffsetDiffBuffer)
    {
        this.COMOffsetDiffBuffer = COMOffsetDiffBuffer;
    }

    @edu.umd.cs.findbugs.annotations.SuppressWarnings(value = "EI_EXPOSE_REP2", justification = "Representations are exposed for efficiency reasons")
    public void setCOMOffsetBuffer(float[] COMOffsetBuffer)
    {
        this.COMOffsetBuffer = COMOffsetBuffer;
    }

    private void setRootSimInfo()
    {
        if (rootSegment != null)
        {
            Vec3f.set(v1, rootSegment.startJointOffset);
            rootSegment.box.getRotation(rootRotationBuffer);

            Quat4f.transformVec3f(rootRotationBuffer, v1);
            rootSegment.box.getTranslation(v2);
            Vec3f.add(rootTranslationBuffer, v1, v2);
        }
    }

    /**
     * Cleans up joint structure, call when the human is removed
     */
    public void clear()
    {
        if (rootSegment != null)
        {
            rootSegment.clear();
        }
        for (PhysicalSegment s : segments)
        {
            s.clear();
        }
        segments.clear();
        joints.clear();
        rootSegment = null;
        nameSegmentMap.clear();
        namePhysicalJointMap.clear();
    }

    /**
     * Translates the physical humanoid
     *
     * @param trans new physical world position of the humanoid
     */
    public void setRelativeTranslation(float[] trans)
    {
        float oldTrans[] = new float[3];
        float absTrans[] = new float[3];
        rootSegment.getTranslation(oldTrans);
        Vec3f.add(absTrans, trans, oldTrans);
        rootSegment.setTranslation(absTrans);
        for (PhysicalSegment s : segments)
        {
            s.getTranslation(oldTrans);
            Vec3f.add(absTrans, trans, oldTrans);
            s.setTranslation(absTrans);
        }
    }

    /**
     * Rotates the physical humanoid around some center
     *
     * @param center
     * @param q
     */
    public void setRotation(float[] center, float q[])
    {
        float oldTrans[] = new float[3];
        float trans[] = new float[3];

        rootSegment.getTranslation(oldTrans);
        Vec3f.sub(trans, oldTrans, center);
        rootSegment.setRotation(q);
        Quat4f.transformVec3f(q, trans);
        rootSegment.setTranslation(trans);

        for (PhysicalSegment s : segments)
        {
            s.getTranslation(oldTrans);
            Vec3f.sub(trans, oldTrans, center);
            Quat4f.transformVec3f(q, trans);
            s.setRotation(q);
            s.setTranslation(trans);
        }
    }

    /**
     * Translates the physical humanoid
     */
    public void setRelativeTranslation(float x, float y, float z)
    {
        float oldTrans[] = new float[3];
        float absTrans[] = new float[3];
        rootSegment.getTranslation(oldTrans);
        Vec3f.set(absTrans, x, y, z);
        Vec3f.add(absTrans, oldTrans);
        rootSegment.setTranslation(absTrans);
        for (PhysicalSegment s : segments)
        {
            s.getTranslation(oldTrans);
            Vec3f.set(absTrans, x, y, z);
            Vec3f.add(absTrans, oldTrans);
            s.setTranslation(absTrans);
        }
    }

    protected void handleCollisions()
    {

    }

    /**
     * @return the id
     */
    public String getId()
    {
        return id;
    }

    private void setJoint(VJoint vj)
    {
        PhysicalSegment ps = getSegment(vj.getSid());
        float v[] = new float[3];
        if (ps != null)
        {
            m = vj.getGlobalMatrix();
            Quat4f.setFromMat4f(qTemp, m);
            Vec3f.scale(-1, v, ps.startJointOffset);
            Mat4f.transformPoint(m, vecTemp, v);
            ps.setTranslation(vecTemp);
            ps.setRotation(qTemp);
        }
    }

    public void setPoseFromVJoint(VJoint vj)
    {
        for (VJoint vjParts : vj.getParts())
        {
            setJoint(vjParts);
        }
    }

    public void setNullPoseFromVJoint(VJoint vj)
    {
        vj.calculateMatrices();
        for (VJoint vjParts : vj.getParts())
        {
            setNullPoseForJoint(vjParts);
        }
    }

    private void setNullPoseForJoint(VJoint vj)
    {
        PhysicalSegment ps = getSegment(vj.getSid());
        float v[] = new float[3];
        float vTemp[] = new float[3];
        float vTempOld[] = new float[3];
        float qTemp2[] = new float[4];
        if (ps != null)
        {
            ps.getTranslation(vTempOld);
            m = vj.getGlobalMatrix();
            Quat4f.setFromMat4f(qTemp, m);
            Vec3f.scale(-1, v, ps.startJointOffset);
            Mat4f.transformPoint(m, vecTemp, v);
            ps.setTranslation(vecTemp);

            // rotate collision representation
            for (CollisionShape sh : ps.box.getCollisionShapes())
            {
                sh.getTranslation(vTemp);
                Quat4f.transformVec3f(qTemp, vTemp);
                sh.setTranslation(vTemp);

                sh.getRotation(qTemp2);
                Quat4f.mul(qTemp2, qTemp, qTemp2);
                Quat4f.normalize(qTemp2);
                sh.setRotation(qTemp2);
                // sh.setRotation(qTemp);
            }

            // set inertia tensor
            ps.box.rotateInertiaTensor(qTemp);
            // Vec3f.sub(vecTemp, vTempOld);
            // ps.box.translateInertiaTensor(vecTemp);

            // reset joint, joint offset
            Quat4f.transformVec3f(qTemp, ps.startJointOffset);
            float anchor[] = new float[3];
            vj.getPathTranslation(null, anchor);
            if (ps.startJoint != null)
            {
                ps.startJoint.setAnchor(anchor[0], anchor[1], anchor[2]);
            }
        }
    }

    // temp vars, so it's not necesary to recreate them every simulation step
    private float[] v1 = new float[3];
    private float[] v2 = new float[3];
    private float[] v3 = new float[3];

    /**
     * @return the cOMOffsetDiff, scaled by mass
     */
    @edu.umd.cs.findbugs.annotations.SuppressWarnings(value = "EI_EXPOSE_REP", justification = "Representations are exposed for efficiency reasons")
    public float[] getCOMOffsetDiff()
    {
        return COMOffsetDiff;
    }

    /**
     * @return the rootSegment
     */
    public PhysicalSegment getRootSegment()
    {
        return rootSegment;
    }

    public void setRootSegment(PhysicalSegment rs)
    {
        rootSegment = rs;
    }

    /**
     * @return an unmodifiable view of the joint list
     */
    public List<PhysicalJoint> getJoints()
    {
        return Collections.unmodifiableList(joints);
    }
}


text:
import marked from 'marked';

export class HTMLFcMarkdown extends HTMLElement {

    set markdownContent(value) {
        this._md = value || '';
        this.innerHTML = marked(this._md);
    }

    get markdownContent() {
        return this._md || '';
    }

}

window.customElements.define('fc-markdown', HTMLFcMarkdown);