text:
<?php

namespace backend\controllers;

use common\components\ActionLogTracking;
use common\models\Contact;
use common\models\ContactDetail;
use common\models\MarkSummary;
use common\models\Subject;
use common\models\UserActivity;
use PHPExcel_IOFactory;
use PHPExcel_Style_Alignment;
use PHPExcel_Style_Border;
use PHPExcel_Style_Fill;
use Yii;
use yii\data\ActiveDataProvider;
use yii\data\ArrayDataProvider;
use yii\filters\VerbFilter;
use yii\helpers\ArrayHelper;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\web\UploadedFile;

/**
 * MarkSummaryController implements the CRUD actions for MarkSummary model.
 */
class MarkSummaryController extends BaseBEController
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return array_merge(parent::behaviors(), [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
            [
                'class' => ActionLogTracking::className(),
                'user' => Yii::$app->user,
                'model_type_default' => UserActivity::ACTION_TARGET_MARKSUMMARY,
            ],
        ]);
    }

    /**
     * Lists all MarkSummary models.
     * @return mixed
     */
    public function actionIndex()
    {
        $dataProvider = new ArrayDataProvider();
        $model = new MarkSummary();
        $dataSubject = array();
        $classes = Contact::getAllClasses()->all();
        $dataContact = ArrayHelper::map($classes, 'id', 'contact_name');

        if (count($classes) < 1) {
            Yii::$app->getSession()->setFlash('error', 'Lớp chưa được tạo trên hệ thống');
        }

        if (count($classes) > 0) {
            $dataProvider = new ActiveDataProvider([
                'query' => MarkSummary::find()->where(['class_id' => $classes[0]->id, 'semester' => 1]),
            ]);
        }

        if ($model->load(Yii::$app->request->post())) {
            $dataSubject = Subject::find()->where(['id' => $model->subject_id])->all();
            $dataProvider = new ActiveDataProvider([
                'query' => MarkSummary::find()->where(['class_id' => $model->class_id, 'semester' => $model->semester]),
            ]);
        }

        return $this->render('index', [
            'dataProvider' => $dataProvider,
            'dataSubject' => $dataSubject,
            'model' => $model,
            'dataContact' => $dataContact,
        ]);
    }

    /**
     * view page upload mark summary
     */
    public function actionViewUpload()
    {
        $model = new MarkSummary();
        $model->setScenario('admin_create_update');
        return $this->render('upload', [
            'model' => $model,
        ]);
    }

    /**
     * view page export mark summary
     */
    public function actionViewExport()
    {
        $model = new MarkSummary();
        $model->setScenario('admin_create_update');
        return $this->render('export', [
            'model' => $model,
        ]);
    }

    /**
     * @return string
     */
    public function actionUpload()
    {

        $model = new MarkSummary();
        $check = 0;

        $post = Yii::$app->request->post();

        // download template
        if ($model->load($post) && strcmp($model->action, "download") == 0) {
            $this->downloadTemplate($model);
            $model->setScenario('admin_create_update');
            return $this->render('upload', [
                'model' => $model,
            ]);
        }

        if (Yii::$app->request->isAjax && isset($post['ajax']) && $model->load($post)) {
            Yii::$app->response->format = Response::FORMAT_JSON;
            return ActiveForm::validate($model);
        }

        if ($model->load($post)) {

            $file_download = UploadedFile::getInstance($model, 'file');

            if ($file_download) {

                $file_name = Yii::$app->user->id . '.' . uniqid() . time() . '.' . $file_download->extension;
                $tmp = Yii::getAlias('@backend') . '/web/' . Yii::getAlias('@file_downloads') . '/';

                if (!file_exists($tmp)) {
                    mkdir($tmp, 0777, true);
                }

                if ($file_download->saveAs($tmp . $file_name)) {
                    $model->file = $file_name;
                }

                try {
                    // validate class
                    $class = Contact::findOne($model->class_id);
                    if (is_null($class)) {
                        Yii::$app->getSession()->setFlash('error', 'Lớp chưa tạo trên hệ thống');
                        return $this->redirect(['index']);
                    }

                    $inputFileType = \PHPExcel_IOFactory::identify($tmp . $file_name);
                    $objReader = \PHPExcel_IOFactory::createReader($inputFileType);
                    $objPHPExcel = $objReader->load($tmp . $file_name);
                    $sheet = $objPHPExcel->getSheet(0);

                    $highestRow = $sheet->getHighestRow();
                    $subjects = Subject::find()->all();
                    $count = count($subjects);

                    for ($row = 12; $row <= $highestRow; $row++) {

                        $rowData = $sheet->rangeToArray('A' . $row . ':' . chr($count + ord('C')) . $row, null, true, false);

                        $mark_summary = MarkSummary::findOne(['student_id' => $rowData[0][1], 'class_id' => $model->class_id, 'semester' => $model->semester]);

                        if (is_null($mark_summary)) {
                            $mark_summary = new MarkSummary();
                            $mark_summary->created_at = time();
                            $mark_summary->created_by = Yii::$app->user->id;
                            $mark_summary->student_id = $rowData[0][1];
                            $mark_summary->class_id = $model->class_id;
                            $mark_summary->semester = $model->semester;
                        } else {
                            $mark_summary->updated_at = time();
                            $mark_summary->updated_by = Yii::$app->user->id;
                        }

                        // set marks
                        $mark_str = '';
                        for ($i = 3; $i < 3 + count($subjects); $i++) {

                            if (!is_null($rowData[0][$i])) {
                                $mark_str = $mark_str . $sheet->getCell(chr(ord('A') + $i) . '10')->getValue() . ':' . $rowData[0][$i] . ';';
                            }
                        }

                        $mark_summary->marks = $mark_str;

                        if ($mark_summary->save(false)) {
                            $check = 1;
                        }
                    }

                    if ($check) {
                        Yii::$app->getSession()->setFlash('success', 'Upload thành công');
                    } else {
                        Yii::$app->getSession()->setFlash('error', 'Upload không thành công');
                    }
                } catch (Exception $ex) {
                }
            } else {
                Yii::$app->getSession()->setFlash('error', 'Bạn chưa chọn file tải mẫu để upload');
                return $this->render('upload', [
                    'model' => $model,
                ]);
            }
        }
        return $this->redirect(['index']);
    }

    /**
     *
     */
    public function downloadTemplate($model)
    {

        $file_name = 'Mark_Summary_Upload.xls';
        $tmp = Yii::getAlias('@backend') . '/web/' . Yii::getAlias('@file_template') . '/';
        $file = $tmp . $file_name;

        if (file_exists($file)) {

            try {

                $inputFileType = \PHPExcel_IOFactory::identify($tmp . $file_name);
                $objReader = \PHPExcel_IOFactory::createReader($inputFileType);
                $objPHPExcel = $objReader->load($tmp . $file_name);
                $sheet = $objPHPExcel->getSheet(0);
                $sheet->getColumnDimension('B')->setWidth(0.1);
                $sheet->getRowDimension('10')->setRowHeight(0.1);

                $subjects = Subject::find()->all();
                $class = Contact::findOne($model->class_id);
                $students = ContactDetail::find()->where(['contact_id' => $model->class_id])->all();

                // validate class
                if (is_null($class)) {
                    Yii::$app->getSession()->setFlash('error', 'Lớp chưa tạo trên hệ thống');
                    return;
                }

                // set semester
                $title_ = $sheet->getCell('A1')->getValue();
                $sheet->setCellValue('A1', $title_ = str_replace("[semester]", $model->semester == 1 ? "1" : "2", $title_));

                // set subject
                $year = date("Y") . '-' . (intval(date("Y")) + 1);
                $title_ = $sheet->getCell('A2')->getValue();
                $sheet->setCellValue('A2', $title_ = str_replace("[class]", $class->contact_name, $title_));
                $sheet->setCellValue('A2', $title_ = str_replace("[year]", $year, $title_));

                // set school
                $school = Contact::findOne($class->path);
                $title_ = $sheet->getCell('A3')->getValue();
                $sheet->setCellValue('A3', $title_ = str_replace("[school]", $school->contact_name, $title_));

                // set sheet name
                $title_ = $sheet->getTitle();
                $sheet->setTitle($title_ = str_replace("semester", $model->semester == 1 ? "1" : "2", $title_));
                $sheet->setTitle($title_ = str_replace("class", $class->contact_name, $title_));

                $column = ord('D');
                $styleArray = array(
                    'fill' => array(
                        'type' => PHPExcel_Style_Fill::FILL_SOLID,
                        'color' => array('rgb' => '0070C0')
                    ),
                    'borders' => array(
                        'allborders' => array(
                            'style' => PHPExcel_Style_Border::BORDER_THIN
                        )
                    )
                );

                foreach ($subjects as $item) {
                    $sheet->setCellValue(chr($column) . '11', $item->name);
                    $sheet->setCellValue(chr($column) . '10', $item->id);;
                    $sheet->getStyle(chr($column) . '11')->applyFromArray($styleArray);
                    $column++;
                }

                $row = 0;
                foreach ($students as $item) {
                    $sheet->setCellValue('A' . ($row + 12), $row + 1);
                    $sheet->setCellValue('B' . ($row + 12), $item->id);
                    $sheet->setCellValue('C' . ($row + 12), $item->fullname);
                    $row++;
                }

                // set file name upload
                $file_name_upload = "Điểm_Tổngkết_";
                $file_name_upload = $file_name_upload . $class->contact_name . "_";
                $file_name_upload = $file_name_upload . ($model->semester == 1 ? "HK1_" : "HK2_");
                $file_name_upload = $file_name_upload . $year;
                $file_name_upload = $file_name_upload . "_Upload.xls";

                header("Content-Length: " . filesize($file));
                header("Content-type: application/octet-stream");
                header("Content-disposition: attachment; filename=" . basename($file_name_upload));
                header('Expires: 0');
                header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
                ob_clean();
                flush();

                $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
                $objWriter->save('php://output');

            } catch (Exception $ex) {
            }
        } else {
            Yii::$app->getSession()->setFlash('error', 'File is not exits');
        }
    }

    /**
     * export mark summary
     */
    public function actionExport()
    {
        $model = new MarkSummary();
        $file_name = 'Mark_Summary_List.xls';
        $tmp = Yii::getAlias('@backend') . '/web/' . Yii::getAlias('@file_template') . '/';
        $file = $tmp . $file_name;

        if (file_exists($file) && $model->load(Yii::$app->request->post())) {

            try {

                $inputFileType = \PHPExcel_IOFactory::identify($tmp . $file_name);
                $objReader = \PHPExcel_IOFactory::createReader($inputFileType);
                $objPHPExcel = $objReader->load($tmp . $file_name);
                $sheet = $objPHPExcel->getSheet(0);

                $subjects = Subject::find()->where(['id' => $model->subject_id])->all();
                $class = Contact::findOne($model->class_id);
                $students = ContactDetail::find()->where(['contact_id' => $model->class_id])->all();

                // validate class
                if (is_null($class)) {
                    Yii::$app->getSession()->setFlash('error', 'Lớp chưa tạo trên hệ thống');
                    return;
                }

                // set semester
                $title_ = $sheet->getCell('A1')->getValue();
                $sheet->setCellValue('A1', $title_ = str_replace("[semester]", $model->semester == 1 ? "1" : "2", $title_));
                $sheet->setCellValue('A1', $title_ = str_replace("[class]", $class->contact_name, $title_));
                $sheet->mergeCells('A1:' . chr(ord('C') + count($subjects)) . '1');
                $sheet->getStyle('A1')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);

                // set sheet name
                $sheet->setTitle("TKHK" . $model->semester . '-' . $class->contact_name);

                $column = ord('D');
                $styleHeader = array(
                    'fill' => array(
                        'type' => PHPExcel_Style_Fill::FILL_SOLID,
                        'color' => array('rgb' => '0070C0')
                    ),
                    'font' => array(
                        'color' => array('rgb' => 'FFFFFF'),
                        'size' => 13
                    ),
                    'alignment' => array(
                        'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER
                    ),
                    'borders' => array(
                        'allborders' => array(
                            'style' => PHPExcel_Style_Border::BORDER_THIN
                        )
                    )
                );

                $styleRow = array(
                    'font' => array(
                        'size' => 13
                    ),
                );

                // set mark summary
                $sheet->setCellValue('C2', 'Điểm tổng kết');
                $sheet->setCellValue('C3', 'HK' . $model->semester);
                $sheet->getStyle('C2')->applyFromArray($styleHeader);
                $sheet->getStyle('C3')->applyFromArray($styleHeader);

                // set mark summary subject
                $subjects_column = array();
                foreach ($subjects as $item) {
                    $sheet->setCellValue(chr($column) . '2', $item->name);
                    $sheet->setCellValue(chr($column) . '3', 'HK' . $model->semester);
                    $sheet->getStyle(chr($column) . '2')->applyFromArray($styleHeader);
                    $sheet->getStyle(chr($column) . '3')->applyFromArray($styleHeader);
                    $subjects_column[$item->id] = chr($column);
                    $column++;
                }

                $row = 0;
                $students_id = array();
                foreach ($students as $item) {
                    array_push($students_id, $item->id);
                }

                $marks_summary_tmp = MarkSummary::find()->where(['student_id' => $students_id, 'class_id' => $model->class_id, 'semester' => $model->semester])->all();
                $marks_summary = array();

                foreach ($marks_summary_tmp as $item) {
                    $marks_summary[$item->student_id] = $item;
                }

                foreach ($students as $item) {

                    $sheet->setCellValue('A' . ($row + 4), $row + 1);
                    $sheet->setCellValue('B' . ($row + 4), $item->fullname);
                    $sheet->getStyle('A' . ($row + 4))->applyFromArray($styleRow);
                    $sheet->getStyle('B' . ($row + 4))->applyFromArray($styleRow);

                    if (!isset($marks_summary[$item->id])) {
                        $row++;
                        continue;
                    }

                    $marks = $marks_summary[$item->id]->marks;
                    $marks = explode(';', $marks);
                    foreach ($marks as $mark) {
                        $tmp = explode(':', $mark);
                        if (isset($subjects_column[$tmp[0]])) {
                            $sheet->setCellValue($subjects_column[$tmp[0]] . ($row + 4), $tmp[1]);
                            $sheet->getStyle($subjects_column[$tmp[0]] . ($row + 4))->applyFromArray($styleRow);
                        }
                    }
                    $row++;
                }

                // set file name upload
                $file_name_upload = "Danh_sach_diem_tong_ket_hoc_ky_";
                $file_name_upload = $file_name_upload . ($model->semester) . ".xls";

                header("Content-Length: " . filesize($file));
                header("Content-type: application/octet-stream");
                header("Content-disposition: attachment; filename=" . basename($file_name_upload));
                header('Expires: 0');
                header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
                ob_clean();
                flush();

                $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
                $objWriter->save('php://output');

            } catch (Exception $ex) {
            }
        } else {
            Yii::$app->getSession()->setFlash('error', 'File is not exits');
        }
        return $this->redirect(['index']);
    }

    /**
     * Finds the MarkSummary model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return MarkSummary the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = MarkSummary::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}


text:
                    {{filterBy.label}}

                            <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">{{filterBy.label}} </button>

{{prop.label}}

                        <form #filterForm="ngForm">
                            <input [(ngModel)]="filterText" name="filterText"  type="text" class="form-control" id="filter" placeholder="Filter By {{filterBy.label}}...">
                        </form>

                        <button type="button"
                                class="btn btn-default dropdown-toggle"
                                data-toggle="tooltip"
                                data-toggle="dropdown"
                                data-placement="top"
                                title="{{sortByTooltip}}"
                                aria-haspopup="true"
                                aria-expanded="false">{{sortBy.label}} </button>

{{prop.label}}

                    <button (click)="toggleSort()" class="btn btn-link" type="button">

                    </button>

                        <button *ngIf="!isIconButton(action)"
                                (click)="action.performAction()"
                                data-toggle="tooltip"
                                data-placement="top"
                                title="{{action.tooltip}}"
                                class="btn btn-default"
                                type="button">{{action.label}}</button>
                        <button *ngIf="isIconButton(action)"
                                (click)="action.performAction()"
                                data-toggle="tooltip"
                                data-placement="top"
                                title="{{action.tooltip}}"
                                class="btn btn-link"
                                type="button">

                        </button>

                        <button (click)="changeView('LargeCards')" class="btn btn-link "></button>
                        <button (click)="changeView('SmallCards')" class="btn btn-link "></button>
                        <button (click)="changeView('List')" class="btn btn-link "></button>

redpajama_set_name: RedPajamaGithub


text:
using System;

namespace Azure.ResourceManager.RecoveryServicesSiteRecovery.Models
{
    /// <summary> Migration item recovery point properties. </summary>
    public partial class MigrationRecoveryPointProperties
    {
        /// <summary> Initializes a new instance of MigrationRecoveryPointProperties. </summary>
        internal MigrationRecoveryPointProperties()
        {
        }

        /// <summary> Initializes a new instance of MigrationRecoveryPointProperties. </summary>
        /// <param name="recoveryPointOn"> The recovery point time. </param>
        /// <param name="recoveryPointType"> The recovery point type. </param>
        internal MigrationRecoveryPointProperties(DateTimeOffset? recoveryPointOn, MigrationRecoveryPointType? recoveryPointType)
        {
            RecoveryPointOn = recoveryPointOn;
            RecoveryPointType = recoveryPointType;
        }

        /// <summary> The recovery point time. </summary>
        public DateTimeOffset? RecoveryPointOn { get; }
        /// <summary> The recovery point type. </summary>
        public MigrationRecoveryPointType? RecoveryPointType { get; }
    }
}


text:
import * as db from '../db'
import { State } from '../types'

type UpsertRemote = Pick<
  Schema.ApplicationRemote,
  'remote' | 'state' | 'state' | 'sha' | 'seen' | 'age'
>

export async function insertRemote(app: Schema.Application, props: UpsertRemote) {
  const existing = await db.getRemote(app.id, props.remote)
  if (existing) {
    const error = 'Attempting to insert remote that already exists'
    log.error(error)
    throw new Error(error)
  }

  await db.insertRemote({
    applicationId: app.id,
    remote: props.remote,
    seen: props.seen,
    sha: props.sha,
    state: props.state,
    age: props.age
  } as Schema.ApplicationRemote)
}

export async function updateRemoteState(app: Schema.Application, remote: string, state: State) {
  await db.updateRemote(app.id, remote, { state })
}


text:
using base::AutoLock;
using base::MessageLoopProxy;

namespace content {

GpuListenerInfo::GpuListenerInfo() {}

GpuListenerInfo::~GpuListenerInfo() {}

ProxyFlushInfo::ProxyFlushInfo()
    : flush_pending(false),
      route_id(MSG_ROUTING_NONE),
      put_offset(0),
      flush_count(0) {
}

ProxyFlushInfo::~ProxyFlushInfo() {
}

// static
scoped_refptr<GpuChannelHost> GpuChannelHost::Create(
    GpuChannelHostFactory* factory,
    const gpu::GPUInfo& gpu_info,
    const IPC::ChannelHandle& channel_handle,
    base::WaitableEvent* shutdown_event,
    gpu::GpuMemoryBufferManager* gpu_memory_buffer_manager) {
  DCHECK(factory->IsMainThread());
  scoped_refptr<GpuChannelHost> host =
      new GpuChannelHost(factory, gpu_info, gpu_memory_buffer_manager);
  host->Connect(channel_handle, shutdown_event);
  return host;
}

GpuChannelHost::GpuChannelHost(
    GpuChannelHostFactory* factory,
    const gpu::GPUInfo& gpu_info,
    gpu::GpuMemoryBufferManager* gpu_memory_buffer_manager)
    : factory_(factory),
      gpu_info_(gpu_info),
      gpu_memory_buffer_manager_(gpu_memory_buffer_manager) {
  next_transfer_buffer_id_.GetNext();
  next_image_id_.GetNext();
  next_route_id_.GetNext();
}

void GpuChannelHost::Connect(const IPC::ChannelHandle& channel_handle,
                             base::WaitableEvent* shutdown_event) {
  // Open a channel to the GPU process. We pass NULL as the main listener here
  // since we need to filter everything to route it to the right thread.
  scoped_refptr<base::MessageLoopProxy> io_loop = factory_->GetIOLoopProxy();
  channel_ = IPC::SyncChannel::Create(channel_handle,
                                      IPC::Channel::MODE_CLIENT,
                                      NULL,
                                      io_loop.get(),
                                      true,
                                      shutdown_event);

  sync_filter_ = new IPC::SyncMessageFilter(shutdown_event);

  channel_->AddFilter(sync_filter_.get());

  channel_filter_ = new MessageFilter();

  // Install the filter last, because we intercept all leftover
  // messages.
  channel_->AddFilter(channel_filter_.get());
}

bool GpuChannelHost::Send(IPC::Message* msg) {
  // Callee takes ownership of message, regardless of whether Send is
  // successful. See IPC::Sender.
  scoped_ptr<IPC::Message> message(msg);
  // The GPU process never sends synchronous IPCs so clear the unblock flag to
  // preserve order.
  message->set_unblock(false);

  // Currently we need to choose between two different mechanisms for sending.
  // On the main thread we use the regular channel Send() method, on another
  // thread we use SyncMessageFilter. We also have to be careful interpreting
  // IsMainThread() since it might return false during shutdown,
  // impl we are actually calling from the main thread (discard message then).
  //
  // TODO: Can we just always use sync_filter_ since we setup the channel
  //       without a main listener?
  if (factory_->IsMainThread()) {
    // http://crbug.com/125264
    base::ThreadRestrictions::ScopedAllowWait allow_wait;
    bool result = channel_->Send(message.release());
    if (!result)
      DVLOG(1) << "GpuChannelHost::Send failed: Channel::Send failed";
    return result;
  }

  bool result = sync_filter_->Send(message.release());
  return result;
}

void GpuChannelHost::OrderingBarrier(
    int route_id,
    int32 put_offset,
    unsigned int flush_count,
    const std::vector<ui::LatencyInfo>& latency_info,
    bool put_offset_changed,
    bool do_flush) {
  AutoLock lock(context_lock_);
  if (flush_info_.flush_pending && flush_info_.route_id != route_id)
    InternalFlush();

  if (put_offset_changed) {
    flush_info_.flush_pending = true;
    flush_info_.route_id = route_id;
    flush_info_.put_offset = put_offset;
    flush_info_.flush_count = flush_count;
    flush_info_.latency_info.insert(flush_info_.latency_info.end(),
                                    latency_info.begin(), latency_info.end());

    if (do_flush)
      InternalFlush();
  }
}

void GpuChannelHost::InternalFlush() {
  DCHECK(flush_info_.flush_pending);
  Send(new GpuCommandBufferMsg_AsyncFlush(
      flush_info_.route_id, flush_info_.put_offset, flush_info_.flush_count,
      flush_info_.latency_info));
  flush_info_.latency_info.clear();
  flush_info_.flush_pending = false;
}

CommandBufferProxyImpl* GpuChannelHost::CreateViewCommandBuffer(
    int32 surface_id,
    CommandBufferProxyImpl* share_group,
    const std::vector<int32>& attribs,
    const GURL& active_url,
    gfx::GpuPreference gpu_preference) {
  TRACE_EVENT1("gpu",
               "GpuChannelHost::CreateViewCommandBuffer",
               "surface_id",
               surface_id);

  GPUCreateCommandBufferConfig init_params;
  init_params.share_group_id =
      share_group ? share_group->GetRouteID() : MSG_ROUTING_NONE;
  init_params.attribs = attribs;
  init_params.active_url = active_url;
  init_params.gpu_preference = gpu_preference;
  int32 route_id = GenerateRouteID();
  CreateCommandBufferResult result = factory_->CreateViewCommandBuffer(
      surface_id, init_params, route_id);
  if (result != CREATE_COMMAND_BUFFER_SUCCEEDED) {
    LOG(ERROR) << "GpuChannelHost::CreateViewCommandBuffer failed.";

    if (result == CREATE_COMMAND_BUFFER_FAILED_AND_CHANNEL_LOST) {
      // The GPU channel needs to be considered lost. The caller will
      // then set up a new connection, and the GPU channel and any
      // view command buffers will all be associated with the same GPU
      // process.
      DCHECK(MessageLoopProxy::current().get());

      scoped_refptr<base::MessageLoopProxy> io_loop =
          factory_->GetIOLoopProxy();
      io_loop->PostTask(
          FROM_HERE,
          base::Bind(&GpuChannelHost::MessageFilter::OnChannelError,
                     channel_filter_.get()));
    }

    return NULL;
  }

  CommandBufferProxyImpl* command_buffer =
      new CommandBufferProxyImpl(this, route_id);
  AddRoute(route_id, command_buffer->AsWeakPtr());

  AutoLock lock(context_lock_);
  proxies_[route_id] = command_buffer;
  return command_buffer;
}

CommandBufferProxyImpl* GpuChannelHost::CreateOffscreenCommandBuffer(
    const gfx::Size& size,
    CommandBufferProxyImpl* share_group,
    const std::vector<int32>& attribs,
    const GURL& active_url,
    gfx::GpuPreference gpu_preference) {
  TRACE_EVENT0("gpu", "GpuChannelHost::CreateOffscreenCommandBuffer");

  GPUCreateCommandBufferConfig init_params;
  init_params.share_group_id =
      share_group ? share_group->GetRouteID() : MSG_ROUTING_NONE;
  init_params.attribs = attribs;
  init_params.active_url = active_url;
  init_params.gpu_preference = gpu_preference;
  int32 route_id = GenerateRouteID();
  bool succeeded = false;
  if (!Send(new GpuChannelMsg_CreateOffscreenCommandBuffer(
          size, init_params, route_id, &succeeded))) {
    LOG(ERROR) << "Failed to send GpuChannelMsg_CreateOffscreenCommandBuffer.";
    return NULL;
  }

  if (!succeeded) {
    LOG(ERROR)
        << "GpuChannelMsg_CreateOffscreenCommandBuffer returned failure.";
    return NULL;
  }

  CommandBufferProxyImpl* command_buffer =
      new CommandBufferProxyImpl(this, route_id);
  AddRoute(route_id, command_buffer->AsWeakPtr());

  AutoLock lock(context_lock_);
  proxies_[route_id] = command_buffer;
  return command_buffer;
}

scoped_ptr<media::VideoDecodeAccelerator> GpuChannelHost::CreateVideoDecoder(
    int command_buffer_route_id) {
  TRACE_EVENT0("gpu", "GpuChannelHost::CreateVideoDecoder");
  AutoLock lock(context_lock_);
  ProxyMap::iterator it = proxies_.find(command_buffer_route_id);
  DCHECK(it != proxies_.end());
  return it->second->CreateVideoDecoder();
}

scoped_ptr<media::VideoEncodeAccelerator> GpuChannelHost::CreateVideoEncoder(
    int command_buffer_route_id) {
  TRACE_EVENT0("gpu", "GpuChannelHost::CreateVideoEncoder");
  AutoLock lock(context_lock_);
  ProxyMap::iterator it = proxies_.find(command_buffer_route_id);
  DCHECK(it != proxies_.end());
  return it->second->CreateVideoEncoder();
}

void GpuChannelHost::DestroyCommandBuffer(
    CommandBufferProxyImpl* command_buffer) {
  TRACE_EVENT0("gpu", "GpuChannelHost::DestroyCommandBuffer");

  int route_id = command_buffer->GetRouteID();
  Send(new GpuChannelMsg_DestroyCommandBuffer(route_id));
  RemoveRoute(route_id);

  AutoLock lock(context_lock_);
  proxies_.erase(route_id);
  if (flush_info_.flush_pending && flush_info_.route_id == route_id)
    flush_info_.flush_pending = false;

  delete command_buffer;
}

void GpuChannelHost::DestroyChannel() {
  // channel_ must be destroyed on the main thread.
  if (channel_.get() && !factory_->IsMainThread())
    factory_->GetMainLoop()->DeleteSoon(FROM_HERE, channel_.release());
  channel_.reset();
}

void GpuChannelHost::AddRoute(
    int route_id, base::WeakPtr<IPC::Listener> listener) {
  DCHECK(MessageLoopProxy::current().get());

  scoped_refptr<base::MessageLoopProxy> io_loop = factory_->GetIOLoopProxy();
  io_loop->PostTask(FROM_HERE,
                    base::Bind(&GpuChannelHost::MessageFilter::AddRoute,
                               channel_filter_.get(), route_id, listener,
                               MessageLoopProxy::current()));
}

void GpuChannelHost::RemoveRoute(int route_id) {
  scoped_refptr<base::MessageLoopProxy> io_loop = factory_->GetIOLoopProxy();
  io_loop->PostTask(FROM_HERE,
                    base::Bind(&GpuChannelHost::MessageFilter::RemoveRoute,
                               channel_filter_.get(), route_id));
}

base::SharedMemoryHandle GpuChannelHost::ShareToGpuProcess(
    base::SharedMemoryHandle source_handle) {
  if (IsLost())
    return base::SharedMemory::NULLHandle();

#if defined(OS_WIN)
  // Windows needs to explicitly duplicate the handle out to another process.
  base::SharedMemoryHandle target_handle;
  if (!BrokerDuplicateHandle(source_handle,
                             channel_->GetPeerPID(),
                             &target_handle,
                             FILE_GENERIC_READ | FILE_GENERIC_WRITE,
                             0)) {
    return base::SharedMemory::NULLHandle();
  }

  return target_handle;
#else
  int duped_handle = HANDLE_EINTR(dup(source_handle.fd));
  if (duped_handle < 0)
    return base::SharedMemory::NULLHandle();

  return base::FileDescriptor(duped_handle, true);
#endif
}

int32 GpuChannelHost::ReserveTransferBufferId() {
  return next_transfer_buffer_id_.GetNext();
}

gfx::GpuMemoryBufferHandle GpuChannelHost::ShareGpuMemoryBufferToGpuProcess(
    const gfx::GpuMemoryBufferHandle& source_handle,
    bool* requires_sync_point) {
  switch (source_handle.type) {
    case gfx::SHARED_MEMORY_BUFFER: {
      gfx::GpuMemoryBufferHandle handle;
      handle.type = gfx::SHARED_MEMORY_BUFFER;
      handle.handle = ShareToGpuProcess(source_handle.handle);
      *requires_sync_point = false;
      return handle;
    }
    case gfx::IO_SURFACE_BUFFER:
    case gfx::SURFACE_TEXTURE_BUFFER:
    case gfx::OZONE_NATIVE_BUFFER:
      *requires_sync_point = true;
      return source_handle;
    default:
      NOTREACHED();
      return gfx::GpuMemoryBufferHandle();
  }
}

int32 GpuChannelHost::ReserveImageId() {
  return next_image_id_.GetNext();
}

int32 GpuChannelHost::GenerateRouteID() {
  return next_route_id_.GetNext();
}

GpuChannelHost::~GpuChannelHost() {
  DestroyChannel();
}

GpuChannelHost::MessageFilter::MessageFilter()
    : lost_(false) {
}

GpuChannelHost::MessageFilter::~MessageFilter() {}

void GpuChannelHost::MessageFilter::AddRoute(
    int route_id,
    base::WeakPtr<IPC::Listener> listener,
    scoped_refptr<MessageLoopProxy> loop) {
  DCHECK(listeners_.find(route_id) == listeners_.end());
  GpuListenerInfo info;
  info.listener = listener;
  info.loop = loop;
  listeners_[route_id] = info;
}

void GpuChannelHost::MessageFilter::RemoveRoute(int route_id) {
  ListenerMap::iterator it = listeners_.find(route_id);
  if (it != listeners_.end())
    listeners_.erase(it);
}

bool GpuChannelHost::MessageFilter::OnMessageReceived(
    const IPC::Message& message) {
  // Never handle sync message replies or we will deadlock here.
  if (message.is_reply())
    return false;

  ListenerMap::iterator it = listeners_.find(message.routing_id());
  if (it == listeners_.end())
    return false;

  const GpuListenerInfo& info = it->second;
  info.loop->PostTask(
      FROM_HERE,
      base::Bind(
          base::IgnoreResult(&IPC::Listener::OnMessageReceived),
          info.listener,
          message));
  return true;
}

void GpuChannelHost::MessageFilter::OnChannelError() {
  // Set the lost state before signalling the proxies. That way, if they
  // themselves post a task to recreate the context, they will not try to re-use
  // this channel host.
  {
    AutoLock lock(lock_);
    lost_ = true;
  }

  // Inform all the proxies that an error has occurred. This will be reported
  // via OpenGL as a lost context.
  for (ListenerMap::iterator it = listeners_.begin();
       it != listeners_.end();
       it++) {
    const GpuListenerInfo& info = it->second;
    info.loop->PostTask(
        FROM_HERE,
        base::Bind(&IPC::Listener::OnChannelError, info.listener));
  }

  listeners_.clear();
}

bool GpuChannelHost::MessageFilter::IsLost() const {
  AutoLock lock(lock_);
  return lost_;
}

}  // namespace content


text:
Routing
=======

While consumers are valid :doc:`ASGI </asgi>` applications, you don't want
to just write one and have that be the only thing you can give to protocol
servers like Daphne. Channels provides routing classes that allow you to
combine and stack your consumers (and any other valid ASGI application) to
dispatch based on what the connection is.

.. important::

    Channels routers only work on the *scope* level, not on the level of
    individual *events*, which means you can only have one consumer for any
    given connection. Routing is to work out what single consumer to give a
    connection, not how to spread events from one connection across
    multiple consumers.

Routers are themselves valid ASGI applications, and it's possible to nest them.
We suggest that you have a ``ProtocolTypeRouter`` as the root application of
your project - the one that you pass to protocol servers - and nest other,
more protocol-specific routing underneath there.

Channels expects you to be able to define a single *root application*, and
provide the path to it as the ``ASGI_APPLICATION`` setting (think of this as
being analogous to the ``ROOT_URLCONF`` setting in Django). There's no fixed
rule as to where you need to put the routing and the root application, but we
recommend following Django's conventions and putting them in a project-level
file called ``asgi.py``, next to ``urls.py``. You can read more about deploying
Channels projects and settings in :doc:`/deploying`.

Here's an example of what that ``asgi.py`` might look like:

.. code-block:: python

    import os

    from channels.auth import AuthMiddlewareStack
    from channels.routing import ProtocolTypeRouter, URLRouter
    from django.conf.urls import url
    from django.core.asgi import get_asgi_application

    from chat.consumers import AdminChatConsumer, PublicChatConsumer

    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")

    application = ProtocolTypeRouter({
        # Django's ASGI application to handle traditional HTTP requests
        "http": get_asgi_application(),

        # WebSocket chat handler
        "websocket": AuthMiddlewareStack(
            URLRouter([
                url(r"^chat/admin/$", AdminChatConsumer.as_asgi()),
                url(r"^chat/$", PublicChatConsumer.as_asgi()),
            ])
        ),
    })

.. note::
  We call the ``as_asgi()`` classmethod when routing our consumers. This
  returns an ASGI wrapper application that will instantiate a new consumer
  instance for each connection or scope. This is similar to Django's
  ``as_view()``, which plays the same role for per-request instances of
  class-based views.

It's possible to have routers from third-party apps, too, or write your own,
but we'll go over the built-in Channels ones here.

ProtocolTypeRouter
------------------

``channels.routing.ProtocolTypeRouter``

This should be the top level of your ASGI application stack and the main entry
in your routing file.

It lets you dispatch to one of a number of other ASGI applications based on the
``type`` value present in the ``scope``. Protocols will define a fixed type
value that their scope contains, so you can use this to distinguish between
incoming connection types.

It takes a single argument - a dictionary mapping type names to ASGI
applications that serve them:

.. code-block:: python

    ProtocolTypeRouter({
        "http": some_app,
        "websocket": some_other_app,
    })

If you want to split HTTP handling between long-poll handlers and Django views,
use a URLRouter using Django's ``get_asgi_application()`` specified as the last
entry with a match-everything pattern.

.. _urlrouter:

URLRouter
---------

``channels.routing.URLRouter``

Routes ``http`` or ``websocket`` type connections via their HTTP path. Takes a
single argument, a list of Django URL objects (either ``path()`` or
``re_path()``):

.. code-block:: python

    URLRouter([
        re_path(r"^longpoll/$", LongPollConsumer.as_asgi()),
        re_path(r"^notifications/(?P<stream>\w+)/$", LongPollConsumer.as_asgi()),
        re_path(r"", get_asgi_application()),
    ])

Any captured groups will be provided in ``scope`` as the key ``url_route``, a
dict with a ``kwargs`` key containing a dict of the named regex groups and
an ``args`` key with a list of positional regex groups. Note that named
and unnamed groups cannot be mixed: Positional groups are discarded as soon
as a single named group is matched.

For example, to pull out the named group ``stream`` in the example above, you
would do this:

.. code-block:: python

    stream = self.scope["url_route"]["kwargs"]["stream"]

Please note that ``URLRouter`` nesting will not work properly with
``path()`` routes if inner routers are wrapped by additional middleware.
See `Issue #1428 <https://github.com/django/channels/issues/1428>`__.

ChannelNameRouter
-----------------

``channels.routing.ChannelNameRouter``

Routes ``channel`` type scopes based on the value of the ``channel`` key in
their scope. Intended for use with the :doc:`/topics/worker`.

It takes a single argument - a dictionary mapping channel names to ASGI
applications that serve them:

.. code-block:: python

    ChannelNameRouter({
        "thumbnails-generate": some_app,
        "thumbnails-delete": some_other_app,
    })


text:
package mil.nga.mapcache.utils;

import mil.nga.geopackage.db.GeoPackageDataType;

public class DataTypeConverter {

    /**
     * Convert string to GeoPackageDataType to make sure we match the enum
     * @param givenType String of the GeoPackageDataType expected
     * @return null if it doesn't match
     */
    public static GeoPackageDataType getGeoPackageDataType(String givenType){
        if(givenType.equalsIgnoreCase("text")){
            return GeoPackageDataType.TEXT;
        } else if(givenType.equalsIgnoreCase("number")){
            return GeoPackageDataType.DOUBLE;
        } else if(givenType.equalsIgnoreCase("check box")){
            return GeoPackageDataType.BOOLEAN;
        } else if(givenType.equalsIgnoreCase("checkbox")){
            return GeoPackageDataType.BOOLEAN;
        }
        return null;
    }
}


text:
NAME            = gotest
IMAGE           = creack/golang-web
GOFILES         = $(shell find . -name '*.go') tpl static

all             : build

build           : .docker_id

.docker_id      : Makefile Dockerfile $(GOFILES)
		docker build -t $(NAME) .
		docker inspect -f '{{.Id}}' $(NAME) > $@

run             : build
		docker run -itP $(NAME)

push            : release
		docker push $(IMAGE)

clean           :
		rm -f .docker_id .release

re              : clean all

.release        : Dockerfile.release .docker_id
		docker run --rm --entrypoint /bin/sh $(NAME) -c 'tar cf - /$(NAME) /etc/ssl' > $@ || (rm -f $@; false)
		docker build --rm -t $(IMAGE) -f Dockerfile.release . || (rm -f $@; false)

release         : .release

.PHONY          : all build run push clean re release


text:
import os
from flask import Flask, request, url_for, send_from_directory
from werkzeug import secure_filename

ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif', 'rar', 'apk', 'zip'])

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = '/Users/aria/temp/test/'
app.config['MAX_CONTENT_LENGTH'] = 1600 * 1024 * 1024

"""
可以选择这个扩展
Flask-Uploads
"""

html = '''
    <!DOCTYPE html>
    <title>Upload File</title>

图片上传

    <form method=post enctype=multipart/form-data>
         <input type=file name=file>
         <input type=submit value=上传>
    </form>
    '''

def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS

@app.route('/uploads/<filename>')
def uploaded_file(filename):
    return send_from_directory(app.config['UPLOAD_FOLDER'],
                               filename)

@app.route('/', methods=['GET', 'POST'])
def test():
    return'test'

@app.route('/upload/', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        print(request.values)
        print('params = ' + request.values.get('params'))

        file = request.files['file']
        print(file)
        #if file and allowed_file(file.filename):
        print('start save')
        filename = secure_filename(file.filename)
        file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            # file_url = url_for('uploaded_file', filename=filename)
            # return html + '
'
        return '200'
    return '405'

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)


text:
class QuestionnaireToCsv
  include Sidekiq::Worker
  sidekiq_options queue: "low"

  def perform(user_id, questionnaire_id, separator)
    user          = User.find(user_id)
    questionnaire = Questionnaire.find(questionnaire_id)
    return if !user || !questionnaire

    file_location = "#{Rails.root}/private/questionnaires/#{questionnaire.id.to_s}/"
    FileUtils.mkdir_p(file_location) if !File.directory?(file_location)

    file_location << "questionnaire_generating.csv"

    # stop here if a "questionnaire_generating.csv" file is found, created less than
    # 30 minutes ago. This means that an import is already running, and we shouldn't
    # start another one
    if File.exist?(file_location) && File.atime(file_location) > 30.minutes.ago
      return false
    end

    begin
      CsvMethods.fill_csv file_location, questionnaire.submitters, questionnaire.sections, separator

      # move file to the final destination
      file_record = questionnaire.csv_file || CsvFile.new(entity: questionnaire)
      if !file_record.new_record? && File.exist?(file_record.location)
        FileUtils.rm(file_record.location)
      end

      file_record.name = questionnaire.title[0,35].gsub(/[^a-z0-9\-]+/i, '_') + "_#{DateTime.now.strftime("%d%m%Y")}.csv"
      file_record.location = "private/questionnaires/#{questionnaire.id.to_s}/" + file_record.name
      file_record.save

      FileUtils.move(file_location, file_record.location)
      FileUtils.touch file_record.location

      # send notifying e-mail
      UserMailer.csv_file_generated(user, questionnaire).deliver
    rescue => e
      UserMailer.csv_generation_failed(user, questionnaire, e).deliver
      FileUtils.rm(file_location) if File.exists?(file_location)

      Appsignal.add_exception(e)
    end

    true
  end
end


text:
package com.spatialfocus.gui;

import java.io.File;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;

import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Device;
import com.spatialfocus.*;

public class AddressToolapp {

	/**
	 * Launch the application.
	 *
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			AddressToolapp window = new AddressToolapp();
			window.loadSwtJar();
			window.open();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void loadSwtJar() {
		String swtFileName = "";
		String swtVer = "3.6.1.v3655c";
	    try {
	        String osName = System.getProperty("os.name").toLowerCase();
	        String osArch = System.getProperty("os.arch").toLowerCase();
	        URLClassLoader classLoader = (URLClassLoader) getClass().getClassLoader();
	        java.lang.reflect.Method addUrlMethod = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
	        addUrlMethod.setAccessible(true);

	        String swtFileNameOsPart =
	            osName.contains("win") ? "win32.win32.x86_64" :
//	            osName.contains("mac") ? "macosx" :
	            osName.contains("linux") || osName.contains("nix") ? "gtk.linux.x86" :
	            ""; // throw new RuntimeException("Unknown OS name: "+osName)

	        swtFileName = "swt."+swtFileNameOsPart+"-"+swtVer+".jar";

	        File swtFile = new File(swtFileName);
	        URL url = swtFile.toURI().toURL();
	        URLClassLoader urlClassLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
	        Class<?> urlClass = URLClassLoader.class;
	        Method method = urlClass.getDeclaredMethod("addURL", new Class<?>[] { URL.class });
	        method.setAccessible(true);
	        method.invoke(urlClassLoader, new Object[] { url });

	    }
	    catch(Exception e) {
	        System.out.println("Unable to add the swt jar to the class path: "+swtFileName);
	        e.printStackTrace();
	    }
	}

	/**
	 * Open the window.
	 */
	public void open() {
		Display display = Display.getDefault();
		final Shell shell = new Shell();
		shell.setSize(450, 300);
		shell.setText("FGDC Address Tool");
		shell.setLayout(null);

		Menu menu = new Menu(shell, SWT.BAR);
		shell.setMenuBar(menu);

		MenuItem mntmFile = new MenuItem(menu, SWT.CASCADE);
		mntmFile.setText("File");

		Menu menu_2 = new Menu(mntmFile);
		mntmFile.setMenu(menu_2);

		MenuItem mntmNewProject = new MenuItem(menu_2, SWT.NONE);
		mntmNewProject.setText("New Project");

		MenuItem mntmOpenProject = new MenuItem(menu_2, SWT.NONE);
		mntmOpenProject.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
		        FileDialog fd = new FileDialog(shell, SWT.OPEN);
		        fd.setText("Open");
		        fd.setFilterPath("C:/");
		        String[] filterExt = { "*.txt", "*.doc", ".rtf", "*.*" };
		        fd.setFilterExtensions(filterExt);
		        String selected = fd.open();
		        System.out.println(selected);
			}
		});
		mntmOpenProject.setText("Open Project");

		new MenuItem(menu_2, SWT.SEPARATOR);

		MenuItem mntmRefresh = new MenuItem(menu_2, SWT.NONE);
		mntmRefresh.setText("Refresh");

		new MenuItem(menu_2, SWT.SEPARATOR);

		MenuItem mntmClose = new MenuItem(menu_2, SWT.NONE);
		mntmClose.setText("Close");

		MenuItem mntmSave = new MenuItem(menu_2, SWT.NONE);
		mntmSave.setText("Save");

		MenuItem mntmExit = new MenuItem(menu_2, SWT.NONE);
		mntmExit.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
		        MessageBox messageBox = new MessageBox(shell, SWT.ICON_QUESTION
		                | SWT.YES | SWT.NO);
		            messageBox.setMessage("Do you really want to exit?");
		            messageBox.setText("Exiting Application");
		            int response = messageBox.open();
		            if (response == SWT.YES)
		              System.exit(0);

			}
		});
		mntmExit.setText("Exit");

		MenuItem mntmTools = new MenuItem(menu, SWT.CASCADE);
		mntmTools.setText("Tools");

		Menu menu_1 = new Menu(mntmTools);
		mntmTools.setMenu(menu_1);

		MenuItem mntmDefine = new MenuItem(menu_1, SWT.NONE);
		mntmDefine.setText("Define ...");

		MenuItem mntmReports = new MenuItem(menu_1, SWT.NONE);
		mntmReports.setText("Reports");

		MenuItem mntmPublish = new MenuItem(menu_1, SWT.NONE);
		mntmPublish.setText("Publish");

		MenuItem mntmExport = new MenuItem(menu_1, SWT.NONE);
		mntmExport.setText("Export");

		MenuItem mntmImport = new MenuItem(menu_1, SWT.NONE);
		mntmImport.setText("Import");

		MenuItem mntmHelp = new MenuItem(menu, SWT.CASCADE);
		mntmHelp.setText("Help");

		Menu menu_3 = new Menu(mntmHelp);
		mntmHelp.setMenu(menu_3);

		MenuItem mntmWelcome = new MenuItem(menu_3, SWT.NONE);
		mntmWelcome.setText("Welcome");

		MenuItem mntmHelpContents = new MenuItem(menu_3, SWT.NONE);
		mntmHelpContents.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				BareBonesBrowserLaunch.openURL("http://meadow.spatialfocus.com/address_standard");
			}
		});
		mntmHelpContents.setText("Help Contents");

		MenuItem mntmCheatSheets = new MenuItem(menu_3, SWT.NONE);
		mntmCheatSheets.setText("Cheat Sheets ...");

		new MenuItem(menu_3, SWT.SEPARATOR);

		MenuItem mntmAbout = new MenuItem(menu_3, SWT.NONE);
		mntmAbout.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {

				Aboutdlg About = new Aboutdlg(e.display.getActiveShell(),
						SWT.APPLICATION_MODAL);
				About.open();

			}
		});
		mntmAbout.setSelection(true);
		mntmAbout.setText("About");

		shell.open();
		shell.layout();
		while (!shell.isDisposed()) {
			if (!display.readAndDispatch()) {
				display.sleep();
			}
		}
	}
}


text:
namespace mojo {
namespace system {

namespace internal {

template <size_t size, size_t alignment>
bool MOJO_SYSTEM_IMPL_EXPORT VerifyUserPointerHelper(const void* pointer);

// Note: This is also used by options_validation.h.
template <size_t size, size_t alignment>
bool MOJO_SYSTEM_IMPL_EXPORT VerifyUserPointerWithCountHelper(
    const void* pointer,
    size_t count);

}  // namespace internal

// Verify (insofar as possible/necessary) that a |T| can be read from the user
// |pointer|.
template <typename T>
bool VerifyUserPointer(const T* pointer) {
  return internal::VerifyUserPointerHelper<sizeof(T), MOJO_ALIGNOF(T)>(pointer);
}

// Verify (insofar as possible/necessary) that |count| |T|s can be read from the
// user |pointer|; |count| may be zero. (This is done carefully since |count *
// sizeof(T)| may overflow a |size_t|.)
template <typename T>
bool VerifyUserPointerWithCount(const T* pointer, size_t count) {
  return internal::VerifyUserPointerWithCountHelper<sizeof(T),
                                                    MOJO_ALIGNOF(T)>(pointer,
                                                                     count);
}

// Verify that |size| bytes (which may be zero) can be read from the user
// |pointer|, and that |pointer| has the specified |alignment| (if |size| is
// nonzero).
template <size_t alignment>
bool MOJO_SYSTEM_IMPL_EXPORT VerifyUserPointerWithSize(const void* pointer,
                                                       size_t size);

}  // namespace system
}  // namespace mojo

#endif  // MOJO_SYSTEM_MEMORY_H_


text:
package com.github.s7uxn37.phase10.ui;

import com.github.s7uxn37.phase10.constructs.Card;

import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;

public final class CardView extends JPanel {
    public enum SORTING {NONE, NUMBER, COLOR, PROBABILITY}

    public static final java.awt.Color PURPLE = new java.awt.Color(128, 40, 128);
    private int sortingIndex;

    CardView(SORTING sorting) {
        this();
        ArrayList<SORTING> list = new ArrayList<>();
        Collections.addAll(list, SORTING.values());
        sortingIndex = list.indexOf(sorting);
    }
    CardView() {
        setBackground(Color.GRAY);
        setLayout(new FlowLayout());
        setVisible(true);
        sortingIndex = 0;
    }

    public final void setCards(Card[] cards) {
        removeAll();

        Arrays.sort(cards, (o1, o2) -> {
            int result;
            int alg = sortingIndex;
            do {
                switch (SORTING.values()[alg]) {
                    case COLOR: // doesn't matter
                        result = Integer.compare(o1.colorIndex, o2.colorIndex);
                        break;
                    case NUMBER: // ascending
                        result = Integer.compare(o1.number, o2.number);
                        break;
                    case PROBABILITY: // descending
                        result = Double.compare(o2.prob, o1.prob);
                        break;
                    default:
                        result = 0;
                        break;
                }
                alg++;
                alg = alg % SORTING.values().length;
            } while (sortingIndex != 0 && result == 0 && alg != sortingIndex);
            return result;
        });

        int i = 0;
        while (i < cards.length) {
            Card c = cards[i];
            SingleCardView v = new SingleCardView(c);

            if (c.isUnknown()) {
                int length = 1;
                for (int j = i+1; j < cards.length; j++) {
                    if (cards[j].isUnknown())
                        length++;
                    else
                        break;
                }

                if (length > 15) {
                    Card replacement = new Card();
                    replacement.number = length;

                    v = new SingleCardView(replacement);
                    add(v);

                    i += length;
                    continue;
                }
            }

            add(v);
            i++;
        }
    }

    public final void setCards(ArrayList<Card> cards) {
        Card[] c = new Card[cards.size()];
        for (int i = 0; i < c.length; i++)
            c[i] = cards.get(i);
        setCards(c);
    }
}

final class SingleCardView extends JPanel {
    private final Card card;
    private final JLabel label;

    SingleCardView(Card c) {
        card = c;

        setSize(50,100);

        label = new Label();
        label.setFont(label.getFont().deriveFont(40f));
        label.setForeground(Color.BLACK);
        add(label);

        setBackground(Color.LIGHT_GRAY);

        update();
    }

    @Override
    protected final void paintComponent(Graphics g) {
        super.paintComponent(g);

        Color c = Color.WHITE;
        if (card.colorIndex != -1) {
            switch (Card.Color.values()[card.colorIndex]) {
                case YELLOW:
                    c = Color.YELLOW;
                    break;
                case GREEN:
                    c = Color.GREEN;
                    break;
                case PURPLE:
                    c = CardView.PURPLE;
                    break;
                case RED:
                    c = Color.RED;
                    break;
            }
        }
        g.setColor(c);
        int height = (int) (getHeight() * card.prob);
        g.fillRect(0, getHeight() - height , getWidth(), height);
    }

    private void update() {
        label.setText(card.number == -1 ? "?" : ("" + card.number));
    }
}


text:
b8r Tests

  <b8r-component path="../test/test-nav.component.js"></b8r-component>

      A
      A
      A
      A
      <input id="e" data-bind="value=test1.sub.list[2];attr(type)=test1.type">
      <input id="f" data-bind="value=test1.sub.list[2]">

Complex Lists

Interpolated Strings

      <select data-bind="value=test1.option">
        <option>ONE</option>
        <option>two</option>
        <option>3</option>
      </select>
      A
      <input data-bind="checked=test1.checkbox" type="checkbox" checked>
      A

        <input data-bind="value=test1.list[0].y"> Test list-bound values

          x, <input style="display: inline" data-bind="value=.y">

        <input type="radio" name="group" value="first" data-bind="value=test1.radio">
        first

        <input type="radio" name="group" value="second" data-bind="value=test1.radio">
        second

        <input type="radio" name="group" value="third" data-bind="value=test1.radio">
        third

Computed List

Complex Bindings

Indirect Binding

Nested Computed List

Composition

      <b8r-component class="composable-outer" name="composable">
        grandparent

          bound to x

        <b8r-component class="composable-inner" name="composable">
          parent

            bound to grandparent x

        </b8r-component>
      </b8r-component>

First Child

Second Child


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

public class DataLogic : MonoBehaviour
{
    public int slot;
    public GameData.GameState state;
	// Use this for initialization
	void Awake ()
    {
        Language.Initialize();
	}

    private void Start()
    {
        state = GameData.LoadGame(slot);
    }

    private void Update()
    {
        if(Input.GetKeyDown(KeyCode.Alpha1))
        {
            Language.SetLanguage(Language.Lang.esES);
        }
        if(Input.GetKeyDown(KeyCode.Alpha2))
        {
            Language.SetLanguage(Language.Lang.enUS);
        }

        if(Input.GetKeyDown(KeyCode.S))
        {
            GameData.gameState = state;
            GameData.SaveGame(slot);
        }
    }
}


text:
package com.google.common.base;

import static com.google.common.base.Preconditions.checkNotNull;

import java.io.Serializable;
import java.util.Map;

/**
 * Useful functions.
 *
 *
All methods returns serializable functions as long as they're given
 * serializable parameters.
 *
 * @author Mike Bostock
 * @author Vlad Patryshev
 * @author Jared Levy
 */
public final class Functions {
  private Functions() {}

  /**
   * Returns a function that calls {@code toString()} on its argument. The
   * function does not accept nulls; it will throw a
   * {@link NullPointerException} when applied to {@code null}.
   */
  public static Function<Object, String> toStringFunction() {
    return ToStringFunction.INSTANCE;
  }

  // enum singleton pattern
  private enum ToStringFunction implements Function<Object, String> {
    INSTANCE;

    public String apply(Object o) {
      return o.toString();
    }

    @Override public String toString() {
      return "toString";
    }
  }

  /**
   * Returns the identity function.
   */
  @SuppressWarnings("unchecked")
  public static <E> Function<E, E> identity() {
    return (Function<E, E>) IdentityFunction.INSTANCE;
  }

  // enum singleton pattern
  private enum IdentityFunction implements Function<Object, Object> {
    INSTANCE;

    public Object apply(Object o) {
      return o;
    }

    @Override public String toString() {
      return "identity";
    }
  }

  /**
   * Returns a function which performs a map lookup.
   *
   *
The difference between a map and a function is that a map is defined on
   * a set of keys, while a function is defined on all inputs of the correct
   * type. The function created by this method returns {@code null} for all
   * inputs that do not belong to the map's key set.
   *
   * @param map source map that determines the function behavior
   * @return function that returns {@code map.get(a)} for each {@code a}
   */
  public static <K, V> Function<K, V> forMap(Map<K, V> map) {
    return new FunctionForMapNoDefault<K, V>(map);
  }

  private static class FunctionForMapNoDefault<K, V>
      implements Function<K, V>, Serializable {
    private final Map<K, V> map;

    public FunctionForMapNoDefault(Map<K, V> map) {
      this.map = checkNotNull(map);
    }
    public V apply(K a) {
      return map.get(a);
    }
    @Override public boolean equals(Object o) {
      if (o instanceof FunctionForMapNoDefault) {
        FunctionForMapNoDefault<?, ?> that = (FunctionForMapNoDefault<?, ?>) o;
        return map.equals(that.map);
      }
      return false;
    }
    @Override public int hashCode() {
      return map.hashCode();
    }
    @Override public String toString() {
      return "forMap(" + map + ")";
    }
    private static final long serialVersionUID = 0;
  }

  /**
   * Returns a function which performs a map lookup with a default value. The
   * function created by this method returns {@code defaultValue} for all
   * inputs that do not belong to the map's key set.
   *
   * @param map source map that determines the function behavior
   * @param defaultValue the value to return for inputs that aren't map keys
   * @return function that returns {@code map.get(a)} when {@code a} is a key,
   *     or {@code defaultValue} otherwise
   */
  public static <K, V> Function<K, V> forMap(
      Map<K, ? extends V> map, V defaultValue) {
    return new ForMapWithDefault<K, V>(map, defaultValue);
  }

  private static class ForMapWithDefault<K, V>
      implements Function<K, V>, Serializable {
    private final Map<K, ? extends V> map;
    private final V defaultValue;

    public ForMapWithDefault(Map<K, ? extends V> map, V defaultValue) {
      this.map = checkNotNull(map);
      this.defaultValue = defaultValue;
    }
    public V apply(K a) {
      return map.containsKey(a) ? map.get(a) : defaultValue;
    }
    @Override public boolean equals(Object o) {
      if (o instanceof ForMapWithDefault) {
        ForMapWithDefault<?, ?> that = (ForMapWithDefault<?, ?>) o;
        return map.equals(that.map)
            && Objects.equal(defaultValue, that.defaultValue);
      }
      return false;
    }
    @Override public int hashCode() {
      return map.hashCode() + defaultValue.hashCode();
    }
    @Override public String toString() {
      return "forMap(" + map + ", defaultValue=" + defaultValue + ")";
    }
    private static final long serialVersionUID = 0;
  }

  /**
   * Returns the composition of two functions. For {@code f: A->B} and
   * {@code g: B->C}, composition is defined as the function h such that
   * {@code h(a) == g(f(a))} for each {@code a}.
   *
   * @see
   * function composition
   *
   * @param g the second function to apply
   * @param f the first function to apply
   * @return the composition of {@code f} and {@code g}
   */
  public static  Function compose(
      Function g, Function f) {
    return new FunctionComposition(g, f);
  }

  private static class FunctionComposition
      implements Function, Serializable {
    private final Function g;
    private final Function f;

    public FunctionComposition(Function g,
        Function f) {
      this.g = checkNotNull(g);
      this.f = checkNotNull(f);
    }
    public C apply(A a) {
      return g.apply(f.apply(a));
    }
    @Override public boolean equals(Object obj) {
      if (obj instanceof FunctionComposition) {
        FunctionComposition<?, ?, ?> that = (FunctionComposition<?, ?, ?>) obj;
        return f.equals(that.f) && g.equals(that.g);
      }
      return false;
    }

    @Override public int hashCode() {
      return f.hashCode() ^ g.hashCode();
    }
    @Override public String toString() {
      return g.toString() + "(" + f.toString() + ")";
    }
    private static final long serialVersionUID = 0;
  }

  /**
   * Creates a function that returns the same boolean output as the given
   * predicate for all inputs.
   */
  public static <T> Function<T, Boolean> forPredicate(Predicate<T> predicate) {
    return new PredicateFunction<T>(predicate);
  }

  /** @see Functions#forPredicate */
  private static class PredicateFunction<T>
      implements Function<T, Boolean>, Serializable {
    private final Predicate<T> predicate;

    private PredicateFunction(Predicate<T> predicate) {
      this.predicate = checkNotNull(predicate);
    }

    public Boolean apply(T t) {
      return predicate.apply(t);
    }
    @Override public boolean equals(Object obj) {
      if (obj instanceof PredicateFunction) {
        PredicateFunction<?> that = (PredicateFunction<?>) obj;
        return predicate.equals(that.predicate);
      }
      return false;
    }
    @Override public int hashCode() {
      return predicate.hashCode();
    }
    @Override public String toString() {
      return "forPredicate(" + predicate + ")";
    }
    private static final long serialVersionUID = 0;
  }

  /**
   * Creates a function that returns {@code value} for any input.
   *
   * @param value the constant value for the function to return
   * @return a function that always returns {@code value}
   */
  public static <E> Function<Object, E> constant(E value) {
    return new ConstantFunction<E>(value);
  }

  private static class ConstantFunction<E>
      implements Function<Object, E>, Serializable {
    private final E value;

    public ConstantFunction(E value) {
      this.value = value;
    }
    public E apply(Object from) {
      return value;
    }
    @Override public boolean equals(Object obj) {
      if (obj instanceof ConstantFunction) {
        ConstantFunction<?> that = (ConstantFunction<?>) obj;
        return Objects.equal(value, that.value);
      }
      return false;
    }
    @Override public int hashCode() {
      return (value == null) ? 0 : value.hashCode();
    }
    @Override public String toString() {
      return "constant(" + value + ")";
    }
    private static final long serialVersionUID = 0;
  }
}


text:
package delete

import (
	"fmt"

	"github.com/pkg/errors"
	"github.com/spf13/cobra"

	"github.com/sapcc/kubernikus/pkg/cmd"
)

func (o *DeleteOptions) NewClusterCommand() *cobra.Command {
	c := &cobra.Command{
		Use:     "cluster [name]",
		Short:   "Deletes the cluster with the given name",
		Aliases: []string{"clusters"},
		PreRun:  o.clusterPreRun,
		Run:     o.clusterRun,
	}

	return c
}

func (o *DeleteOptions) clusterPreRun(c *cobra.Command, args []string) {
	cmd.CheckError(validateClusterCommandArgs(args))
	cmd.CheckError(o.SetupKubernikusClient())
}

func (o *DeleteOptions) clusterRun(c *cobra.Command, args []string) {
	cmd.CheckError(o.Kubernikus.DeleteCluster(args[0]))
	fmt.Printf("Cluster %v scheduled for deletion.", args[0])
}

func validateClusterCommandArgs(args []string) error {
	if len(args) > 1 {
		return errors.Errorf("Surplus arguments to cluster delete.")
	}
	if len(args) < 1 {
		return errors.Errorf("Please supply the name of the cluster to be deleted.")
	}
	return nil
}


text:
package com.facebook.buck.io.watchman;

import com.facebook.buck.core.filesystems.AbsPath;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import java.io.Closeable;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Map;
import java.util.Optional;

/** Contains the configuration for a Watchman client as well as the ability to create a client. */
public abstract class Watchman implements Closeable {

  private final ImmutableMap<AbsPath, ProjectWatch> projectWatches;
  private final ImmutableSet<Capability> capabilities;
  private final ImmutableMap<WatchRoot, String> clockIdsByWatchRoot;
  private final Optional<Path> transportPath;
  private final String version;
  private final long queryPollTimeoutNanos;
  private final long queryWarnTimeoutNanos;
  private final PooledWatchmanClient pooledClient;

  public Watchman(
      ImmutableMap<AbsPath, ProjectWatch> projectWatches,
      ImmutableSet<Capability> capabilities,
      ImmutableMap<WatchRoot, String> clockIdsByWatchRoot,
      Optional<Path> transportPath,
      String version,
      long queryPollTimeoutNanos,
      long queryWarnTimeoutNanos) {
    this.projectWatches = projectWatches;
    this.capabilities = capabilities;
    this.clockIdsByWatchRoot = clockIdsByWatchRoot;
    this.transportPath = transportPath;
    this.version = version;
    this.queryPollTimeoutNanos = queryPollTimeoutNanos;
    this.queryWarnTimeoutNanos = queryWarnTimeoutNanos;
    this.pooledClient = new PooledWatchmanClient(this::createReconnectingClient);
  }

  /** Build. */
  public ImmutableMap<AbsPath, WatchmanCursor> buildClockWatchmanCursorMap() {
    ImmutableMap.Builder<AbsPath, WatchmanCursor> cursorBuilder = ImmutableMap.builder();
    for (Map.Entry<AbsPath, ProjectWatch> entry : projectWatches.entrySet()) {
      String clockId = clockIdsByWatchRoot.get(entry.getValue().getWatchRoot());
      Preconditions.checkNotNull(
          clockId, "No ClockId found for watch root %s", entry.getValue().getWatchRoot());
      cursorBuilder.put(entry.getKey(), new WatchmanCursor(clockId));
    }
    return cursorBuilder.build();
  }

  public ImmutableMap<AbsPath, ProjectWatch> getProjectWatches() {
    return projectWatches;
  }

  public ImmutableSet<Capability> getCapabilities() {
    return capabilities;
  }

  public ImmutableMap<WatchRoot, String> getClockIdsByWatchRoot() {
    return clockIdsByWatchRoot;
  }

  public boolean hasWildmatchGlob() {
    return capabilities.contains(Capability.WILDMATCH_GLOB);
  }

  public Optional<Path> getTransportPath() {
    return transportPath;
  }

  public String getVersion() {
    return version;
  }

  public abstract WatchmanError getInitError();

  /**
   * Note this method will throw an {@link IOException} if:
   *
   *

   *
{@link #getTransportPath()} returns {@link Optional#empty()}
   *
It cannot establish a connection to Watchman.
   *

   *
   * @return a new client that the caller is responsible for closing.
   */
  public abstract WatchmanClient createClient() throws IOException;

  /**
   * Create a watchman client which will drop the underlying connect on timeout or any error and
   * reconnect on next query.
   */
  public WatchmanClient createReconnectingClient() {
    return new ReconnectingWatchmanClient(this::createClient);
  }

  /** Get a thread-safe pooled watchman client. */
  public PooledWatchmanClient getPooledClient() {
    return pooledClient;
  }

  @Override
  public void close() throws IOException {
    pooledClient.closePool();
  }

  public long getQueryWarnTimeoutNanos() {
    return queryWarnTimeoutNanos;
  }

  public long getQueryPollTimeoutNanos() {
    return queryPollTimeoutNanos;
  }
}


text:
using UnityEngine;

// composantes du personnage
[RequireComponent(typeof (Animator))]
[RequireComponent(typeof (CapsuleCollider))]
[RequireComponent(typeof (Rigidbody))]
[RequireComponent(typeof (Renderer))]

public class Character : MonoBehaviour
{
  public enum EmotionType
  {
    EMOTION_NONE,
    EMOTION_HAPPY,
    EMOTION_SAD,
    EMOTION_ANGRY,
    EMOTION_FLABBERGAST,
  };

  // données membres publiques exposées dans l'éditeur
  public EmotionType     characterEmotion;
  public Animator        characterAnimator;
  public CapsuleCollider characterCollider;
  public Rigidbody       characterRigidbody;
  public GameObject      characterFace;
  public Renderer        characterFaceRenderer;

  // fonction d'initialisation
  void Start()
  {
    characterAnimator = GetComponent<Animator>();

    print("character animator: " + characterAnimator);

    characterCollider = GetComponent<CapsuleCollider>();

    print("character collider: " + characterCollider);

    characterRigidbody = GetComponent<Rigidbody>();

    print("character rigidbody: " + characterRigidbody);

    characterFace = GameObject.Find("CharacterFace");

    characterFaceRenderer = characterFace.GetComponent<Renderer>();

    ChangeEmotion(EmotionType.EMOTION_ANGRY);
  }

  // fonction de mise à jour
  void Update(){}

  // fonction qui permet de changer l'émotion du personnage
  public void ChangeEmotion(EmotionType emotion)
  {
    characterEmotion = emotion;

    switch(emotion)
    {
      case EmotionType.EMOTION_HAPPY:
        characterFaceRenderer.material.mainTextureOffset = new Vector2(0.0f, 0.5f);
        print("<character emotion is now HAPPY>");
        break;

      case EmotionType.EMOTION_SAD:
        characterFaceRenderer.material.mainTextureOffset = new Vector2(0.5f, 0.5f);
        print("<character emotion is now SAD>");
        break;

      case EmotionType.EMOTION_ANGRY:
        characterFaceRenderer.material.mainTextureOffset = new Vector2(0.0f, 0.0f);
        print("<character emotion is now ANGRY>");
        break;

      case EmotionType.EMOTION_FLABBERGAST:
        characterFaceRenderer.material.mainTextureOffset = new Vector2(0.5f, 0.0f);
        print("<character emotion is now FLABBERGAST>");
        break;

      default:
        print("<character emotion is unkown>");
        break;
    }
  }
}


text:
module Gecko
  module Helpers
    # Helper for providing custom #inspect values to Records
    module InspectionHelper
      # Overrides the default inspect to just return the defined attributes
      #
      # @example
      #   company.inspect #=> <Gecko::Record::Company id=123 name="Gecko Inc">
      #
      # @return [String]
      #
      # @api public
      def inspect
        inspection = self.class.attribute_set.map do |attribute|
          name = attribute.name
          "#{name}: #{attribute_for_inspect(name)}"
        end.join(', ')
        "#<#{self.class} #{inspection}>"
      end

    private

      # Returns an #inspect-like string for the value of the attribute
      # attr_name.
      # String attributes are truncated up to 50 characters,
      # and Date and Time attributes are returned in the :db format.
      # Other attributes return the value of #inspect without modification.
      # Duplicated from Rails implementation
      #
      # @example
      #   company.inspect #=> <Gecko::Record::Company id=123 name="Gecko Inc">
      #
      # @return [String]
      #
      # @api private
      def attribute_for_inspect(attr_name)
        value = attributes[attr_name]

        if value.is_a?(String) && value.length > 50
          "#{value[0..50]}...".inspect
        elsif value.is_a?(DateTime) || value.is_a?(Time)
          %("#{value.strftime('%Y-%m-%d %H:%M:%S')}")
        elsif value.is_a?(Date)
          %("#{value.strftime('%Y-%m-%d')}")
        else
          value.inspect
        end
      end
    end
  end
end


text:
<?php

/**
 * This is the model class for table "catalog_product_entity_group_price".
 *
 * The followings are the available columns in table 'catalog_product_entity_group_price':
 * @property integer $value_id
 * @property string $entity_id
 * @property integer $all_groups
 * @property integer $customer_group_id
 * @property string $value
 * @property integer $website_id
 */
class Mage2CatalogProductEntityGroupPricePeer extends Mage2ActiveRecord
{
	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return '{{catalog_product_entity_group_price}}';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('website_id', 'required'),
			array('all_groups, customer_group_id, website_id', 'numerical', 'integerOnly'=>true),
			array('entity_id', 'length', 'max'=>10),
			array('value', 'length', 'max'=>12),
		);
	}

	/**
	 * Returns the static model of the specified AR class.
	 * Please note that you should have this exact method in all your CActiveRecord descendants!
	 * @param string $className active record class name.
	 * @return Mage2CatalogProductEntityGroupPricePeer the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}
}


text:
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft 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.
// ----------------------------------------------------------------------------------

using Microsoft.Azure.Commands.EventHub.Models;
using Microsoft.Azure.Management.EventHub.Models;
using System.Management.Automation;
using System.Collections.Generic;
using Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters;

namespace Microsoft.Azure.Commands.EventHub.Commands
{
    /// <summary>
    /// 'Set-AzureRmEventHubAuthorizationRule' Cmdlet updates the specified AuthorizationRule
    /// </summary>
    [Cmdlet(VerbsCommon.Set, EventHubAuthorizationRuleVerb, DefaultParameterSetName = NamespaceAuthoRuleParameterSet, SupportsShouldProcess = true), OutputType(typeof(PSSharedAccessAuthorizationRuleAttributes))]
    public class SetAzureEventhubAuthorizationRules : AzureEventHubsCmdletBase
    {
        [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, Position = 0, HelpMessage = "Resource Group Name")]
        [ResourceGroupCompleter]
        [ValidateNotNullOrEmpty]
        public string ResourceGroupName { get; set; }

        [Parameter(Mandatory = true, ParameterSetName = NamespaceAuthoRuleParameterSet, ValueFromPipelineByPropertyName = true, Position = 1, HelpMessage = "Namespace Name")]
        [Parameter(Mandatory = true, ParameterSetName = EventhubAuthoRuleParameterSet, ValueFromPipelineByPropertyName = true, Position = 1, HelpMessage = "Namespace Name")]
        [ValidateNotNullOrEmpty]
        [Alias(AliasNamespaceName)]
        public string Namespace { get; set; }

        [Parameter(Mandatory = true, ParameterSetName = EventhubAuthoRuleParameterSet, ValueFromPipelineByPropertyName = true, Position = 2, HelpMessage = "EventHub Name")]
        [ValidateNotNullOrEmpty]
        [Alias(AliasEventHubName)]
        public string EventHub { get; set; }

        [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, Position = 3, HelpMessage = "AuthorizationRule Name")]
        [ValidateNotNullOrEmpty]
        [Alias(AliasAuthorizationRuleName)]
        public string Name { get; set; }

        [Parameter(Mandatory = true, ParameterSetName = AuthoRuleInputObjectParameterSet, ValueFromPipeline = true, Position = 4, HelpMessage = "AuthorizationRule Object")]
        [Parameter(Mandatory = false, ParameterSetName = NamespaceAuthoRuleParameterSet, ValueFromPipeline = true, Position = 4, HelpMessage = "AuthorizationRule Object")]
        [Parameter(Mandatory = false, ParameterSetName = EventhubAuthoRuleParameterSet, ValueFromPipeline = true, Position = 4, HelpMessage = "AuthorizationRule Object")]
        [ValidateNotNullOrEmpty]
        [Alias(AliasAuthRuleObj)]
        public PSSharedAccessAuthorizationRuleAttributes InputObject { get; set; }

        [Parameter(Mandatory = false, ParameterSetName = NamespaceAuthoRuleParameterSet, ValueFromPipelineByPropertyName = true, Position = 4, HelpMessage = "Rights, e.g.  @(\"Listen\",\"Send\",\"Manage\")")]
        [Parameter(Mandatory = false, ParameterSetName = EventhubAuthoRuleParameterSet, ValueFromPipelineByPropertyName = true, Position = 4, HelpMessage = "Rights, e.g.  @(\"Listen\",\"Send\",\"Manage\")")]
        [ValidateNotNullOrEmpty]
        [ValidateSet("Listen", "Send", "Manage", IgnoreCase = true)]
        public string[] Rights { get; set; }

        public override void ExecuteCmdlet()
        {
            PSSharedAccessAuthorizationRuleAttributes sasRule = new PSSharedAccessAuthorizationRuleAttributes();

            if (InputObject != null)
            {
                sasRule = InputObject;
            }
            else
            {
                sasRule.Rights = new List<string>();
                if (Rights != null && Rights.Length > 0)
                    foreach (string test in Rights)
                    {
                        sasRule.Rights.Add(test);
                    }
            }

            // InputObject Authorization Rule
            if (ParameterSetName.Equals(AuthoRuleInputObjectParameterSet))
                if (EventHub != null)
                {
                    if (ShouldProcess(target: sasRule.Name, action: string.Format(Resources.UpdateEventHubAuthorizationrule, Name, EventHub)))
                    {
                        WriteObject(Client.CreateOrUpdateEventHubAuthorizationRules(ResourceGroupName, Namespace, EventHub, Name, sasRule));
                    }
                }
                else
                {
                    if (ShouldProcess(target: sasRule.Name, action: string.Format(Resources.UpdateNamespaceAuthorizationrule, Name, Namespace)))
                    {
                        sasRule = InputObject;
                        WriteObject(Client.CreateOrUpdateNamespaceAuthorizationRules(ResourceGroupName, Namespace, Name, sasRule));
                    }
                }

            // update Namespace Authorization Rule
            if (ParameterSetName.Equals(NamespaceAuthoRuleParameterSet))
                if (ShouldProcess(target: sasRule.Name, action: string.Format(Resources.UpdateNamespaceAuthorizationrule, Name, Namespace)))
                {
                    WriteObject(Client.CreateOrUpdateNamespaceAuthorizationRules(ResourceGroupName, Namespace, Name, sasRule));
                }

            // Update EventHub authorizationRule
            if (ParameterSetName.Equals(EventhubAuthoRuleParameterSet))
                if (ShouldProcess(target: sasRule.Name, action: string.Format(Resources.UpdateEventHubAuthorizationrule, Name, EventHub)))
                {
                    WriteObject(Client.CreateOrUpdateEventHubAuthorizationRules(ResourceGroupName, Namespace, EventHub, Name, sasRule));
                }
        }
    }
}


text:
package types

import (
	v1 "k8s.io/api/core/v1"
	utilfeature "k8s.io/apiserver/pkg/util/feature"
	"k8s.io/kubernetes/pkg/features"
)

// PodConditionsByKubelet is the list of pod conditions owned by kubelet
var PodConditionsByKubelet = []v1.PodConditionType{
	v1.PodScheduled,
	v1.PodReady,
	v1.PodInitialized,
	v1.ContainersReady,
}

// PodConditionByKubelet returns if the pod condition type is owned by kubelet
func PodConditionByKubelet(conditionType v1.PodConditionType) bool {
	for _, c := range PodConditionsByKubelet {
		if c == conditionType {
			return true
		}
	}
	if utilfeature.DefaultFeatureGate.Enabled(features.PodHasNetworkCondition) {
		if conditionType == PodHasNetwork {
			return true
		}
	}
	return false
}

// PodConditionSharedByKubelet returns if the pod condition type is shared by kubelet
func PodConditionSharedByKubelet(conditionType v1.PodConditionType) bool {
	if utilfeature.DefaultFeatureGate.Enabled(features.PodDisruptionConditions) {
		if conditionType == v1.AlphaNoCompatGuaranteeDisruptionTarget {
			return true
		}
	}
	return false
}


text:
web server use for line bot webhooker

Installed uwsgi, flask, line-bot-sdk, uwsgi-plugin-python on ubuntu 14.04 docker

## Steps
1. install docker

    sudo apt-get install docker

2. login docker public repository: hub.docker.com

    docker login

3. replace the parameters (YOUR_LINE_CHANNEL_ACCESS_TOKEN and YOUR_LINE_CHANNEL_SECRET) on below command then run docker

    docker run -ti --net=host -p 80:80 -p 443:443 \
    -v ~/dockers/bot/app:/var/www/app \
    -v ~/dockers/bot/nginx_config:/etc/nginx/sites-enabled/ \
    -v ~/dockers/bot/extdrive:/extdrive \
    -e PATH=/extdrive:$PATH \
    -e LINE_CHANNEL_ACCESS_TOKEN=YOUR_LINE_CHANNEL_ACCESS_TOKEN \
    -e LINE_CHANNEL_SECRET=YOUR_LINE_CHANNEL_SECRET \
    sportingapp/botwebhook:v1.3 bash

4. start web server

    docker> webrestart
    webrestart is an alias
    service nginx stop;pkill -f uwsgi -9; service nginx start; uwsgi --ini /var/www/app/uwsgi.ini --plugin python &

## Reference
http://sportingmobile.blogspot.tw/2016/11/flask-nginx-uwsgi.html


text:
package com.hazelcast.simulator.coordinator.tasks;

import com.hazelcast.simulator.agent.operations.StopTimeoutDetectionOperation;
import com.hazelcast.simulator.common.SimulatorProperties;
import com.hazelcast.simulator.coordinator.registry.Registry;
import com.hazelcast.simulator.coordinator.registry.WorkerData;
import com.hazelcast.simulator.protocol.CoordinatorClient;
import com.hazelcast.simulator.worker.operations.TerminateWorkerOperation;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;

import static com.hazelcast.simulator.utils.CommonUtils.getElapsedSeconds;
import static com.hazelcast.simulator.utils.CommonUtils.sleepMillis;
import static com.hazelcast.simulator.utils.CommonUtils.sleepSeconds;
import static java.lang.String.format;
import static java.lang.System.currentTimeMillis;
import static java.util.concurrent.TimeUnit.MINUTES;
import static java.util.concurrent.TimeUnit.SECONDS;

/**
 * This task shuts down all workers.
 */
public class TerminateWorkersTask {

    private static final int FINISHED_WORKERS_SLEEP_MILLIS = 500;

    private static final Logger LOGGER = LogManager.getLogger(TerminateWorkersTask.class);
    private final Registry registry;
    private final SimulatorProperties simulatorProperties;
    private final CoordinatorClient client;

    public TerminateWorkersTask(
            SimulatorProperties simulatorProperties,
            Registry registry,
            CoordinatorClient client) {
        this.simulatorProperties = simulatorProperties;
        this.registry = registry;
        this.client = client;
    }

    public void run() {
        try {
            run0();
        } catch (Exception e) {
            LOGGER.error("Failed to terminate workers", e);
        }
    }

    private void run0() throws TimeoutException, InterruptedException, ExecutionException {
        int currentWorkerCount = registry.workerCount();
        if (currentWorkerCount == 0) {
            return;
        }

        LOGGER.info(format("Terminating %d Workers...", currentWorkerCount));

        client.invokeOnAllAgents(new StopTimeoutDetectionOperation(), MINUTES.toMillis(1));

        // prevent any failures from being printed due to killing the members.
        Set<WorkerData> clients = new HashSet<>();
        Set<WorkerData> members = new HashSet<>();
        for (WorkerData worker : registry.getWorkers()) {
            worker.setIgnoreFailures(true);
            if (worker.getParameters().getWorkerType().equals("member")) {
                members.add(worker);
            } else {
                clients.add(worker);
            }
        }

        // first shut down all clients
        for (WorkerData worker : clients) {
            client.send(worker.getAddress(), new TerminateWorkerOperation(true));
        }

        // wait some if there were any clients
        if (!clients.isEmpty()) {
            sleepSeconds(simulatorProperties.getMemberWorkerShutdownDelaySeconds());
        }

        // and then terminate all members
        for (WorkerData worker : members) {
            client.send(worker.getAddress(), new TerminateWorkerOperation(true));
        }

        // now we wait for the workers to die
        waitForWorkerShutdown(currentWorkerCount);
    }

    private void waitForWorkerShutdown(int expectedWorkerCount) {
        int timeoutSeconds = simulatorProperties.getWaitForWorkerShutdownTimeoutSeconds();

        long started = System.nanoTime();
        LOGGER.info(format("Waiting up to %d seconds for shutdown of %d Workers...", timeoutSeconds, expectedWorkerCount));
        long expirationTimeMillis = currentTimeMillis() + SECONDS.toMillis(timeoutSeconds);

        while (registry.workerCount() > 0 && currentTimeMillis() < expirationTimeMillis) {
            sleepMillis(FINISHED_WORKERS_SLEEP_MILLIS);
        }

        List<WorkerData> remainingWorkers = registry.getWorkers();
        if (remainingWorkers.isEmpty()) {
            LOGGER.info(format("Finished shutdown of all Workers (%d seconds)", getElapsedSeconds(started)));
        } else {
            LOGGER.warn(format("Aborted waiting for shutdown of all Workers (%d still running)...", remainingWorkers.size()));
            LOGGER.warn(format("Unfinished workers: %s", toString(remainingWorkers)));
        }
    }

    private String toString(List<WorkerData> remainingWorkers) {
        StringBuilder sb = new StringBuilder();
        for (int k = 0; k < remainingWorkers.size(); k++) {
            sb.append(remainingWorkers.get(k).getAddress());
            if (k < remainingWorkers.size() - 1) {
                sb.append(',');
            }
        }
        return sb.toString();
    }
}


text:
{% extends "base.html" %}
{% load wagtailcore_tags %}
{% load wagtailcore_tags snippets %}
{% load highlight %}

{% block body_class %}template-searchresults{% endblock %}

{% block title %}Search{% endblock %}

{% block content %}

        <form method="get" action=".">

                {{ form.as_table }}

                        <input type="submit" value="Search">

            {% if query %}

Results

                {% for result in page.object_list %}

                    {%  if result.object.first_name %}

                            {% highlight result.object.first_name with query %} {% highlight result.object.last_name with query %}

                    {% elif not result.object.url%}

                        {% highlight result.object.title with query max_length 50 %}

                        {% highlight result.object.skills with query max_length 50 %}

                        {% highlight result.object.benefits with query max_length 50 %}

                    {% else %}

                            {% highlight result.object.title with query %}

                        {% highlight result.intro with query max_length 50 %}

                            {% highlight result.body with query max_length 50 %}

                            {% highlight result.content with query max_length 50 %}

                    {% endif %}

                {% empty %}

No results found.

                {% endfor %}

                {% if page.has_previous or page.has_next %}

                        {% if page.has_previous %}{% endif %}« Previous{% if page.has_previous %}{% endif %}
                        |
                        {% if page.has_next %}{% endif %}Next »{% if page.has_next %}{% endif %}

                {% endif %}
            {% else %}
                {# Show some example queries to run, maybe query syntax, something else? #}
            {% endif %}
        </form>

    {% footer %}
{% endblock %}


text:
import sys
import traceback

from . import Qt
from .future import Future

def runInThread(thread, func, *args, **kwds):
    """Run a function in another thread and return the result.

    The remote thread must be running a Qt event loop.
    """
    return ThreadCallFuture(thread, func, *args, **kwds)()

def runInGuiThread(func, *args, **kwds):
    """Run a function the main GUI thread and return the result.
    """
    return ThreadCallFuture(None, func, *args, **kwds)()

class ThreadCallFuture(Future):
    sigRequestCall = Qt.Signal()
    def __init__(self, thread, func, *args, **kwds):
        Future.__init__(self)
        self.func = func
        self.args = args
        self.kwds = kwds
        self.exc = None

        if thread is None:
            thread = Qt.QApplication.instance().thread()
        self.moveToThread(thread)
        self.sigRequestCall.connect(self._callRequested)
        self.sigRequestCall.emit()

    def _callRequested(self):
        try:
            self.ret = self.func(*self.args, **self.kwds)
            self._taskDone()
        except Exception as exc:
            self.exc = exc
            err = ''.join(traceback.format_exception(*sys.exc_info()))
            self._taskDone(interrupted=True, error=err)

    def __call__(self):
        self.wait()
        if self.exc is not None:
            raise self.exc
        else:
            return self.ret


text:
title: Features
features:
  - title: "Digital Design"
    icon: laptop shadow
    content: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed a lorem quis neque interdum consequat ut sed sem. Duis quis tempor nunc. Interdum et malesuada fames ac ante ipsum primis in faucibus."
    link: ""
    text: ""
  - title: "Web Development"
    icon: code shadow
    content: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed a lorem quis neque interdum consequat ut sed sem. Duis quis tempor nunc. Interdum et malesuada fames ac ante ipsum primis in faucibus."
    link: ""
    text: ""
    delay: "05"
  - title: "Creative Direction"
    icon: heart shadow
    content: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed a lorem quis neque interdum consequat ut sed sem. Duis quis tempor nunc. Interdum et malesuada fames ac ante ipsum primis in faucibus."
    link: ""
    text: ""
    delay: "1"
---

# Love what you do, and you'll do it well {.arrow}


text:
app.controller('loginCtrl', function($scope, $stateParams,$state,$http,$ionicLoading) {

$scope.login = function(pass){
  console.log(pass);
  $ionicLoading.show({
    template: 'Loading...'
  });
  var tempData = {
    "pass" : pass
  }
  $http.post('https://mighty-caverns-81522.herokuapp.com/api/login', tempData).success(function(data, status) {
    console.log(data);
    $ionicLoading.hide();
    $scope.falsePass = false;
    $scope.loggedin = true;
  }).error(function(err) {
    console.log(err);
    $ionicLoading.hide();
    $scope.loggedin = false;
    $scope.falsePass = true;
  });

}

})
;