text:
// ==========================================================================
//  Squidex Headless CMS
// ==========================================================================
//  Copyright (c) Squidex UG (haftungsbeschraenkt)
//  All rights reserved. Licensed under the MIT license.
// ==========================================================================

using System.Text.Json.Serialization;
using Elasticsearch.Net;
using Squidex.Domain.Apps.Core.HandleRules;
using Squidex.Domain.Apps.Core.Rules.EnrichedEvents;
using Squidex.Domain.Apps.Core.Scripting;
using Squidex.Infrastructure;
using Squidex.Infrastructure.Json;

#pragma warning disable IDE0059 // Value assigned to symbol is never used
#pragma warning disable MA0048 // File name must match type name

namespace Squidex.Extensions.Actions.ElasticSearch;

public sealed class ElasticSearchActionHandler : RuleActionHandler<ElasticSearchAction, ElasticSearchJob>
{
    private readonly ClientPool<(Uri Host, string Username, string Password), ElasticLowLevelClient> clients;
    private readonly IScriptEngine scriptEngine;
    private readonly IJsonSerializer serializer;

    public ElasticSearchActionHandler(RuleEventFormatter formatter, IScriptEngine scriptEngine, IJsonSerializer serializer)
        : base(formatter)
    {
        clients = new ClientPool<(Uri Host, string Username, string Password), ElasticLowLevelClient>(key =>
        {
            var config = new ConnectionConfiguration(key.Host);

            if (!string.IsNullOrEmpty(key.Username) && !string.IsNullOrWhiteSpace(key.Password))
            {
                config = config.BasicAuthentication(key.Username, key.Password);
            }

            return new ElasticLowLevelClient(config);
        });

        this.scriptEngine = scriptEngine;
        this.serializer = serializer;
    }

    protected override async Task<(string Description, ElasticSearchJob Data)> CreateJobAsync(EnrichedEvent @event, ElasticSearchAction action)
    {
        var delete = @event.ShouldDelete(scriptEngine, action.Delete);

        string contentId;

        if (@event is IEnrichedEntityEvent enrichedEntityEvent)
        {
            contentId = enrichedEntityEvent.Id.ToString();
        }
        else
        {
            contentId = DomainId.NewGuid().ToString();
        }

        var ruleDescription = string.Empty;
        var ruleJob = new ElasticSearchJob
        {
            IndexName = await FormatAsync(action.IndexName, @event),
            ServerHost = action.Host.ToString(),
            ServerUser = action.Username,
            ServerPassword = action.Password,
            ContentId = contentId
        };

        if (delete)
        {
            ruleDescription = $"Delete entry index: {action.IndexName}";
        }
        else
        {
            ruleDescription = $"Upsert to index: {action.IndexName}";

            ElasticSearchContent content;
            try
            {
                string jsonString;

                if (!string.IsNullOrEmpty(action.Document))
                {
                    jsonString = await FormatAsync(action.Document, @event);
                    jsonString = jsonString?.Trim();
                }
                else
                {
                    jsonString = ToJson(@event);
                }

                content = serializer.Deserialize<ElasticSearchContent>(jsonString);
            }
            catch (Exception ex)
            {
                content = new ElasticSearchContent
                {
                    More = new Dictionary<string, object>
                    {
                        ["error"] = $"Invalid JSON: {ex.Message}"
                    }
                };
            }

            content.ContentId = contentId;

            ruleJob.Content = serializer.Serialize(content, true);
        }

        return (ruleDescription, ruleJob);
    }

    protected override async Task<Result> ExecuteJobAsync(ElasticSearchJob job,
        CancellationToken ct = default)
    {
        if (string.IsNullOrWhiteSpace(job.ServerHost))
        {
            return Result.Ignored();
        }

        var client = await clients.GetClientAsync((new Uri(job.ServerHost, UriKind.Absolute), job.ServerUser, job.ServerPassword));

        try
        {
            if (job.Content != null)
            {
                var response = await client.IndexAsync<StringResponse>(job.IndexName, job.ContentId, job.Content, ctx: ct);

                return Result.SuccessOrFailed(response.OriginalException, response.Body);
            }
            else
            {
                var response = await client.DeleteAsync<StringResponse>(job.IndexName, job.ContentId, ctx: ct);

                return Result.SuccessOrFailed(response.OriginalException, response.Body);
            }
        }
        catch (ElasticsearchClientException ex)
        {
            return Result.Failed(ex);
        }
    }
}

public sealed class ElasticSearchContent
{
    public string ContentId { get; set; }

    [JsonExtensionData]
    public Dictionary<string, object> More { get; set; } = new Dictionary<string, object>();
}

public sealed class ElasticSearchJob
{
    public string ServerHost { get; set; }

    public string ServerUser { get; set; }

    public string ServerPassword { get; set; }

    public string ContentId { get; set; }

    public string Content { get; set; }

    public string IndexName { get; set; }
}


text:
package com.idea.it.core.menue;

import java.util.List;

import com.idea.it.core.context.IIdeaServletHandler;
import com.idea.it.core.menue.vo.MenueVO;

/**
 * 类说明
 *
 * @author ****
 * @date 2017年8月11日 新建
 */
public interface IMenueOperatable extends IIdeaServletHandler
{

    /**
     * 查询菜单栏目
     *
     * @param appName
     * @return
     */
    List<MenueVO> queryMenues( String appName );
}

redpajama_set_name: RedPajamaGithub


text:
jint JNI_OnLoad(JavaVM* vm, void* reserved)
{
    JNIEnv* env;
    if (vm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_6) != JNI_OK) {
        return -1;
    }

    // Get jclass with env->FindClass.
    // Register methods with env->RegisterNatives.

    return JNI_VERSION_1_6;
}


text:
#include "paddle/fluid/operators/fc_op.h"
#include <vector>

namespace paddle {
namespace operators {

class FCOp : public framework::OperatorWithKernel {
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

  void InferShape(framework::InferShapeContext* ctx) const override {
    PADDLE_ENFORCE_EQ(ctx->HasInput("Input"), true,
                      "X(Input) of Fully Connected should not be null.");
    PADDLE_ENFORCE_EQ(ctx->HasOutput("Out"), true,
                      "Out(Output) of Fully Connected should not be null.");
    PADDLE_ENFORCE_EQ(ctx->HasInput("W"), true,
                      "W(Input) of Fully Connected should not be null.");

    auto in_dims = ctx->GetInputDim("Input");
    auto w_dims = ctx->GetInputDim("W");

    if (ctx->HasInput("Bias")) {
      auto bias_dims = ctx->GetInputDim("Bias");
      if (bias_dims.size() == 2) {
        PADDLE_ENFORCE_EQ(bias_dims[0], 1,
                          "The shape of Bias must be [1, dim].");
        PADDLE_ENFORCE_EQ(bias_dims[1], w_dims[1],
                          "The shape of Bias must be [1, dim].");
      } else if (bias_dims.size() == 1) {
        PADDLE_ENFORCE_EQ(bias_dims[0], w_dims[1],
                          "The shape of Bias must be [1, dim].");
      }
    }

    auto& activation_type = ctx->Attrs().Get<std::string>("activation_type");
    if (!activation_type.empty()) {
      PADDLE_ENFORCE_EQ(activation_type, "relu",
                        "Activation %s is not supportetd in fc now.",
                        activation_type.c_str());
    }
    if (ctx->Attrs().Get<bool>("use_mkldnn")) {
      PADDLE_ENFORCE_EQ(in_dims.size() == 2 || in_dims.size() == 4, true,
                        "Fully Connected input should be 2-D or 4-D tensor.");
    }
    PADDLE_ENFORCE_EQ(w_dims.size(), 2,
                      "Fully Connected input should be 2-D tensor.");
    int in_num_col_dims = ctx->Attrs().Get<int>("in_num_col_dims");
    PADDLE_ENFORCE_GT(
        in_dims.size(), in_num_col_dims,
        "The input tensor Input's rank of FCOp should be larger than "
        "in_num_col_dims.");

    std::vector<int64_t> output_dims;
    FCOutputSize(in_dims, w_dims, output_dims, in_num_col_dims);

    ctx->SetOutputDim("Out", framework::make_ddim(output_dims));
    ctx->ShareLoD("Input", "Out");
  }

 protected:
  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext& ctx) const override {
    framework::LibraryType library = framework::LibraryType::kPlain;
    framework::DataLayout layout = framework::DataLayout::kAnyLayout;
    if (ctx.Attr<bool>("use_mkldnn")) {
      library = framework::LibraryType::kMKLDNN;
      layout = framework::DataLayout::kMKLDNN;
    }
    return framework::OpKernelType(
        OperatorWithKernel::IndicateVarDataType(ctx, "Input"), ctx.GetPlace(),
        layout, library);
  }
};

class FCOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
  void Make() override {
    AddInput("Input",
             "(Tensor), The input tensor of fully connected operator.");
    AddInput("W", "(Tensor), The weight fc op with shape (I, O).");
    AddInput("Bias", "(Tensor, optional) Bias vector with shape (1 x O")
        .AsDispensable();
    AddOutput("Out",
              "(Tensor) The output tensor of fully connected operator. ");
    AddAttr<int>("in_num_col_dims",
                 "(int, default 1), The fc op can take tensors with more than "
                 "two dimensions as its inputs.")
        .SetDefault(1)
        .EqualGreaterThan(1);
    AddAttr<std::string>("activation_type",
                         "Activation type used in fully connected operator.")
        .SetDefault("");
    AddAttr<bool>("use_mkldnn",
                  "(bool, default false) Only used in mkldnn kernel")
        .SetDefault(false);
    AddAttr<bool>(framework::kAllKernelsMustComputeRuntimeShape,
                  "Skip calling InferShape() function in the runtime.")
        .SetDefault(true);
    AddComment(R"DOC(
Fully Connected Operator.

The fully connected operation calculates the output based on the input, weights and bias.
The size of each dimension of the parameters checked in the infer-shape.
)DOC");
  }
};

}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
REGISTER_OPERATOR(fc, ops::FCOp, ops::FCOpMaker,
                  paddle::framework::EmptyGradOpMaker);
REGISTER_OP_CPU_KERNEL(
    fc, ops::FCOpKernel<paddle::platform::CPUDeviceContext, float>,
    ops::FCOpKernel<paddle::platform::CPUDeviceContext, double>);


text:
@interface DXAppManager : NSObject

+ (instancetype)sharedInstance;

@property (weak,nonatomic) NSManagedObjectContext *pManagedContext;
@property (weak,nonatomic) DXAppDelegate *pAppDelegate;

@end


text:
/* eslint-disable complexity */
import {
  PortableTextEditor,
  usePortableTextEditor,
  PortableTextBlock,
} from '@sanity/portable-text-editor'
import {Path, isKeySegment, isKeyedObject} from '@sanity/types'
import {useMemo} from 'react'
import {ObjectEditData} from '../types'

// This hook will gather the info we need to create a edit modal for some embedded object in the editor
// based on the current focusPath details.
export function useObjectEditData(
  focusPath: Path,
  refs: {
    block: React.MutableRefObject<HTMLDivElement>
    child: React.MutableRefObject<HTMLSpanElement>
    inline: React.MutableRefObject<HTMLSpanElement>
  }
): ObjectEditData | null {
  const editor = usePortableTextEditor()
  const blockKey = focusPath && isKeySegment(focusPath[0]) ? focusPath[0]._key : undefined
  const isChild =
    blockKey && focusPath && focusPath[1] === 'children' && isKeyedObject(focusPath[2])
  const childKey = isChild && isKeyedObject(focusPath[2]) ? focusPath[2]._key : undefined
  const isAnnotation = blockKey && focusPath[1] === 'markDefs'
  const markDefKey = isAnnotation && isKeyedObject(focusPath[2]) ? focusPath[2]._key : undefined
  const focusPathLength = focusPath.length
  return useMemo(() => {
    // Annotations
    if (markDefKey) {
      const [node] = PortableTextEditor.findByPath(editor, [{_key: blockKey}])
      const block = node ? (node as PortableTextBlock) : undefined
      if (markDefKey) {
        const span = block.children.find(
          (child) => Array.isArray(child.marks) && child.marks.includes(markDefKey)
        )
        if (span) {
          return {
            editorPath: [{_key: blockKey}, 'children', {_key: span._key}],
            formBuilderPath: [{_key: blockKey}, 'markDefs', {_key: markDefKey}],
            kind: 'annotation',
            editorHTMLElementRef: refs.child,
          }
        }
      }
    }

    // Inline object
    if (blockKey && childKey && focusPathLength > 3) {
      const path = [{_key: blockKey}, 'children', {_key: childKey}]
      return {
        editorPath: path,
        formBuilderPath: path,
        kind: 'inlineObject',
        editorHTMLElementRef: refs.child,
      }
    }

    // Block object
    if (blockKey && !childKey && focusPathLength > 1) {
      const path = [{_key: blockKey}]
      return {
        editorPath: path,
        formBuilderPath: path,
        kind: 'blockObject',
        editorHTMLElementRef: refs.block,
      }
    }
    refs.child.current = null
    refs.block.current = null
    return null
  }, [editor, blockKey, childKey, markDefKey, refs.block, refs.child, focusPathLength])
}


text:
// UUID
// https://gist.github.com/LeverOne/1308368
/* jshint ignore:start */
function uuid (a, b) { for (b = a = ''; a++ < 36; b += a * 51 & 52 ? (a ^ 15 ? 8 ^ Math.random() * (a ^ 20 ? 16 : 4) : 4).toString(16) : '-');return b }
/* jshint ignore:end */

// Credits to typicode/lodash-id
// Based on: https://github.com/typicode/lodash-id/blob/adf8c8e99e598c448e6db6ec5705de9d9edb96ed/src/index.js
module.exports = {
  // Empties properties
  __empty: function (doc) {
    this.forEach(doc, function (value, key) {
      delete doc[key]
    })
  },

  // Copies properties from an object to another
  __update: function (dest, src) {
    this.forEach(src, function (value, key) {
      dest[key] = value
    })
  },

  // Removes an item from an array
  __remove: function (array, item) {
    const index = this.indexOf(array, item)
    if (index !== -1) array.splice(index, 1)
  },

  __id: function () {
    const id = this.id || 'id'
    return id
  },

  // TODO: Handle situation when collection has docs with id === null
  getById: function (collection, id) {
    const self = this
    return this.find(collection, function (doc) {
      if (self.has(doc, self.__id())) {
        return doc[self.__id()].toString() === id.toString()
      }
    })
  },

  createId: function (collection, doc) {
    return uuid()
  },

  insert: function (collection, doc) {
    doc[this.__id()] = doc[this.__id()] || this.createId(collection, doc)
    const d = this.getById(collection, doc[this.__id()])
    if (d) throw new Error('Insert failed, duplicate id')
    collection.push(doc)
    return doc
  },

  upsert: function (collection, doc) {
    if (doc[this.__id()]) {
      // id is set
      const d = this.getById(collection, doc[this.__id()])
      if (d) {
        // replace properties of existing object
        this.__empty(d)
        this.assign(d, doc)
      } else {
        // push new object
        collection.push(doc)
      }
    } else {
      // create id and push new object
      doc[this.__id()] = this.createId(collection, doc)
      collection.push(doc)
    }

    return doc
  },

  updateById: function (collection, id, attrs) {
    const doc = this.getById(collection, id)

    if (doc) {
      this.assign(doc, attrs, { id: doc.id })
    }

    return doc
  },

  updateWhere: function (collection, predicate, attrs) {
    const self = this
    const docs = this.filter(collection, predicate)

    docs.forEach(function (doc) {
      self.assign(doc, attrs, { id: doc.id })
    })

    return docs
  },

  replaceById: function (collection, id, attrs) {
    const doc = this.getById(collection, id)

    if (doc) {
      const docId = doc.id
      this.__empty(doc)
      this.assign(doc, attrs, { id: docId })
    }

    return doc
  },

  removeById: function (collection, id) {
    const doc = this.getById(collection, id)

    this.__remove(collection, doc)

    return doc
  },

  removeWhere: function (collection, predicate) {
    const self = this
    const docs = this.filter(collection, predicate)

    docs.forEach(function (doc) {
      self.__remove(collection, doc)
    })

    return docs
  }
}


text:
package org.commoniab;

interface IABConst {
    String TAG = "IABConst";

    // actions messages
    String BILLING_PLUGGIN_IS_NOT_INITIALIZED = "Billing plugin was not initialized";
    String BILLING_SUPPORTED_CALLBACK = "OnBillingSupported";
    String BILLING_NOT_SUPPORTED_CALLBACK = "OnBillingNotSupported";
    String QUERY_INVENTORY_SUCCEEDED_CALLBACK = "OnQueryInventorySucceeded";
    String QUERY_INVENTORY_FAILED_CALLBACK = "OnQueryInventoryFailed";
    String PURCHASE_SUCCEEDED_CALLBACK = "OnPurchaseSucceeded";
    String PURCHASE_FAILED_CALLBACK = "OnPurchaseFailed";
    String CONSUME_PURCHASE_SUCCEEDED_CALLBACK = "OnConsumePurchaseSucceeded";
    String CONSUME_PURCHASE_FAILED_CALLBACK = "OnConsumePurchaseFailed";
    String MAP_SKU_FAILED_CALLBACK = "OnMapSkuFailed";
    String MAP_SKU_SUCCEEDED_CALLBACK = "OnMapSkuSucceeded";

    //Keys for options json object from javascript
    String OPTION_CHECKINVENTORY = "checkInventory";
    String OPTION_VERIFYMODE = "verifyMode";
    String OPTION_DISCOVERYTIMEOUT = "discoveryTimeout";
    String OPTION_CHECKINVENTORYTIMEOUT= "checkInventoryTimeout";
    String OPTION_SAMSUNGCERTIFICATIONREQUESTCODE= "samsungCertificationRequestCode";
    String OPTION_PREFERREDSTORENAMES = "preferredStoreNames";
    String OPTION_STOREKEYS = "storeKeys";

    //Subscription result key to pass to js, JSON {"result:true/false"}
    String SUBSCRIPTION_RESULT_KEY = "result";

    // Purchase keys to transfer to purchase activity
    String PURCHASE_KEY_SKU = "sku";
    String PURCHASE_KEY_INAPP = "inapp";
    String PURCHASE_KEY_DEVPAYLOAD = "developerPayload";
    String PURCHASE_KEY_APPSTORENAME = "appstoreName";
    String PURCHASE_KEY_ORIGINALJSON = "originalJson";
    String PURCHASE_KEY_PACKAGENAME = "packageName";
    String PURCHASE_KEY_TOKEN = "token";
    String PURCHASE_KEY_ITEMTYPE = "itemType";
    String PURCHASE_KEY_SIGNATURE = "signature";

    // Yandex specific information
    String YANDEX_STORE_SERVICE = "com.yandex.store.service";
    String YANDEX_STORE_ACTION_PURCHASE_STATE_CHANGED = YANDEX_STORE_SERVICE + ".PURCHASE_STATE_CHANGED";
    int RC_REQUEST = 10001; /**< (arbitrary) request code for the purchase flow */
}


text:
package com.spotify.featran.transformers

import com.spotify.featran.{FeatureBuilder, FeatureRejection, FlatReader, FlatWriter}
import com.twitter.algebird.{Aggregator, Max}

/**
 * Transform features by rescaling each feature to range [-1, 1] by dividing through the maximum
 * absolute value in each feature.
 *
 * Missing values are transformed to 0.0.
 *
 * When using aggregated feature summary from a previous session, out of bound values are truncated
 * to -1.0 or 1.0 and [[FeatureRejection.OutOfBound]] rejections are reported.
 */
object MaxAbsScaler extends SettingsBuilder {

  /** Create a new [[MaxAbsScaler]] instance. */
  def apply(name: String): Transformer[Double, Max[Double], Double] =
    new MaxAbsScaler(name)

  /**
   * Create a new [[MaxAbsScaler]] from a settings object
   * @param setting
   *   Settings object
   */
  def fromSettings(setting: Settings): Transformer[Double, Max[Double], Double] =
    MaxAbsScaler(setting.name)
}

private[featran] class MaxAbsScaler(name: String)
    extends OneDimensional[Double, Max[Double], Double](name) {
  override val aggregator: Aggregator[Double, Max[Double], Double] =
    Aggregators.from[Double](x => Max(math.abs(x))).to(_.get)
  override def buildFeatures(a: Option[Double], c: Double, fb: FeatureBuilder[_]): Unit = a match {
    case Some(x) =>
      // truncate x to [-max, max]
      val truncated = math.min(math.abs(x), c) * math.signum(x)
      fb.add(name, truncated / c)
      if (math.abs(x) > c) {
        fb.reject(this, FeatureRejection.OutOfBound(-c, c, x))
      }
    case None => fb.skip()
  }
  override def encodeAggregator(c: Double): String = c.toString
  override def decodeAggregator(s: String): Double = s.toDouble
  override def flatRead[T: FlatReader]: T => Option[Any] = FlatReader[T].readDouble(name)

  override def flatWriter[T](implicit fw: FlatWriter[T]): Option[Double] => fw.IF =
    fw.writeDouble(name)
}


text:
%% Time Frequency
% 1) Calculate TF at source level on given frequency
% 2) TF is separate long and short session (with bst loops)
% 3) other loops are made separately for subjects,

%% PRELIMINARY PREPARATION
clear

run('NOPOSA_startpath')

cd(curr_path)
addpath(genpath('functions'))

% launch brainstorm, with no gui (but only if is not already running)
if ~brainstorm('status')
    brainstorm %nogui
end

%% SET EXPORT FOLDER FOR REPORTS
export_main_folder=curr_path;
export_folder='Reports';

if ~exist([export_main_folder, '/' export_folder])
    mkdir([export_main_folder, '/' export_folder]) % create folder if it does not exist
end;

%% GET CURRENT SCRIPT NAME

script_name = mfilename('fullpath')

if (length(script_name) == 0)
    error('You must run this script by calling it from the prompt or clicking the Run button!')
end

%%

%% SET PROTOCOL
ProtocolName = 'NOPOSA_analysis1';

% get the protocol index, knowing the name
iProtocol = bst_get('Protocol', ProtocolName);

% set the current protocol
gui_brainstorm('SetCurrentProtocol', iProtocol);

% check info
ProtocolInfo=bst_get('ProtocolInfo')

% get the subject list
my_subjects = bst_get('ProtocolSubjects')

%% SELECT FILES WITH BRAINSTORM FUNCTION
% select all files

% Input files
sFiles = [];

%% SELECT SUBJECT NAMES (note that only subject names are used to calculate bem).
SubjectNames = sel_files_bst({my_subjects.Subject.Name}, '.');

%% SELECT FILES
% select all files

% Input files
sFiles = [];
% SubjectNames = {...
%     'All'};

%% LOOP OVER SHORT/LONG

% I use the selection by comment of bst cause I could not add the tag to the comment
Session_names={'long', 'short'};

for iSession=1:length(Session_names);

    % Process: Select data files in: */*
    my_sFiles_ini = bst_process('CallProcess', 'process_select_files_data', [], [], ...
        'subjectname',   SubjectNames, ...
        'condition',     '', ...
        'tag',           Session_names{iSession}, ...
        'includebad',    0, ...
        'includeintra',  0, ...
        'includecommon', 0);

    my_sFiles = sel_files_bst({my_sFiles_ini.FileName}, 'standard_adj|deviant_adj');

    %% SELECT HERE THE CORRECT FILES
    sel_subjects = 'NP807|NP810';
    SubjectNames = sel_files_bst(SubjectNames, sel_subjects);

    % select only files of the selected subjects (to be sure to exclude group
    % analysis).
    my_sFiles = sel_files_bst(my_sFiles, sel_subjects);

    %% DIVIDE BY SUBJECTS
    Subj_grouped = group_by_str_bst(my_sFiles, SubjectNames);

    % divide by condition
    cond_names={'deviant_adj', 'standard_adj'};
    run_names = {'_01', '_02'}; % i create this cause I want to be sure to have two files.

    Subj_cond = cell (1, length(Subj_grouped));
    for iSubj = 1: length(Subj_grouped);
        Subj_cond{iSubj} = group_by_str_bst(Subj_grouped{iSubj}, cond_names);
    end

    % TO EXCLUDE SOME SUBJECTS
    % my_sFiles = sel_files_bst(my_sFiles, '.', 'S001_|S002_');
    my_tag = ['subsetsour'] % NOTE! I dont's use subsetsource, so "source" is not included in this tag

    % loop over subjects
    for iSubj = 1:length(SubjectNames)

        iCond=2; % i removed a loop cause I want only standard

        % get only standard wich are
        curr_files_ini=Subj_cond{iSubj}{2};
        % DETERMINE NUMBER OF FILES TO TAKE FROM THE SELECTED FILES IN
        % DEVIANT (so the number is exactly the same)
        n_files_to_take = length(Subj_cond{iSubj}{1});

        % Start a new report
        bst_report('Start', curr_files_ini);

        % Process: Select 30 files (uniform)
        curr_files = bst_process('CallProcess', 'process_select_subset', curr_files_ini, [], ...
            'nfiles', n_files_to_take, ...
            'method', 4);  % Uniformly distributed

        curr_files = {curr_files.FileName};

        %% RETRIEVE SOURCE (LINK) FILES
        % retrieve condition path
        curr_study=bst_get('StudyWithCondition', bst_fileparts(curr_files{1}));

        % exclude with the following steps the empty filenames, in the
        % ResultFile, otherwise cannot use intersect
        no_empty_DataFile_ind=find(~cellfun(@isempty, {curr_study.Result.DataFile}));
        no_empty_Resultfile=curr_study.Result(no_empty_DataFile_ind);

        % find intersection between curr-files (the data to be processed)
        % and the non-empty Resultfile names
        [a ind_curr_files ind_no_empty_Resultfile]=intersect(curr_files, {no_empty_Resultfile.DataFile});

        % retrieve link_files
        link_files={no_empty_Resultfile(ind_no_empty_Resultfile).FileName};

        % Start a new report
        bst_report('Start', link_files);

        % Process: Hilbert transform
        Res = bst_process('CallProcess', 'process_hilbert', link_files, [], ...
            'clusters',  {}, ...
            'scoutfunc', 1, ...  % Mean
            'edit',      struct(...
            'Comment',         ['Avg,Magnitude,', my_tag, ',', cond_names{iCond}, ',', Session_names{iSession}], ...
            'TimeBands',       [], ...
            'Freqs',           {{'theta', '4,7', 'mean'; 'alpha', '8,12', 'mean'; 'beta', '13, 30', 'mean'; 'low_gamma', '30, 60', 'mean'; 'high_gamma', '60, 80', 'mean'}}, ...
            'ClusterFuncTime', 'none', ...
            'Measure',         'Magnitude', ...
            'Output',          'average', ...
            'RemoveEvoked',    0, ...
            'SaveKernel',      0), ...
            'normalize', 'none', ...  % None: Save non-standardized time-frequency maps
            'mirror',    0);

        % Process: Add tag: Response_adj
        Res = bst_process('CallProcess', 'process_add_tag', Res, [], ...
            'tag',    [my_tag, '_', cond_names{iCond}, '_', Session_names{iSession}], ...
            'output', 2);  % Add to filename

        % Save and display report
        ReportFile = bst_report('Save', curr_files);
        bst_report('Open', ReportFile);
        bst_report('Export', ReportFile, [export_main_folder, '/', export_folder]);

    end;
end;
%% BACKUP SCRIPT AND OBJECT WITH DATA

export_script(script_name, my_sFiles_ini)


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System.Collections.Immutable;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
using System.Diagnostics;

namespace Microsoft.CodeAnalysis.CSharp
{
    internal sealed class ForLoopBinder : LoopBinder
    {
        private readonly ForStatementSyntax _syntax;

        public ForLoopBinder(Binder enclosing, ForStatementSyntax syntax)
            : base(enclosing)
        {
            Debug.Assert(syntax != null);
            _syntax = syntax;
        }

        override protected ImmutableArray<LocalSymbol> BuildLocals()
        {
            var locals = ArrayBuilder<LocalSymbol>.GetInstance();

            // Deconstruction, Declaration, and Initializers are mutually exclusive.
            if (_syntax.Deconstruction != null)
            {
                CollectLocalsFromDeconstruction(
                    _syntax.Deconstruction.VariableComponent,
                    LocalDeclarationKind.ForInitializerVariable,
                    locals,
                    _syntax);
                ExpressionVariableFinder.FindExpressionVariables(this, locals, _syntax.Deconstruction.Value);
            }
            else if (_syntax.Declaration != null)
            {
                foreach (var vdecl in _syntax.Declaration.Variables)
                {
                    var localSymbol = MakeLocal(_syntax.Declaration, vdecl, LocalDeclarationKind.ForInitializerVariable);
                    locals.Add(localSymbol);

                    // also gather expression-declared variables from the bracketed argument lists and the initializers
                    ExpressionVariableFinder.FindExpressionVariables(this, locals, vdecl);
                }
            }
            else
            {
                ExpressionVariableFinder.FindExpressionVariables(this, locals, _syntax.Initializers);
            }

            ExpressionVariableFinder.FindExpressionVariables(this, locals, node: _syntax.Condition);
            ExpressionVariableFinder.FindExpressionVariables(this, locals, _syntax.Incrementors);
            return locals.ToImmutableAndFree();
        }

        internal override BoundForStatement BindForParts(DiagnosticBag diagnostics, Binder originalBinder)
        {
            BoundForStatement result = BindForParts(_syntax, originalBinder, diagnostics);
            return result;
        }

        private BoundForStatement BindForParts(ForStatementSyntax node, Binder originalBinder, DiagnosticBag diagnostics)
        {
            BoundStatement initializer;
            // Deconstruction, Declaration, and Initializers are mutually exclusive.
            if (_syntax.Deconstruction != null)
            {
                var assignment = originalBinder.BindDeconstructionDeclaration(node.Deconstruction, node.Deconstruction.VariableComponent, node.Deconstruction.Value, diagnostics);
                initializer = new BoundLocalDeconstructionDeclaration(node, assignment);
            }
            else if (_syntax.Declaration != null)
            {
                ImmutableArray<BoundLocalDeclaration> unused;
                initializer = originalBinder.BindForOrUsingOrFixedDeclarations(node.Declaration, LocalDeclarationKind.ForInitializerVariable, diagnostics, out unused);
            }
            else
            {
                initializer = originalBinder.BindStatementExpressionList(node.Initializers, diagnostics);
            }

            var condition = (node.Condition != null) ? originalBinder.BindBooleanExpression(node.Condition, diagnostics) : null;
            var increment = originalBinder.BindStatementExpressionList(node.Incrementors, diagnostics);
            var body = originalBinder.BindPossibleEmbeddedStatement(node.Statement, diagnostics);

            Debug.Assert(this.Locals == this.GetDeclaredLocalsForScope(node));
            return new BoundForStatement(node,
                                         this.Locals,
                                         initializer,
                                         condition,
                                         increment,
                                         body,
                                         this.BreakLabel,
                                         this.ContinueLabel);
        }

        internal override ImmutableArray<LocalSymbol> GetDeclaredLocalsForScope(SyntaxNode scopeDesignator)
        {
            if (_syntax == scopeDesignator)
            {
                return this.Locals;
            }

            throw ExceptionUtilities.Unreachable;
        }

        internal override ImmutableArray<LocalFunctionSymbol> GetDeclaredLocalFunctionsForScope(CSharpSyntaxNode scopeDesignator)
        {
            throw ExceptionUtilities.Unreachable;
        }

        internal override SyntaxNode ScopeDesignator
        {
            get
            {
                return _syntax;
            }
        }
    }
}


text:
class Dir {

 public:

	bool set      ( char *dirName );
	bool set      ( char *d1 , char *d2 );

	void reset    ( );

	bool open     ( );

	bool close    ( );

	void rewind   ( ); // rewind to get the first filename

	bool cleanOut ( ); // remove all files/dir in directory

	bool create   ( ); // create the directory

	char *getNextFilename ( char *pattern = NULL );

	// . calls getNextFilename and returns number of files matching the
	//   pattern
	int getNumFiles             ( char *pattern = NULL );

	// . does not yet support recursion
	long long   getUsedSpace    ( );

	char *getNewFilename ( char *pattern  ) ;
	long long   getNewId       ( char *pattern  ) ;
	long long   getFileId      ( char *filename ) ;

	char *getDir     ( ) { return m_dirname; };
	char *getDirName ( ) { return m_dirname; };
	char *getDirname ( ) { return m_dirname; };
	char *getFullName ( char *filename ); // prepends path

	 Dir     ( );
	~Dir     ( );

 private:

	char          *m_dirname;
	DIR           *m_dir;
	bool m_needsClose;
};

#endif


text:
<!doctype html>

        <meta charset="UTF-8">
        <title>Pedal - Alert</title>
        <link rel="stylesheet/less" href="less/style.less">


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Revis. gen. pl. (Leipzig) 3: 467 (1898)

#### Original name
Uredo aegopodii (Rebent.) G. Winter

### Remarks
null


text:
            <m-icon :name="meta.tag" size="140px"></m-icon>

                    <m-i18n class="modul-category-list__title__i18n" :k="meta.name"></m-i18n> {{ meta.status }}

{{meta.tag}}

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Itaque, deleniti dolores facilis aut, maxime sequi
                ullam suscipit deserunt quam obcaecati totam nisi magni ipsum ut dolorem fuga nostrum pariatur provident.


text:
using System;
using PetsWonderland.Business.MVP.Requests.BoardingRequest.GetAllBoardingRequests.Args;
using PetsWonderland.Business.MVP.Requests.BoardingRequest.GetAllBoardingRequests.ViewModels;
using WebFormsMvp;

namespace PetsWonderland.Business.MVP.Requests.BoardingRequest.GetAllBoardingRequests.Views
{
    public interface IGetAllBoardingRequestsView : IView<GetAllBoardingRequestsModel>
    {
        event EventHandler<GetAllBoardingRequestsArgs> GetAllBoardingRequests;
    }
}


text:
all::
	@echo "There is nothing in this directory to build."

vi:
	make readme

include common.mk


text:
package org.nd4j.jdbc.mysql;

import org.nd4j.jdbc.loader.impl.BaseLoader;

import javax.sql.DataSource;

/**
 * Mysql loader for ndarrays
 *
 * @author Adam Gibson
 */
public class MysqlLoader extends BaseLoader {

    public MysqlLoader(DataSource dataSource, String jdbcUrl, String tableName, String columnName) throws Exception {
        super(dataSource, jdbcUrl, tableName, columnName);
    }

    /**
     * Create an insert statement
     *
     * @return a new insert statement
     */
    @Override
    public String insertStatement() {
        return "INSERT INTO " + tableName + " VALUES(?,?)";
    }

    /**
     * Create an insert statement. This should be a templated query.
     * IE: Question mark at the end, we will take care of setting the proper value.
     *
     * @return a new insert statement
     */
    @Override
    public String loadStatement() {
        return "SELECT * FROM " + tableName + " WHERE " + this.idColumnName + " =?";

    }

    /**
     * Create an delete statement
     *
     * @return a new delete statement
     */
    @Override
    public String deleteStatement() {
        return "DELETE  FROM " + tableName + " WHERE " + this.idColumnName + " =?";

    }
}


text:
#include <aws/keyspaces/model/GetKeyspaceResult.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/UnreferencedParam.h>

#include <utility>

using namespace Aws::Keyspaces::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
using namespace Aws;

GetKeyspaceResult::GetKeyspaceResult()
{
}

GetKeyspaceResult::GetKeyspaceResult(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
  *this = result;
}

GetKeyspaceResult& GetKeyspaceResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
  JsonView jsonValue = result.GetPayload().View();
  if(jsonValue.ValueExists("keyspaceName"))
  {
    m_keyspaceName = jsonValue.GetString("keyspaceName");

  }

  if(jsonValue.ValueExists("resourceArn"))
  {
    m_resourceArn = jsonValue.GetString("resourceArn");

  }

  return *this;
}


text:
#ifndef _IAS_Lang_Interpreter_Extern_Std_System_ExecuteAdHoc_H_
#define _IAS_Lang_Interpreter_Extern_Std_System_ExecuteAdHoc_H_

#include <lang/interpreter/extern/Statement.h>
#include <lang/tools/helper/AdHocPrograms.h>

namespace IAS {
namespace Lang {
namespace Interpreter {
namespace Exe{
class Context;
}
namespace Extern {
namespace Std {
namespace System {

/*************************************************************************/
/** The ExecuteAdHoc class.
 *
 */
class ExecuteAdHoc : public ::IAS::Lang::Interpreter::Extern::Statement {
public:

	virtual ~ExecuteAdHoc() throw();

	/** Creates an instance. */
	static Statement* Create(const DM::Type* pType, const StringList& lstParamaters, const ModuleProxy* pModuleProxy);

protected:

	virtual void executeExternal(::IAS::Lang::Interpreter::Exe::Context *pCtx) const;

	ExecuteAdHoc(const DM::Type* pType, const StringList& lstParamaters, const ModuleProxy* pModuleProxy);

	Tools::Helper::AdHocPrograms *pAdHocPrograms;

	friend class ::IAS::Factory<ExecuteAdHoc>;
};

/*************************************************************************/
}
}
}
}
}

}
#endif /* _IAS_Lang_Interpreter_Extern_Std_System_ExecuteAdHoc_H_ */


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Kulturpflanze 17: 275 (1969)

#### Original name
Discina leucoxantha Bres., 1882

### Remarks
null


text:
'use strict'

const co = require('co')
const cli = require('heroku-cli-util')
const pg = require('@heroku-cli/plugin-pg-v5')

function * run (context, heroku) {
  const db = yield pg.fetcher(heroku).database(context.app, context.args.database)

  const query = `
WITH table_opts AS (
  SELECT
    pg_class.oid, relname, nspname, array_to_string(reloptions, '') AS relopts
  FROM
     pg_class INNER JOIN pg_namespace ns ON relnamespace = ns.oid
), vacuum_settings AS (
  SELECT
    oid, relname, nspname,
    CASE
      WHEN relopts LIKE '%autovacuum_vacuum_threshold%'
        THEN substring(relopts, '.*autovacuum_vacuum_threshold=([0-9.]+).*')::integer
        ELSE current_setting('autovacuum_vacuum_threshold')::integer
      END AS autovacuum_vacuum_threshold,
    CASE
      WHEN relopts LIKE '%autovacuum_vacuum_scale_factor%'
        THEN substring(relopts, '.*autovacuum_vacuum_scale_factor=([0-9.]+).*')::real
        ELSE current_setting('autovacuum_vacuum_scale_factor')::real
      END AS autovacuum_vacuum_scale_factor
  FROM
    table_opts
)
SELECT
  vacuum_settings.nspname AS schema,
  vacuum_settings.relname AS table,
  to_char(psut.last_vacuum, 'YYYY-MM-DD HH24:MI') AS last_vacuum,
  to_char(psut.last_autovacuum, 'YYYY-MM-DD HH24:MI') AS last_autovacuum,
  to_char(pg_class.reltuples, '9G999G999G999') AS rowcount,
  to_char(psut.n_dead_tup, '9G999G999G999') AS dead_rowcount,
  to_char(autovacuum_vacuum_threshold
       + (autovacuum_vacuum_scale_factor::numeric * pg_class.reltuples), '9G999G999G999') AS autovacuum_threshold,
  CASE
    WHEN autovacuum_vacuum_threshold + (autovacuum_vacuum_scale_factor::numeric * pg_class.reltuples) < psut.n_dead_tup
    THEN 'yes'
  END AS expect_autovacuum
FROM
  pg_stat_user_tables psut INNER JOIN pg_class ON psut.relid = pg_class.oid
    INNER JOIN vacuum_settings ON pg_class.oid = vacuum_settings.oid
ORDER BY 1
`

  const output = yield pg.psql.exec(db, query)
  process.stdout.write(output)
}

const cmd = {
  topic: 'pg',
  description: 'show dead rows and whether an automatic vacuum is expected to be triggered',
  needsApp: true,
  needsAuth: true,
  args: [{ name: 'database', optional: true }],
  run: cli.command({ preauth: true }, co.wrap(run))
}

module.exports = [
  Object.assign({ command: 'vacuum-stats' }, cmd),
  Object.assign({ command: 'vacuum_stats', hidden: true }, cmd)
]


text:
namespace Igneel
{
    public static class Affectable
    {
        public static void BindTo(this IAffectable target, IAffector affector)
        {
            target.BindAffectorPose = Matrix.Invert(affector.GlobalPose);
            target.Affector = affector;
            affector.Affectable = target;
        }

        public static void UnBindFrom(this IAffectable target, IAffector affector)
        {
            target.BindAffectorPose = Matrix.Identity;
            target.Affector = null;
            affector.Affectable = null;
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using MatterHackers.Agg;
using MatterHackers.Agg.Image;
using MatterHackers.Agg.Platform;
using MatterHackers.Agg.UI;
using MatterHackers.ImageProcessing;
using MatterHackers.MatterControl.CustomWidgets;
using MatterHackers.MatterControl.DesignTools;
using MatterHackers.VectorMath;

namespace MatterHackers.MatterControl.SlicerConfiguration
{
	public class EnumDisplayField : UIField
	{
		private readonly EditableProperty property;
		private readonly EnumDisplayAttribute enumDisplayAttibute;
		private readonly ThemeConfig theme;

		public EnumDisplayField(EditableProperty property, EnumDisplayAttribute iconsAttribute, ThemeConfig theme)
		{
			this.property = property;
			this.enumDisplayAttibute = iconsAttribute;
			this.theme = theme;
		}

		// TODO: Violates UIField norms but consistent with past behavior - state is only correct at construction time, often reconstructed
		public string InitialValue { get; set; }

		T GetAttribute<T>(Enum value)
			where T : Attribute
		{
			var type = value.GetType();
			var name = Enum.GetName(type, value);
			return type.GetField(name) // I prefer to get attributes this way
				.GetCustomAttributes(false)
				.OfType<T>()
				.SingleOrDefault();
		}

		public override void Initialize(int tabIndex)
		{
			(string key, string name) GetKeyName(Enum value)
			{
				var name = value.ToString();

				if (GetAttribute<EnumNameAttribute>(value) is EnumNameAttribute attr)
				{
					return (name, attr.Name);
				}

				return (name, name.Replace('_', ' ').Trim());
			}

			string GetDescription(Enum value)
			{
				if (GetAttribute<DescriptionAttribute>(value) is DescriptionAttribute attr)
				{
					return attr.Description.Trim();
				}

				return null;
			}

			var enumDescriptions = new List<(string key, string name, string description)>();
			foreach (var value in Enum.GetValues(property.PropertyType))
			{
				var keyName = GetKeyName((Enum)value);
				enumDescriptions.Add((keyName.key, keyName.name, GetDescription((Enum)value)));
			}

			switch (enumDisplayAttibute.Mode)
			{
				case EnumDisplayAttribute.PresentationMode.IconRow:
					AddIconRow(enumDescriptions);
					break;

				case EnumDisplayAttribute.PresentationMode.Tabs:
					AddTabs(enumDescriptions);
					break;

				case EnumDisplayAttribute.PresentationMode.Buttons:
					AddButtons(enumDescriptions);
					break;

				default:
					throw new NotImplementedException();
			}
		}

		private void EnableReduceWidth(ThemedRadioTextButton enumTab)
		{
			var deviceScale = GuiWidget.DeviceScale;
			var padingSize = enumTab.Padding.Left * deviceScale;
			enumTab.MinimumSize = new Vector2(padingSize * 3, enumTab.Height);
			enumTab.HAnchor = HAnchor.Stretch;

			// delay this for an update so that the layout of the text widget has happened and its size has been updated.
			var textWidget = enumTab.Descendants<TextWidget>().First();
			textWidget.Margin = new BorderDouble(enumTab.Padding.Left, 0, 0, 0);
			textWidget.HAnchor = HAnchor.Left;

			enumTab.AfterDraw += (s, e) =>
			{
				if (enumTab.Width < enumTab.MaximumSize.X)
				{
					var bounds = enumTab.LocalBounds;
					var g = e.Graphics2D;
					var color = enumTab.SelectedBackgroundColor;
					if (!enumTab.Checked)
					{
						foreach (var parent in enumTab.Parents<GuiWidget>())
						{
							if (parent.BackgroundColor.alpha > 200)
							{
								color = parent.BackgroundColor;
								break;
							}
						}
					}
					// cover the text with an alpha mask
					for (int i = 0; i < padingSize + 1; i++)
					{
						var x = bounds.Right - padingSize + i;
						g.Line(x, bounds.Bottom, x, bounds.Top, color.WithAlpha(Math.Min(255, i / 10.0 * deviceScale)));
					}
				}
			};

			// the text
			var maxWidth = textWidget.Width + enumTab.Padding.Width * deviceScale;
			enumTab.MaximumSize = new Vector2(maxWidth, enumTab.MaximumSize.Y);
			enumTab.Padding = new BorderDouble(0, enumTab.Padding.Bottom, 0, enumTab.Padding.Top);

			if (string.IsNullOrEmpty(enumTab.ToolTipText))
			{
				// wait for this size change to take effect and update the tool tip
				enumTab.BoundsChanged += (s, e) =>
				{
					if (enumTab.Width < enumTab.MaximumSize.X)
					{
						enumTab.ToolTipText = textWidget.Text;
					}
					else
					{
						enumTab.ToolTipText = "";
					}
				};
			}

			enumTab.HAnchor = HAnchor.Stretch;
		}

		private void AddTabs(List<(string key, string name, string description)> items)
		{
			var menuRow = new FlowLayoutWidget()
			{
				Margin = 5,
			};

			int index = 0;
			foreach (var item in items)
			{
				var localIndex = index;

				var radioButton = new ThemedRadioTextButton(item.name, theme)
				{
					ToolTipText = item.description,
				};

				menuRow.AfterDraw += (s, e) =>
				{
					e.Graphics2D.Rectangle(menuRow.LocalBounds.Left, 0, menuRow.LocalBounds.Right, 2, theme.PrimaryAccentColor);
				};

				radioButton.CheckedStateChanged += (s, e) =>
				{
					var button = s as ThemedRadioTextButton;
					button.TextColor = button.Checked ? theme.BackgroundColor : theme.TextColor;
				};

				radioButton.SelectedBackgroundColor = theme.PrimaryAccentColor;

				// set it if checked
				if (item.key == this.InitialValue)
				{
					radioButton.Checked = true;
				}

				EnableReduceWidth(radioButton);

				menuRow.AddChild(radioButton);

				var localItem = item;
				radioButton.CheckedStateChanged += (s, e) =>
				{
					if (radioButton.Checked)
					{
						this.SetValue(localItem.key, true);
					}
				};

				index++;
			}

			this.Content = menuRow;
		}

		private void AddButtons(List<(string key, string name, string description)> items)
		{
			var menuRow = new FlowLayoutWidget();

			int index = 0;
			foreach (var item in items)
			{
				var localIndex = index;

				var radioButton = CreateThemedRadioButton(item.name, item.key, item.description, this.InitialValue == item.key, () => this.SetValue(item.key, true), theme);

				menuRow.AddChild(radioButton);

				var localItem = item;

				index++;
			}

			this.Content = menuRow;
		}

		public static ThemedRadioTextButton CreateThemedRadioButton(string text, string key, string toolTipText, bool startChecked, Action setChecked, ThemeConfig theme)
		{
			var radioButton = new ThemedRadioTextButton(text, theme)
			{
				VAnchor = VAnchor.Center | VAnchor.Fit,
				DrawUnderline = false,
				BackgroundRadius = (theme.ButtonRadius + 4) * GuiWidget.DeviceScale,
				Margin = new BorderDouble(5, 0, 0, 0),
				Padding = new BorderDouble(9, 5),
				// BackgroundInset = new BorderDouble(5, 4),
				SelectedBackgroundColor = theme.PrimaryAccentColor,
				UnselectedBackgroundColor = theme.MinimalShade,
				BackgroundColor = theme.MinimalShade,
				ToolTipText = toolTipText
			};

			radioButton.CheckedStateChanged += (s, e) =>
			{
				var button = s as ThemedRadioTextButton;
				button.TextColor = button.Checked ? theme.BackgroundColor : theme.TextColor;
			};

			// set it if checked
			radioButton.Checked = startChecked;

			radioButton.CheckedStateChanged += (s, e) =>
			{
				if (radioButton.Checked)
				{
					setChecked?.Invoke();
				}
			};

			return radioButton;
		}

		public static ThemedTextButton CreateThemedButton(string text, string key, string toolTipText, ThemeConfig theme)
		{
			var button = new ThemedTextButton(text, theme)
			{
				VAnchor = VAnchor.Center | VAnchor.Fit,
				BackgroundRadius = (theme.ButtonRadius + 4) * GuiWidget.DeviceScale,
				Margin = new BorderDouble(5, 0, 0, 0),
				Padding = new BorderDouble(9, 5),
				// BackgroundInset = new BorderDouble(5, 4),
				BackgroundColor = theme.MinimalShade,
				ToolTipText = toolTipText
			};

			return button;
		}

		private void AddIconRow(List<(string key, string name, string description)> items)
		{
			var iconsRow = new FlowLayoutWidget();

			int index = 0;
			var radioButtonSize = new Vector2(enumDisplayAttibute.IconWidth, enumDisplayAttibute.IconHeight);
			foreach (var item in items)
			{
				var localIndex = index;
				ImageBuffer iconImage = null;
				var iconPath = enumDisplayAttibute.IconPaths[localIndex];
				if (!string.IsNullOrWhiteSpace(iconPath))
				{
					if (enumDisplayAttibute.IconWidth > 0)
					{
						// If the attribute allows invert, use the theme.InvertIcons state
						iconImage = StaticData.Instance.LoadIcon(iconPath, enumDisplayAttibute.IconWidth, enumDisplayAttibute.IconHeight).SetToColor(theme.TextColor);
					}
					else
					{
						iconImage = StaticData.Instance.LoadIcon(iconPath);
					}

					var radioButton = new ThemedRadioIconButton(iconImage, theme)
					{
						ToolTipText = item.description == null ? item.name : item.description,
					};

					radioButtonSize = new Vector2(radioButton.Width, radioButton.Height);

					// set it if checked
					if (item.key == this.InitialValue)
					{
						radioButton.Checked = true;
					}

					iconsRow.AddChild(radioButton);

					var localItem = item;
					radioButton.CheckedStateChanged += (s, e) =>
					{
						if (radioButton.Checked)
						{
							this.SetValue(localItem.key, true);
						}
					};
				}
				else if (enumDisplayAttibute.IconWidth > 0)
				{
					// hold the space of the empty icon
					iconsRow.AddChild(new GuiWidget(radioButtonSize.X, radioButtonSize.Y));
				}

				index++;
			}

			this.Content = iconsRow;
		}

		protected override void OnValueChanged(FieldChangedEventArgs fieldChangedEventArgs)
		{
			//dropdownList.SelectedLabel = this.Value;
			base.OnValueChanged(fieldChangedEventArgs);
		}
	}

    public static class MenuExtensions
    {
		public static MenuItem CreateButtonSelectMenuItem(this PopupMenu popuMenu, GuiWidget guiWidget, string name, IEnumerable<(string key, string text)> buttonKvps, string startingValue, Action<string> setter, double minSpacerWidth = 0)
		{
			var row = new FlowLayoutWidget()
			{
				HAnchor = HAnchor.MaxFitOrStretch,
				Name = name + " Menu Item",
			};

			row.AddChild(guiWidget);
			row.AddChild(new HorizontalSpacer()
			{
				MinimumSize = new Vector2(minSpacerWidth, 0)
			}); ;

			foreach (var buttonKvp in buttonKvps)
			{
				var localKey = buttonKvp.key;
				var button = EnumDisplayField.CreateThemedRadioButton(buttonKvp.text, buttonKvp.key, "", startingValue == buttonKvp.key, () =>
				{
					setter?.Invoke(localKey);
				}, popuMenu.Theme);
				row.AddChild(button);
			}

			MenuItem menuItem = new MenuItemHoldOpen(row);

			popuMenu.AddChild(menuItem);

			return menuItem;
		}

		public static MenuItem CreateButtonMenuItem(this PopupMenu popupMenu, GuiWidget guiWidget, string name, IEnumerable<(string key, string text, EventHandler<MouseEventArgs> click)> buttonKvps, double minSpacerWidth = 0)
		{
			var row = new FlowLayoutWidget()
			{
				HAnchor = HAnchor.MaxFitOrStretch,
				Name = name + " Menu Item",
			};

			row.AddChild(guiWidget);
			row.AddChild(new HorizontalSpacer()
			{
				MinimumSize = new Vector2(minSpacerWidth, 0)
			});

			foreach (var buttonKvp in buttonKvps)
			{
				var button = EnumDisplayField.CreateThemedButton(buttonKvp.text, buttonKvp.key, "", popupMenu.Theme);
				button.Click += buttonKvp.click;
				row.AddChild(button);
			}

			var menuItem = new MenuItemHoldOpen(row)
			{
			};

			popupMenu.AddChild(menuItem);

			return menuItem;
		}

		/// <summary>
		/// Create and add a new menu item
		/// </summary>
		/// <param name="text">The text of the item</param>
		/// <param name="items"></param>
		/// <param name="getter"></param>
		/// <param name="setter"></param>
		/// <returns></returns>
		public static MenuItem CreateButtonSelectMenuItem(this PopupMenu popupMenu, string text, IEnumerable<(string key, string text)> buttonKvps, string startingValue, Action<string> setter, double minSpacerWidth = 0)
		{
			var textWidget = new TextWidget(text, pointSize: popupMenu.Theme.DefaultFontSize, textColor: popupMenu.Theme.TextColor)
			{
				Padding = PopupMenu.MenuPadding,
				VAnchor = VAnchor.Center,
                Margin = new BorderDouble(8, 1),
            };

			return popupMenu.CreateButtonSelectMenuItem(textWidget, text, buttonKvps, startingValue, setter, minSpacerWidth);
		}

		public static MenuItem CreateButtonMenuItem(this PopupMenu popupMenu,
			string text,
			IEnumerable<(string key, string text, EventHandler<MouseEventArgs> click)> buttonKvps,
			double minSpacerWidth = 0,
			bool bold = false)
		{
			var textWidget = new TextWidget(text, pointSize: popupMenu.Theme.DefaultFontSize, textColor: popupMenu.Theme.TextColor, bold: bold)
			{
				Padding = PopupMenu.MenuPadding,
				VAnchor = VAnchor.Center,
                Margin = new BorderDouble(8, 1),
            };

			return popupMenu.CreateButtonMenuItem(textWidget, text, buttonKvps, minSpacerWidth);
		}

		public static MenuItem CreateButtonSelectMenuItem(this PopupMenu popupMenu, string text, ImageBuffer icon, IEnumerable<(string key, string text)> buttonKvps, string startingValue, Action<string> setter)
		{
			var row = new FlowLayoutWidget()
			{
				Selectable = false
			};
			row.AddChild(new ThemedIconButton(icon, popupMenu.Theme));

			var textWidget = new TextWidget(text, pointSize: popupMenu.Theme.DefaultFontSize, textColor: popupMenu.Theme.TextColor)
			{
				Padding = PopupMenu.MenuPadding,
				VAnchor = VAnchor.Center
			};
			row.AddChild(textWidget);

			return popupMenu.CreateButtonSelectMenuItem(row, text, buttonKvps, startingValue, setter);
		}
	}
}


text:
Dialog::Dialog(const vector<string>* PlayerSentences,const vector<string>* NpcSentences, const char* NoteName){
	this->PlayerSentences = PlayerSentences;
	this->NpcSentences = NpcSentences;
	this->NoteName = NoteName;
}

Dialog::~Dialog(){
	delete PlayerSentences;
	delete NpcSentences;
}


text:
    <title>Let's play boxs!</title>

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

Welcome to North Wind website!

                Control Panel

                     <input type="button" value="up" id="up"/>

              <input type="button" value="left" id="left"/>
            <input type="button" value="down" id="down"/>
            <input type="button" value="right" id="right"/>

Contect:

Email:north.wind@qq.com


text:
title: In javascript string replace doesn't do what you think it does
author: Justin Ball
layout: post
permalink: "/2011/01/20/in-javascript-string-replace-doesnt-do-what-you-think-it-does/"
tags:
  - "Javascript"
  - "global"
  - "regular expressions"
  - "replace"
date: '2011-01-20T07:00:00Z'
templateKey: blog-post
path: "/in-javascript-string-replace-doesnt-do-what-you-think-it-does"
description: ''
---

When doing a string replace in javascript if you try something like this:

    var str = 'test';
    str.replace('t', 's');

You'll find that the result is:

    sest

The replace method in javascript is not a global replace. Instead it does a single replace and moves on.

If you want to do a global replace try using a regular expression instead:

    var str = 'test';
    str.replace(/t/g, 's');

the result will be:

    sess

The reason for that is the 'g' hanging of the end of the expression /t/g. That tells javascript that the replace should be global.


text:
using System;

namespace AppKit.Core.Logging.Performance
{
    /// <summary>
    /// Log levels:
    /// Fatal - not used
    /// Error - not used
    /// Warn    - Performance messages (only selected public methods)
    /// Info    - Performance messages (only selected private methods)
    /// Debug   - Will use if future for switching
    /// </summary>
    public class PerformanceLogProvider : LogProvider
    {
        #region Instance

        private static readonly Lazy<PerformanceLogProvider> LazyInstance = new Lazy<PerformanceLogProvider>(() => new PerformanceLogProvider());

        private PerformanceLogProvider() { }

        public static PerformanceLogProvider Instance { get { return LazyInstance.Value;  } }

        #endregion
    }
}


text:
from .probabilistic_direction_getter import ProbabilisticDirectionGetter
from .probabilistic_direction_getter import DeterministicMaximumDirectionGetter
from .peaks import *


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

namespace SmallWorkflow
{
    public static class WFTask
    {
        public static WFTask<TPrev, TResult> F<TPrev, TResult>(Func<TPrev, TResult> func)
        {
            return new WFTask<TPrev, TResult>(func);
        }

        public static WFTask<object, TResult> F<TResult>(Func<TResult> func)
        {
            return new WFTask<object, TResult>(func);
        }

        public static WFTask<TPrev, object> A<TPrev>(Action<TPrev> action)
        {
            AssertHelper.ThrowIfNull(action, "action");
            return new WFTask<TPrev, object>(prev =>
            {
                action(prev);
                return null;
            });
        }

        public static WFTask<object, object> A(Action action)
        {
            AssertHelper.ThrowIfNull(action, "action");
            return new WFTask<object, object>(() =>
            {
                action();
                return null;
            });
        }
    }

    public sealed class WFTask<TPrev, TResult> : IRunnableTask<TPrev>
    {
        private Action<TPrev> TaskAction { get; set; }
        private TResult _result = default(TResult);

        private IRunnableTask<TResult> SuccessTask { get; set; }
        private IRunnableTask<TResult> FailureTask { get; set; }
        private IRunnableTask<TResult> FinallyTask { get; set; }
        private Dictionary<Type, dynamic> OnExceptionTask { get; set; }

        private WFTask()
        {
            OnExceptionTask = new Dictionary<Type, dynamic>();
        }

        internal WFTask(Func<TPrev, TResult> func)
            : this()
        {
            AssertHelper.ThrowIfNull(func, "func");
            TaskAction = prev =>
            {
                try
                {
                    _result = func(prev);
                    CallSuccess();
                }
                catch (Exception ex)
                {
                    CallFailure();
                    if (!CallException(ex)) throw;
                }
                finally
                {
                    CallFinally();
                }
            };
        }

        internal WFTask(Func<TResult> func)
            : this()
        {
            AssertHelper.ThrowIfNull(func, "func");
            TaskAction = prev =>
            {
                try
                {
                    _result = func();
                    CallSuccess();
                }
                catch (Exception ex)
                {
                    CallFailure();
                    if (!CallException(ex)) throw;
                }
                finally
                {
                    CallFinally();
                }
            };
        }

        public void Run(TPrev prev)
        {
            TaskAction(prev);
        }

        public void Run()
        {
            TaskAction(default(TPrev));
        }

        public WFTask<TPrev, TResult> OnSuccess<TNext>(Func<TResult, TNext> func)
        {
            AssertHelper.ThrowIfNull(func, "func");
            SuccessTask = WFTask.F(func);
            return this;
        }

        public WFTask<TPrev, TResult> OnSuccess(Action<TResult> action)
        {
            AssertHelper.ThrowIfNull(action, "action");
            SuccessTask = WFTask.A(action);
            return this;
        }

        public WFTask<TPrev, TResult> OnSuccess(Action action)
        {
            AssertHelper.ThrowIfNull(action, "action");
            SuccessTask = WFTask.A((TResult prev) => action());
            return this;
        }

        public WFTask<TPrev, TResult> OnSuccess<TNext>(WFTask<TResult, TNext> nextTask)
        {
            AssertHelper.ThrowIfNull(nextTask, "nextTask");
            SuccessTask = nextTask;
            return this;
        }

        public WFTask<TPrev, TResult> OnFailure<TNext>(Func<TResult, TNext> func)
        {
            AssertHelper.ThrowIfNull(func, "func");
            FailureTask = new WFTask<TResult, TNext>(func);
            return this;
        }

        public WFTask<TPrev, TResult> OnFailure(Action<TResult> action)
        {
            AssertHelper.ThrowIfNull(action, "action");
            FailureTask = WFTask.A(action);
            return this;
        }

        public WFTask<TPrev, TResult> OnFailure(Action action)
        {
            AssertHelper.ThrowIfNull(action, "action");
            FailureTask = WFTask.A((TResult prev) => action());
            return this;
        }

        public WFTask<TPrev, TResult> OnFailure<TNext>(WFTask<TResult, TNext> nextTask)
        {
            AssertHelper.ThrowIfNull(nextTask, "nextTask");
            FailureTask = nextTask;
            return this;
        }

        public WFTask<TPrev, TResult> OnFinally<TNext>(Func<TResult, TNext> func)
        {
            AssertHelper.ThrowIfNull(func, "func");
            FinallyTask = new WFTask<TResult, TNext>(func);
            return this;
        }

        public WFTask<TPrev, TResult> OnFinally(Action<TResult> action)
        {
            AssertHelper.ThrowIfNull(action, "action");
            FinallyTask = WFTask.A(action);
            return this;
        }

        public WFTask<TPrev, TResult> OnFinally(Action action)
        {
            AssertHelper.ThrowIfNull(action, "action");
            FinallyTask = WFTask.A((TResult prev) => action());
            return this;
        }

        public WFTask<TPrev, TResult> OnFinally<TNext>(WFTask<TResult, TNext> nextTask)
        {
            AssertHelper.ThrowIfNull(nextTask, "nextTask");
            FinallyTask = nextTask;
            return this;
        }

        public WFTask<TPrev, TResult> OnException<TEx, TNext>(Func<TEx, TNext> func) where TEx : Exception
        {
            AssertHelper.ThrowIfNull(func, "func");
            OnExceptionTask[typeof(TEx)] = new WFTask<TEx, TNext>(func);
            return this;
        }

        public WFTask<TPrev, TResult> OnException<TEx>(Action<TEx> action) where TEx : Exception
        {
            AssertHelper.ThrowIfNull(action, "action");
            OnExceptionTask[typeof(TEx)] = WFTask.A(action);
            return this;
        }

        public WFTask<TPrev, TResult> OnException<TEx>(Action action) where TEx : Exception
        {
            AssertHelper.ThrowIfNull(action, "action");
            OnExceptionTask[typeof(TEx)] = WFTask.A((TEx ex) => action());
            return this;
        }

        public WFTask<TPrev, TResult> OnException<TEx, TNext>(WFTask<TEx, TNext> nextTask) where TEx : Exception
        {
            AssertHelper.ThrowIfNull(nextTask, "nextTask");
            OnExceptionTask[typeof(TEx)] = nextTask;
            return this;
        }

        private void CallSuccess()
        {
            if (SuccessTask == null) return;
            SuccessTask.Run(_result);
        }

        private void CallFailure()
        {
            if (FailureTask == null) return;
            FailureTask.Run(_result);
        }

        private void CallFinally()
        {
            if (FinallyTask == null) return;
            FinallyTask.Run(_result);
        }

        private bool CallException(dynamic ex)
        {
            var first = GetAssignableException(ex);
            if (first == null) return false;
            OnExceptionTask[first].Run(ex);
            return true;
        }

        private Type GetAssignableException(dynamic ex)
        {
            var exType = ex.GetType();
            return OnExceptionTask.Keys.FirstOrDefault(e => e.IsAssignableFrom(exType));
        }
    }
}


text:
'use strict';

var Lib = require('../lib');
var Axes = require('../plots/cartesian/axes');
var pointsAccessorFunction = require('./helpers').pointsAccessorFunction;

var BADNUM = require('../constants/numerical').BADNUM;

exports.moduleType = 'transform';

exports.name = 'sort';

exports.attributes = {
    enabled: {
        valType: 'boolean',
        dflt: true,
        role: 'info',
        editType: 'calc',
        description: [
            'Determines whether this sort transform is enabled or disabled.'
        ].join(' ')
    },
    target: {
        valType: 'string',
        strict: true,
        noBlank: true,
        arrayOk: true,
        dflt: 'x',
        role: 'info',
        editType: 'calc',
        description: [
            'Sets the target by which the sort transform is applied.',

            'If a string, *target* is assumed to be a reference to a data array',
            'in the parent trace object.',
            'To sort about nested variables, use *.* to access them.',
            'For example, set `target` to *marker.size* to sort',
            'about the marker size array.',

            'If an array, *target* is then the data array by which',
            'the sort transform is applied.'
        ].join(' ')
    },
    order: {
        valType: 'enumerated',
        values: ['ascending', 'descending'],
        dflt: 'ascending',
        role: 'info',
        editType: 'calc',
        description: [
            'Sets the sort transform order.'
        ].join(' ')
    },
    editType: 'calc'
};

exports.supplyDefaults = function(transformIn) {
    var transformOut = {};

    function coerce(attr, dflt) {
        return Lib.coerce(transformIn, transformOut, exports.attributes, attr, dflt);
    }

    var enabled = coerce('enabled');

    if(enabled) {
        coerce('target');
        coerce('order');
    }

    return transformOut;
};

exports.calcTransform = function(gd, trace, opts) {
    if(!opts.enabled) return;

    var targetArray = Lib.getTargetArray(trace, opts);
    if(!targetArray) return;

    var target = opts.target;

    var len = targetArray.length;
    if(trace._length) len = Math.min(len, trace._length);

    var arrayAttrs = trace._arrayAttrs;
    var d2c = Axes.getDataToCoordFunc(gd, trace, target, targetArray);
    var indices = getIndices(opts, targetArray, d2c, len);
    var originalPointsAccessor = pointsAccessorFunction(trace.transforms, opts);
    var indexToPoints = {};
    var i, j;

    for(i = 0; i < arrayAttrs.length; i++) {
        var np = Lib.nestedProperty(trace, arrayAttrs[i]);
        var arrayOld = np.get();
        var arrayNew = new Array(len);

        for(j = 0; j < len; j++) {
            arrayNew[j] = arrayOld[indices[j]];
        }

        np.set(arrayNew);
    }

    for(j = 0; j < len; j++) {
        indexToPoints[j] = originalPointsAccessor(indices[j]);
    }

    opts._indexToPoints = indexToPoints;
    trace._length = len;
};

function getIndices(opts, targetArray, d2c, len) {
    var sortedArray = new Array(len);
    var indices = new Array(len);
    var i;

    for(i = 0; i < len; i++) {
        sortedArray[i] = {v: targetArray[i], i: i};
    }

    sortedArray.sort(getSortFunc(opts, d2c));

    for(i = 0; i < len; i++) {
        indices[i] = sortedArray[i].i;
    }

    return indices;
}

function getSortFunc(opts, d2c) {
    switch(opts.order) {
        case 'ascending':
            return function(a, b) {
                var ac = d2c(a.v);
                var bc = d2c(b.v);
                if(ac === BADNUM) {
                    return 1;
                }
                if(bc === BADNUM) {
                    return -1;
                }
                return ac - bc;
            };
        case 'descending':
            return function(a, b) {
                var ac = d2c(a.v);
                var bc = d2c(b.v);
                if(ac === BADNUM) {
                    return 1;
                }
                if(bc === BADNUM) {
                    return -1;
                }
                return bc - ac;
            };
    }
}


text:
package org.apache.spark.ml.feature

import scala.collection.mutable

import org.apache.spark.annotation.Experimental
import org.apache.spark.ml.UnaryTransformer
import org.apache.spark.ml.param.{ParamMap, IntParam, ParamValidators}
import org.apache.spark.ml.util.Identifiable
import org.apache.spark.mllib.linalg._
import org.apache.spark.sql.types.DataType

/**
 * :: Experimental ::
 * Perform feature expansion in a polynomial space. As said in wikipedia of Polynomial Expansion,
  * 在多项式空间中执行特征扩展,如在多项式扩展的维基百科中所述
 * which is available at [[http://en.wikipedia.org/wiki/Polynomial_expansion]], "In mathematics, an
 * expansion of a product of sums expresses it as a sum of products by using the fact that
 * multiplication distributes over addition". Take a 2-variable feature vector as an example:
 * `(x, y)`, if we want to expand it with degree 2, then we get `(x, x * x, y, x * y, y * y)`.
 */
@Experimental
class PolynomialExpansion(override val uid: String)
  extends UnaryTransformer[Vector, Vector, PolynomialExpansion] {

  def this() = this(Identifiable.randomUID("poly"))

  /**
   * The polynomial degree to expand, which should be >= 1.  A value of 1 means no expansion.
    * 要扩展的多项式度,应该> = 1.值为1表示不扩展
   * Default: 2
   * @group param
   */
  val degree = new IntParam(this, "degree", "the polynomial degree to expand (>= 1)",
    ParamValidators.gt(1))

  setDefault(degree -> 2)

  /** @group getParam */
  def getDegree: Int = $(degree)

  /** @group setParam */
  def setDegree(value: Int): this.type = set(degree, value)

  override protected def createTransformFunc: Vector => Vector = { v =>
    PolynomialExpansion.expand(v, $(degree))
  }

  override protected def outputDataType: DataType = new VectorUDT()

  override def copy(extra: ParamMap): PolynomialExpansion = defaultCopy(extra)
}

/**
 * The expansion is done via recursion. Given n features and degree d, the size after expansion is
 * (n + d choose d) (including 1 and first-order values). For example, let f([a, b, c], 3) be the
 * function that expands [a, b, c] to their monomials of degree 3. We have the following recursion:
  * 扩展是通过递归完成的,给定n个特征和度数d,扩展后的大小为(n + d选择d)(包括1和1阶值)。
  * 例如,设f([a,b,c],3)是将[a,b,c]扩展为3阶单项式的函数。我们有以下递归:
 *
 * {{{
 * f([a, b, c], 3) = f([a, b], 3) ++ f([a, b], 2) * c ++ f([a, b], 1) * c^2 ++ [c^3]
 * }}}
 *
 * To handle sparsity, if c is zero, we can skip all monomials that contain it. We remember the
 * current index and increment it properly for sparse input.
 */
private[feature] object PolynomialExpansion {

  private def choose(n: Int, k: Int): Int = {
    Range(n, n - k, -1).product / Range(k, 1, -1).product
  }

  private def getPolySize(numFeatures: Int, degree: Int): Int = choose(numFeatures + degree, degree)

  private def expandDense(
      values: Array[Double],
      lastIdx: Int,
      degree: Int,
      multiplier: Double,
      polyValues: Array[Double],
      curPolyIdx: Int): Int = {
    if (multiplier == 0.0) {
      // do nothing
    } else if (degree == 0 || lastIdx < 0) {
      if (curPolyIdx >= 0) { // skip the very first 1
        polyValues(curPolyIdx) = multiplier
      }
    } else {
      val v = values(lastIdx)
      val lastIdx1 = lastIdx - 1
      var alpha = multiplier
      var i = 0
      var curStart = curPolyIdx
      while (i <= degree && alpha != 0.0) {
        curStart = expandDense(values, lastIdx1, degree - i, alpha, polyValues, curStart)
        i += 1
        alpha *= v
      }
    }
    curPolyIdx + getPolySize(lastIdx + 1, degree)
  }

  private def expandSparse(
      indices: Array[Int],
      values: Array[Double],
      lastIdx: Int,
      lastFeatureIdx: Int,
      degree: Int,
      multiplier: Double,
      polyIndices: mutable.ArrayBuilder[Int],
      polyValues: mutable.ArrayBuilder[Double],
      curPolyIdx: Int): Int = {
    if (multiplier == 0.0) {
      // do nothing
    } else if (degree == 0 || lastIdx < 0) {
      if (curPolyIdx >= 0) { // skip the very first 1
        polyIndices += curPolyIdx
        polyValues += multiplier
      }
    } else {
      // Skip all zeros at the tail.
      val v = values(lastIdx)
      val lastIdx1 = lastIdx - 1
      val lastFeatureIdx1 = indices(lastIdx) - 1
      var alpha = multiplier
      var curStart = curPolyIdx
      var i = 0
      while (i <= degree && alpha != 0.0) {
        curStart = expandSparse(indices, values, lastIdx1, lastFeatureIdx1, degree - i, alpha,
          polyIndices, polyValues, curStart)
        i += 1
        alpha *= v
      }
    }
    curPolyIdx + getPolySize(lastFeatureIdx + 1, degree)
  }

  private def expand(dv: DenseVector, degree: Int): DenseVector = {
    val n = dv.size
    val polySize = getPolySize(n, degree)
    val polyValues = new Array[Double](polySize - 1)
    expandDense(dv.values, n - 1, degree, 1.0, polyValues, -1)
    new DenseVector(polyValues)
  }

  private def expand(sv: SparseVector, degree: Int): SparseVector = {
    val polySize = getPolySize(sv.size, degree)
    val nnz = sv.values.length
    val nnzPolySize = getPolySize(nnz, degree)
    val polyIndices = mutable.ArrayBuilder.make[Int]
    polyIndices.sizeHint(nnzPolySize - 1)
    val polyValues = mutable.ArrayBuilder.make[Double]
    polyValues.sizeHint(nnzPolySize - 1)
    expandSparse(
      sv.indices, sv.values, nnz - 1, sv.size - 1, degree, 1.0, polyIndices, polyValues, -1)
    new SparseVector(polySize - 1, polyIndices.result(), polyValues.result())
  }

  def expand(v: Vector, degree: Int): Vector = {
    v match {
      case dv: DenseVector => expand(dv, degree)
      case sv: SparseVector => expand(sv, degree)
      case _ => throw new IllegalArgumentException
    }
  }
}


text:
var simpleLevelPlan = [
  "                      ",
  "                      ",
  "  x              = x  ",
  "  x         o o    x  ",
  "  x @      xxxxx   x  ",
  "  xxxxx            x  ",
  "      x!!!!!!!!!!!!x  ",
  "      xxxxxxxxxxxxxx  ",
  "                      "
];

function Level(plan) {
  this.width = plan[0].length;
  this.height = plan.length;
  this.grid = [];
  this.actors = [];

  for (var y = 0; y < this.height; y++) {
    var line = plan[y], gridLine = [];
    for (var x = 0; x < this.width; x++) {
      var ch = line[x], fieldType = null;
      var Actor = actorChars[ch];
      if (Actor)
        this.actors.push(new Actor(new Vector(x, y), ch));
      else if (ch == "x")
        fieldType = "wall";
      else if (ch == "!")
        fieldType = "sun";
      gridLine.push(fieldType);
    }
    this.grid.push(gridLine);
  }

  this.player = this.actors.filter(function(actor) {
    return actor.type == "player";
  })[0];
  this.status = this.finishDelay = null;
}

Level.prototype.isFinished = function() {
  return this.status != null && this.finishDelay < 0;
};

function Vector(x, y) {
  this.x = x; this.y = y;
}
Vector.prototype.plus = function(other) {
  return new Vector(this.x + other.x, this.y + other.y);
};
Vector.prototype.times = function(factor) {
  return new Vector(this.x * factor, this.y * factor);
};

var actorChars = {
  "@": Player,
  "o": Bird,
  "=": Sun, "|": Sun, "v": Sun
};

function Player(pos) {
  this.pos = pos.plus(new Vector(0, 0));
  this.size = new Vector(3, 3);
  this.speed = new Vector(0, 0);
}
Player.prototype.type = "player";

function Sun(pos, ch) {
  this.pos = pos;
  this.size = new Vector(1, 1);
  // (iteration2) moving sunrise
  if (ch == "=") {
    this.speed = new Vector(0.8, -0.8); //this.speed = new Vector(2, 0);
  } else if (ch == "|") {
    this.speed = new Vector(0, 2);
  } else if (ch == "v") {
    this.speed = new Vector(0, 3);
    this.repeatPos = pos;
  }
}
Sun.prototype.type = "sun";

function Bird(pos) {
  this.basePos = this.pos = pos.plus(new Vector(0.2, 0.1));
  this.size = new Vector(0.6, 0.6);
  this.wobble = Math.random() * Math.PI * 2;
}
Bird.prototype.type = "bird";

var simpleLevel = new Level(simpleLevelPlan);

function elt(name, className) {
  var elt = document.createElement(name);
  if (className) elt.className = className;
  return elt;
}

function DOMDisplay(parent, level) {
  this.wrap = parent.appendChild(elt("div", "game"));
  this.level = level;

  this.wrap.appendChild(this.drawBackground());
  this.actorLayer = null;
  this.drawFrame();
}

console.log("window.width : " + window.innerWidth);
console.log("window.height : " + window.innerHeight);

// (iteration??) scaling screen sizes
var scaleCalc = function() {
  var width = window.innerWidth;
  var x = width / 30;
  console.log("scale : " + x);
  return x;
};

// (iteration ??) screen resizing
var scale = scaleCalc();

DOMDisplay.prototype.drawBackground = function() {
  var table = elt("table", "background");
  table.style.width = this.level.width * scale + "px";
  this.level.grid.forEach(function(row) {
    var rowElt = table.appendChild(elt("tr"));
    rowElt.style.height = scale + "px";
    row.forEach(function(type) {
      rowElt.appendChild(elt("td", type));
    });
  });
  return table;
};

DOMDisplay.prototype.drawActors = function() {
  var wrap = elt("div");
  this.level.actors.forEach(function(actor) {
    var rect = wrap.appendChild(elt("div",
                                    "actor " + actor.type));
    rect.style.width = actor.size.x * scale + "px";
    rect.style.height = actor.size.y * scale + "px";
    rect.style.left = actor.pos.x * scale + "px";
    rect.style.top = actor.pos.y * scale + "px";
  });
  return wrap;
};

DOMDisplay.prototype.drawFrame = function() {
  if (this.actorLayer)
    this.wrap.removeChild(this.actorLayer);
  this.actorLayer = this.wrap.appendChild(this.drawActors());
  this.wrap.className = "game " + (this.level.status || "");
  this.scrollPlayerIntoView();
};

DOMDisplay.prototype.scrollPlayerIntoView = function() {
  var width = this.wrap.clientWidth;
  var height = this.wrap.clientHeight;
  var margin = width / 3;

  // The viewport
  var left = this.wrap.scrollLeft, right = left + width;
  var top = this.wrap.scrollTop, bottom = top + height;

  var player = this.level.player;
  var center = player.pos.plus(player.size.times(0.5))
                 .times(scale);

  if (center.x < left + margin)
    this.wrap.scrollLeft = center.x - margin;
  else if (center.x > right - margin)
    this.wrap.scrollLeft = center.x + margin - width;
  if (center.y < top + margin)
    this.wrap.scrollTop = center.y - margin;
  else if (center.y > bottom - margin)
    this.wrap.scrollTop = center.y + margin - height;
};

DOMDisplay.prototype.clear = function() {
  this.wrap.parentNode.removeChild(this.wrap);
};

Level.prototype.obstacleAt = function(pos, size) {
  var xStart = Math.floor(pos.x);
  var xEnd = Math.ceil(pos.x + size.x);
  var yStart = Math.floor(pos.y);
  var yEnd = Math.ceil(pos.y + size.y);

  if (xStart < 0 || xEnd > this.width || yStart < 0)
    return "wall";
  if (yEnd > this.height)
    return "sun";
  for (var y = yStart; y < yEnd; y++) {
    for (var x = xStart; x < xEnd; x++) {
      var fieldType = this.grid[y][x];
      if (fieldType) return fieldType;
    }
  }
};

Level.prototype.actorAt = function(actor) {
  for (var i = 0; i < this.actors.length; i++) {
    var other = this.actors[i];
    if (other != actor &&
        actor.pos.x + actor.size.x > other.pos.x &&
        actor.pos.x < other.pos.x + other.size.x &&
        actor.pos.y + actor.size.y > other.pos.y &&
        actor.pos.y < other.pos.y + other.size.y)
      return other;
  }
};

var maxStep = 0.05;

Level.prototype.animate = function(step, keys) {
  if (this.status != null)
    this.finishDelay -= step;

  while (step > 0) {
    var thisStep = Math.min(step, maxStep);
    this.actors.forEach(function(actor) {
      actor.act(thisStep, this, keys);
    }, this);
    step -= thisStep;
  }
};

// (iteration2) moving sunrise
Sun.prototype.act = function(step) {
  var newPos = this.pos.plus(this.speed.times(step));
  var destination = new Vector(7.5, 0);

  if (newPos.x < destination.x)
    this.pos = newPos;
  else {
    this.speed = this.speed.times(0);
  }
};

var wobbleSpeed = 8, wobbleDist = 0.07;

Bird.prototype.act = function(step) {
  this.wobble += step * wobbleSpeed;
  var wobblePos = Math.sin(this.wobble) * wobbleDist;
  this.pos = this.basePos.plus(new Vector(0, wobblePos));
};

var playerXSpeed = 7;

Player.prototype.moveX = function(step, level, keys) {
  this.speed.x = 0;
  if (keys.left) this.speed.x -= playerXSpeed;
  if (keys.right) this.speed.x += playerXSpeed;

  var motion = new Vector(this.speed.x * step, 0);
  var newPos = this.pos.plus(motion);
  var obstacle = level.obstacleAt(newPos, this.size);
  if (obstacle)
    level.playerTouched(obstacle);
  else
    this.pos = newPos;
};

var playerYSpeed = 7;

Player.prototype.moveY = function(step, level, keys) {
  this.speed.y = 0;
  if (keys.up) this.speed.y -= playerYSpeed;
  if (keys.down) this.speed.y += playerYSpeed;

  var motion = new Vector(0, this.speed.y * step);
  var newPos = this.pos.plus(motion);
  var obstacle = level.obstacleAt(newPos, this.size);
  if (obstacle)
    level.playerTouched(obstacle);
  else
    this.pos = newPos;
};

Player.prototype.act = function(step, level, keys) {
  this.moveX(step, level, keys);
  this.moveY(step, level, keys);

  var otherActor = level.actorAt(this);
  if (otherActor)
    level.playerTouched(otherActor.type, otherActor);

  // Losing animation
  if (level.status == "lost") {
    this.pos.y += step;
    this.size.y -= step;
  }
};

Level.prototype.playerTouched = function(type, actor) {
  if (type == "sun" && this.status == null) {
    this.status = "lost";
    this.finishDelay = 1;
  } else if (type == "bird") {
    this.actors = this.actors.filter(function(other) {
      return other != actor;
    });
    if (!this.actors.some(function(actor) {
      return actor.type == "bird";
    })) {
      this.status = "won";
      this.finishDelay = 1;
    }
  }
};

var arrowCodes = {37: "left", 38: "up", 39: "right", 40: "down"};

function trackKeys(codes) {
  var pressed = Object.create(null);
  function handler(event) {
    if (codes.hasOwnProperty(event.keyCode)) {
      var down = event.type == "keydown";
      pressed[codes[event.keyCode]] = down;
      event.preventDefault();
    }
  }
  addEventListener("keydown", handler);
  addEventListener("keyup", handler);
  return pressed;
}

function runAnimation(frameFunc) {
  var lastTime = null;
  function frame(time) {
    var stop = false;
    if (lastTime != null) {
      var timeStep = Math.min(time - lastTime, 100) / 1000;
      stop = frameFunc(timeStep) === false;
    }
    lastTime = time;
    if (!stop)
      requestAnimationFrame(frame);
  }
  requestAnimationFrame(frame);
}

var arrows = trackKeys(arrowCodes);

function runLevel(level, Display, andThen) {
  var display = new Display(document.body, level);
  runAnimation(function(step) {
    //console.log("step : " + step);
    level.animate(step, arrows);
    display.drawFrame(step);
    if (level.isFinished()) {
      display.clear();
      if (andThen)
        andThen(level.status);
      return false;
    }
  });
}

function runGame(plans, Display) {
  function startLevel(n) {
    runLevel(new Level(plans[n]), Display, function(status) {
      if (status == "lost")
        startLevel(n);
      else if (n < plans.length - 1)
        startLevel(n + 1);
      else
        console.log("You win!");
    });
  }
  startLevel(0);
}


text:
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
     android:fillAfter="true"
     android:delay="5%">

    <scale
        android:duration="@integer/px_default_animation_time"
        android:fromXScale="1.0"
        android:fromYScale="1.0"
        android:interpolator="@android:anim/accelerate_interpolator"
        android:toXScale="1.0"
        android:toYScale="0.0"/>

</set>


text:
<?php
namespace Xi\Zend\Application\Resource;

use Zend_Application_Resource_ResourceAbstract as ResourceAbstract,
    Zend_Application_Exception,
    Zend_Cache_Core,
    Zend_Db_Table_Abstract,
    Zend_Date,
    Zend_Translate,
    Zend_Locale,
    Zend_Currency;

/**
 * Cache application resource
 *
 * @category   Xi
 * @package    Application
 * @subpackage Resource
 * @author     pekkis
 * @todo       The whole Zend Cache is soooo retarded. This does not work as it should work.
 * @license    http://www.opensource.org/licenses/BSD-3-Clause New BSD License
 */
class Cache extends ResourceAbstract
{
    protected $backends;

    protected $frontends;

    /**
     * @return Zend_Cache_Manager
     */
    public function init()
    {
        $opts = $this->getOptions();

        $cm = $this->getBootstrap()->bootstrap('cachemanager')->getResource('cachemanager');

        if(isset($opts['framework'])) {
            foreach($opts['framework'] as $key => $cache) {
                $method = '_init' . ucfirst($key);
                $this->$method($cm->getCache($cache));
            }
        }

        // output caching
        if(isset($opts['view'])) {
            $view = $this->getBootstrap()->bootstrap('view')->getResource('view');
            $cache = $cm->getCache($opts['view']);
            if(!$cache) {
                throw new Zend_Application_Exception("Cache '{$opts['cache']}' not found", 500);
            }
            $view->cache()->setCache($cache);
        }

        return $cm;
    }

    protected function _initTable(Zend_Cache_Core $cache)
    {
        Zend_Db_Table_Abstract::setDefaultMetadataCache($cache);
    }

    protected function _initDate(Zend_Cache_Core $cache)
    {
        Zend_Date::setOptions(array('cache' => $cache));
    }

    protected function _initTranslate(Zend_Cache_Core $cache)
    {
        Zend_Translate::setCache($cache);
    }

    protected function _initLocale(Zend_Cache_Core $cache)
    {
        Zend_Locale::setCache($cache);
    }

    protected function _initCurrency(Zend_Cache_Core $cache)
    {
        Zend_Currency::setCache($cache);
    }
}


text: .scTabHeaderFont { text-align: left }


text:
"""
Django settings for urlShortenerServer project.

Generated by 'django-admin startproject' using Django 1.10.4.

For more information on this file, see
https://docs.djangoproject.com/en/1.10/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.10/ref/settings/
"""

import os
import datetime

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'g8#+4$33lyw3d!&2^m9%329t5)@u(^bhhq6)*25^kc*&53291o'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'shortener',
    'rest_framework',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'urlShortenerServer.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'urlShortenerServer.wsgi.application'

# Database
# https://docs.djangoproject.com/en/1.10/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

# Password validation
# https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# Internationalization
# https://docs.djangoproject.com/en/1.10/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.10/howto/static-files/

STATIC_URL = '/static/'

SITE_URL = "http://localhost:8000/"

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.AllowAny'
    ),
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.BasicAuthentication',
        'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
    ),
}

LOGIN_REDIRECT_URL = '/'


text:
using System;

namespace Twice.ViewModels.Settings
{
	internal class MuteEditArgs : EventArgs
	{
		public MuteEditArgs( MuteEditAction action, string filter, DateTime? endDate )
		{
			Action = action;
			Filter = filter;
			EndDate = endDate;
		}

		public readonly MuteEditAction Action;
		public readonly DateTime? EndDate;
		public readonly string Filter;
	}
}


text:
<TITLE>Ask Question</TITLE>

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

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

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

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

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

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

<link rel="stylesheet" type="text/css"
	href="css/jquery-ui-1.8.11.custom.css" />
<link rel="stylesheet" type="text/css" href="item_image_style.css" />
<link rel="stylesheet" type="text/css" href="home_recommendation.css" />
<link rel="stylesheet" type="text/css" href="stylesheets/foundation.css" />

		<form name="search_bar" action="search.html" class="nice" method="GET">
			<input type="hidden" name="userID" value=""> <input
				type="hidden" name="authToken" value=""> <input type="text"
				id="searchTerm" name="searchTerm" value="" /> <input type="submit"
				class="nice small radius white button" value="Search">
		</form>

<form name="askquestion" id="questionform" class="nice" action="">
					Please input your question:
<textarea id="question" cols="30" rows="5" value="" required></textarea>

<input type="button" class="nice small radius white button" value="Submit" onClick="submitQuestion();">
					</form>

								Errors:

								Server:

								Time to process parameters:
								0

								Time to access database:
								0

								Time to process page data:
								0

								Time to render page:
								0

								Total time to process:
								0


text:
<!DOCTYPE html>

  <title th:text="#{SEC0047}">Login History Management</title>

  <yq:breadcrumbs menu="SECURITY_LOGIN_HISTORY"/>

    <yq:alert level="danger"/>

        <form action="#" th:action="@{/security/history}" th:object="${searchForm}" method="post">

            <input class="form-control" th:field="*{criterion}" type="text"/>

                <button class="btn-u" type="submit"></button>

        </form>

          Username
          Session ID
          IP Address
          Login Time

          NAME
          ABCDEFGHIJKLMNOPQRSTUVWXYZ
          127.0.0.1
          2016-11-10 21:35:00

        <yq:pagination page="${page}" th:href="@{/security/history}"/>


text:
@interface PodsDummy_Pods_PYUtil_Example : NSObject
@end
@implementation PodsDummy_Pods_PYUtil_Example
@end


text:
import { interfaceHasValueIn } from './interfaceHasValueIn';

describe('propTruthyInAllPaths', () => {
  it('should return false', () => {
    const o: any = {
      controls: {
        name: {
          dirty: false,
          pristine: true,
        },
        email: {
          dirty: false,
          pristine: true,
        },
        password: {
          dirty: false,
          pristine: true,
        },
        verifyPassword: {
          dirty: false,
          pristine: true,
        },
      },
    };

    // basePath may be a path such as 'a.b.c[0]' etc.
    expect(interfaceHasValueIn(o, 'controls', 'dirty')).toBe(true);
  });

  it('should return true', () => {
    const o: any = {
      controls: {
        name: {
          dirty: true,
          pristine: false,
        },
        email: {
          dirty: null, // <-- no value
          pristine: false,
        },
        password: {
          dirty: true,
          pristine: false,
        },
        verifyPassword: {
          dirty: true,
          pristine: false,
        },
      },
    };

    // basePath may be a path such as 'a.b.c[0]' etc.
    expect(interfaceHasValueIn(o, 'controls', 'dirty')).toBe(false);
  });
});


text:
layout: post
title: "Adobe Advertises Apollo on Diggnation"
category: "Blog"
---
{% include JB/setup %}

Yes, I listen to podcasts. I was listening to [Diggnation](http://revision3.com/diggnation) this weekend, the companion podcast for the [Digg.com](http://digg.com) web site. For those not familiar with this site, it was started by Kevin Rose of Tech TV fame as a way for users to vote for which stories get promoted to the front page of the site. On this weeks episode, Kevin mentioned that the sponsor of the show this week was Adobe Apollo. He even went into the detail of how Apollo uses web technologies to create cross platform desktop applications.

Kevin also mentioned that Digg was looking into using Apollo for future applications.

I think it is great that Adobe is using this type of marketing because it directly targets the audience they need to reach which is technophiles.


text:
"""Package contenant la commande 'asseoir'."""

from primaires.interpreteur.commande.commande import Commande

class CmdAsseoir(Commande):

    """Commande 'asseoir'"""

    def __init__(self):
        """Constructeur de la commande."""
        Commande.__init__(self, "asseoir", "sit")
        self.schema = "(<element_observable>)"
        self.nom_categorie = "bouger"
        self.aide_courte = "permet de s'asseoir"
        self.aide_longue = \
            "Cette commande permet de s'asseoir. Sans paramètre, " \
            "vous vous assierez sur le sol. Vous pouvez également " \
            "préciser un nom d'élément observable dans la salle " \
            "(un détail de la description qui le supporte). " \
            "Le facteur de récupération de vos différentes statistiques " \
            "sera différent en fonction de l'élément choisi."

    def interpreter(self, personnage, dic_masques):
        """Méthode d'interprétation de commande"""
        masque = dic_masques["element_observable"]
        personnage.agir("asseoir")
        salle = personnage.salle
        if salle.nom_terrain in ("aquatique", "subaquatique"):
            personnage << "|err|Vous ne pouvez vous asseoir ici.|ff|"
            return

        if masque:
            elt = masque.element
            if not hasattr(elt, "peut_asseoir") or not elt.peut_asseoir:
                personnage << "|err|Vous ne pouvez vous asseoir ici.|ff|"
                return

            nb = len([p for p in personnage.salle.personnages if \
                    "assis" in p.etats and p.etats.get("assis").sur is elt])
            if nb >= elt.nb_places_assises:
                personnage << "|err|Toutes les places sont prises ici.|ff|"
                return

            elt.script["allonge"]["avant"].executer(personnage=personnage, salle=salle)
            personnage.etats.retirer("allonge")
            personnage.etats.ajouter("assis", elt)

            if hasattr(elt, "messages"):
                # elt est un meuble
                message = elt.messages["assis"]
                message = message.replace("$meuble", elt.get_nom(1))
                personnage << message
                message = elt.messages["oassis"]
                message = message.replace("$meuble", elt.get_nom(1))
                message = message.replace("$personnage", "{}")
                personnage.salle.envoyer(message, personnage)
            else:
                personnage << "Vous vous asseyez {} {}.".format(
                        elt.connecteur, elt.titre)
                personnage.salle.envoyer("{{}} s'asseoit {} {}.".format(
                        elt.connecteur, elt.titre), personnage)
                elt.script["asseoit"]["après"].executer(personnage=personnage,
                        salle=salle)
        else:
            personnage.etats.retirer("allonge")
            personnage.etats.ajouter("assis", None)
            personnage << "Vous vous asseyez sur le sol."
            personnage.salle.envoyer("{} s'asseoit sur le sol.", personnage)


text:
import os.path

#def xfile(afile, globalz=None, localz=None):
#    with open(afile, "r") as fh:
#        exec(fh.read(), globalz, localz)

parent_dir = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
parent_dir = os.path.dirname(parent_dir)
path = os.path.join(parent_dir, 'bin', 'activate_this.py')
#execfile(path, {'__file__': path})
#xfile(path)
exec(open(path).read())