text:
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.ui.base;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.IntentSender.SendIntentException;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.PermissionInfo;
import android.os.Build;
import android.os.Handler;
import android.os.Process;
import android.text.TextUtils;
import android.util.SparseArray;
import android.view.View;

import org.chromium.base.ActivityState;
import org.chromium.base.ApiCompatibilityUtils;
import org.chromium.base.ApplicationStatus;
import org.chromium.base.Callback;
import org.chromium.base.ContextUtils;
import org.chromium.ui.UiUtils;

import java.lang.ref.WeakReference;

/**
 * The class provides the WindowAndroid's implementation which requires
 * Activity Instance.
 * Only instantiate this class when you need the implemented features.
 */
public class ActivityWindowAndroid
        extends WindowAndroid
        implements ApplicationStatus.ActivityStateListener, View.OnLayoutChangeListener {
    // Constants used for intent request code bounding.
    private static final int REQUEST_CODE_PREFIX = 1000;
    private static final int REQUEST_CODE_RANGE_SIZE = 100;

    private static final String PERMISSION_QUERIED_KEY_PREFIX = "HasRequestedAndroidPermission::";

    private final Handler mHandler;
    private final SparseArray<PermissionCallback> mOutstandingPermissionRequests;

    private int mNextRequestCode;

    /**
     * Creates an Activity-specific WindowAndroid with associated intent functionality.
     * TODO(jdduke): Remove this overload when all callsites have been updated to
     * indicate their activity state listening preference.
     * @param context Context wrapping an activity associated with the WindowAndroid.
     */
    public ActivityWindowAndroid(Context context) {
        this(context, true);
    }

    /**
     * Creates an Activity-specific WindowAndroid with associated intent functionality.
     * @param context Context wrapping an activity associated with the WindowAndroid.
     * @param listenToActivityState Whether to listen to activity state changes.
     */
    public ActivityWindowAndroid(Context context, boolean listenToActivityState) {
        super(context);
        Activity activity = activityFromContext(context);
        if (activity == null) {
            throw new IllegalArgumentException("Context is not and does not wrap an Activity");
        }
        mHandler = new Handler();
        mOutstandingPermissionRequests = new SparseArray<PermissionCallback>();
        if (listenToActivityState) {
            ApplicationStatus.registerStateListenerForActivity(this, activity);
        }

        setAndroidPermissionDelegate(new ActivityAndroidPermissionDelegate());
    }

    @Override
    protected void registerKeyboardVisibilityCallbacks() {
        Activity activity = getActivity().get();
        if (activity == null) return;
        View content = activity.findViewById(android.R.id.content);
        mIsKeyboardShowing = UiUtils.isKeyboardShowing(getActivity().get(), content);
        content.addOnLayoutChangeListener(this);
    }

    @Override
    protected void unregisterKeyboardVisibilityCallbacks() {
        Activity activity = getActivity().get();
        if (activity == null) return;
        activity.findViewById(android.R.id.content).removeOnLayoutChangeListener(this);
    }

    @Override
    public int showCancelableIntent(
            PendingIntent intent, IntentCallback callback, Integer errorId) {
        Activity activity = getActivity().get();
        if (activity == null) return START_INTENT_FAILURE;

        int requestCode = generateNextRequestCode();

        try {
            activity.startIntentSenderForResult(
                    intent.getIntentSender(), requestCode, new Intent(), 0, 0, 0);
        } catch (SendIntentException e) {
            return START_INTENT_FAILURE;
        }

        storeCallbackData(requestCode, callback, errorId);
        return requestCode;
    }

    @Override
    public int showCancelableIntent(Intent intent, IntentCallback callback, Integer errorId) {
        Activity activity = getActivity().get();
        if (activity == null) return START_INTENT_FAILURE;

        int requestCode = generateNextRequestCode();

        try {
            activity.startActivityForResult(intent, requestCode);
        } catch (ActivityNotFoundException e) {
            return START_INTENT_FAILURE;
        }

        storeCallbackData(requestCode, callback, errorId);
        return requestCode;
    }

    @Override
    public int showCancelableIntent(Callback<Integer> intentTrigger, IntentCallback callback,
            Integer errorId) {
        Activity activity = getActivity().get();
        if (activity == null) return START_INTENT_FAILURE;

        int requestCode = generateNextRequestCode();

        intentTrigger.onResult(requestCode);

        storeCallbackData(requestCode, callback, errorId);
        return requestCode;
    }

    @Override
    public void cancelIntent(int requestCode) {
        Activity activity = getActivity().get();
        if (activity == null) return;
        activity.finishActivity(requestCode);
    }

    /**
     * Responds to the intent result if the intent was created by the native window.
     * @param requestCode Request code of the requested intent.
     * @param resultCode Result code of the requested intent.
     * @param data The data returned by the intent.
     * @return Boolean value of whether the intent was started by the native window.
     */
    public boolean onActivityResult(int requestCode, int resultCode, Intent data) {
        IntentCallback callback = mOutstandingIntents.get(requestCode);
        mOutstandingIntents.delete(requestCode);
        String errorMessage = mIntentErrors.remove(requestCode);

        if (callback != null) {
            callback.onIntentCompleted(this, resultCode, data);
            return true;
        } else {
            if (errorMessage != null) {
                showCallbackNonExistentError(errorMessage);
                return true;
            }
        }
        return false;
    }

    private String getHasRequestedPermissionKey(String permission) {
        String permissionQueriedKey = permission;
        try {
            // Runtime permissions are controlled at the group level.  So when determining whether
            // we have requested a particular permission before, we should check whether we
            // have requested any permission in that group as that mimics the logic in the Android
            // framework.
            //
            // e.g. Requesting first the permission ACCESS_FINE_LOCATION will result in Chrome
            //      treating ACCESS_COARSE_LOCATION as if it had already been requested as well.
            PermissionInfo permissionInfo = getApplicationContext().getPackageManager()
                    .getPermissionInfo(permission, PackageManager.GET_META_DATA);

            if (!TextUtils.isEmpty(permissionInfo.group)) {
                permissionQueriedKey = permissionInfo.group;
            }
        } catch (NameNotFoundException e) {
            // Unknown permission.  Default back to the permission name instead of the group.
        }

        return PERMISSION_QUERIED_KEY_PREFIX + permissionQueriedKey;
    }

    /**
     * Responds to a pending permission result.
     * @param requestCode The unique code for the permission request.
     * @param permissions The list of permissions in the result.
     * @param grantResults Whether the permissions were granted.
     * @return Whether the permission request corresponding to a pending permission request.
     */
    public boolean onRequestPermissionsResult(int requestCode, String[] permissions,
            int[] grantResults) {
        Activity activity = getActivity().get();
        assert activity != null;

        SharedPreferences.Editor editor = ContextUtils.getAppSharedPreferences().edit();
        for (int i = 0; i < permissions.length; i++) {
            editor.putBoolean(getHasRequestedPermissionKey(permissions[i]), true);
        }
        editor.apply();

        PermissionCallback callback = mOutstandingPermissionRequests.get(requestCode);
        mOutstandingPermissionRequests.delete(requestCode);
        if (callback == null) return false;
        callback.onRequestPermissionsResult(permissions, grantResults);
        return true;
    }

    @Override
    public WeakReference<Activity> getActivity() {
        return new WeakReference<Activity>(activityFromContext(getContext().get()));
    }

    @Override
    public void onActivityStateChange(Activity activity, int newState) {
        if (newState == ActivityState.STOPPED) {
            onActivityStopped();
        } else if (newState == ActivityState.STARTED) {
            onActivityStarted();
        }
    }

    @Override
    public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft,
            int oldTop, int oldRight, int oldBottom) {
        keyboardVisibilityPossiblyChanged(UiUtils.isKeyboardShowing(getActivity().get(), v));
    }

    private int generateNextRequestCode() {
        int requestCode = REQUEST_CODE_PREFIX + mNextRequestCode;
        mNextRequestCode = (mNextRequestCode + 1) % REQUEST_CODE_RANGE_SIZE;
        return requestCode;
    }

    private void storeCallbackData(int requestCode, IntentCallback callback, Integer errorId) {
        mOutstandingIntents.put(requestCode, callback);
        mIntentErrors.put(
                requestCode, errorId == null ? null : mApplicationContext.getString(errorId));
    }

    private class ActivityAndroidPermissionDelegate implements AndroidPermissionDelegate {
        @Override
        public boolean hasPermission(String permission) {
            return ApiCompatibilityUtils.checkPermission(
                    mApplicationContext, permission, Process.myPid(), Process.myUid())
                    == PackageManager.PERMISSION_GRANTED;
        }

        @Override
        public boolean canRequestPermission(String permission) {
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) return false;

            Activity activity = getActivity().get();
            if (activity == null) return false;

            if (isPermissionRevokedByPolicy(permission)) {
                return false;
            }

            if (activity.shouldShowRequestPermissionRationale(permission)) {
                return true;
            }

            // Check whether we have ever asked for this permission by checking whether we saved
            // a preference associated with it before.
            String permissionQueriedKey = getHasRequestedPermissionKey(permission);
            SharedPreferences prefs = ContextUtils.getAppSharedPreferences();
            if (!prefs.getBoolean(permissionQueriedKey, false)) return true;

            return false;
        }

        @Override
        public boolean isPermissionRevokedByPolicy(String permission) {
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) return false;

            Activity activity = getActivity().get();
            if (activity == null) return false;

            return activity.getPackageManager().isPermissionRevokedByPolicy(
                    permission, activity.getPackageName());
        }

        @Override
        public void requestPermissions(
                final String[] permissions, final PermissionCallback callback) {
            if (requestPermissionsInternal(permissions, callback)) return;

            // If the permission request was not sent successfully, just post a response to the
            // callback with whatever the current permission state is for all the requested
            // permissions.  The response is posted to keep the async behavior of this method
            // consistent.
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    int[] results = new int[permissions.length];
                    for (int i = 0; i < permissions.length; i++) {
                        results[i] = hasPermission(permissions[i])
                                ? PackageManager.PERMISSION_GRANTED
                                : PackageManager.PERMISSION_DENIED;
                    }
                    callback.onRequestPermissionsResult(permissions, results);
                }
            });
        }

        /**
         * Issues the permission request and returns whether it was sent successfully.
         */
        private boolean requestPermissionsInternal(
                String[] permissions, PermissionCallback callback) {
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) return false;
            Activity activity = getActivity().get();
            if (activity == null) return false;

            int requestCode = generateNextRequestCode();
            mOutstandingPermissionRequests.put(requestCode, callback);
            activity.requestPermissions(permissions, requestCode);
            return true;
        }
    }
}


text:
import argparse
import boto
import boto.ec2
from boto_cli import configure_logging
import logging
log = logging.getLogger('boto_cli')
from pprint import pprint

# configure command line argument parsing
parser = argparse.ArgumentParser(description='Describe EC2 images in all/some available EC2 regions')
parser.add_argument("-f", "--filter", action="append", help="An EC2 image filter. [can be used multiple times]")
parser.add_argument("-i", "--id", dest="resource_ids", action="append", help="An EC2 image id. [can be used multiple times]")
parser.add_argument("-r", "--region", help="A region substring selector (e.g. 'us-west')")
parser.add_argument("-v", "--verbose", action='store_true', help="Include volume details") # TODO: drop in favor of a log formatter?!
parser.add_argument("--access_key_id", dest='aws_access_key_id', help="Your AWS Access Key ID")
parser.add_argument("--secret_access_key", dest='aws_secret_access_key', help="Your AWS Secret Access Key")
parser.add_argument("-l", "--log", dest='log_level', default='WARNING',
                    choices=['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'],
                    help="The logging level to use. [default: WARNING]")
args = parser.parse_args()

configure_logging(log, args.log_level)

def isSelected(region):
    return True if region.name.find(args.region) != -1 else False

# execute business logic
credentials = {'aws_access_key_id': args.aws_access_key_id, 'aws_secret_access_key': args.aws_secret_access_key}
heading = "Describing EBS images"
regions = boto.ec2.regions()
if args.region:
    heading += " (filtered by region '" + args.region + "')"
    regions = filter(isSelected, regions)

filters = None
if args.filter:
    filters = dict([filter.split('=') for filter in args.filter])
log.info(args.filter)
log.debug(filters)
log.info(args.resource_ids)

print heading + ":"
for region in regions:
    try:
        ec2 = boto.connect_ec2(region=region, **credentials)
        resources = ec2.get_all_images(image_ids=args.resource_ids, owners=['self'], filters=filters)
        print region.name + ": " + str(len(resources)) + " images"
        for resource in resources:
            if args.verbose:
                pprint(vars(resource))
            else:
                print resource.id
    except boto.exception.BotoServerError, e:
        log.error(e.error_message)

redpajama_set_name: RedPajamaGithub


text:
const React = require('react');
const ReactDOM = require('react-dom');

const ajaxApi = require('../../../../util/ajaxApi');
const  EditSecondTable = require('./EditSecondTable');

var EditTable = React.createClass({

 render_body(item,targetData,attrs){
    var tableTree = this.props.tableTree;
    var setData = this.props.setData;
    var obj_props = attrs.map(function(attr,i){
      var style = attr.style;
      var value = attr.code=="btn"?'':targetData[attr.code];
      var spanClass = attr.code;
      var index_key = item+"_td_"+i;
      if(attr.code=="firm"){
        return(

            <select id="firm">
              <option value="01">abc廠商</option>
            </select>

        )
      }else if(attr.code=='btn'){
        return(

        )
      }else if(attr.code=='contractPrice'){
        if(tableTree._root){
           var nodes = tableTree._root.children;
          if(nodes.length>0){
            // value = treeData.calculate(nodes,'contractPrice');
            return (

                    {value}

            )
          }
        }
        return (

              <input type='text' value={value} />

        )

      }else{
        return {value}	;
      }

    }.bind(this))
    return (

        {obj_props}

    )
 },
  render(){
    console.log("==========render editTable============")
    console.log(this.props.tableTree)
     var targetData = this.props.targetData;
     var tableTree = this.props.tableTree;
     var nodes =[];
     if(tableTree._root){
         nodes = tableTree._root.children;
     }
     console.log('render editTable nodes=s',nodes)

      var header = this.props.tableData.map(function(obj,i){
        var style = obj.style;
        return (
          {obj.name}
        )
      });

    var cumNumber =   header.length;
    return (

              {header}

            {this.render_body('workItem',this.props.targetData,this.props.tableData)}

                <EditSecondTable nodes={nodes} removeItem={this.props.removeItem} addItem={this._handleAddItem} attrOnChange={this._handleAttrChange} codeOnBlur={this._handleCodeBlur} priceOnBlur={this._handlePriceBlur}/>

    )
  },
  _handlePriceBlur:function(obj,e){
     var index = obj.index;
    var targetData = this.props.targetData;
    var tableTree = this.props.tableTree;
    var nodes = tableTree._root.children;
    var price = e.target.value;
    var changeData ;
    if(obj.type=='node'){
      var indexs = index.split('-');
      var parent_index = Number(indexs[0])-1;
      var sub_index = Number(indexs[1])-1;
      changeData = nodes[parent_index].children[sub_index].data;

    }else{
      var sub_index = Number(index)-1;
      changeData = nodes[sub_index].data;
    }
    if(price){
      changeData.contractPrice=price;
      this.props.saveWorkmapping( changeData,index);
    }
  },
  _handleCodeBlur:function(obj,e){
     var index = obj.index;
     var targetData = this.props.targetData;
     var tableTree = this.props.tableTree;
     var nodes = tableTree._root.children;
     var changeData ;
     if(obj.type=='node'){
       var indexs = index.split('-');
       var parent_index = Number(indexs[0])-1;
       var sub_index = Number(indexs[1])-1;
       changeData = nodes[parent_index].children[sub_index].data;

     }else{
       var sub_index = Number(index)-1;
       changeData = nodes[sub_index].data;
     }
     var code = e.target.value;
     if(code){
       ajaxApi.categoriesDetaileDao('MaterialItem','getByCode',{code:code,state:'Y'},function(result){
         if(result[0]){
           var data = {
             code:code,
             item:result[0].item,
             unit:result[0].unit,
             contractPrice:result[0].contractPrice,
             WorkItemId:targetData.id
           }
           changeData=_.assign(changeData, data);
           this.props.saveWorkmapping(changeData,index);

         }else{
          // nodes[index].data =nodes[index].data.code;
          this.props.saveWorkmapping( null,index);
           alert('無此編號,請重新輸入');
         }

       }.bind(this))
     }
  },

  _handleAttrChange:function(obj,e){
    var index = obj.index;
    var attr = obj.attr;
    var tableTree = this.props.tableTree;
    var nodes = tableTree._root.children;
    var value = e.target.value;
    var changeData;
    console.log(obj.type);
    if(obj.type=='node'){
      var indexs = index.split('-');
      var parent_index = Number(indexs[0])-1;
      var sub_index = Number(indexs[1])-1;
      changeData = nodes[parent_index].children[sub_index].data;

    }else{
      var sub_index = Number(index)-1;
      changeData = nodes[sub_index].data;
    }
    changeData[attr]= value;
    this.props.setTabletree(tableTree);
  },
  _handleAddItem:function(obj,e){
    var parent = obj.parent;
    var type = obj.type;
    console.log("_handleAddItem parent = ",parent)
    console.log("_handleAddItem type = ",type)
    var targetData = this.props.targetData;
    var tableTree = this.props.tableTree;

    var order =0;
    if(tableTree._root){
      order = tableTree._root.children.length;
    }
    var newItem = {
      WorkItemId:targetData.id,
      order:order,
      hasChild:'N',
      type:type,
      parent:parent
    }

    if(type=='node'){
      if(parent){
        tableTree.add(newItem,parent,tableTree.traverseDF,"id");
      }
    }else{
      tableTree.add(newItem,"project",tableTree.traverseDF,"item");
    }

    this.props.setTabletree(tableTree);
  }
});
module.exports = EditTable;


text:
// ======================================================================== //
// Copyright 2009-2016 Intel Corporation                                    //
//                                                                          //
// Licensed under the Apache License, Version 2.0 (the "License");          //
// you may not use this file except in compliance with the License.         //
// You may obtain a copy of the License at                                  //
//                                                                          //
//     http://www.apache.org/licenses/LICENSE-2.0                           //
//                                                                          //
// Unless required by applicable law or agreed to in writing, software      //
// distributed under the License is distributed on an "AS IS" BASIS,        //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and      //
// limitations under the License.                                           //
// ======================================================================== //

#include "miniSG.h"
#include "importer.h"

namespace ospray {
  namespace miniSG {
    using std::cout;
    using std::endl;

    struct STLTriangle {
      vec3f normal;
      vec3f v0, v1, v2;
      uint16_t attribute;
    };

    /*! import a list of STL files */
    void importSTL(std::vector<Model *> &animation, const ospcommon::FileName &fileName)
    {
      FILE *file = fopen(fileName.c_str(),"rb");
      if (!file) error("could not open input file");
      char line[10000];
      while (fgets(line,10000,file) && !feof(file)) {
        char *eol = strstr(line,"\n");
        if (eol) *eol = 0;
        Model *model = new Model;
        animation.push_back(model);
        importSTL(*model,line);
      }
      cout << "done importing STL animation; found "
           << animation.size() << " time steps" << endl;
      fclose(file);
    }

    void importSTL(Model &model,
                   const ospcommon::FileName &fileName)
    {
      FILE *file = fopen(fileName.c_str(),"rb");
      if (!file) error("could not open input file");
      char header[80];
      int32_t rc = fread(header,1,80,file);
      if (rc < 80)
        error("could not read header");
      int32_t numTriangles;
      rc = fread(&numTriangles,sizeof(int),1,file);
      Assert(rc == 1 && "could not read num triangles from STL file");
      cout << "miniSG::importSTL: #tris="
           << numTriangles << " (" << fileName.c_str() << ")" << endl;

      ImportHelper importer(model,fileName.c_str());

      miniSG::Triangle triangle;
      STLTriangle stlTri;
      for (int32_t i=0 ; i < numTriangles ; i++) {
        rc = fread(&stlTri.normal,sizeof(stlTri.normal),1,file);
        Assert(rc == 1 && "partial or broken STL file!?");
        rc = fread(&stlTri.v0,sizeof(stlTri.v0),1,file);
        Assert(rc == 1 && "partial or broken STL file!?");
        rc = fread(&stlTri.v1,sizeof(stlTri.v1),1,file);
        Assert(rc == 1 && "partial or broken STL file!?");
        rc = fread(&stlTri.v2,sizeof(stlTri.v2),1,file);
        Assert(rc == 1 && "partial or broken STL file!?");
        rc = fread(&stlTri.attribute,sizeof(unsigned short),1,file);
        Assert(rc == 1 && "partial or broken STL file!?");

        triangle.v0 = importer.addVertex(stlTri.v0);
        triangle.v1 = importer.addVertex(stlTri.v1);
        triangle.v2 = importer.addVertex(stlTri.v2);
        // triangle.materialID = -1;
        importer.addTriangle(triangle);
      }
      importer.finalize();
    }

  } // ::ospray::minisg
} // ::ospray


text:
<?xml version='1.0' encoding='UTF-8'?>
<Info location="fcn_SupportExtensionVerticalTypeI.m" type="File" />


text:
#ifndef INCLUDE_remote_h__
#define INCLUDE_remote_h__

#include "git2/remote.h"
#include "git2/transport.h"
#include "git2/sys/transport.h"

#include "refspec.h"
#include "vector.h"

#define GIT_REMOTE_ORIGIN "origin"

struct git_remote {
	char *name;
	char *url;
	char *pushurl;
	git_vector refs;
	git_vector refspecs;
	git_vector active_refspecs;
	git_vector passive_refspecs;
	git_transport_cb transport_cb;
	void *transport_cb_payload;
	git_transport *transport;
	git_repository *repo;
	git_push *push;
	git_remote_callbacks callbacks;
	git_transfer_progress stats;
	unsigned int need_pack;
	git_remote_autotag_option_t download_tags;
	int update_fetchhead;
	int prune_refs;
	int passed_refspecs;
};

const char* git_remote__urlfordirection(struct git_remote *remote, int direction);
int git_remote__get_http_proxy(git_remote *remote, bool use_ssl, char **proxy_url);

git_refspec *git_remote__matching_refspec(git_remote *remote, const char *refname);
git_refspec *git_remote__matching_dst_refspec(git_remote *remote, const char *refname);

#endif


text:
ProfileListDesktop::ProfileListDesktop(
    ProfileAttributesStorage* profile_storage)
    : profile_storage_(profile_storage) {
}

ProfileListDesktop::~ProfileListDesktop() {
}

// static
ProfileList* ProfileList::Create(ProfileAttributesStorage* profile_storage) {
  return new ProfileListDesktop(profile_storage);
}

size_t ProfileListDesktop::GetNumberOfItems() const {
  return items_.size();
}

const AvatarMenu::Item& ProfileListDesktop::GetItemAt(size_t index) const {
  DCHECK_LT(index, items_.size());
  return *items_[index];
}

void ProfileListDesktop::RebuildMenu() {
  std::vector<ProfileAttributesEntry*> entries =
      profile_storage_->GetAllProfilesAttributesSortedByName();

  items_.clear();
  for (ProfileAttributesEntry* entry : entries) {
    if (entry->IsOmitted())
      continue;

    gfx::Image icon = entry->GetAvatarIcon();
    std::unique_ptr<AvatarMenu::Item> item(
        new AvatarMenu::Item(items_.size(), entry->GetPath(), icon));
    item->name = entry->GetName();
    item->username = entry->GetUserName();
    item->legacy_supervised = entry->IsLegacySupervised();
    item->child_account = entry->IsChild();
    item->signed_in = entry->IsAuthenticated();
    if (entry->GetSigninState() == SigninState::kNotSignedIn) {
      item->username = l10n_util::GetStringUTF16(
          item->legacy_supervised ? IDS_LEGACY_SUPERVISED_USER_AVATAR_LABEL :
                                    IDS_PROFILES_LOCAL_PROFILE_STATE);
    }
    item->active = item->profile_path == active_profile_path_;
    item->signin_required = entry->IsSigninRequired();
    items_.push_back(std::move(item));
  }
}

size_t ProfileListDesktop::MenuIndexFromProfilePath(const base::FilePath& path)
    const {
  const size_t menu_count = GetNumberOfItems();

  for (size_t i = 0; i < menu_count; ++i) {
    const AvatarMenu::Item item = GetItemAt(i);
    if (item.profile_path == path)
      return i;
  }

  // The desired index was not found; return a fallback value.
  NOTREACHED();
  return 0;
}

void ProfileListDesktop::ActiveProfilePathChanged(
    const base::FilePath& active_profile_path) {
  active_profile_path_ = active_profile_path;
}


text:
// excanvas
// Copyright 2006 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/*
 * jQueryGeo/geo
 * (c) 2011-2015, jQueryGeo
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 */


text:
package org.jetbrains.plugins.scala.testingSupport.test.sbt

import com.intellij.openapi.module.Module
import org.jetbrains.plugins.scala.testingSupport.test.AbstractTestRunConfiguration.{SettingEntry, SettingMap}
import org.jetbrains.sbt.SbtUtil
import org.jetbrains.sbt.shell.{SbtShellCommunication, SettingQueryHandler}

import scala.concurrent.{ExecutionContextExecutor, Future}

abstract class SbtTestRunningSupportBase extends SbtTestRunningSupport {

  override implicit def executionContext: ExecutionContextExecutor = scala.concurrent.ExecutionContext.global

  override def allowsSbtUiRun: Boolean = false

  override def initialize(comm: SbtShellCommunication): Future[String] =
    comm.command("initialize")

  override def modifySbtSettingsForUi(module: Module, comm: SbtShellCommunication): Future[SettingMap] =
    Future.successful(Map.empty)

  def createSettingQueryHandler(settingsEntry: SettingEntry, comm: SbtShellCommunication) =
    new SettingQueryHandler(settingsEntry.settingName, settingsEntry.task, settingsEntry.sbtProjectUri,
      settingsEntry.sbtProjectId, comm)

  override def resetSbtSettingsForUi(
    comm: SbtShellCommunication,
    oldSettings: SettingMap
  ): Future[Boolean] = {
    val futures = for ((settingEntry, value) <- oldSettings)
      yield createSettingQueryHandler(settingEntry, comm).setSettingValue(value)
    Future.sequence(futures).map(_.forall(identity))
  }

  private def getSbtProjectUriAndId(module: Module): (Option[String], Option[String]) =
    SbtUtil.getSbtProjectIdSeparated(module)

  override def modifySbtSetting(
    comm: SbtShellCommunication,
    module: Module,
    settings: SettingMap,
    setting: String,
    showTaskName: String,
    setTaskName: String,
    value: String,
    modificationCondition: String => Boolean,
    shouldSet: Boolean,
    shouldRevert: Boolean
  ): Future[SettingMap] = {
    val (projectUri, projectId) = getSbtProjectUriAndId(module)
    val showHandler = SettingQueryHandler(setting, Some(showTaskName), projectUri, projectId, comm)
    val setHandler = if (showTaskName == setTaskName) showHandler else
      SettingQueryHandler(setting, Some(setTaskName), projectUri, projectId, comm)

    for {
      oldSettings <- showHandler.getSettingValue
      success <- {
        if (modificationCondition(oldSettings))
          if (shouldSet) setHandler.setSettingValue(value)
          else setHandler.addToSettingValue(value)
        else
          Future.successful(true)
      }
      //TODO: meaningful report if settings were not set correctly
      settings <- {
        //TODO check 'opts.nonEmpty()' is required so that we don't try to mess up settings if nothing was read
        if (success)
          if (shouldRevert && oldSettings.nonEmpty && modificationCondition(oldSettings))
            Future.successful(settings + (SettingEntry(setting, Some(setTaskName), projectUri, projectId) -> oldSettings))
          else
            Future.successful(settings)
        else
          Future.failed[SettingMap](new RuntimeException("Failed to modify sbt project settings"))
      }
    } yield settings
  }
}


text:
_ = require("underscore");
exports.plugin = function(cli) {

	cli.option = function(command, description, callback) {

		var ops = { command: command,
		description: description,
		callback: callback };

		if(typeof command == 'object') {
			ops = command;
		}

		if(typeof description == 'function') {

			if(typeof ops.description != 'string') ops.description = undefined;

			ops.callback = description;
		}

		if(typeof callback == 'function') {
			ops.callback = callback;
		}

		var mainCmd = cli.parseCommand(ops.command).shift();

		ops.name = mainCmd.path.segments[0].value;
		ops.usage = ops.usage || ops.command;

		if(ops.description) cli.addHelp(ops);

		cli.onCommand(ops.command, function(data) {
			_.defaults(data, ops.defaults || {});
			ops.callback.apply(this, arguments);
		});

		return cli;
	}
}


text:
ACCEPTED

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

#### Published in
Trans. Br. mycol. Soc. 65(3): 500 (1975)

#### Original name
Monochaetia dimorphospora T. Yokoy., 1975

### Remarks
null


text:
''' Converter classes that wrap multiple conversion steps under one class. '''

from pliers.stimuli.base import Stim
from pliers.stimuli.audio import AudioStim
from pliers.stimuli.video import VideoStim
from pliers.stimuli.text import TextStim, ComplexTextStim
from .base import Converter, get_converter

class MultiStepConverter(Converter):

    ''' Base class for Converters doing more than one step.

    Args:
        steps (list): Ordered list describing the sequence of desired
            conversions. Each element in the list can be either a Converter or
            a Stim class. If the former, the exact Converter provided is used
            as the step. If a Stim subclass is passed (e.g., AudioStim), then
            the first matching Converter class will be used.
    '''

    _loggable = False

    def __init__(self, steps=None):
        self.steps = self._steps if steps is None else steps
        super().__init__()

    def _convert(self, stim):
        for i, step in enumerate(self.steps):
            if issubclass(step, Stim):
                converter = get_converter(type(stim), step)
                if converter is None:
                    msg = ("Conversion failed at step %d; unable to find a "
                           "Converter capable of transforming a %s into a %s.") \
                        % (i, stim.__class__.__name__, step.__name__)
                    raise ValueError(msg)
            else:
                converter = step
            stim = converter.transform(stim)
        return stim

# Current approach requires explicit naming of every possible path. This is
# not ideal and could get big in a hurry. We should probably switch to
# walking the inheritance hierarchy of each Stim instance and using the first
# MultiStepConverter that matches (e.g., a VideoFrameCollectionStim that needs
# to be converted to a TextStim should use the VideoToTextConverter).

class VideoToTextConverter(MultiStepConverter):

    ''' Converts a VideoStim directly to a TextStim. '''

    _input_type = VideoStim
    _output_type = TextStim
    _steps = [AudioStim, TextStim]

class VideoToComplexTextConverter(MultiStepConverter):

    ''' Converts a VideoStim directly to a ComplexTextStim. '''

    _input_type = VideoStim
    _output_type = ComplexTextStim
    _steps = [AudioStim, TextStim]


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package lab9;

public class Wait {
  public static void oneSec() {
     try {
       Thread.sleep(1000);
       }
     catch (InterruptedException e) {
       System.err.println(e);
       }
     }
  public static void manySec(long s) {
     try {
       Thread.sleep(s * 1000);
       }
     catch (InterruptedException e) {
       System.err.println(e);
       }
     }
 }


text:
/**
 * Glory for knights.
 */

package com.wandrell.tabletop.pendragon.model.glory;


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

namespace Snake.Core.Enums
{
    public enum CacheTargetType
    {
        Redis,
        CouchBase,
        Memcached,
        WebCache,
    }
}


text:
package ru.org.linux.util.markdown

import com.vladsch.flexmark.ast.{AutoLink, Link}
import com.vladsch.flexmark.html.renderer.{AttributablePart, LinkResolverContext}
import com.vladsch.flexmark.html.{AttributeProvider, HtmlRenderer, IndependentAttributeProviderFactory}
import com.vladsch.flexmark.util.ast.Node
import com.vladsch.flexmark.util.html.Attributes
import com.vladsch.flexmark.util.options.MutableDataHolder

class NofollowExtension extends HtmlRenderer.HtmlRendererExtension {
  override def rendererOptions(options: MutableDataHolder): Unit = {}

  override def extend(rendererBuilder: HtmlRenderer.Builder, rendererType: String): Unit = {
    rendererBuilder.attributeProviderFactory(new IndependentAttributeProviderFactory {
      override def create(context: LinkResolverContext): AttributeProvider =
        new NofollowAttributeProvider
    })
  }
}

class NofollowAttributeProvider extends AttributeProvider {
  override def setAttributes(node: Node, part: AttributablePart, attributes: Attributes): Unit = {
    node match {
      case _: Link if part == AttributablePart.LINK ⇒
        attributes.addValue("rel", "nofollow")
      case _: AutoLink if part == AttributablePart.LINK ⇒
        attributes.addValue("rel", "nofollow")
      case _ ⇒
    }
  }
}


text:
from ConfigParser import ConfigParser
import logging
import os

import graphviz
from hunmisc.corpustools.tsv_tools import get_dependencies, sentence_iterator
import numpy as np
from scipy.sparse import csr_matrix

from pymachine.machine import Machine
from pymachine.utils import MachineGraph

def ensure_dir(path):
    if not os.path.exists(path):
        os.makedirs(path)

def batches(l, n):
    """ Yield successive n-sized chunks from l.
    (source: http://stackoverflow.com/questions/312443/
    how-do-you-split-a-list-into-evenly-sized-chunks-in-python
    """
    for i in xrange(0, len(l), n):
        yield l[i:i+n]

def draw_text_graph(
        words_to_machines, out_dir, fn='text', orig_machines=[]):
    graph = MachineGraph.create_from_machines(
        words_to_machines.values(), orig_machines=orig_machines)
    src_str = graph.to_dot().encode('utf-8')
    src = graphviz.Source(src_str, format='png')
    pic_path = src.render(filename=fn, directory=out_dir)
    return pic_path

def print_text_graph(words_to_machines, graph_dir, fn='text'):
    graph = MachineGraph.create_from_machines(
        words_to_machines.values())
    fn = os.path.join(graph_dir, '{0}.dot'.format(fn))
    with open(fn, 'w') as f:
        f.write(graph.to_dot().encode('utf-8'))
    return fn

def print_4lang_graphs(lexicon, graph_dir):
    logging.info('printing graphs to {0}'.format(graph_dir))
    for word, machine_set in lexicon.iteritems():
        print_4lang_graph(word, next(iter(machine_set)), graph_dir)

def print_4lang_graph(word, machine, graph_dir, max_depth=None):
    graph = MachineGraph.create_from_machines([machine], max_depth=max_depth)
    fn = os.path.join(graph_dir, u"{0}.dot".format(word)).encode('utf-8')
    with open(fn, 'w') as dot_obj:
        dot_obj.write(graph.to_dot().encode('utf-8'))

HEADER = u"digraph finite_state_machine {\n\tdpi=100;\n\trankdir=LR;\n"
EXCLUDE = ("punct")

def dep_to_dot(deps):
    if isinstance(deps[0], dict):
        # new dep structure
        edges = [
            (d['dep']['lemma'], d['type'], d['gov']['lemma']) for d in deps
            if d['type'] not in EXCLUDE]
    else:
        # old dep structure
        edges = [(d[1][0], d[0], d[2][0]) for d in deps if d[0] not in EXCLUDE]

    words = set([e[0] for e in edges] + [e[2] for e in edges])
    lines = []
    for word in words:
        lines.append(u'\t{0} [shape=rectangle, label="{0}"];'.format(
            Machine.d_clean(word)))
    for edge in edges:
        dep, dtype, gov = map(Machine.d_clean, edge)
        lines.append(u'\t{0} -> {1} [label="{2}"];'.format(dep, gov, dtype))

    dot_str = HEADER.encode("utf-8")
    dot_str += u"\n".join(lines).encode("utf-8")
    dot_str += "}\n"
    return dot_str

def draw_dep_graph(deps, out_dir, fn):
    dot_str = dep_to_dot(deps)
    src = graphviz.Source(dot_str, format='png')
    pic_path = src.render(filename=fn, directory=out_dir)
    return pic_path

def get_raw_deps(fn):
    curr_deps = []
    with open(fn) as f:
        for line in f:
            l = line.strip()
            if not l:
                if curr_deps:
                    yield curr_deps
                    curr_deps = []
                continue
            elif l[0] == '(':
                continue
            else:
                curr_deps.append(l)

def conll_to_deps(stream):
    for sen in sentence_iterator(stream):
        yield get_dependencies(sen)

def get_cfg(cfg_file=None):
    cfg_files = [os.path.join(os.environ['FOURLANGPATH'], 'conf/default.cfg')]
    not_found = [fn for fn in cfg_files if not os.path.exists(fn)]
    if cfg_file is not None:
        cfg_files.append(cfg_file)
    if not_found:
        raise Exception("cfg file(s) not found: {0}".format(not_found))
    cfg = ConfigParser(os.environ)
    cfg.read(cfg_files)
    return cfg

"""these two copied from http://stackoverflow.com/questions/8955448/
save-load-scipy-sparse-csr-matrix-in-portable-data-format"""

def save_sparse_csr(filename, array):
    np.savez(filename, data=array.data, indices=array.indices,
             indptr=array.indptr, shape=array.shape)

def load_sparse_csr(filename):
    loader = np.load(filename)
    return csr_matrix(
        (loader['data'], loader['indices'], loader['indptr']),
        shape=loader['shape'])