text:
:woman_technologist: github
[@parispittman]
:bird: twitter:
[parisinbmore@]
:hash: slack: `paris`

## Contributions

- Co-Chair, [Contributor Experience], 22 months
- Subproject Owner:
   - [contributor events] (summits, elections);
   - community management ([operational tactics], [guidelines], and policies aligned with [governance docs] (meetings, communication, etc.) for 40+ community groups: SIGs, WGs, committees, and user groups). I call it the transparency pipelines. :smile:
   - [mentoring]
  (outreachy, #meet-our-contributors, onsite sessions at KubeCon, group mentoring, empowering SIGs to create shadow roles/teams, hands on learning, and more);
- Member of first [Kubernetes Code of Conduct Committee]
- Work with Steering and/or CNCF directly on funding, process improvements, and contributor events and needs. Proposed and advocated for a contributor summit sustainability plan for a funding model that allows us to have logo free spaces among other things which aligns with our community > product or company [values].
- I've never missed a pubic steering committee meeting to date;
I try to provide context to decision makers.

:sparkles: tl;dr: focus on governance operations, contributor growth, advocating for contributor matters to CNCF and Steering, and trying to figure out how to glue it all together. :sparkles:

## What I'll do :bowtie:
:checkered_flag: Continue to uphold the [values],
:checkered_flag: Continue to clean up governance documentation, educate our large contributor base on governance topics,
:checkered_flag: Encourage more dialogue with the steering committee and members of the community;
:checkered_flag: Continue to work on project wide communications, like the [Need to Know Chairs] email, but at a steering committee level
:checkered_flag: Delegate decision making to the appropriate owners and/or SIGs or work to ensure there is a communicated decision making path with the committee on unresolved matters

## Where I work
Google

[@parispittman]: https://github.com/
[parisinbmore@]: https://twitter.com/parisinbmore
[Contributor Experience]: https://github.com/kubernetes/community/blob/master/sig-contributor-experience/charter.md
[contributor events]: https://github.com/kubernetes/community/tree/master/events
[mentoring]: https://github.com/kubernetes/community/tree/master/mentoring
[operational tactics]: https://github.com/kubernetes/community/blob/master/sig-wg-lifecycle.md
[guidelines]: https://github.com/kubernetes/community/tree/master/communication
[governance docs]: https://github.com/kubernetes/community/blob/master/committee-steering/governance/sig-governance.md
[Kubernetes Code of Conduct Committee]: https://github.com/kubernetes/community/tree/master/committee-code-of-conduct
[values]: https://github.com/kubernetes/community/blob/master/values.md
[Need to Know Chairs]: https://docs.google.com/document/d/1ivmV-ouim7YcTnmv21m0pP6prmj-FFZxcRBuWbT706c/edit?usp=sharing


text:
FROM mbaltrusitis/centos-python:3.4

RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app

ONBUILD COPY requirements.txt /usr/src/app/
ONBUILD RUN pip3 install --no-cache-dir -r requirements.txt

ONBUILD COPY . /usr/src/app

redpajama_set_name: RedPajamaGithub


text:
<?php
class Category_model extends CI_Model {
	public $category;
  public $slug;
  public $image;
  public $description;
  public $created_by;
  public $created_at;
  public $updated_by;
  public $updated_at;

  public function __construct()
  {
    parent::__construct();
//    $this->load->database();
  }

  //obtenemos el total de registros
  function count()
  {
    return $this->db->count_all('categories');
    /*
    $query=$this->db
                ->from("article")
                ->count_all_results();
                return $query;
    */
  }

  public function delete($id)
  {
    $this->db->where("id", $id);
    $this->db->delete("categories");
  }

  public function find($id = null)
  {
      if (is_null($id)) {
        $query = $this->db->get("categories");

        return $query->result();
      } else {
        $this->db->where("id", $id);
        $query = $this->db->get("categories");

        return $query->row();
      }
  }

  /**
   * $limit -> cantidad por páginas
   * $offset -> inicio de registro
   */
  public function get($limit = null, $offset = null)
  {
    if (is_null($limit) or is_null($offset)) {
      $query=$this->db
                ->from("categories")
                ->order_by("category","asc")
                ->get();
                return $query->result();
    } else {
      $query=$this->db
                ->from("categories")
                ->order_by("category","asc")
                ->limit($offset,$limit)
                ->get();
                return $query->result();
    }
  }

  public function add()
  {
    $this->load->view("category/add");
  }

  public function create($image)
  {
    $this->category			= $this->input->post('category');
		$this->slug					= $this->input->post('category');
    $this->image				= $image;
		$this->description	= $this->input->post('description');
		$this->created_by		= 1;
    $this->created_at 	= date("Y-m-d H:i:s");
		$this->updated_by		= 1;
    $this->updated_at 	= date("Y-m-d H:i:s");
/*
		echo "<pre>";
		print_r($this);
		exit;
*/
    $this->db->insert("categories", $this);
    return $this->db->insert_id();
  }
  /**
   * actualiza una categoría
   * @param int $category datos de la categoría
   */
  public function update($category = array())
	{
		$this->db->where("id", $category["id"]);
		$this->db->update("categories", $category);
	}
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>The Vigilante</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">

    <link href="css/simple-sidebar.css" rel="stylesheet">

    <link href='https://fonts.googleapis.com/css?family=Open+Sans:400,700,300' rel='stylesheet' type='text/css'>

                                Motion Graphics

                    SeeClickFix

                    Powerless

                    The Vigilante

THE VIGILANTE

The Vigilante from Andrew Ginzberg on Vimeo.

My first project I have ever done. It is an intro sequence to an imaginary action show/movie

View vimeo page


text:
<?php

namespace app\modules\agency\models;

use Yii;
use yii\base\Model;

/**
 * Signup form
 */
class UserForm extends Model
{
    public $username;
    public $email;
    public $password;
    public $repassword;
    public $is_staff;
    public $mobile;
    public $category;
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            ['username', 'filter', 'filter' => 'trim'],
            ['username', 'required'],
            ['username', 'unique', 'targetClass' => '\app\modules\user\models\User', 'message' => '此用户名已被占用,请尝试新的用户名.'],
            ['username', 'string', 'min' => 2, 'max' => 255],

            ['email', 'filter', 'filter' => 'trim'],
            ['email', 'required'],
            ['email', 'email'],
            ['email', 'string', 'max' => 255],
            ['email', 'unique', 'targetClass' => '\app\modules\user\models\User', 'message' => '此邮箱已被使用'],

            ['mobile', 'string', 'max' => 12],

            ['is_staff', 'required'],

            ['category', 'required'],
            ['category', 'integer'],

            // ['password', 'required'],
            ['password', 'string', 'min' => 6],

            ['repassword', 'compare', 'compareAttribute'=>'password']

        ];
    }

    public function attributeLabels()
    {
        return array(
            'username'=> '用户名',
            'email' => '邮箱',
            'password' => '注册密码',
            'repassword' => '再次输入密码',
            'is_staff' => '用户类别',
            'mobile' => '手机',
            'category' => '办事处'
        );
    }

    /**
     * Signs user up.
     *
     * @return User|null the saved model or null if saving fails
     */
    public function create()
    {
        if ($this->validate()) {
            $user = new User();
            $user->username = $this->username;
            $user->email = $this->email;
            $user->category = $this->category;

            $this->password = $this->password ? $this->password : '999999';
            $user->setPassword($this->password);
            $user->generateAuthKey();
            $user->is_staff = $this->is_staff;
            $user->status = User::STATUS_ACTIVE;
            if ($user->save()) {
                return $user;
            }
        }

        return null;
    }
}


text:
module app.dialogs.dataschemaimport {

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

    export class FromUrlHookController extends AbstractWizardStep {

        public url:string;

        constructor(wizard:AbstractWizard, private $http:IHttpService){
            super(wizard);
        }

        getTitle(index: number):string {
            return index+1+". URL";
        }

        getDescription(): string {
            return "Insert the URL from where you want to load your data-schema"
        }

        getTemplate():string {
            return "app/src/components/dialogs/dataschemaImport/fromUrlHook/fromUrlStep.html";
        }

        hasNavigation():boolean {
            return true;
        }

        shallSubmit():boolean {
            return true;
        }

        submit():IPromise<any> {
            return this.$http.get(this.url).then((res)=>{
                var result = {
                    dataSchema: res.data
                };
                return result;
            });
        }
    }

}


text:
import sys
import txaio

txaio.use_twisted()

from twisted import logger
from twisted.logger import ILogObserver
from zope.interface import provider

# some library you use is using txaio logging stuff
class Library(object):
    log = txaio.make_logger()

    def something(self):
        self.log.info("info log from library foo={foo}", foo='bar')
        self.log.debug("debug information")

# lets say you start your own observer
@provider(ILogObserver)
class Observer(object):
    def __init__(self):
        self._out = sys.stdout
    def __call__(self, event):
        self._out.write("Observe: {}\n".format(event))

lib = Library()
print("logging not started")
logger.globalLogBeginner.beginLoggingTo([Observer()])
print("logging started; calling library")
lib.something()
print("finished library call")
# should see "Observe: " ...


text:
namespace folly { namespace wangle {

template <typename R>
void ObservingHandler<R>::transportActive(Context* ctx) {
  if (broadcastHandler_) {
    // Already connected
    return;
  }

  // Pause ingress until the remote connection is established and
  // broadcast handler is ready
  auto pipeline = dynamic_cast<DefaultPipeline*>(ctx->getPipeline());
  CHECK(pipeline);
  pipeline->transportInactive();

  auto pool = broadcastPool();
  pool->getHandler(routingData_)
      .then([this, pipeline](
          BroadcastHandler<std::unique_ptr<folly::IOBuf>>* broadcastHandler) {
        broadcastHandler_ = broadcastHandler;
        subscriptionId_ = broadcastHandler_->subscribe(this);
        VLOG(10) << "Subscribed to a broadcast";

        // Resume ingress
        pipeline->transportActive();
      })
      .onError([this, ctx](const std::exception& ex) {
        LOG(ERROR) << "Error subscribing to a broadcast: " << ex.what();
        closeHandler();
      });
}

template <typename R>
void ObservingHandler<R>::readEOF(Context* ctx) {
  closeHandler();
}

template <typename R>
void ObservingHandler<R>::readException(Context* ctx,
                                        folly::exception_wrapper ex) {
  LOG(ERROR) << "Error on read: " << exceptionStr(ex);
  closeHandler();
}

template <typename R>
void ObservingHandler<R>::onNext(const std::unique_ptr<folly::IOBuf>& buf) {
  if (!buf || paused_) {
    return;
  }

  write(getContext(), buf->clone())
      .onError([this](const std::exception& ex) {
        LOG(ERROR) << "Error on write: " << ex.what();
        closeHandler();
      });
}

template <typename R>
void ObservingHandler<R>::onError(folly::exception_wrapper ex) {
  LOG(ERROR) << "Error observing a broadcast: " << exceptionStr(ex);

  // broadcastHandler_ will clear its subscribers and delete itself
  broadcastHandler_ = nullptr;
  closeHandler();
}

template <typename R>
void ObservingHandler<R>::onCompleted() {
  // broadcastHandler_ will clear its subscribers and delete itself
  broadcastHandler_ = nullptr;
  closeHandler();
}

template <typename R>
void ObservingHandler<R>::closeHandler() {
  if (broadcastHandler_) {
    auto broadcastHandler = broadcastHandler_;
    broadcastHandler_ = nullptr;
    broadcastHandler->unsubscribe(subscriptionId_);
  }
  close(getContext());
}

template <typename R>
BroadcastPool<std::unique_ptr<folly::IOBuf>, R>*
ObservingHandler<R>::broadcastPool() {
  if (!broadcastPool_) {
    broadcastPool_.reset(newBroadcastPool());
  }
  return broadcastPool_.get();
}

template <typename R>
BroadcastPool<std::unique_ptr<folly::IOBuf>, R>*
ObservingHandler<R>::newBroadcastPool() {
  return (new BroadcastPool<std::unique_ptr<folly::IOBuf>, R>(
      serverPool_, broadcastHandlerFactory_));
}

}} // namespace folly::wangle


text:
#pragma once
#include <aws/s3-crt/S3Crt_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>

namespace Aws
{
namespace S3Crt
{
namespace Model
{
  enum class InventoryFormat
  {
    NOT_SET,
    CSV,
    ORC,
    Parquet
  };

namespace InventoryFormatMapper
{
AWS_S3CRT_API InventoryFormat GetInventoryFormatForName(const Aws::String& name);

AWS_S3CRT_API Aws::String GetNameForInventoryFormat(InventoryFormat value);
} // namespace InventoryFormatMapper
} // namespace Model
} // namespace S3Crt
} // namespace Aws


text:
package com.comandante.creeper.command.commands.admin;

import com.comandante.creeper.command.commands.Command;
import com.comandante.creeper.core_game.GameManager;
import com.comandante.creeper.items.Loot;
import com.comandante.creeper.npc.Npc;
import com.comandante.creeper.npc.NpcBuilder;
import com.comandante.creeper.player.PlayerRole;
import com.comandante.creeper.server.player_communication.Color;
import com.google.common.base.Joiner;
import com.google.common.collect.Sets;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.MessageEvent;

import java.util.Arrays;
import java.util.List;
import java.util.Set;

public class SpawnCommand  extends Command {

    final static List<String> validTriggers = Arrays.asList("spawn");
    final static String description = "Spawn a NPC.";
    final static String correctUsage = "spawn <npc name> | spawn";
    final static Set<PlayerRole> roles = Sets.newHashSet(PlayerRole.ADMIN);

    public SpawnCommand(GameManager gameManager) {
        super(gameManager, validTriggers, description, correctUsage, roles);
    }

    @Override
    public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
        execCommand(ctx, e, () -> {
            List<Npc> npcsFromFile = gameManager.getNpcStorage().getAllNpcs();
            if (originalMessageParts.size() == 1) {
                write(getHeader());
                for (Npc npc: npcsFromFile) {
                    write(npc.getName() + "\r\n");
                }
            } else {
                originalMessageParts.remove(0);
                String targetNpc = Joiner.on(" ").join(originalMessageParts);
                for (Npc npc: npcsFromFile) {
                    if (targetNpc.equals(npc.getName())) {
                        Loot loot = new Loot(0,0, Sets.newHashSet());
                        Npc modifiedNpc = new NpcBuilder(npc).setSpawnRules(null).setLoot(loot).createNpc();
                        modifiedNpc.getStats().setExperience(0);
                        modifiedNpc.setCurrentRoom(currentRoom);
                        gameManager.getEntityManager().addEntity(modifiedNpc);
                        currentRoom.addPresentNpc(modifiedNpc.getEntityId());
                        writeToRoom("A " + modifiedNpc.getColorName() + " appears." + "\r\n");
                        return;
                    }
                }
                write("No npc found with name: " + targetNpc + "\r\n");
            }
        });
    }

    public String getHeader() {
        StringBuilder sb = new StringBuilder();
        sb.append(Color.MAGENTA + "-+=[ " + Color.RESET).append("Spawn").append(Color.MAGENTA + " ]=+- " + Color.RESET).append("\r\n");
        sb.append(Color.MAGENTA + "AvailableNpcs-----------------------" + Color.RESET).append("\r\n");
        return sb.toString();
    }
}


text:
package java.util;

import java.util.function.IntConsumer;

/**
 * A state object for collecting statistics such as count, min, max, sum, and
 * average.
 *
 *
This class is designed to work with (though does not require)
 * {@linkplain java.util.stream streams}. For example, you can compute
 * summary statistics on a stream of ints with:
 *
 {@code
 * IntSummaryStatistics stats = intStream.collect(IntSummaryStatistics::new,
 *                                                IntSummaryStatistics::accept,
 *                                                IntSummaryStatistics::combine);
 * }

 *
 *
{@code IntSummaryStatistics} can be used as a
 * {@linkplain java.util.stream.Stream#collect(Collector) reduction}
 * target for a {@linkplain java.util.stream.Stream stream}. For example:
 *
 *
 {@code
 * IntSummaryStatistics stats = people.stream()
 *                                    .collect(Collectors.summarizingInt(Person::getDependents));
 *}

 *
 * This computes, in a single pass, the count of people, as well as the minimum,
 * maximum, sum, and average of their number of dependents.
 *
 * @implNote This implementation is not thread safe. However, it is safe to use
 * {@link java.util.stream.Collectors#summarizingInt(java.util.function.ToIntFunction)
 * Collectors.toIntStatistics()} on a parallel stream, because the parallel
 * implementation of {@link java.util.stream.Stream#collect Stream.collect()}
 * provides the necessary partitioning, isolation, and merging of results for
 * safe and efficient parallel execution.
 *
 *
This implementation does not check for overflow of the sum.
 * @since 1.8
 */
public class IntSummaryStatistics implements IntConsumer {
    private long count;
    private long sum;
    private int min = Integer.MAX_VALUE;
    private int max = Integer.MIN_VALUE;

    /**
     * Construct an empty instance with zero count, zero sum,
     * {@code Integer.MAX_VALUE} min, {@code Integer.MIN_VALUE} max and zero
     * average.
     */
    public IntSummaryStatistics() { }

    /**
     * Records a new value into the summary information
     *
     * @param value the input value
     */
    @Override
    public void accept(int value) {
        ++count;
        sum += value;
        min = Math.min(min, value);
        max = Math.max(max, value);
    }

    /**
     * Combines the state of another {@code IntSummaryStatistics} into this one.
     *
     * @param other another {@code IntSummaryStatistics}
     * @throws NullPointerException if {@code other} is null
     */
    public void combine(IntSummaryStatistics other) {
        count += other.count;
        sum += other.sum;
        min = Math.min(min, other.min);
        max = Math.max(max, other.max);
    }

    /**
     * Returns the count of values recorded.
     *
     * @return the count of values
     */
    public final long getCount() {
        return count;
    }

    /**
     * Returns the sum of values recorded, or zero if no values have been
     * recorded.
     *
     * @return the sum of values, or zero if none
     */
    public final long getSum() {
        return sum;
    }

    /**
     * Returns the minimum value recorded, or {@code Integer.MAX_VALUE} if no
     * values have been recorded.
     *
     * @return the minimum value, or {@code Integer.MAX_VALUE} if none
     */
    public final int getMin() {
        return min;
    }

    /**
     * Returns the maximum value recorded, or {@code Integer.MIN_VALUE} if no
     * values have been recorded.
     *
     * @return the maximum value, or {@code Integer.MIN_VALUE} if none
     */
    public final int getMax() {
        return max;
    }

    /**
     * Returns the arithmetic mean of values recorded, or zero if no values have been
     * recorded.
     *
     * @return the arithmetic mean of values, or zero if none
     */
    public final double getAverage() {
        return getCount() > 0 ? (double) getSum() / getCount() : 0.0d;
    }

    @Override
    /**
     * {@inheritDoc}
     *
     * Returns a non-empty string representation of this object suitable for
     * debugging. The exact presentation format is unspecified and may vary
     * between implementations and versions.
     */
    public String toString() {
        return String.format(
            "%s{count=%d, sum=%d, min=%d, average=%f, max=%d}",
            this.getClass().getSimpleName(),
            getCount(),
            getSum(),
            getMin(),
            getAverage(),
            getMax());
    }
}


text:
// Copyright (C) 2013 The Android Open Source Project
//
// 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.

package com.google.gerrit.server.notedb;

import com.google.common.annotations.VisibleForTesting;
import com.google.gerrit.server.config.GerritServerConfig;
import com.google.inject.Inject;
import com.google.inject.Singleton;

import org.eclipse.jgit.lib.Config;

/**
 * Holds the current state of the notes DB migration.
 * <p>
 * During a transitional period, different subsets of the former gwtorm DB
 * functionality may be enabled on the site, possibly only for reading or
 * writing.
 */
@Singleton
public class NotesMigration {
  @VisibleForTesting
  static NotesMigration allEnabled() {
    Config cfg = new Config();
    cfg.setBoolean("notedb", null, "write", true);
    cfg.setBoolean("notedb", "patchSetApprovals", "read", true);
    cfg.setBoolean("notedb", "changeMessages", "read", true);
    cfg.setBoolean("notedb", "publishedComments", "read", true);
    return new NotesMigration(cfg);
  }

  private final boolean write;
  private final boolean readPatchSetApprovals;
  private final boolean readChangeMessages;
  private final boolean readPublishedComments;

  @Inject
  NotesMigration(@GerritServerConfig Config cfg) {
    write = cfg.getBoolean("notedb", null, "write", false);
    readPatchSetApprovals =
        cfg.getBoolean("notedb", "patchSetApprovals", "read", false);
    readChangeMessages =
        cfg.getBoolean("notedb", "changeMessages", "read", false);
    readPublishedComments =
        cfg.getBoolean("notedb", "publishedComments", "read", false);
  }

  public boolean write() {
    return write;
  }

  public boolean readPatchSetApprovals() {
    return readPatchSetApprovals;
  }

  public boolean readChangeMessages() {
    return readChangeMessages;
  }

  public boolean readPublishedComments() {
    return readPublishedComments;
  }
}


text:
int main()
{
	printf("Compilation successful!\n");
	testAll();

	CountryRepo* countryRepo = createCountryRepo();
	CountryRepoController controller = createCountryRepoController(countryRepo);
	UI* ui = createUI(&controller);

	startUI(ui);

	destroyUI(&ui);
	destroyCountryRepo(&countryRepo);
	_CrtDumpMemoryLeaks();
    return 0;
}


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

using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;

namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders
{
    internal class TypeKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
    {
        public TypeKeywordRecommender()
            : base(SyntaxKind.TypeKeyword)
        {
        }

        protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
        {
            return context.IsTypeAttributeContext(cancellationToken);
        }
    }
}


text:
<?php

namespace MusicBox\Controller;

use MusicBox\Entity\Artist;
use Silex\Application;
use Symfony\Component\Form\FormError;
use Symfony\Component\HttpFoundation\Request;

class ApiArtistController
{
    public function indexAction(Request $request, Application $app)
    {
        $limit = $request->query->get('limit', 20);
        $offset = $request->query->get('offset', 0);
        $artists = $app['repository.artist']->findAll($limit, $offset);
        $data = array();
        foreach ($artists as $artist) {
            $data[] = array(
                'id' => $artist->getId(),
                'name' => $artist->getName(),
                'short_biography' => $artist->getShortBiography(),
                'biography' => $artist->getBiography(),
                'soundcloud_url' => $artist->getSoundCloudUrl(),
                'likes' => $artist->getLikes(),
            );
        }

        return $app->json($data);
    }

    public function viewAction(Request $request, Application $app)
    {
        $artist = $request->attributes->get('artist');
        if (!$artist) {
            return $app->json('Not Found', 404);
        }
        $data = array(
            'id' => $artist->getId(),
            'name' => $artist->getName(),
            'short_biography' => $artist->getShortBiography(),
            'biography' => $artist->getBiography(),
            'soundcloud_url' => $artist->getSoundCloudUrl(),
            'likes' => $artist->getLikes(),
        );

        return $app->json($data);
    }

    public function addAction(Request $request, Application $app)
    {
        if (!$request->request->has('name')) {
            return $app->json('Missing required parameter: name', 400);
        }
        if (!$request->request->has('short_biography')) {
            return $app->json('Missing required parameter: short_biography', 400);
        }

        $artist = new Artist();
        $artist->setName($request->request->get('name'));
        $artist->setShortBiography($request->request->get('short_biography'));
        $artist->setBiography($request->request->get('biography'));
        $artist->setSoundCloudUrl($request->request->get('soundcloud_url'));
        $app['repository.artist']->save($artist);

        $headers = array('Location' => '/api/artist/' . $artist->getId());
        return $app->json('Created', 201, $headers);
    }

    public function editAction(Request $request, Application $app)
    {
        $artist = $request->attributes->get('artist');
        if (!$artist) {
            return $app->json('Not Found', 404);
        }
        if (!$request->request->has('name')) {
            return $app->json('Missing required parameter: name', 400);
        }
        if (!$request->request->has('short_biography')) {
            return $app->json('Missing required parameter: short_biography', 400);
        }
        $artist->setName($request->request->get('name'));
        $artist->setShortBiography($request->request->get('short_biography'));
        $artist->setBiography($request->request->get('biography'));
        $artist->setSoundCloudUrl($request->request->get('soundcloud_url'));
        $app['repository.artist']->save($artist);

        return $app->json('OK', 200);
    }

    public function deleteAction(Request $request, Application $app)
    {
        $artist = $request->attributes->get('artist');
        if (!$artist) {
            return $app->json('Not Found', 404);
        }
        $app['repository.artist']->delete($artist);

        return $app->json('No Content', 204);
    }
}


text:
package db;

import com.sleepycat.db.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.PrintStream;

class AccessExample {
    private static final int EXIT_SUCCESS = 0;
    private static final int EXIT_FAILURE = 1;

    public AccessExample() {
    }

    public static void usage() {
        System.out.println("usage: java " +
               "db.AccessExample [-r] [database]\n");
        System.exit(EXIT_FAILURE);
    }

    public static void main(String[] argv) {
        boolean removeExistingDatabase = false;
        String databaseName = "access.db";

        for (int i = 0; i < argv.length; i++) {
            if (argv[i].equals("-r"))
                removeExistingDatabase = true;
            else if (argv[i].equals("-?"))
                usage();
            else if (argv[i].startsWith("-"))
                usage();
            else {
                if ((argv.length - i) != 1)
                    usage();
                databaseName = argv[i];
                break;
            }
        }

        try {
            AccessExample app = new AccessExample();
            app.run(removeExistingDatabase, databaseName);
        } catch (DatabaseException dbe) {
            System.err.println("AccessExample: " + dbe.toString());
            System.exit(EXIT_FAILURE);
        } catch (FileNotFoundException fnfe) {
            System.err.println("AccessExample: " + fnfe.toString());
            System.exit(EXIT_FAILURE);
        }
        System.exit(EXIT_SUCCESS);
    }

    // Prompts for a line, and keeps prompting until a non blank
    // line is returned.  Returns null on error.
    //
    public static String askForLine(InputStreamReader reader,
                                    PrintStream out, String prompt) {
        String result = "";
        while (result != null && result.length() == 0) {
            out.print(prompt);
            out.flush();
            result = getLine(reader);
        }
        return result;
    }

    // Not terribly efficient, but does the job.
    // Works for reading a line from stdin or a file.
    // Returns null on EOF.  If EOF appears in the middle
    // of a line, returns that line, then null on next call.
    //
    public static String getLine(InputStreamReader reader) {
        StringBuffer b = new StringBuffer();
        int c;
        try {
            while ((c = reader.read()) != -1 && c != '\n') {
                if (c != '\r')
                    b.append((char)c);
            }
        } catch (IOException ioe) {
            c = -1;
        }

        if (c == -1 && b.length() == 0)
            return null;
        else
            return b.toString();
    }

    public void run(boolean removeExistingDatabase, String databaseName)
        throws DatabaseException, FileNotFoundException {

        // Remove the previous database.
        if (removeExistingDatabase)
            new File(databaseName).delete();

        // Create the database object.
        // There is no environment for this simple example.
        DatabaseConfig dbConfig = new DatabaseConfig();
        dbConfig.setErrorStream(System.err);
        dbConfig.setErrorPrefix("AccessExample");
        dbConfig.setType(DatabaseType.BTREE);
        dbConfig.setAllowCreate(true);
        Database table = new Database(databaseName, null, dbConfig);

        //
        // Insert records into the database, where the key is the user
        // input and the data is the user input in reverse order.
        //
        InputStreamReader reader = new InputStreamReader(System.in);

        for (;;) {
            String line = askForLine(reader, System.out, "input> ");
            if (line == null)
                break;

            String reversed = (new StringBuffer(line)).reverse().toString();

            // See definition of StringDbt below
            //
            StringEntry key = new StringEntry(line);
            StringEntry data = new StringEntry(reversed);

            try {
                if (table.putNoOverwrite(null, key, data) == OperationStatus.KEYEXIST)
                    System.out.println("Key " + line + " already exists.");
            } catch (DatabaseException dbe) {
                System.out.println(dbe.toString());
            }
        }

        // Acquire an iterator for the table.
        Cursor cursor;
        cursor = table.openCursor(null, null);

        // Walk through the table, printing the key/data pairs.
        // See class StringDbt defined below.
        //
        StringEntry key = new StringEntry();
        StringEntry data = new StringEntry();
        while (cursor.getNext(key, data, null) == OperationStatus.SUCCESS)
            System.out.println(key.getString() + " : " + data.getString());
        cursor.close();
        table.close();
    }

    // Here's an example of how you can extend DatabaseEntry in a
    // straightforward way to allow easy storage/retrieval of strings,
    // or whatever kind of data you wish.  We've declared it as a static
    // inner class, but it need not be.
    //
    static /*inner*/
    class StringEntry extends DatabaseEntry {
        StringEntry() {
        }

        StringEntry(String value) {
            setString(value);
        }

        void setString(String value) {
            byte[] data = value.getBytes();
            setData(data);
            setSize(data.length);
        }

        String getString() {
            return new String(getData(), getOffset(), getSize());
        }
    }
}


text:
var assert = require("assert"),
    expect = require('expect.js'),
    cda = require("../utils/xml.js").cda,
    DOMParser = require('xmldom').DOMParser,
    XmlSerializer = require('xmldom').XMLSerializer,
    xmlUtils = require("../utils/xml.js").xml,
    AllergySectionCreator = require("../Model/AllergySection.js"),
    AllergyEntryCreator = require("../Model/AllergyEntry.js"),
    Σ = xmlUtils.CreateNode,
    A = xmlUtils.CreateAttributeWithNameAndValue,
    adapter = require("../CDA/ModeltoCDA.js").cda;

var createMockAllergyEntry = function(num) {
    var entry = AllergyEntryCreator.create();
    entry.id = num;
    entry.AuthorFirstName = 'First Name ' + num;
    entry.AuthorLastName = 'Last Name ' + num;
    entry.AllergyTo = 'Allergy To ' + num;
    entry.AllergyType = 'Allergy Type ' + num;
    entry.Severity = 'Severity ' + num;
    entry.Reaction = 'Reaction ' + num;
    entry.NoticeDate = new Date('3/1/2011');

    return entry;
};

describe("Build Allergy Section.", function() {

    it("Should be able to generate an entry.", function() {
        var mockEntry = createMockAllergyEntry(1);
        var section = AllergySectionCreator.create();
        section.TransformedNarrative = "<text>Test</text>";
        section.Allergies.push(mockEntry);
        var serializer = new XmlSerializer();

        var e = new adapter.ImmunizationSection();
        var document = new DOMParser().parseFromString("<?xml version='1.0' standalone='yes'?><ClinicalDocument xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xsi:schemaLocation='urn:hl7-org:v3 CDA/infrastructure/cda/CDA_SDTC.xsd' xmlns='urn:hl7-org:v3' xmlns:cda='urn:hl7-org:v3' xmlns:sdtc='urn:hl7-org:sdtc'></ClinicalDocument>", "text/xml");
        var cdaAdapter = new adapter.AllergySection();
        var node = cdaAdapter.BuildAll(section, document);

        assert.equal(node.getElementsByTagName("templateId")[0].getAttributeNode("root").value, "2.16.840.1.113883.10.20.22.2.6");
        assert.equal(node.getElementsByTagName("code")[0].getAttributeNode("code").value, "48765-2");
        assert.equal(node.getElementsByTagName("code")[0].getAttributeNode("codeSystem").value, "2.16.840.1.113883.6.1");
        assert.equal(node.getElementsByTagName("code")[0].getAttributeNode("codeSystemName").value, "LOINC");
        assert.equal(node.getElementsByTagName("code")[0].getAttributeNode("displayName").value, "Allergies, adverse reactions, alerts");
        assert.equal(node.getElementsByTagName("title")[0].childNodes[0].nodeValue, "ALLERGIES, ADVERSE REACTIONS, ALERTS");
        assert.notEqual(node.getElementsByTagName("text").length, 0);
    });
});


text:
package cgeo.geocaching.settings;

import cgeo.geocaching.R;
import cgeo.geocaching.activity.ActivityMixin;
import cgeo.geocaching.network.Network;
import cgeo.geocaching.network.Parameters;
import cgeo.geocaching.ui.dialog.Dialogs;
import cgeo.geocaching.utils.AndroidRxUtils;
import cgeo.geocaching.utils.Log;

import android.app.ProgressDialog;
import android.content.Context;
import android.preference.Preference;
import android.util.AttributeSet;

import java.util.concurrent.Callable;

import io.reactivex.Observable;
import io.reactivex.functions.Consumer;
import okhttp3.Response;
import org.apache.commons.lang3.StringUtils;

public class RegisterSend2CgeoPreference extends AbstractClickablePreference {

    public RegisterSend2CgeoPreference(final Context context, final AttributeSet attrs) {
        super(context, attrs);
    }

    public RegisterSend2CgeoPreference(final Context context, final AttributeSet attrs, final int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected OnPreferenceClickListener getOnPreferenceClickListener(final SettingsActivity activity) {
        return new OnPreferenceClickListener() {
            @Override
            public boolean onPreferenceClick(final Preference preference) {
                // satisfy static code analysis
                if (activity == null) {
                    return true;
                }

                final String deviceName = Settings.getWebDeviceName();
                if (StringUtils.isBlank(deviceName)) {
                    ActivityMixin.showToast(activity, R.string.err_missing_device_name);
                    return false;
                }

                final String deviceCode = Settings.getWebDeviceCode();

                final ProgressDialog progressDialog = ProgressDialog.show(activity,
                        activity.getString(R.string.init_sendToCgeo),
                        activity.getString(R.string.init_sendToCgeo_registering), true);
                progressDialog.setCancelable(false);

                AndroidRxUtils.bindActivity(activity, Observable.defer(new Callable<Observable<Integer>>() {
                    @Override
                    public Observable<Integer> call() {
                        final String nam = StringUtils.defaultString(deviceName);
                        final String cod = StringUtils.defaultString(deviceCode);

                        final Parameters params = new Parameters("name", nam, "code", cod);

                        try {
                            final Response response = Network.getRequest("http://send2.cgeo.org/auth.html", params)
                                    .flatMap(Network.withSuccess).blockingGet();

                            final String[] strings = StringUtils.split(Network.getResponseData(response), ',');
                            if (strings != null) {
                                Settings.setWebNameCode(nam, strings[0]);
                                return Observable.just(Integer.valueOf(strings[1].trim()));
                            }
                        } catch (final Exception e) {
                            Log.e("RegisterSend2CgeoPreference", e);
                        }

                        return Observable.empty();
                    }
                }).first(0)).subscribeOn(AndroidRxUtils.networkScheduler).subscribe(new Consumer<Integer>() {
                    @Override
                    public void accept(final Integer pin) {
                        progressDialog.dismiss();
                        if (pin > 0) {
                            Dialogs.message(activity, R.string.init_sendToCgeo,
                                    activity.getString(R.string.init_sendToCgeo_register_ok, pin));
                        } else {
                            Dialogs.message(activity, R.string.init_sendToCgeo, R.string.init_sendToCgeo_register_fail);
                        }
                    }
                });

                return true;
            }
        };
    }

}


text:
var pluginlist = [
  "https://github.com/VersoSolutions/CordovaClipboard",
  "https://github.com/jcsmesquita/cordova-speechrecognition",
  "https://github.com/ThomasDalla/cordova-plugin-koc",
  "https://github.com/whiteoctober/cordova-plugin-app-version.git",
  "https://github.com/apache/cordova-plugin-inappbrowser.git",
  "https://github.com/driftyco/ionic-plugin-deploy",
  "cordova-plugin-whitelist",
];

// no need to configure below

var fs = require('fs');
var path = require('path');
var exec = require('child_process').exec;

pluginlist.forEach( function(plug) {
  exec("ionic plugin add " + plug, function (err, stdout, stderr) {
    console.log(stdout);
    console.log(stderr);
    if(err) console.log(err);
  });
});

pluginlist.forEach(function(plug) {
  console.log("ionic plugin add " + plug)
});


text:
BSI serves as an integration point for our web components and component-based applications. We're using [open-wc](https://open-wc.org/)'s Rollup tooling to build our components and manage dependencies.

## Integrating a New Component

To integrate a new web component into BSI, perform the following steps:

### Add Dependency

You can add your component as an NPM dependency either using a GitHub reference to a public repo or from NPM directly.

As a GitHub reference:

```json
// package.json
{
  "dependencies": {
    "d2l-navigation": "BrightspaceUI/navigation#semver:^3"
  }
}
```

**Important**: do not include minor or patch versions for GitHub-based dependencies as it can result in duplicate copies of components, and consequently browser errors related to multiple definitions of those components with the same tag name.

Alternately, if your component is published to NPM you can pull it in that way:

```json
// package.json
{
  "dependencies": {
    "@brightspace-ui/core": "^1"
  }
}
```

### Include it in the build

Inside `/rollup/rollup-wc.config.js`, add your component to either the `componentFiles` (for simple web components) or `appFiles` (for component-based applications) collections.

```javascript
const componentFiles = [
  ...
  './node_modules/<your-component>/path/to/component.js,
  ...
]
const appFiles = [
  ...
  './node_modules/<your-app/app.js'
]
```

### Lang Terms

Optionally, if your component has lang terms managed by Serge.io, add an entry to the `.serge-mapping.json` file:

```json
{
  ...
  "my-component": "my-component/my-component.serge.json"
  ...
}
```

## Using Components on Brightspace Pages

Once a component is included in BSI, you can then start to reference it from pages in Brightspace.

### Create an IBsiAsset

In your project, add a new `IBsiAsset` representation of your component's file in BSI. The easiest way to do this is through Visual Studio's `Add` > `New Item...` menu, select `Desire2Learn` and then `BsiAsset`. Name your asset `{ComponentName}Module.codegen`.

The contents of the file should look like this:

```xml
<?xml version="1.0" encoding="utf-8"?>
<bsiAsset xmlns="http://schemas.desire2learn.com/codegen/bsiAsset/v3.0">
  <typeName>D2L.YourProduct.Your.Namespace.ComponentNameModule</typeName>
  <path>node_modules/<your-component>/path/to/component</path>
  <extension>js</extension>
</bsiAsset>
```

The path here should match exactly what was included in the build earlier in BSI's `/rollup/rollup-wc.config.js` file.

Build your solution once so that the codegen can generate a class for your component.

### Load the BSI Asset

The last step is to actually load your component's asset file whenever it gets rendered to a page. Usually it's easiest to wrap your component in a [View-Data-Based Control](https://docs.dev.d2l/index.php/HOWTO_Create_a_View-Data-Based_Control), load the asset from the control's renderer, and then use that control whenever you want to render your component.

To load the asset, dependency inject `IBsiLoader` and call `LoadModules()`:

```csharp
partial class MyComponent {

  internal sealed class Renderer : IViewDataRenderer<MyComponent> {

    private readonly IBsiLoader m_bsiLoader;

    public Renderer( IBsiLoader bsiLoader ) {
      m_bsiLoader = bsiLoader;
    }

    void IViewDataRenderer<MyComponent>.Render(
        IHtmlRenderContext rc,
        MyControl viewData
      ) {

      m_bsiLoader.LoadModules( ComponentNameModule.Instance );

      rc.Writer.WriteTagBeginFull("d2l-my-component");
      rc.Writer.WriteTagEnd("d2l-my-component");

    }

  }

}
```

Now whenever `MyComponent` is rendered in a view, you should see your component's BSI asset loaded from the CDN.

### Troubleshooting

Sometimes, the first time you add a codegen to a project it doesn't wrap it in `<AutoGenerate>`. You have to manually add the `<AutoGenerate>`.
Make sure you have the following `<Import>` and `<AutoGenerate>` in the .csproj file.

```
  <Import Project="$(D2LPackagesDir)D2L.DevTools.CodeGen.MsBuild\build\D2L.DevTools.CodeGen.MsBuild.targets" />

  <ItemGroup>
	<AutoGenerate Include="<codegenFileLocation>\<codegenFileName>.codegen" />
  </ItemGroup>
```

If you still have an issue after adding both `<Import>` and `<AutoGenerate>` to csproj file, comment out the usage of the module
`m_bsiLoader.LoadModules( <codegenFileName>.Instance );` until you build the project once (which will auto-generate the class), then you should be able to uncomment it and use it.

## Local Component Development

A common use case for running a local BSI is to test out a web component you're also working on locally with a Brightspace instance. That way you can avoid releasing the component and pulling the new release into BSI until you're ready.

To link your local BSI with a local web component, follow these steps:
1. Ensure that your component has a valid `package.json` with a `name` entry
2. Ensure that BSI is already pulling in your component in its `package.json` as a dependency (see above)
3. In the component's directory, run `npm link`
4. In BSI, run `npm link <component-name>`, where `<component-name>` matches the `name` entry in `package.json`
5. Follow the instructions in the [main README](../README.md) on building & running a local BSI and configuring Brightspace to use it

This process creates a symbolic link from BSI's `node_modules/<your-component>` directory to the local location of the component on your system. If you want to revert things back, simply delete the directory and `npm update`. Your component will then be freshly pulled from NPM.


text:
import _extends from "@babel/runtime/helpers/extends";
import _defineProperty from "@babel/runtime/helpers/defineProperty";
import _slicedToArray from "@babel/runtime/helpers/slicedToArray";
import _objectWithoutProperties from "@babel/runtime/helpers/objectWithoutProperties";
var _excluded = ["active", "hovered", "children", "getRootRef"];
import { createScopedElement } from "../../lib/jsxRuntime";
import * as React from "react";
import Tappable from "../Tappable/Tappable";
import { getClassName } from "../../helpers/getClassName";
import { classNames } from "../../lib/classNames";
import { usePlatform } from "../../hooks/usePlatform";
import Text from "../Typography/Text/Text";

var SliderSwitchButton = function SliderSwitchButton(props) {
  var _classNames;

  var active = props.active,
      hovered = props.hovered,
      children = props.children,
      getRootRef = props.getRootRef,
      restProps = _objectWithoutProperties(props, _excluded);

  var platform = usePlatform();

  var _React$useState = React.useState(false),
      _React$useState2 = _slicedToArray(_React$useState, 2),
      focus = _React$useState2[0],
      setFocus = _React$useState2[1];

  var toggleFocus = function toggleFocus() {
    setFocus(!focus);
  };

  return createScopedElement(Tappable, _extends({}, restProps, {
    vkuiClass: classNames(getClassName("SliderSwitch__button", platform), (_classNames = {}, _defineProperty(_classNames, "SliderSwitch__button--active", active), _defineProperty(_classNames, "SliderSwitch__button--hover", !active && hovered), _defineProperty(_classNames, "SliderSwitch__button--activeHover", active && hovered), _defineProperty(_classNames, "SliderSwitch__button--focus", focus && !hovered), _classNames)),
    Component: "button",
    type: "button",
    getRootRef: getRootRef,
    "aria-pressed": active,
    onFocus: toggleFocus,
    onBlur: toggleFocus,
    tabIndex: 0,
    hasActive: false,
    hoverMode: "opacity"
  }), createScopedElement(Text, {
    weight: "medium"
  }, children));
};

export default SliderSwitchButton;
//# sourceMappingURL=SliderSwitchButton.js.map


text:
#!/usr/bin/env ruby
require 'json'
require './lib/hdfs_scanner.rb'

base_dir = File.dirname(__FILE__)

state_file_name = File.join(base_dir, 'hadoop_state.json')
hadoop_state = JSON.parse(IO.read(state_file_name)) rescue {}

hadoop_state.each do  |key,value|
  if value.nil? or value['skip']

    empty_file = value && value['size'] <= 20
    if empty_file
      puts "#{value.inspect} looks like an empty file, ignoring #{key}"
    else
      puts "Something seems wrong about #{key}, rescanning"
      hadoop_state.delete(key) unless empty_zip
    end
  end
end

hdfs = Druid::HdfsScanner.new :file_pattern => (ENV['DRUID_HDFS_FILEPATTERN'] || '/events/*/*/*/*/part*'), :cache => hadoop_state
hdfs.scan

raw_start, raw_end = hdfs.range

# save hdfs state early...
IO.write(state_file_name, hdfs.to_json)
puts "We got raw data from #{Time.at raw_start} to #{Time.at raw_end}"


text:
from __future__ import unicode_literals, division, absolute_import

import logging
from builtins import *  # pylint: disable=unused-import, redefined-builtin
from collections import MutableSet
from datetime import datetime

from sqlalchemy import Column, Unicode, Integer, ForeignKey, func, DateTime
from sqlalchemy.orm import relationship
from sqlalchemy.sql.elements import and_

from flexget import plugin
from flexget.db_schema import versioned_base, with_session
from flexget.entry import Entry
from flexget.event import event
from flexget.manager import Session
from flexget.plugin import get_plugin_by_name
from flexget.plugins.parsers.parser_common import normalize_name, remove_dirt
from flexget.utils.tools import split_title_year

log = logging.getLogger('movie_list')
Base = versioned_base('movie_list', 0)

class MovieListBase(object):
    """
    Class that contains helper methods for movie list as well as plugins that use it,
    such as API and CLI.
    """

    @property
    def supported_ids(self):
        # Return a list of supported series identifier as registered via their plugins
        return [p.instance.movie_identifier for p in plugin.get_plugins(group='movie_metainfo')]

class MovieListList(Base):
    __tablename__ = 'movie_list_lists'
    id = Column(Integer, primary_key=True)
    name = Column(Unicode, unique=True)
    added = Column(DateTime, default=datetime.now)
    movies = relationship('MovieListMovie', backref='list', cascade='all, delete, delete-orphan', lazy='dynamic')

    def __repr__(self):
        return '<MovieListList name=%d>' % (self.id)

    def to_dict(self):
        return {
            'id': self.id,
            'name': self.name,
            'added_on': self.added
        }

class MovieListMovie(Base):
    __tablename__ = 'movie_list_movies'
    id = Column(Integer, primary_key=True)
    added = Column(DateTime, default=datetime.now)
    title = Column(Unicode)
    year = Column(Integer)
    list_id = Column(Integer, ForeignKey(MovieListList.id), nullable=False)
    ids = relationship('MovieListID', backref='movie', cascade='all, delete, delete-orphan')

    def __repr__(self):
        return '<MovieListMovie title=%s,year=%s,list_id=%d>' % (self.title, self.year, self.list_id)

    def to_entry(self, strip_year=False):
        entry = Entry()
        entry['title'] = entry['movie_name'] = self.title
        entry['url'] = 'mock://localhost/movie_list/%d' % self.id
        entry['added'] = self.added
        if self.year:
            if strip_year is False:
                entry['title'] += ' (%d)' % self.year
            entry['movie_year'] = self.year
        for movie_list_id in self.ids:
            entry[movie_list_id.id_name] = movie_list_id.id_value
        return entry

    def to_dict(self):
        movies_list_ids = [movie_list_id.to_dict() for movie_list_id in self.ids]
        return {
            'id': self.id,
            'added_on': self.added,
            'title': self.title,
            'year': self.year,
            'list_id': self.list_id,
            'movies_list_ids': movies_list_ids
        }

    @property
    def identifiers(self):
        """ Return a dict of movie identifiers """
        return {identifier.id_name: identifier.id_value for identifier in self.ids}

class MovieListID(Base):
    __tablename__ = 'movie_list_ids'
    id = Column(Integer, primary_key=True)
    added = Column(DateTime, default=datetime.now)
    id_name = Column(Unicode)
    id_value = Column(Unicode)
    movie_id = Column(Integer, ForeignKey(MovieListMovie.id))

    def __repr__(self):
        return '<MovieListID id_name=%s,id_value=%s,movie_id=%d>' % (self.id_name, self.id_value, self.movie_id)

    def to_dict(self):
        return {
            'id': self.id,
            'added_on': self.added,
            'id_name': self.id_name,
            'id_value': self.id_value,
            'movie_id': self.movie_id
        }

class MovieList(MutableSet):
    def _db_list(self, session):
        return session.query(MovieListList).filter(MovieListList.name == self.list_name).first()

    def _from_iterable(self, it):
        # TODO: is this the right answer? the returned object won't have our custom __contains__ logic
        return set(it)

    @with_session
    def __init__(self, config, session=None):
        if not isinstance(config, dict):
            config = {'list_name': config}
        config.setdefault('strip_year', False)
        self.list_name = config.get('list_name')
        self.strip_year = config.get('strip_year')

        db_list = self._db_list(session)
        if not db_list:
            session.add(MovieListList(name=self.list_name))

    def __iter__(self):
        with Session() as session:
            return iter([movie.to_entry(self.strip_year) for movie in self._db_list(session).movies])

    def __len__(self):
        with Session() as session:
            return len(self._db_list(session).movies)

    def add(self, entry):
        with Session() as session:
            # Check if this is already in the list, refresh info if so
            db_list = self._db_list(session=session)
            db_movie = self._find_entry(entry, session=session)
            # Just delete and re-create to refresh
            if db_movie:
                session.delete(db_movie)
            db_movie = MovieListMovie()
            if 'movie_name' in entry:
                db_movie.title, db_movie.year = entry['movie_name'], entry.get('movie_year')
            else:
                db_movie.title, db_movie.year = split_title_year(entry['title'])
            for id_name in MovieListBase().supported_ids:
                if id_name in entry:
                    db_movie.ids.append(MovieListID(id_name=id_name, id_value=entry[id_name]))
            log.debug('adding entry %s', entry)
            db_list.movies.append(db_movie)
            session.commit()
            return db_movie.to_entry()

    def discard(self, entry):
        with Session() as session:
            db_movie = self._find_entry(entry, session=session)
            if db_movie:
                log.debug('deleting movie %s', db_movie)
                session.delete(db_movie)

    def __contains__(self, entry):
        return self._find_entry(entry) is not None

    @with_session
    def _find_entry(self, entry, session=None):
        """Finds `MovieListMovie` corresponding to this entry, if it exists."""
        for id_name in MovieListBase().supported_ids:
            if entry.get(id_name):
                log.debug('trying to match movie based off id %s: %s', id_name, entry[id_name])
                res = (self._db_list(session).movies.join(MovieListMovie.ids).filter(
                    and_(
                        MovieListID.id_name == id_name,
                        MovieListID.id_value == entry[id_name]))
                       .first())
                if res:
                    log.verbose('found movie %s', res)
                    return res
        # Fall back to title/year match
        if not entry.get('movie_name'):
            self._parse_title(entry)
        if entry.get('movie_name'):
            name = entry['movie_name']
            year = entry.get('movie_year') if entry.get('movie_year') else None
        else:
            log.warning('Could not get a movie name, skipping')
            return
        log.debug('trying to match movie based of name: %s and year: %s', name, year)
        res = (self._db_list(session).movies.filter(func.lower(MovieListMovie.title) == name.lower())
               .filter(MovieListMovie.year == year).first())
        if res:
            log.verbose('found movie %s', res)
        return res

    @staticmethod
    def _parse_title(entry):
        parser = get_plugin_by_name('parsing').instance.parse_movie(data=entry['title'])
        if parser and parser.valid:
            parser.name = normalize_name(remove_dirt(parser.name))
            entry.update(parser.fields)

    @property
    def immutable(self):
        return False

    @property
    def online(self):
        """ Set the online status of the plugin, online plugin should be treated differently in certain situations,
        like test mode"""
        return False

    @with_session
    def get(self, entry, session):
        match = self._find_entry(entry=entry, session=session)
        return match.to_entry() if match else None

class PluginMovieList(object):
    """Remove all accepted elements from your trakt.tv watchlist/library/seen or custom list."""
    schema = {'oneOf': [
        {'type': 'string'},
        {'type': 'object',
         'properties': {
             'list_name': {'type': 'string'},
             'strip_year': {'type': 'boolean'}
         },
         'required': ['list_name'],
         'additionalProperties': False
         }
    ]}

    @staticmethod
    def get_list(config):
        return MovieList(config)

    def on_task_input(self, task, config):
        return list(MovieList(config))

@event('plugin.register')
def register_plugin():
    plugin.register(PluginMovieList, 'movie_list', api_ver=2, groups=['list'])

@with_session
def get_movies_by_list_id(list_id, count=False, start=None, stop=None, order_by='added', descending=False,
                          session=None):
    query = session.query(MovieListMovie).filter(MovieListMovie.list_id == list_id)
    if count:
        return query.count()
    query = query.slice(start, stop).from_self()
    if descending:
        query = query.order_by(getattr(MovieListMovie, order_by).desc())
    else:
        query = query.order_by(getattr(MovieListMovie, order_by))
    return query.all()

@with_session
def get_movie_lists(name=None, session=None):
    log.debug('retrieving movie lists')
    query = session.query(MovieListList)
    if name:
        log.debug('filtering by name %s', name)
        query = query.filter(MovieListList.name.contains(name))
    return query.all()

@with_session
def get_list_by_exact_name(name, session=None):
    log.debug('returning list with name %s', name)
    return session.query(MovieListList).filter(func.lower(MovieListList.name) == name.lower()).one()

@with_session
def get_list_by_id(list_id, session=None):
    log.debug('fetching list with id %d', list_id)
    return session.query(MovieListList).filter(MovieListList.id == list_id).one()

@with_session
def get_movie_by_id(list_id, movie_id, session=None):
    log.debug('fetching movie with id %d from list id %d', movie_id, list_id)
    return session.query(MovieListMovie).filter(
        and_(MovieListMovie.id == movie_id, MovieListMovie.list_id == list_id)).one()

@with_session
def get_movie_by_title(list_id, title, session=None):
    movie_list = get_list_by_id(list_id=list_id, session=session)
    if movie_list:
        log.debug('searching for movie %s in list %d', title, list_id)
        return session.query(MovieListMovie).filter(
            and_(
                func.lower(MovieListMovie.title) == title.lower(),
                MovieListMovie.list_id == list_id)
        ).first()

@with_session
def get_movie_identifier(identifier_name, identifier_value, movie_id=None, session=None):
    db_movie_id = session.query(MovieListID).filter(
        and_(MovieListID.id_name == identifier_name,
             MovieListID.id_value == identifier_value,
             MovieListID.movie_id == movie_id)).first()
    if db_movie_id:
        log.debug('fetching movie identifier %s: %s', db_movie_id.id_name, db_movie_id.id_value)
        return db_movie_id

@with_session
def get_db_movie_identifiers(identifier_list, movie_id=None, session=None):
    db_movie_ids = []
    for identifier in identifier_list:
        for key, value in identifier.items():
            if key in MovieListBase().supported_ids:
                db_movie_id = get_movie_identifier(identifier_name=key, identifier_value=value, movie_id=movie_id,
                                                   session=session)
                if not db_movie_id:
                    log.debug('creating movie identifier %s: %s', key, value)
                    db_movie_id = MovieListID(id_name=key, id_value=value, movie_id=movie_id)
                session.merge(db_movie_id)
                db_movie_ids.append(db_movie_id)
    return db_movie_ids


text:
package com.graphhopper.reader.osm;

public class Pair<F, S> {
    public F first;
    public S second;

    public Pair(F first, S second) {
        this.first = first;
        this.second = second;
    }
}


text:
<!doctype html>

  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>

<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />

  <meta name="baidu-site-verification" content="kvtiRyD7oL" />

  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />

    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">

<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

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

  <meta name="keywords" content="Hexo, NexT" />

  <link rel="alternate" href="/atom.xml" title="Just Let It Be" type="application/atom+xml" />

  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.0" />

<meta property="og:type" content="website">
<meta property="og:title" content="Just Let It Be">
<meta property="og:url" content="https://zqg.github.io/tags/Spectral-Clustering/index.html">
<meta property="og:site_name" content="Just Let It Be">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Just Let It Be">

  <link rel="canonical" href="https://zqg.github.io/tags/Spectral-Clustering/"/>

  <title> Tag: Spectral Clustering | Just Let It Be </title>

        Just Let It Be

    <button>

    </button>

            Home

            Archives

            Categories

            Tags

            About

            Search

      <input autocapitalize="off" autocomplete="off" autocorrect="off"
             placeholder="Searching..." spellcheck="false"
             type="text" id="local-search-input">

        Spectral Clustering
        Tag

                Spectral Clustering谱聚类 - 聚类算法

        <time class="post-time" itemprop="dateCreated"
              datetime="2017-04-20T16:35:38+08:00"
              content="2017-04-20" >
          04-20
        </time>

Quangang Zheng

                8
                posts

                6
                categories

                15
                tags

              RSS

            0%

  ©  2016 -
  2017

  Quangang Zheng

  Powered by Hexo

  Theme -

    NexT.Muse


text:
/*
 * (C) Copyright Taligent, Inc. 1996 - All Rights Reserved
 * (C) Copyright IBM Corp. 1996 - All Rights Reserved
 *
 *   The original version of this source code and documentation is copyrighted
 * and owned by Taligent, Inc., a wholly-owned subsidiary of IBM. These
 * materials are provided under terms of a License Agreement between Taligent
 * and Sun. This technology is protected by multiple US and International
 * patents. This notice and attribution to Taligent may not be removed.
 *   Taligent is a registered trademark of Taligent, Inc.
 *
 */

package java.util;

import java.io.Serializable;
import java.time.ZoneId;

import jdk.internal.util.StaticProperty;
import sun.security.action.GetPropertyAction;
import sun.util.calendar.ZoneInfo;
import sun.util.calendar.ZoneInfoFile;
import sun.util.locale.provider.TimeZoneNameUtility;

/**
 * {@code TimeZone} represents a time zone offset, and also figures out daylight
 * savings.
 *
 *

 * Typically, you get a {@code TimeZone} using {@code getDefault}
 * which creates a {@code TimeZone} based on the time zone where the program
 * is running. For example, for a program running in Japan, {@code getDefault}
 * creates a {@code TimeZone} object based on Japanese Standard Time.
 *
 *

 * You can also get a {@code TimeZone} using {@code getTimeZone}
 * along with a time zone ID. For instance, the time zone ID for the
 * U.S. Pacific Time zone is "America/Los_Angeles". So, you can get a
 * U.S. Pacific Time {@code TimeZone} object with:
 *

 * TimeZone tz = TimeZone.getTimeZone("America/Los_Angeles");
 *

 * You can use the {@code getAvailableIDs} method to iterate through
 * all the supported time zone IDs. You can then choose a
 * supported ID to get a {@code TimeZone}.
 * If the time zone you want is not represented by one of the
 * supported IDs, then a custom time zone ID can be specified to
 * produce a TimeZone. The syntax of a custom time zone ID is:
 *
 *

 * CustomID:
 *         {@code GMT} Sign Hours {@code :} Minutes
 *         {@code GMT} Sign Hours Minutes
 *         {@code GMT} Sign Hours
 * Sign: one of
 *         {@code + -}
 * Hours:
 *         Digit
 *         Digit Digit
 * Minutes:
 *         Digit Digit
 * Digit: one of
 *         {@code 0 1 2 3 4 5 6 7 8 9}
 *

 *
 * Hours must be between 0 to 23 and Minutes must be
 * between 00 to 59.  For example, "GMT+10" and "GMT+0010" mean ten
 * hours and ten minutes ahead of GMT, respectively.
 *

 * The format is locale independent and digits must be taken from the
 * Basic Latin block of the Unicode standard. No daylight saving time
 * transition schedule can be specified with a custom time zone ID. If
 * the specified string doesn't match the syntax, {@code "GMT"}
 * is used.
 *

 * When creating a {@code TimeZone}, the specified custom time
 * zone ID is normalized in the following syntax:
 *

 * NormalizedCustomID:
 *         {@code GMT} Sign TwoDigitHours {@code :} Minutes
 * Sign: one of
 *         {@code + -}
 * TwoDigitHours:
 *         Digit Digit
 * Minutes:
 *         Digit Digit
 * Digit: one of
 *         {@code 0 1 2 3 4 5 6 7 8 9}
 *

 * For example, TimeZone.getTimeZone("GMT-8").getID() returns "GMT-08:00".
 *
 *
Three-letter time zone IDs

 *
 * For compatibility with JDK 1.1.x, some other three-letter time zone IDs
 * (such as "PST", "CTT", "AST") are also supported. However, their
 * use is deprecated because the same abbreviation is often used
 * for multiple time zones (for example, "CST" could be U.S. "Central Standard
 * Time" and "China Standard Time"), and the Java platform can then only
 * recognize one of them.
 *
 *
 * @see          Calendar
 * @see          GregorianCalendar
 * @see          SimpleTimeZone
 * @author       Mark Davis, David Goldsmith, Chen-Lieh Huang, Alan Liu
 * @since        1.1
 */
public abstract class TimeZone implements Serializable, Cloneable {
    /**
     * Sole constructor.  (For invocation by subclass constructors, typically
     * implicit.)
     */
    public TimeZone() {
    }

    /**
     * A style specifier for {@code getDisplayName()} indicating
     * a short name, such as "PST."
     * @see #LONG
     * @since 1.2
     */
    public static final int SHORT = 0;

    /**
     * A style specifier for {@code getDisplayName()} indicating
     * a long name, such as "Pacific Standard Time."
     * @see #SHORT
     * @since 1.2
     */
    public static final int LONG  = 1;

    // Constants used internally; unit is milliseconds
    private static final int ONE_MINUTE = 60*1000;
    private static final int ONE_HOUR   = 60*ONE_MINUTE;
    private static final int ONE_DAY    = 24*ONE_HOUR;

    // Proclaim serialization compatibility with JDK 1.1
    @java.io.Serial
    static final long serialVersionUID = 3581463369166924961L;

    /**
     * Gets the time zone offset, for current date, modified in case of
     * daylight savings. This is the offset to add to UTC to get local time.
     *

     * This method returns a historically correct offset if an
     * underlying {@code TimeZone} implementation subclass
     * supports historical Daylight Saving Time schedule and GMT
     * offset changes.
     *
     * @param era the era of the given date.
     * @param year the year in the given date.
     * @param month the month in the given date.
     * Month is 0-based. e.g., 0 for January.
     * @param day the day-in-month of the given date.
     * @param dayOfWeek the day-of-week of the given date.
     * @param milliseconds the milliseconds in day in standard
     * local time.
     *
     * @return the offset in milliseconds to add to GMT to get local time.
     *
     * @see Calendar#ZONE_OFFSET
     * @see Calendar#DST_OFFSET
     */
    public abstract int getOffset(int era, int year, int month, int day,
                                  int dayOfWeek, int milliseconds);

    /**
     * Returns the offset of this time zone from UTC at the specified
     * date. If Daylight Saving Time is in effect at the specified
     * date, the offset value is adjusted with the amount of daylight
     * saving.
     *

     * This method returns a historically correct offset value if an
     * underlying TimeZone implementation subclass supports historical
     * Daylight Saving Time schedule and GMT offset changes.
     *
     * @param date the date represented in milliseconds since January 1, 1970 00:00:00 GMT
     * @return the amount of time in milliseconds to add to UTC to get local time.
     *
     * @see Calendar#ZONE_OFFSET
     * @see Calendar#DST_OFFSET
     * @since 1.4
     */
    public int getOffset(long date) {
        if (inDaylightTime(new Date(date))) {
            return getRawOffset() + getDSTSavings();
        }
        return getRawOffset();
    }

    /**
     * Gets the raw GMT offset and the amount of daylight saving of this
     * time zone at the given time.
     * @param date the milliseconds (since January 1, 1970,
     * 00:00:00.000 GMT) at which the time zone offset and daylight
     * saving amount are found
     * @param offsets an array of int where the raw GMT offset
     * (offset[0]) and daylight saving amount (offset[1]) are stored,
     * or null if those values are not needed. The method assumes that
     * the length of the given array is two or larger.
     * @return the total amount of the raw GMT offset and daylight
     * saving at the specified date.
     *
     * @see Calendar#ZONE_OFFSET
     * @see Calendar#DST_OFFSET
     */
    int getOffsets(long date, int[] offsets) {
        int rawoffset = getRawOffset();
        int dstoffset = 0;
        if (inDaylightTime(new Date(date))) {
            dstoffset = getDSTSavings();
        }
        if (offsets != null) {
            offsets[0] = rawoffset;
            offsets[1] = dstoffset;
        }
        return rawoffset + dstoffset;
    }

    /**
     * Sets the base time zone offset to GMT.
     * This is the offset to add to UTC to get local time.
     *

     * If an underlying {@code TimeZone} implementation subclass
     * supports historical GMT offset changes, the specified GMT
     * offset is set as the latest GMT offset and the difference from
     * the known latest GMT offset value is used to adjust all
     * historical GMT offset values.
     *
     * @param offsetMillis the given base time zone offset to GMT.
     */
    public abstract void setRawOffset(int offsetMillis);

    /**
     * Returns the amount of time in milliseconds to add to UTC to get
     * standard time in this time zone. Because this value is not
     * affected by daylight saving time, it is called raw
     * offset.
     *

     * If an underlying {@code TimeZone} implementation subclass
     * supports historical GMT offset changes, the method returns the
     * raw offset value of the current date. In Honolulu, for example,
     * its raw offset changed from GMT-10:30 to GMT-10:00 in 1947, and
     * this method always returns -36000000 milliseconds (i.e., -10
     * hours).
     *
     * @return the amount of raw offset time in milliseconds to add to UTC.
     * @see Calendar#ZONE_OFFSET
     */
    public abstract int getRawOffset();

    /**
     * Gets the ID of this time zone.
     * @return the ID of this time zone.
     */
    public String getID()
    {
        return ID;
    }

    /**
     * Sets the time zone ID. This does not change any other data in
     * the time zone object.
     * @param ID the new time zone ID.
     */
    public void setID(String ID)
    {
        if (ID == null) {
            throw new NullPointerException();
        }
        this.ID = ID;
        this.zoneId = null;   // invalidate cache
    }

    /**
     * Returns a long standard time name of this {@code TimeZone} suitable for
     * presentation to the user in the default locale.
     *
     *
This method is equivalent to:
     *

     * getDisplayName(false, {@link #LONG},
     *                Locale.getDefault({@link Locale.Category#DISPLAY}))
     *

     *
     * @return the human-readable name of this time zone in the default locale.
     * @since 1.2
     * @see #getDisplayName(boolean, int, Locale)
     * @see Locale#getDefault(Locale.Category)
     * @see Locale.Category
     */
    public final String getDisplayName() {
        return getDisplayName(false, LONG,
                              Locale.getDefault(Locale.Category.DISPLAY));
    }

    /**
     * Returns a long standard time name of this {@code TimeZone} suitable for
     * presentation to the user in the specified {@code locale}.
     *
     *
This method is equivalent to:
     *

     * getDisplayName(false, {@link #LONG}, locale)
     *

     *
     * @param locale the locale in which to supply the display name.
     * @return the human-readable name of this time zone in the given locale.
     * @throws    NullPointerException if {@code locale} is {@code null}.
     * @since 1.2
     * @see #getDisplayName(boolean, int, Locale)
     */
    public final String getDisplayName(Locale locale) {
        return getDisplayName(false, LONG, locale);
    }

    /**
     * Returns a name in the specified {@code style} of this {@code TimeZone}
     * suitable for presentation to the user in the default locale. If the
     * specified {@code daylight} is {@code true}, a Daylight Saving Time name
     * is returned (even if this {@code TimeZone} doesn't observe Daylight Saving
     * Time). Otherwise, a Standard Time name is returned.
     *
     *
This method is equivalent to:
     *

     * getDisplayName(daylight, style,
     *                Locale.getDefault({@link Locale.Category#DISPLAY}))
     *

     *
     * @param daylight {@code true} specifying a Daylight Saving Time name, or
     *                 {@code false} specifying a Standard Time name
     * @param style either {@link #LONG} or {@link #SHORT}
     * @return the human-readable name of this time zone in the default locale.
     * @throws    IllegalArgumentException if {@code style} is invalid.
     * @since 1.2
     * @see #getDisplayName(boolean, int, Locale)
     * @see Locale#getDefault(Locale.Category)
     * @see Locale.Category
     * @see java.text.DateFormatSymbols#getZoneStrings()
     */
    public final String getDisplayName(boolean daylight, int style) {
        return getDisplayName(daylight, style,
                              Locale.getDefault(Locale.Category.DISPLAY));
    }

    /**
     * Returns a name in the specified {@code style} of this {@code TimeZone}
     * suitable for presentation to the user in the specified {@code
     * locale}. If the specified {@code daylight} is {@code true}, a Daylight
     * Saving Time name is returned (even if this {@code TimeZone} doesn't
     * observe Daylight Saving Time). Otherwise, a Standard Time name is
     * returned.
     *
     *
When looking up a time zone name, the {@linkplain
     * ResourceBundle.Control#getCandidateLocales(String,Locale) default
     * {@code Locale} search path of {@code ResourceBundle}} derived
     * from the specified {@code locale} is used. (No {@linkplain
     * ResourceBundle.Control#getFallbackLocale(String,Locale) fallback
     * {@code Locale}} search is performed.) If a time zone name in any
     * {@code Locale} of the search path, including {@link Locale#ROOT}, is
     * found, the name is returned. Otherwise, a string in the
     * normalized custom ID format is returned.
     *
     * @param daylight {@code true} specifying a Daylight Saving Time name, or
     *                 {@code false} specifying a Standard Time name
     * @param style either {@link #LONG} or {@link #SHORT}
     * @param locale   the locale in which to supply the display name.
     * @return the human-readable name of this time zone in the given locale.
     * @throws    IllegalArgumentException if {@code style} is invalid.
     * @throws    NullPointerException if {@code locale} is {@code null}.
     * @since 1.2
     * @see java.text.DateFormatSymbols#getZoneStrings()
     */
    public String getDisplayName(boolean daylight, int style, Locale locale) {
        if (style != SHORT && style != LONG) {
            throw new IllegalArgumentException("Illegal style: " + style);
        }
        String id = getID();
        String name = TimeZoneNameUtility.retrieveDisplayName(id, daylight, style, locale);
        if (name != null) {
            return name;
        }

        if (id.startsWith("GMT") && id.length() > 3) {
            char sign = id.charAt(3);
            if (sign == '+' || sign == '-') {
                return id;
            }
        }
        int offset = getRawOffset();
        if (daylight) {
            offset += getDSTSavings();
        }
        return ZoneInfoFile.toCustomID(offset);
    }

    private static String[] getDisplayNames(String id, Locale locale) {
        return TimeZoneNameUtility.retrieveDisplayNames(id, locale);
    }

    /**
     * Returns the amount of time to be added to local standard time
     * to get local wall clock time.
     *
     *
The default implementation returns 3600000 milliseconds
     * (i.e., one hour) if a call to {@link #useDaylightTime()}
     * returns {@code true}. Otherwise, 0 (zero) is returned.
     *
     *
If an underlying {@code TimeZone} implementation subclass
     * supports historical and future Daylight Saving Time schedule
     * changes, this method returns the amount of saving time of the
     * last known Daylight Saving Time rule that can be a future
     * prediction.
     *
     *
If the amount of saving time at any given time stamp is
     * required, construct a {@link Calendar} with this {@code
     * TimeZone} and the time stamp, and call {@link Calendar#get(int)
     * Calendar.get}{@code (}{@link Calendar#DST_OFFSET}{@code )}.
     *
     * @return the amount of saving time in milliseconds
     * @since 1.4
     * @see #inDaylightTime(Date)
     * @see #getOffset(long)
     * @see #getOffset(int,int,int,int,int,int)
     * @see Calendar#ZONE_OFFSET
     */
    public int getDSTSavings() {
        if (useDaylightTime()) {
            return 3600000;
        }
        return 0;
    }

    /**
     * Queries if this {@code TimeZone} uses Daylight Saving Time.
     *
     *
If an underlying {@code TimeZone} implementation subclass
     * supports historical and future Daylight Saving Time schedule
     * changes, this method refers to the last known Daylight Saving Time
     * rule that can be a future prediction and may not be the same as
     * the current rule. Consider calling {@link #observesDaylightTime()}
     * if the current rule should also be taken into account.
     *
     * @return {@code true} if this {@code TimeZone} uses Daylight Saving Time,
     *         {@code false}, otherwise.
     * @see #inDaylightTime(Date)
     * @see Calendar#DST_OFFSET
     */
    public abstract boolean useDaylightTime();

    /**
     * Returns {@code true} if this {@code TimeZone} is currently in
     * Daylight Saving Time, or if a transition from Standard Time to
     * Daylight Saving Time occurs at any future time.
     *
     *
The default implementation returns {@code true} if
     * {@code useDaylightTime()} or {@code inDaylightTime(new Date())}
     * returns {@code true}.
     *
     * @return {@code true} if this {@code TimeZone} is currently in
     * Daylight Saving Time, or if a transition from Standard Time to
     * Daylight Saving Time occurs at any future time; {@code false}
     * otherwise.
     * @since 1.7
     * @see #useDaylightTime()
     * @see #inDaylightTime(Date)
     * @see Calendar#DST_OFFSET
     */
    public boolean observesDaylightTime() {
        return useDaylightTime() || inDaylightTime(new Date());
    }

    /**
     * Queries if the given {@code date} is in Daylight Saving Time in
     * this time zone.
     *
     * @param date the given Date.
     * @return {@code true} if the given date is in Daylight Saving Time,
     *         {@code false}, otherwise.
     */
    public abstract boolean inDaylightTime(Date date);

    /**
     * Gets the {@code TimeZone} for the given ID.
     *
     * @param ID the ID for a {@code TimeZone}, either an abbreviation
     * such as "PST", a full name such as "America/Los_Angeles", or a custom
     * ID such as "GMT-8:00". Note that the support of abbreviations is
     * for JDK 1.1.x compatibility only and full names should be used.
     *
     * @return the specified {@code TimeZone}, or the GMT zone if the given ID
     * cannot be understood.
     */
    public static synchronized TimeZone getTimeZone(String ID) {
        return getTimeZone(ID, true);
    }

    /**
     * Gets the {@code TimeZone} for the given {@code zoneId}.
     *
     * @param zoneId a {@link ZoneId} from which the time zone ID is obtained
     * @return the specified {@code TimeZone}, or the GMT zone if the given ID
     *         cannot be understood.
     * @throws NullPointerException if {@code zoneId} is {@code null}
     * @since 1.8
     */
    public static TimeZone getTimeZone(ZoneId zoneId) {
        String tzid = zoneId.getId(); // throws an NPE if null
        char c = tzid.charAt(0);
        if (c == '+' || c == '-') {
            tzid = "GMT" + tzid;
        } else if (c == 'Z' && tzid.length() == 1) {
            tzid = "UTC";
        }
        return getTimeZone(tzid, true);
    }

    /**
     * Converts this {@code TimeZone} object to a {@code ZoneId}.
     *
     * @return a {@code ZoneId} representing the same time zone as this
     *         {@code TimeZone}
     * @since 1.8
     */
    public ZoneId toZoneId() {
        ZoneId zId = zoneId;
        if (zId == null) {
            zoneId = zId = toZoneId0();
        }
        return zId;
    }

    private ZoneId toZoneId0() {
        String id = getID();
        TimeZone defaultZone = defaultTimeZone;
        // are we not defaultTimeZone but our id is equal to default's?
        if (defaultZone != this &&
            defaultZone != null && id.equals(defaultZone.getID())) {
            // delegate to default TZ which is effectively immutable
            return defaultZone.toZoneId();
        }
        // derive it ourselves
        if (ZoneInfoFile.useOldMapping() && id.length() == 3) {
            if ("EST".equals(id))
                return ZoneId.of("America/New_York");
            if ("MST".equals(id))
                return ZoneId.of("America/Denver");
            if ("HST".equals(id))
                return ZoneId.of("America/Honolulu");
        }
        return ZoneId.of(id, ZoneId.SHORT_IDS);
    }

    private static TimeZone getTimeZone(String ID, boolean fallback) {
        TimeZone tz = ZoneInfo.getTimeZone(ID);
        if (tz == null) {
            tz = parseCustomTimeZone(ID);
            if (tz == null && fallback) {
                tz = new ZoneInfo(GMT_ID, 0);
            }
        }
        return tz;
    }

    /**
     * Gets the available IDs according to the given time zone offset in milliseconds.
     *
     * @param rawOffset the given time zone GMT offset in milliseconds.
     * @return an array of IDs, where the time zone for that ID has
     * the specified GMT offset. For example, "America/Phoenix" and "America/Denver"
     * both have GMT-07:00, but differ in daylight saving behavior.
     * @see #getRawOffset()
     */
    public static synchronized String[] getAvailableIDs(int rawOffset) {
        return ZoneInfo.getAvailableIDs(rawOffset);
    }

    /**
     * Gets all the available IDs supported.
     * @return an array of IDs.
     */
    public static synchronized String[] getAvailableIDs() {
        return ZoneInfo.getAvailableIDs();
    }

    /**
     * Gets the platform defined TimeZone ID.
     **/
    private static native String getSystemTimeZoneID(String javaHome);

    /**
     * Gets the custom time zone ID based on the GMT offset of the
     * platform. (e.g., "GMT+08:00")
     */
    private static native String getSystemGMTOffsetID();

    /**
     * Gets the default {@code TimeZone} of the Java virtual machine. If the
     * cached default {@code TimeZone} is available, its clone is returned.
     * Otherwise, the method takes the following steps to determine the default
     * time zone.
     *
     *

     *
Use the {@code user.timezone} property value as the default
     * time zone ID if it's available.

     *
Detect the platform time zone ID. The source of the
     * platform time zone and ID mapping may vary with implementation.

     *
Use {@code GMT} as the last resort if the given or detected
     * time zone ID is unknown.

     *

     *
     *
The default {@code TimeZone} created from the ID is cached,
     * and its clone is returned. The {@code user.timezone} property
     * value is set to the ID upon return.
     *
     * @return the default {@code TimeZone}
     * @see #setDefault(TimeZone)
     */
    public static TimeZone getDefault() {
        return (TimeZone) getDefaultRef().clone();
    }

    /**
     * Returns the reference to the default TimeZone object. This
     * method doesn't create a clone.
     */
    static TimeZone getDefaultRef() {
        TimeZone defaultZone = defaultTimeZone;
        if (defaultZone == null) {
            // Need to initialize the default time zone.
            defaultZone = setDefaultZone();
            assert defaultZone != null;
        }
        // Don't clone here.
        return defaultZone;
    }

    private static synchronized TimeZone setDefaultZone() {
        TimeZone tz;
        // get the time zone ID from the system properties
        Properties props = GetPropertyAction.privilegedGetProperties();
        String zoneID = props.getProperty("user.timezone");

        // if the time zone ID is not set (yet), perform the
        // platform to Java time zone ID mapping.
        if (zoneID == null || zoneID.isEmpty()) {
            String javaHome = StaticProperty.javaHome();
            try {
                zoneID = getSystemTimeZoneID(javaHome);
                if (zoneID == null) {
                    zoneID = GMT_ID;
                }
            } catch (NullPointerException e) {
                zoneID = GMT_ID;
            }
        }

        // Get the time zone for zoneID. But not fall back to
        // "GMT" here.
        tz = getTimeZone(zoneID, false);

        if (tz == null) {
            // If the given zone ID is unknown in Java, try to
            // get the GMT-offset-based time zone ID,
            // a.k.a. custom time zone ID (e.g., "GMT-08:00").
            String gmtOffsetID = getSystemGMTOffsetID();
            if (gmtOffsetID != null) {
                zoneID = gmtOffsetID;
            }
            tz = getTimeZone(zoneID, true);
        }
        assert tz != null;

        final String id = zoneID;
        props.setProperty("user.timezone", id);

        defaultTimeZone = tz;
        return tz;
    }

    /**
     * Sets the {@code TimeZone} that is returned by the {@code getDefault}
     * method. {@code zone} is cached. If {@code zone} is null, the cached
     * default {@code TimeZone} is cleared. This method doesn't change the value
     * of the {@code user.timezone} property.
     *
     * @param zone the new default {@code TimeZone}, or null
     * @throws SecurityException if the security manager's {@code checkPermission}
     *                           denies {@code PropertyPermission("user.timezone",
     *                           "write")}
     * @see #getDefault
     * @see PropertyPermission
     */
    public static void setDefault(TimeZone zone)
    {
        @SuppressWarnings("removal")
        SecurityManager sm = System.getSecurityManager();
        if (sm != null) {
            sm.checkPermission(new PropertyPermission
                               ("user.timezone", "write"));
        }
        // by saving a defensive clone and returning a clone in getDefault() too,
        // the defaultTimeZone instance is isolated from user code which makes it
        // effectively immutable. This is important to avoid races when the
        // following is evaluated in ZoneId.systemDefault():
        // TimeZone.getDefault().toZoneId().
        defaultTimeZone = (zone == null) ? null : (TimeZone) zone.clone();
    }

    /**
     * Returns true if this zone has the same rule and offset as another zone.
     * That is, if this zone differs only in ID, if at all.  Returns false
     * if the other zone is null.
     * @param other the {@code TimeZone} object to be compared with
     * @return true if the other zone is not null and is the same as this one,
     * with the possible exception of the ID
     * @since 1.2
     */
    public boolean hasSameRules(TimeZone other) {
        return other != null && getRawOffset() == other.getRawOffset() &&
            useDaylightTime() == other.useDaylightTime();
    }

    /**
     * Creates a copy of this {@code TimeZone}.
     *
     * @return a clone of this {@code TimeZone}
     */
    public Object clone()
    {
        try {
            return super.clone();
        } catch (CloneNotSupportedException e) {
            throw new InternalError(e);
        }
    }

    /**
     * The null constant as a TimeZone.
     */
    static final TimeZone NO_TIMEZONE = null;

    // =======================privates===============================

    /**
     * The string identifier of this {@code TimeZone}.  This is a
     * programmatic identifier used internally to look up {@code TimeZone}
     * objects from the system table and also to map them to their localized
     * display names.  {@code ID} values are unique in the system
     * table but may not be for dynamically created zones.
     * @serial
     */
    private String           ID;

    /**
     * Cached {@link ZoneId} for this TimeZone
     */
    private transient ZoneId zoneId;

    private static volatile TimeZone defaultTimeZone;

    static final String         GMT_ID        = "GMT";
    private static final int    GMT_ID_LENGTH = 3;

    /**
     * Parses a custom time zone identifier and returns a corresponding zone.
     * This method doesn't support the RFC 822 time zone format. (e.g., +hhmm)
     *
     * @param id a string of the custom ID form.
     * @return a newly created TimeZone with the given offset and
     * no daylight saving time, or null if the id cannot be parsed.
     */
    private static final TimeZone parseCustomTimeZone(String id) {
        int length;

        // Error if the length of id isn't long enough or id doesn't
        // start with "GMT".
        if ((length = id.length()) < (GMT_ID_LENGTH + 2) ||
            id.indexOf(GMT_ID) != 0) {
            return null;
        }

        ZoneInfo zi;

        // First, we try to find it in the cache with the given
        // id. Even the id is not normalized, the returned ZoneInfo
        // should have its normalized id.
        zi = ZoneInfoFile.getZoneInfo(id);
        if (zi != null) {
            return zi;
        }

        int index = GMT_ID_LENGTH;
        boolean negative = false;
        char c = id.charAt(index++);
        if (c == '-') {
            negative = true;
        } else if (c != '+') {
            return null;
        }

        int hours = 0;
        int num = 0;
        int countDelim = 0;
        int len = 0;
        while (index < length) {
            c = id.charAt(index++);
            if (c == ':') {
                if (countDelim > 0) {
                    return null;
                }
                if (len > 2) {
                    return null;
                }
                hours = num;
                countDelim++;
                num = 0;
                len = 0;
                continue;
            }
            if (c < '0' || c > '9') {
                return null;
            }
            num = num * 10 + (c - '0');
            len++;
        }
        if (index != length) {
            return null;
        }
        if (countDelim == 0) {
            if (len <= 2) {
                hours = num;
                num = 0;
            } else {
                hours = num / 100;
                num %= 100;
            }
        } else {
            if (len != 2) {
                return null;
            }
        }
        if (hours > 23 || num > 59) {
            return null;
        }
        int gmtOffset =  (hours * 60 + num) * 60 * 1000;

        if (gmtOffset == 0) {
            zi = ZoneInfoFile.getZoneInfo(GMT_ID);
            if (negative) {
                zi.setID("GMT-00:00");
            } else {
                zi.setID("GMT+00:00");
            }
        } else {
            zi = ZoneInfoFile.getCustomTimeZone(id, negative ? -gmtOffset : gmtOffset);
        }
        return zi;
    }
}