text:
package com.wt.calendarcard;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.StateListDrawable;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.*;

import com.wt.calendar_card.R;

public class CalendarCard extends RelativeLayout {

	private TextView cardTitle;
	private int itemLayout = R.layout.card_item_simple;
	private OnItemRender mOnItemRender;
	private OnItemRender mOnItemRenderDefault;
	private OnCellItemClick mOnCellItemClick;
	private Calendar dateDisplay;
	private ArrayList<CheckableLayout> cells = new ArrayList<CheckableLayout>();
	private LinearLayout cardGrid;

	/**
	 * AJOUTE -------------------------
	 */
	List<Date> datesAColorier = new ArrayList<Date>();
	int couleurDates = Color.YELLOW;
	int couleurAujourdHui = Color.parseColor("#7AAFFF");
	boolean refresh = true;

	public boolean isToday(Date date) {
		return inDates(Arrays.asList(new Date()), date);
	}

	public StateListDrawable getStateList(int color) {
		StateListDrawable states = new StateListDrawable();
		states.addState(
				new int[] { android.R.attr.state_pressed },
				new ColorDrawable(getContext().getResources().getColor(
						R.color.bleu_fonce)));
		states.addState(
				new int[] { android.R.attr.state_checked },
				new ColorDrawable(getContext().getResources().getColor(
						R.color.bleu_fonce)));
		states.addState(new int[] {}, new ColorDrawable(color));
		return states;
	}

	public boolean inDates(List<Date> dates, Date date) {
		DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.FULL);
		for (Date d : dates) {
			String s1 = dateFormat.format(date);
			String s2 = dateFormat.format(d);

			if (s1.equals(s2))
				return true;
		}
		return false;
	}

	public void afficherDates(List<Date> dates, int couleur) {
		this.datesAColorier = dates;
		this.couleurDates = couleur;
		couleurAujourdHui = getContext().getResources().getColor(
				R.color.vert_fonce);
		if (refresh) {
			updateCells();
			refresh = !refresh;
		}
	}

	public void refresh() {
		refresh = true;
		updateCells();
		refresh = false;
	}

	/**
	 * -------------------------
	 */

	public CalendarCard(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		init(context);
	}

	public CalendarCard(Context context, AttributeSet attrs) {
		super(context, attrs);
		init(context);
	}

	public CalendarCard(Context context) {
		super(context);
		init(context);
	}

	@SuppressLint("NewApi")
	private void init(Context ctx) {
		if (isInEditMode())
			return;
		View layout = LayoutInflater.from(ctx).inflate(R.layout.card_view,
				null, false);

		if (dateDisplay == null)
			dateDisplay = Calendar.getInstance();

		cardTitle = (TextView) layout.findViewById(R.id.cardTitle);
		cardGrid = (LinearLayout) layout.findViewById(R.id.cardGrid);

		cardTitle
		.setText(new SimpleDateFormat("MMMM yyyy", Locale.getDefault())
		.format(dateDisplay.getTime()));

		Calendar cal = Calendar.getInstance();
		cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
		((TextView) layout.findViewById(R.id.cardDay1)).setText(cal
				.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.SHORT,
						Locale.getDefault()));
		cal.add(Calendar.DAY_OF_WEEK, 1);
		((TextView) layout.findViewById(R.id.cardDay2)).setText(cal
				.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.SHORT,
						Locale.getDefault()));
		cal.add(Calendar.DAY_OF_WEEK, 1);
		((TextView) layout.findViewById(R.id.cardDay3)).setText(cal
				.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.SHORT,
						Locale.getDefault()));
		cal.add(Calendar.DAY_OF_WEEK, 1);
		((TextView) layout.findViewById(R.id.cardDay4)).setText(cal
				.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.SHORT,
						Locale.getDefault()));
		cal.add(Calendar.DAY_OF_WEEK, 1);
		((TextView) layout.findViewById(R.id.cardDay5)).setText(cal
				.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.SHORT,
						Locale.getDefault()));
		cal.add(Calendar.DAY_OF_WEEK, 1);
		((TextView) layout.findViewById(R.id.cardDay6)).setText(cal
				.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.SHORT,
						Locale.getDefault()));
		cal.add(Calendar.DAY_OF_WEEK, 1);
		((TextView) layout.findViewById(R.id.cardDay7)).setText(cal
				.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.SHORT,
						Locale.getDefault()));

		LayoutInflater la = LayoutInflater.from(ctx);
		for (int y = 0; y < cardGrid.getChildCount(); y++) {
			LinearLayout row = (LinearLayout) cardGrid.getChildAt(y);
			for (int x = 0; x < row.getChildCount(); x++) {
				CheckableLayout cell = (CheckableLayout) row.getChildAt(x);

				cell.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						for (CheckableLayout c : cells)
							c.setChecked(false);
						((CheckableLayout) v).setChecked(true);

						if (getOnCellItemClick() != null)
							getOnCellItemClick().onCellClick(v,
									(CardGridItem) v.getTag()); // TODO create
						// item
					}
				});

				View cellContent = la.inflate(itemLayout, cell, false);
				cell.addView(cellContent);
				cells.add(cell);
			}
		}

		addView(layout);

		mOnItemRenderDefault = new OnItemRender() {
			@Override
			public void onRender(CheckableLayout v, CardGridItem item) {
				((TextView) v.getChildAt(0)).setText(item.getDayOfMonth()
						.toString());
			}
		};

		updateCells();
	}

	private int getDaySpacing(int dayOfWeek) {
		if (Calendar.SUNDAY == dayOfWeek)
			return 6;
		else
			return dayOfWeek - 2;
	}

	private int getDaySpacingEnd(int dayOfWeek) {
		return 8 - dayOfWeek;
	}

	private void updateCells() {
		Calendar cal;
		Integer counter = 0;
		if (dateDisplay != null)
			cal = (Calendar) dateDisplay.clone();
		else
			cal = Calendar.getInstance();

		cal.set(Calendar.DAY_OF_MONTH, 1);

		int daySpacing = getDaySpacing(cal.get(Calendar.DAY_OF_WEEK));

		if (daySpacing > 0) {
			Calendar prevMonth = (Calendar) dateDisplay.clone();
			prevMonth.add(Calendar.MONTH, -1);
			prevMonth.set(Calendar.MONTH, prevMonth.get(Calendar.MONTH));

			prevMonth.set(Calendar.DAY_OF_MONTH,
					prevMonth.getActualMaximum(Calendar.DAY_OF_MONTH));
			// Log.wtf("calendarcard- updatecell month",
			// "" + prevMonth.get(Calendar.MONTH));
			// Log.wtf("calendarcard- updatecell nbdays",
			// "" + prevMonth.getMaximum(Calendar.DAY_OF_MONTH));
			int lastDayOfPrevMonth = prevMonth
					.getActualMaximum(Calendar.DAY_OF_MONTH);/* +1 */// the +1 if
			// too much
			for (int i = lastDayOfPrevMonth - daySpacing + 1; i < lastDayOfPrevMonth + 1; i++) {
				CheckableLayout cell = cells.get(counter);
				cell.setTag(new CardGridItem(i).setEnabled(false));
				cell.setEnabled(false);

				try{
					((TextView) cell.getChildAt(0)).setTextColor(Color.GRAY);
					}catch(Exception e){}

				(mOnItemRender == null ? mOnItemRenderDefault : mOnItemRender)
				.onRender(cell, (CardGridItem) cell.getTag());
				counter++;
			}
		}

		int firstDay = cal.get(Calendar.DAY_OF_MONTH);
		cal.set(Calendar.DAY_OF_MONTH,
				cal.getActualMaximum(Calendar.DAY_OF_MONTH));
		int lastDay = cal.get(Calendar.DAY_OF_MONTH) + 1;

		for (int i = firstDay; i < lastDay; i++) {
			cal.set(Calendar.DAY_OF_MONTH, i - 1);
			Calendar date = (Calendar) cal.clone();
			date.add(Calendar.DAY_OF_MONTH, 1);
			CheckableLayout cell = cells.get(counter);
			cell.setTag(new CardGridItem(i).setEnabled(true).setDate(date));

			try{
				((TextView) cell.getChildAt(0)).setTextColor(Color.GRAY);
				}catch(Exception e){}

			/**
			 * AJOUTE ----------------
			 */

			if (refresh) {
				if (isToday(date.getTime())) {
					cell.setBackgroundDrawable(getStateList(couleurAujourdHui));
					((TextView) cell.getChildAt(0)).setTextColor(Color.WHITE);
				} else {
					// DESACTIVER LES DATES ANTERIEURES A AUJOURDHUI
					if (new Date().compareTo(date.getTime()) >= 0) {
						cell.setEnabled(false);
						cell.setBackgroundColor(Color.parseColor("#F0F0F0"));
						((TextView) cell.getChildAt(0)).setTextColor(Color.GRAY);
						((TextView) cell.getChildAt(0)).setTypeface(null, Typeface.BOLD);
					} else {

						if (inDates(this.datesAColorier, date.getTime())) {
							cell.setBackgroundDrawable(getStateList(couleurDates));
							((TextView) cell.getChildAt(0)).setTextColor(Color.WHITE);
							((TextView) cell.getChildAt(0)).setTypeface(null, Typeface.BOLD);
						} else {
							cell.setBackgroundDrawable(getStateList(Color.WHITE));
							((TextView) cell.getChildAt(0)).setTextColor(Color.GRAY);
							((TextView) cell.getChildAt(0)).setTypeface(null, Typeface.BOLD);
						}

						cell.setEnabled(true);
					}

				}
			}

			/**
			 * ----------------
			 */

			cell.setVisibility(View.VISIBLE);
			(mOnItemRender == null ? mOnItemRenderDefault : mOnItemRender)
			.onRender(cell, (CardGridItem) cell.getTag());
			counter++;
		}

		if (dateDisplay != null)
			cal = (Calendar) dateDisplay.clone();
		else
			cal = Calendar.getInstance();

		cal.set(Calendar.DAY_OF_MONTH,
				cal.getActualMaximum(Calendar.DAY_OF_MONTH));

		daySpacing = getDaySpacingEnd(cal.get(Calendar.DAY_OF_WEEK));

		if (daySpacing > 0) {
			for (int i = 0; i < daySpacing; i++) {
				CheckableLayout cell = cells.get(counter);
				cell.setTag(new CardGridItem(i + 1).setEnabled(false)); // .setDate((Calendar)cal.clone())
				cell.setEnabled(false);
				cell.setBackgroundColor(Color.parseColor("#F0F0F0"));

				try{
				((TextView) cell.getChildAt(0)).setTextColor(Color.GRAY);
				}catch(Exception e){}

				cell.setVisibility(View.VISIBLE);
				(mOnItemRender == null ? mOnItemRenderDefault : mOnItemRender)
				.onRender(cell, (CardGridItem) cell.getTag());
				counter++;
			}
		}

		if (counter < cells.size()) {
			for (int i = counter; i < cells.size(); i++) {
				cells.get(i).setVisibility(View.GONE);
			}
		}
	}

	@Override
	protected void onLayout(boolean changed, int l, int t, int r, int b) {
		super.onLayout(changed, l, t, r, b);
		if (changed && cells.size() > 0) {
			int size = (r - l) / 7;
			for (CheckableLayout cell : cells) {
				cell.getLayoutParams().height = size;
			}
		}
	}

	public int getItemLayout() {
		return itemLayout;
	}

	public void setItemLayout(int itemLayout) {
		this.itemLayout = itemLayout;
		// mCardGridAdapter.setItemLayout(itemLayout);
	}

	public OnItemRender getOnItemRender() {
		return mOnItemRender;
	}

	public void setOnItemRender(OnItemRender mOnItemRender) {
		this.mOnItemRender = mOnItemRender;
		// mCardGridAdapter.setOnItemRender(mOnItemRender);
	}

	public Calendar getDateDisplay() {
		return dateDisplay;
	}

	public void setDateDisplay(Calendar dateDisplay) {
		this.dateDisplay = dateDisplay;
		String mois = new SimpleDateFormat("MMMM yyyy", Locale.getDefault())
		.format(dateDisplay.getTime());
		mois = String.valueOf(mois.charAt(0)).toUpperCase()
				+ mois.subSequence(1, mois.length());
		cardTitle.setText(mois);

		cardTitle.setTextColor(Color.WHITE);
		cardTitle.setTypeface(null, Typeface.BOLD);
	}

	public OnCellItemClick getOnCellItemClick() {
		return mOnCellItemClick;
	}

	public void setOnCellItemClick(OnCellItemClick mOnCellItemClick) {
		this.mOnCellItemClick = mOnCellItemClick;
	}

	/**
	 * call after change any input data - to refresh view
	 */
	public void notifyChanges() {
		// mCardGridAdapter.init();
		updateCells();
	}

}


text:
set -e
echo "${OS_DISTRO}: Configuring messaging"
################################################################################
. /etc/os-container.env
. /opt/harbor/service-hosts.sh
. /opt/harbor/harbor-common.sh
. /opt/harbor/zun/vars.sh

################################################################################
check_required_vars ZUN_CONFIG_FILE \
                    OS_DOMAIN \
                    AUTH_MESSAGING_PASS \
                    AUTH_MESSAGING_USER \
                    RABBITMQ_SERVICE_HOST_SVC \
                    ZUN_DB_KEY \
                    ZUN_DB_CERT \
                    ZUN_DB_CA

echo "${OS_DISTRO}: RPC Backend"
################################################################################
crudini --set ${ZUN_CONFIG_FILE} DEFAULT rpc_backend "rabbit"

echo "${OS_DISTRO}: Connection"
################################################################################
crudini --set ${ZUN_CONFIG_FILE} oslo_messaging_rabbit rabbit_use_ssl "True"

crudini --set ${ZUN_CONFIG_FILE} oslo_messaging_rabbit rabbit_host "${RABBITMQ_SERVICE_HOST_SVC}"
crudini --set ${ZUN_CONFIG_FILE} oslo_messaging_rabbit rabbit_port "5672"
crudini --set ${ZUN_CONFIG_FILE} oslo_messaging_rabbit rabbit_hosts "${RABBITMQ_SERVICE_HOST_SVC}:5672"

crudini --set ${ZUN_CONFIG_FILE} oslo_messaging_rabbit rabbit_userid "${AUTH_MESSAGING_USER}"
crudini --set ${ZUN_CONFIG_FILE} oslo_messaging_rabbit rabbit_password "${AUTH_MESSAGING_PASS}"

echo "${OS_DISTRO}: TLS"
################################################################################
crudini --set ${ZUN_CONFIG_FILE} oslo_messaging_rabbit kombu_ssl_version "TLSv1_2"
crudini --set ${ZUN_CONFIG_FILE} oslo_messaging_rabbit kombu_ssl_keyfile "${ZUN_DB_KEY}"
crudini --set ${ZUN_CONFIG_FILE} oslo_messaging_rabbit kombu_ssl_certfile "${ZUN_DB_CERT}"
crudini --set ${ZUN_CONFIG_FILE} oslo_messaging_rabbit kombu_ssl_ca_certs "${ZUN_DB_CA}"

echo "${OS_DISTRO}: Rabbit Config"
################################################################################
crudini --set ${ZUN_CONFIG_FILE} oslo_messaging_rabbit rabbit_virtual_host "/"
crudini --set ${ZUN_CONFIG_FILE} oslo_messaging_rabbit rabbit_ha_queues "False"
crudini --set ${ZUN_CONFIG_FILE} oslo_messaging_rabbit amqp_durable_queues "False"

echo "${OS_DISTRO}: Config"
################################################################################
crudini --set ${ZUN_CONFIG_FILE} DEFAULT instance_usage_audit "True"
crudini --set ${ZUN_CONFIG_FILE} DEFAULT instance_usage_audit_period "hour"
crudini --set ${ZUN_CONFIG_FILE} DEFAULT notify_on_state_change "vm_and_task_state"
crudini --set ${ZUN_CONFIG_FILE} oslo_messaging_notifications driver "messagingv2"

redpajama_set_name: RedPajamaGithub


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

#include "chrome/test/webdriver/webdriver_util.h"

#include "base/base64.h"
#include "base/basictypes.h"
#include "base/file_util.h"
#include "base/files/file_enumerator.h"
#include "base/files/scoped_temp_dir.h"
#include "base/format_macros.h"
#include "base/json/json_reader.h"
#include "base/json/json_writer.h"
#include "base/memory/scoped_ptr.h"
#include "base/rand_util.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_split.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/third_party/icu/icu_utf.h"
#include "chrome/common/automation_id.h"
#include "chrome/test/automation/automation_json_requests.h"
#include "third_party/zlib/google/zip.h"

using base::DictionaryValue;
using base::ListValue;
using base::Value;

namespace webdriver {

SkipParsing* kSkipParsing = NULL;

std::string GenerateRandomID() {
  uint64 msb = base::RandUint64();
  uint64 lsb = base::RandUint64();
  return base::StringPrintf("%016" PRIx64 "%016" PRIx64, msb, lsb);
}

bool Base64Decode(const std::string& base64,
                  std::string* bytes) {
  std::string copy = base64;
  // Some WebDriver client base64 encoders follow RFC 1521, which require that
  // 'encoded lines be no more than 76 characters long'. Just remove any
  // newlines.
  RemoveChars(copy, "\n", &copy);
  return base::Base64Decode(copy, bytes);
}

namespace {

bool UnzipArchive(const base::FilePath& unzip_dir,
                  const std::string& bytes,
                  std::string* error_msg) {
  base::ScopedTempDir dir;
  if (!dir.CreateUniqueTempDir()) {
    *error_msg = "Unable to create temp dir";
    return false;
  }
  base::FilePath archive = dir.path().AppendASCII("temp.zip");
  int length = bytes.length();
  if (file_util::WriteFile(archive, bytes.c_str(), length) != length) {
    *error_msg = "Could not write file to temp dir";
    return false;
  }
  if (!zip::Unzip(archive, unzip_dir)) {
    *error_msg = "Could not unzip archive";
    return false;
  }
  return true;
}

}  // namespace

bool Base64DecodeAndUnzip(const base::FilePath& unzip_dir,
                          const std::string& base64,
                          std::string* error_msg) {
  std::string zip_data;
  if (!Base64Decode(base64, &zip_data)) {
    *error_msg = "Could not decode base64 zip data";
    return false;
  }
  return UnzipArchive(unzip_dir, zip_data, error_msg);
}

namespace {

// Stream for writing binary data.
class DataOutputStream {
 public:
  DataOutputStream() {}
  ~DataOutputStream() {}

  void WriteUInt16(uint16 data) {
    WriteBytes(&data, sizeof(data));
  }

  void WriteUInt32(uint32 data) {
    WriteBytes(&data, sizeof(data));
  }

  void WriteString(const std::string& data) {
    WriteBytes(data.c_str(), data.length());
  }

  void WriteBytes(const void* bytes, int size) {
    size_t next = buffer_.length();
    buffer_.resize(next + size);
    memcpy(&buffer_[next], bytes, size);
  }

  const std::string& buffer() const { return buffer_; }

 private:
  std::string buffer_;
};

// Stream for reading binary data.
class DataInputStream {
 public:
  DataInputStream(const char* data, int size)
      : data_(data), size_(size), iter_(0) {}
  ~DataInputStream() {}

  bool ReadUInt16(uint16* data) {
    return ReadBytes(data, sizeof(*data));
  }

  bool ReadUInt32(uint32* data) {
    return ReadBytes(data, sizeof(*data));
  }

  bool ReadString(std::string* data, int length) {
    if (length < 0)
      return false;
    // Check here to make sure we don't allocate wastefully.
    if (iter_ + length > size_)
      return false;
    data->resize(length);
    return ReadBytes(&(*data)[0], length);
  }

  bool ReadBytes(void* bytes, int size) {
    if (iter_ + size > size_)
      return false;
    memcpy(bytes, &data_[iter_], size);
    iter_ += size;
    return true;
  }

  int remaining() const { return size_ - iter_; }

 private:
  const char* data_;
  int size_;
  int iter_;
};

// A file entry within a zip archive. This may be incomplete and is not
// guaranteed to be able to parse all types of zip entries.
// See http://www.pkware.com/documents/casestudies/APPNOTE.TXT for the zip
// file format.
struct ZipEntry {
  // The given bytes must contain the whole zip entry and only the entry,
  // although the entry may include a data descriptor.
  static bool FromBytes(const std::string& bytes, ZipEntry* zip,
                        std::string* error_msg) {
    DataInputStream stream(bytes.c_str(), bytes.length());

    uint32 signature;
    if (!stream.ReadUInt32(&signature) || signature != kFileHeaderSignature) {
      *error_msg = "Invalid file header signature";
      return false;
    }
    if (!stream.ReadUInt16(&zip->version_needed)) {
      *error_msg = "Invalid version";
      return false;
    }
    if (!stream.ReadUInt16(&zip->bit_flag)) {
      *error_msg = "Invalid bit flag";
      return false;
    }
    if (!stream.ReadUInt16(&zip->compression_method)) {
      *error_msg = "Invalid compression method";
      return false;
    }
    if (!stream.ReadUInt16(&zip->mod_time)) {
      *error_msg = "Invalid file last modified time";
      return false;
    }
    if (!stream.ReadUInt16(&zip->mod_date)) {
      *error_msg = "Invalid file last modified date";
      return false;
    }
    if (!stream.ReadUInt32(&zip->crc)) {
      *error_msg = "Invalid crc";
      return false;
    }
    uint32 compressed_size;
    if (!stream.ReadUInt32(&compressed_size)) {
      *error_msg = "Invalid compressed size";
      return false;
    }
    if (!stream.ReadUInt32(&zip->uncompressed_size)) {
      *error_msg = "Invalid compressed size";
      return false;
    }
    uint16 name_length;
    if (!stream.ReadUInt16(&name_length)) {
      *error_msg = "Invalid name length";
      return false;
    }
    uint16 field_length;
    if (!stream.ReadUInt16(&field_length)) {
      *error_msg = "Invalid field length";
      return false;
    }
    if (!stream.ReadString(&zip->name, name_length)) {
      *error_msg = "Invalid name";
      return false;
    }
    if (!stream.ReadString(&zip->fields, field_length)) {
      *error_msg = "Invalid fields";
      return false;
    }
    if (zip->bit_flag & 0x8) {
      // Has compressed data and a separate data descriptor.
      if (stream.remaining() < 16) {
        *error_msg = "Too small for data descriptor";
        return false;
      }
      compressed_size = stream.remaining() - 16;
      if (!stream.ReadString(&zip->compressed_data, compressed_size)) {
        *error_msg = "Invalid compressed data before descriptor";
        return false;
      }
      if (!stream.ReadUInt32(&signature) ||
          signature != kDataDescriptorSignature) {
        *error_msg = "Invalid data descriptor signature";
        return false;
      }
      if (!stream.ReadUInt32(&zip->crc)) {
        *error_msg = "Invalid crc";
        return false;
      }
      if (!stream.ReadUInt32(&compressed_size)) {
        *error_msg = "Invalid compressed size";
        return false;
      }
      if (compressed_size != zip->compressed_data.length()) {
        *error_msg = "Compressed data does not match data descriptor";
        return false;
      }
      if (!stream.ReadUInt32(&zip->uncompressed_size)) {
        *error_msg = "Invalid compressed size";
        return false;
      }
    } else {
      // Just has compressed data.
      if (!stream.ReadString(&zip->compressed_data, compressed_size)) {
        *error_msg = "Invalid compressed data";
        return false;
      }
      if (stream.remaining() != 0) {
        *error_msg = "Leftover data after zip entry";
        return false;
      }
    }
    return true;
  }

  // Returns bytes for a valid zip file that just contains this zip entry.
  std::string ToZip() {
    // Write zip entry with no data descriptor.
    DataOutputStream stream;
    stream.WriteUInt32(kFileHeaderSignature);
    stream.WriteUInt16(version_needed);
    stream.WriteUInt16(bit_flag);
    stream.WriteUInt16(compression_method);
    stream.WriteUInt16(mod_time);
    stream.WriteUInt16(mod_date);
    stream.WriteUInt32(crc);
    stream.WriteUInt32(compressed_data.length());
    stream.WriteUInt32(uncompressed_size);
    stream.WriteUInt16(name.length());
    stream.WriteUInt16(fields.length());
    stream.WriteString(name);
    stream.WriteString(fields);
    stream.WriteString(compressed_data);
    uint32 entry_size = stream.buffer().length();

    // Write central directory.
    stream.WriteUInt32(kCentralDirSignature);
    stream.WriteUInt16(0x14);  // Version made by. Unused at version 0.
    stream.WriteUInt16(version_needed);
    stream.WriteUInt16(bit_flag);
    stream.WriteUInt16(compression_method);
    stream.WriteUInt16(mod_time);
    stream.WriteUInt16(mod_date);
    stream.WriteUInt32(crc);
    stream.WriteUInt32(compressed_data.length());
    stream.WriteUInt32(uncompressed_size);
    stream.WriteUInt16(name.length());
    stream.WriteUInt16(fields.length());
    stream.WriteUInt16(0);  // Comment length.
    stream.WriteUInt16(0);  // Disk number where file starts.
    stream.WriteUInt16(0);  // Internal file attr.
    stream.WriteUInt32(0);  // External file attr.
    stream.WriteUInt32(0);  // Offset to file.
    stream.WriteString(name);
    stream.WriteString(fields);
    uint32 cd_size = stream.buffer().length() - entry_size;

    // End of central directory.
    stream.WriteUInt32(kEndOfCentralDirSignature);
    stream.WriteUInt16(0);  // num of this disk
    stream.WriteUInt16(0);  // disk where cd starts
    stream.WriteUInt16(1);  // number of cds on this disk
    stream.WriteUInt16(1);  // total cds
    stream.WriteUInt32(cd_size);  // size of cd
    stream.WriteUInt32(entry_size);  // offset of cd
    stream.WriteUInt16(0);  // comment len

    return stream.buffer();
  }

  static const uint32 kFileHeaderSignature;
  static const uint32 kDataDescriptorSignature;
  static const uint32 kCentralDirSignature;
  static const uint32 kEndOfCentralDirSignature;
  uint16 version_needed;
  uint16 bit_flag;
  uint16 compression_method;
  uint16 mod_time;
  uint16 mod_date;
  uint32 crc;
  uint32 uncompressed_size;
  std::string name;
  std::string fields;
  std::string compressed_data;
};

const uint32 ZipEntry::kFileHeaderSignature = 0x04034b50;
const uint32 ZipEntry::kDataDescriptorSignature = 0x08074b50;
const uint32 ZipEntry::kCentralDirSignature = 0x02014b50;
const uint32 ZipEntry::kEndOfCentralDirSignature = 0x06054b50;

bool UnzipEntry(const base::FilePath& unzip_dir,
                const std::string& bytes,
                std::string* error_msg) {
  ZipEntry entry;
  std::string zip_error_msg;
  if (!ZipEntry::FromBytes(bytes, &entry, &zip_error_msg)) {
    *error_msg = "Error while reading zip entry: " + zip_error_msg;
    return false;
  }
  std::string archive = entry.ToZip();
  return UnzipArchive(unzip_dir, archive, error_msg);
}

}  // namespace

bool UnzipSoleFile(const base::FilePath& unzip_dir,
                   const std::string& bytes,
                   base::FilePath* file,
                   std::string* error_msg) {
  std::string archive_error, entry_error;
  if (!UnzipArchive(unzip_dir, bytes, &archive_error) &&
      !UnzipEntry(unzip_dir, bytes, &entry_error)) {
    *error_msg = base::StringPrintf(
        "Failed to unzip file: Archive error: (%s) Entry error: (%s)",
        archive_error.c_str(), entry_error.c_str());
    return false;
  }

  base::FileEnumerator enumerator(unzip_dir, false /* recursive */,
      base::FileEnumerator::FILES | base::FileEnumerator::DIRECTORIES);
  base::FilePath first_file = enumerator.Next();
  if (first_file.empty()) {
    *error_msg = "Zip contained 0 files";
    return false;
  }
  base::FilePath second_file = enumerator.Next();
  if (!second_file.empty()) {
    *error_msg = "Zip contained multiple files";
    return false;
  }
  *file = first_file;
  return true;
}

std::string JsonStringify(const Value* value) {
  std::string json;
  base::JSONWriter::Write(value, &json);
  return json;
}

namespace {

// Truncates the given string to 100 characters, adding an ellipsis if
// truncation was necessary.
void TruncateString(std::string* data) {
  const size_t kMaxLength = 100;
  if (data->length() > kMaxLength) {
    data->resize(kMaxLength);
    data->replace(kMaxLength - 3, 3, "...");
  }
}

// Truncates all strings contained in the given value.
void TruncateContainedStrings(Value* value) {
  ListValue* list = NULL;
  DictionaryValue* dict = NULL;
  if (value->GetAsDictionary(&dict)) {
    for (DictionaryValue::Iterator it(*dict); !it.IsAtEnd(); it.Advance()) {
      std::string data;
      if (it.value().GetAsString(&data)) {
        TruncateString(&data);
        dict->SetWithoutPathExpansion(it.key(), new base::StringValue(data));
      } else {
        Value* child = NULL;
        dict->GetWithoutPathExpansion(it.key(), &child);
        TruncateContainedStrings(child);
      }
    }
  } else if (value->GetAsList(&list)) {
    for (size_t i = 0; i < list->GetSize(); ++i) {
      Value* child;
      if (!list->Get(i, &child))
        continue;
      std::string data;
      if (child->GetAsString(&data)) {
        TruncateString(&data);
        list->Set(i, new base::StringValue(data));
      } else {
        TruncateContainedStrings(child);
      }
    }
  }
}

}  // namespace

std::string JsonStringifyForDisplay(const Value* value) {
  scoped_ptr<Value> copy;
  if (value->IsType(Value::TYPE_STRING)) {
    std::string data;
    value->GetAsString(&data);
    TruncateString(&data);
    copy.reset(new base::StringValue(data));
  } else {
    copy.reset(value->DeepCopy());
    TruncateContainedStrings(copy.get());
  }
  std::string json;
  base::JSONWriter::WriteWithOptions(copy.get(),
                                     base::JSONWriter::OPTIONS_PRETTY_PRINT,
                                     &json);
  return json;
}

const char* GetJsonTypeName(Value::Type type) {
  switch (type) {
    case Value::TYPE_NULL:
      return "null";
    case Value::TYPE_BOOLEAN:
      return "boolean";
    case Value::TYPE_INTEGER:
      return "integer";
    case Value::TYPE_DOUBLE:
      return "double";
    case Value::TYPE_STRING:
      return "string";
    case Value::TYPE_BINARY:
      return "binary";
    case Value::TYPE_DICTIONARY:
      return "dictionary";
    case Value::TYPE_LIST:
      return "list";
  }
  return "unknown";
}

std::string AutomationIdToString(const AutomationId& id) {
  return base::StringPrintf("%d-%s", id.type(), id.id().c_str());
}

bool StringToAutomationId(const std::string& string_id, AutomationId* id) {
  std::vector<std::string> split_id;
  base::SplitString(string_id, '-', &split_id);
  if (split_id.size() != 2)
    return false;
  int type;
  if (!base::StringToInt(split_id[0], &type))
    return false;
  *id = AutomationId(static_cast<AutomationId::Type>(type), split_id[1]);
  return true;
}

std::string WebViewIdToString(const WebViewId& view_id) {
  return base::StringPrintf(
      "%s%s",
      view_id.old_style() ? "t" : "f",
      AutomationIdToString(view_id.GetId()).c_str());
}

bool StringToWebViewId(const std::string& string_id, WebViewId* view_id) {
  if (string_id.empty() || (string_id[0] != 'f' && string_id[0] != 't'))
    return false;
  bool old_style = string_id[0] == 't';
  AutomationId id;
  if (!StringToAutomationId(string_id.substr(1), &id))
    return false;

  if (old_style) {
    int tab_id;
    if (!base::StringToInt(id.id(), &tab_id))
      return false;
    *view_id = WebViewId::ForOldStyleTab(tab_id);
  } else {
    *view_id = WebViewId::ForView(id);
  }
  return true;
}

Error* FlattenStringArray(const ListValue* src, string16* dest) {
  string16 keys;
  for (size_t i = 0; i < src->GetSize(); ++i) {
    string16 keys_list_part;
    src->GetString(i, &keys_list_part);
    for (size_t j = 0; j < keys_list_part.size(); ++j) {
      if (CBU16_IS_SURROGATE(keys_list_part[j])) {
        return new Error(kBadRequest,
                         "ChromeDriver only supports characters in the BMP");
      }
    }
    keys.append(keys_list_part);
  }
  *dest = keys;
  return NULL;
}

ValueParser::ValueParser() { }

ValueParser::~ValueParser() { }

}  // namespace webdriver

bool ValueConversionTraits<webdriver::SkipParsing>::SetFromValue(
    const Value* value, const webdriver::SkipParsing* t) {
  return true;
}

bool ValueConversionTraits<webdriver::SkipParsing>::CanConvert(
    const Value* value) {
  return true;
}


text:
// Copyright 2021 The Oppia Authors. All Rights Reserved.
//
// 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.

/**
 * @fileoverview Component for the blog admin page.
 */

import { Component, OnInit } from '@angular/core';
import { downgradeComponent } from '@angular/upgrade/static';

import { BlogAdminBackendApiService, ConfigPropertiesBackendResponse, ConfigPropertyValues }
  from 'domain/blog-admin/blog-admin-backend-api.service';
import { BlogAdminDataService } from 'pages/blog-admin-page/services/blog-admin-data.service';
import { AdminTaskManagerService } from 'pages/admin-page/services/admin-task-manager.service';
import { Schema } from 'services/schema-default-value.service';
import { WindowRef } from 'services/contextual/window-ref.service';
import { RoleToActionsBackendResponse } from 'domain/admin/admin-backend-api.service';

interface UpdateRoleAction {
  // 'newRole' is 'null' when the form is refreshed.
  newRole: string | null;
  username: string;
  isValid: () => boolean;
}

interface RemoveEditorRole {
  username: string;
  isValid: () => boolean;
}

interface FormData {
  updateRole: UpdateRoleAction;
  removeEditorRole: RemoveEditorRole;
}

type ConfigPropertyValuesRecord = (
  Record<keyof ConfigPropertyValues, string[] | number>);

@Component({
  selector: 'oppia-blog-admin-page',
  templateUrl: './blog-admin-page.component.html',
})
export class BlogAdminPageComponent implements OnInit {
  // These properties are initialized using Angular lifecycle hooks
  // and we need to do non-null assertion, for more information see
  // https://github.com/oppia/oppia/wiki/Guide-on-defining-types#ts-7-1
  roleToActions!: RoleToActionsBackendResponse;
  formData!: FormData;
  UPDATABLE_ROLES = {};
  statusMessage: string = '';
  configProperties: ConfigPropertiesBackendResponse = {};
  constructor(
    private backendApiService: BlogAdminBackendApiService,
    private blogAdminDataService: BlogAdminDataService,
    private adminTaskManagerService: AdminTaskManagerService,
    private windowRef: WindowRef,
  ) {}

  ngOnInit(): void {
    this.refreshFormData();
    this.blogAdminDataService.getDataAsync().then((DataObject) => {
      this.UPDATABLE_ROLES = DataObject.updatableRoles;
      this.roleToActions = DataObject.roleToActions;
    });
    this.reloadConfigProperties();
  }

  refreshFormData(): void {
    this.formData = {
      updateRole: {
        newRole: null,
        username: '',
        isValid(): boolean {
          if (this.newRole === 'BLOG_POST_EDITOR') {
            return Boolean(this.username);
          } else if (this.newRole === 'BLOG_ADMIN') {
            return Boolean(this.username);
          }
          return false;
        }
      },
      removeEditorRole: {
        username: '',
        isValid(): boolean {
          if (this.username === '') {
            return false;
          }
          return true;
        }
      }
    };
  }

  submitUpdateRoleForm(formResponse: UpdateRoleAction): void {
    if (this.adminTaskManagerService.isTaskRunning()) {
      return;
    }
    this.statusMessage = 'Updating User Role';
    this.adminTaskManagerService.startTask();
    this.backendApiService.updateUserRoleAsync(
      // Update role button will not be enabled if 'newRole' is 'null'.
      // hence whenever this method is called 'newRole' will exist and
      // we can safely typecast it to a 'string'.
      formResponse.newRole as string, formResponse.username,
    ).then(() => {
      this.statusMessage = (
        'Role of ' + formResponse.username + ' successfully updated to ' +
        formResponse.newRole);
      this.refreshFormData();
    }, errorResponse => {
      this.statusMessage = 'Server error: ' + errorResponse;
    });
    this.adminTaskManagerService.finishTask();
  }

  submitRemoveEditorRoleForm(
      formResponse: RemoveEditorRole): void {
    if (this.adminTaskManagerService.isTaskRunning()) {
      return;
    }
    this.statusMessage = 'Processing query...';
    this.adminTaskManagerService.startTask();
    this.backendApiService.removeBlogEditorAsync(
      formResponse.username
    ).then(() => {
      this.statusMessage = 'Success.';
      this.refreshFormData();
    }, error => {
      this.statusMessage = 'Server error: ' + error.error.error;
    });
    this.adminTaskManagerService.finishTask();
  }

  reloadConfigProperties(): void {
    this.blogAdminDataService.getDataAsync().then((DataObject) => {
      this.configProperties = DataObject.configProperties;
    });
  }

  getSchemaCallback(schema: Schema): () => Schema {
    return () => {
      return schema;
    };
  }

  revertToDefaultConfigPropertyValue(configPropertyId: string): void {
    if (!this.windowRef.nativeWindow.confirm(
      'This action is irreversible. Are you sure?')) {
      return;
    }

    this.backendApiService.revertConfigPropertyAsync(configPropertyId)
      .then(() => {
        this.statusMessage = 'Config property reverted successfully.';
        this.reloadConfigProperties();
      }, errorResponse => {
        this.statusMessage = 'Server error: ' + errorResponse;
      });
  }

  saveConfigProperties(): void {
    if (this.adminTaskManagerService.isTaskRunning()) {
      return;
    }
    if (!this.windowRef.nativeWindow.confirm(
      'This action is irreversible. Are you sure?')) {
      return;
    }

    this.statusMessage = 'Saving...';

    this.adminTaskManagerService.startTask();
    let newConfigPropertyValues = {} as ConfigPropertyValuesRecord;
    for (let property in this.configProperties) {
      const prop = property as keyof ConfigPropertyValues;
      newConfigPropertyValues[prop] = this.configProperties[prop].value;
    }

    this.backendApiService.saveConfigPropertiesAsync(
      newConfigPropertyValues as ConfigPropertyValues).then(() => {
      this.statusMessage = 'Data saved successfully.';
      this.adminTaskManagerService.finishTask();
    }, errorResponse => {
      this.statusMessage = 'Server error: ' + errorResponse;
      this.adminTaskManagerService.finishTask();
    });
  }
}

angular.module('oppia').directive(
  'oppiaBlogAdminPage', downgradeComponent(
    {component: BlogAdminPageComponent}));


text:
import unittest
import os
import shutil

from sublime.util import get_exe_dir
from sublime.core import Episode
from sublime.core import NamePattern as pattern

# -----------------------------------------------------------------------------
#
# EpisodeTestCase class
#
# -----------------------------------------------------------------------------
class EpisodeTestCase(unittest.TestCase):
    """ Tests Episode class functions. """

    def setUp(self):
        self.video_filename = os.path.join(
            get_exe_dir(), 'Tests', 'Fixtures', 'movie.avi')
        self.expected_renamed_video_filename = os.path.join(
            get_exe_dir(), 'Tests', 'Fixtures', 'Twin_Peaks_S01E01_Pilot.avi')
        self.expected_renamed_new_pattern_video_filename = os.path.join(
            get_exe_dir(), 'Tests', 'Fixtures', 'Twin_Peaks_1x01_Pilot.avi')
        self.expected_renamed_video_filename_without_underscore = os.path.join(
            get_exe_dir(), 'Tests', 'Fixtures', 'Twin Peaks S01E01 Pilot.avi')

    def test_change_pattern(self):
        """ Tests that the rename method use different
        pattern defined by user. """
        new_pattern = "{serie_name}_{season}x{episode:02d}_{episode_name}"

        episode = Episode(self.video_filename)
        episode.name = "Twin Peaks"
        episode.season = 1
        episode.episode = 1
        episode.episode_name = "Pilot"

        # Rename episode with default pattern
        episode.rename()
        self.assertTrue(os.path.exists(self.expected_renamed_video_filename))

        # Rename again with a new pattern
        with pattern(new_pattern):
            episode.rename()
        self.assertTrue(os.path.exists(
            self.expected_renamed_new_pattern_video_filename))

        # Rename again without underscore
        with pattern(underscore=False):
            episode.rename()
        self.assertTrue(os.path.exists(
            self.expected_renamed_video_filename_without_underscore))

    def tearDown(self):
        """ Clean up """
        if os.path.exists(self.expected_renamed_video_filename):
            shutil.move(
                self.expected_renamed_video_filename, self.video_filename)

        if os.path.exists(self.expected_renamed_new_pattern_video_filename):
            shutil.move(
                self.expected_renamed_new_pattern_video_filename,
                self.video_filename)

        if os.path.exists(
                self.expected_renamed_video_filename_without_underscore):
            shutil.move(
                self.expected_renamed_video_filename_without_underscore,
                self.video_filename)

if __name__ == "__main__":
    unittest.main()

# EOF


text:
#region Apache License Version 2.0

#endregion Apache License Version 2.0

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Senparc.CO2NET.Helpers;
using Senparc.Weixin.Helpers;
using Senparc.Weixin.MP.Helpers;

namespace Senparc.Weixin.MP.Test
{
    [TestClass]
    public class DateTimeHelperTest
    {
        long timeStamp = 1358061152;
        DateTimeOffset expect = new DateTimeOffset(2013, 1, 13, 15, 12, 32,TimeSpan.Zero);

        /// <summary>
        /// 测试Unix时间(基本方法)
        /// </summary>
        [TestMethod]
        public void UnixTimeTest()
        {
            var result = DateTimeHelper.BaseTime.AddTicks((timeStamp + 8 * 60 * 60) * 10000000);
            Assert.AreEqual(expect, result);
        }

        [TestMethod]
        public void GetDateTimeFromXmlTest()
        {
            var result = DateTimeHelper.GetDateTimeFromXml(timeStamp);
            Assert.AreEqual(expect, result);

            var result2 = DateTimeHelper.GetDateTimeFromXml(1432094942);
            Console.WriteLine(result2);
        }

         [TestMethod]
        public void GetWeixinDateTimeTest()
        {
            var result = DateTimeHelper.GetUnixDateTime(expect);
            Assert.AreEqual(timeStamp, result);
        }
    }
}


text:
<?php

namespace LPC\Mocks;

use Blainesch\LaravelPrettyController\Action\PrettyController;

class MockController extends PrettyController {

	public function indexAction()
	{
		return ['name' => 'blainesch'];
	}

}


text:
@interface OZLModelIssueStatus : NSObject

@property(nonatomic) int index;
@property(nonatomic, strong) NSString* name;

-(id)initWithDictionary:(NSDictionary*)dic;

@end


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"/>

  <title>movies</title>
  <meta name="author" content="" />
  <meta name="description"
        content=""/>

  <meta name="yandex-verification" content="48a8210fc043c5e8" />

  <meta name="generator" content="Hugo 0.54.0" />

  <meta itemprop="name" content="movies"/>
  <meta itemprop="description"
        content=""/>
  <meta itemprop="image"
        content="/img/logo.svg"/>

  <meta property="og:title" content="movies"/>
  <meta property="og:type"
        content="website"/>
  <meta property="og:url" content="http://www.cinetenisverde.com.br/categories/movies/"/>
  <meta property="og:image"
        content="/img/logo.svg"/>
  <meta property="og:description"
        content=""/>
  <meta property="og:site_name" content="Cine Tênis Verde"/>
  <meta property="article:section" content="categories"/>

  <meta name="twitter:card" content="summary"/>
  <meta name="twitter:site"
        content=""/>
  <meta name="twitter:title" content="movies"/>
  <meta name="twitter:description"
        content=""/>
  <meta name="twitter:creator"
        content=""/>
  <meta name="twitter:image:src"
        content="/img/logo.svg"/>

  <link href="http://www.cinetenisverde.com.br/categories/movies/index.xml" rel="alternate" type="application/rss+xml"
        title="Cine Tênis Verde"/>
  <link href="http://www.cinetenisverde.com.br/categories/movies/index.xml" rel="feed" type="application/rss+xml"
        title="Cine Tênis Verde"/>

  <link rel="stylesheet" type="text/css" href="/css/capsule.min.css"/>
  <link rel="stylesheet" type="text/css" href="/css/custom.css"/>

  <link rel="apple-touch-icon" href="/img/apple-touch-icon.png"/>
  <link rel="icon" href="/img/favicon.ico"/>

 Cine Tênis Verde

    <input type="checkbox" id="navbar-burger-state"/>

      search

      twitter

      rss

Category: movies

A Morte lhe Cai Bem

      Nov 2, 2013
      1 min.

Comédia da sessão da tarde feita nos anos 90, era um filme engraçadinho com efeitos visuais de espantar. Hoje se transformou em uma surpreendente crítica aos cosméticos e uma direção extremamente inspirada de Robert Zemeckis (O Voo), que já naquela época prezava pelo controle e expressão do tom do filme através dos nada sutil enquadramentos.
O importante é que o filme envelheceu muito bem, e manteve sua qualidade sobretudo nos efeitos visuais e maquiagem, que são partes vitais da narrativa.

South Park Maior Melhor e Sem Cortes

      Nov 2, 2013
      2 min.

Não é nenhuma novidade que South Park preza pelo irreverente e polêmico em prol da comédia e, principalmente, na análise da estupidez humana (espectadores inclusos). No seu longa-metragem, portanto, nada muda. O diferencial é um frescor de piadas sobre os últimos acontecimentos no mundo que seriam feitas na versão televisiva de uma forma ou outra.
Só que o estilo do seriado atira para todos os lados, e atira mais forte na moral americana que combate sexo e palavrões, mas favorece e até incentiva a violência, em um caráter permanentemente pró-bélico.

Era uma Vez em Tóquio

      Oct 31, 2013
      2 min.

Tokyo Story, ou Era Uma Vez em Tóquio, como seus títulos ocidentais sugerem, é um conto, que se constrói no Japão pós-guerra e faz uma dura crítica à sociedade ocidentalista da época, mas como todo grande filme se torna atual mesmo 50 anos depois pelas suas mensagens eternas sobre vida e família.
Iniciando com uma viagem do marido e esposa já aposentados que vão se encontrar com seus filhos em Tóquio, vão aos poucos percebendo que a cidade grande e seus afazeres da vida moderna não têm tempo nem espaço para acomodá-los, com exceção de sua amável nora, que parece sempre priorizar o bem estar dos seus sogros mesmo que este não sejam de fato sua família e que seu marido já tenha falecido há mais de oito anos na guerra.

O Vento Está Soprando

      Oct 28, 2013
      2 min.

Não há o que criticar da perfeição técnica dos estúdios Ghibli. Acostumados a entregar desenhos que já seriam motivo de prazer e satisfação só de olhar, os filmes dirigidos pelo mestre Hayao Miyazaki prezam também por uma história completa, uma trilha sonora, uma fotografia, direção de arte, efeitos sonoros que representam juntos sempre o ápice daquele estilo.
Aqui fugimos um pouco do mundo de fantasia de trabalhos como Ponyo e A Viagem de Chihiro para conhecermos a vida de Jiro (Hideaki Anno), um designer de aviões japonês que trabalhou durante a época da segunda guerra.

Giuseppe Tornatore Todo Filme é Meu Primeiro Filme

      Oct 26, 2013
      1 min.

Giuseppe Tornatore (Baária, Malena, Uma Simples Formalidade, A Lenda do Pianista do Mar) é visto nesse documentário-homenagem quase que na superfície e de uma forma bem burocrática. Não há grandes momentos, salvo poucas e elegantes transições - como a que envolve o diretor olhar para o topo do extinto cinema onde era projecionista e encontrar os sinos da igreja de Cinema Paradiso - e em contrapartida há muitos planos de entrevista seguindo o modelo “ator fala sobre diretor e tece elogios quase genéricos sobre seu trabalho”, o que torna a experiência parecida com os extras do DVD.

Los tentados

      Oct 26, 2013
      1 min.

Primeiro longa do diretor Mariano Blanco, não existem muitas ideias a serem seguidas em Los Tentados, ou elas estão tão sutilmente colocadas ali que fica difícil encontrar base para qualquer tipo de interpretação.
Acompanhando a rotina de um casal pobre que mora próximo de uma praia e que mantém uma rotina quase que banal, o tédio explorado no filme encontra respaldo pelos longos e intermináveis quadros que não se fecham, como o que inicia a história com a moça dormindo de manhã na cama.

Os Suspeitos

      Oct 25, 2013
      3 min.

O cansaço, desânimo e um envolvimento ilimitado na busca de duas meninas desaparecidas é o que forma a base de Os Suspeitos, mantida todo o tempo por três pilares fundamentais: o detetive e o pai incansáveis formam dois deles; a direção impecável de Denis Villeneuve (do excelente Incêndios) no desenvolvimento da trama forma o terceiro.
Construindo a tensão mesmo antes que as duas crianças sumam usando a figura do furgão como uma ameaça sem rosto, o Dia de Ação de Graças entre os vizinhos vira um pesadelo em questão de segundos.

O Grande Golpe

      Oct 24, 2013
      2 min.

A partir da apresentação dos personagens de O Grande Golpe, o diretor Stanley Kubrick vai aos poucos revelando que a “operação” em torno da qual gira o filme está muito bem arquitetada e vem sendo planejada cuidadosamente por todas as partes envolvidas: um tira corrupto, um apostador de cavalos, um barman, um caixa do guichê de apostas, entre tantos outros.
Não sabemos a história de todos, mas focamos na vida de dois deles: o caixa e o mandante da quadrilha.

2001: Uma Odisseia no Espaço

      Oct 23, 2013
      2 min.

A obra maior de Stanley Kubrick - ou pelo menos a mais ambiciosa e enigmática - permanece em seu auge mesmo mais de 45 anos depois da estreia. Diferente de filmes que podem ser compreendidos no conforto de sua casa, este é dos que deve ser degustado no espaço sagrado do Cinema. Aliás, ele funciona tão bem nessas condições que assinaria uma petição para que fosse exibido eternamente em uma sala tombada pelo patrimônio da humanidade.

Aqui é o Meu Lugar

      Oct 20, 2013
      2 min.

Sean Penn é um excelente ator, diga-se de passagem. Mas nesse trabalho em que ele coloca uma peruca (que insiste em assoprar) e fala como se fosse desmaiar a qualquer momento é daqueles típicos casos de vergonha alheia.
Não há nada que se defenda no filme do diretor italiano Paolo Sorrentino exceto seus detalhes técnicos. A fotografia é limpa e exuberante, exibindo tomadas grandiosas (como a do estádio construído atrás de um simpático e pacato bairro) e horizontes quase infinitos.

  Previous
  Next

      1

      …

      115

      116

      117

      …

175


text:
create type NodeType as enum (
  'ground',
  'stairs_up'
);

create type Direction as enum (
  'right',
  'left',
  'up',
  'down'
);

create table grid (
  id serial primary key,
  name text not null unique,
  created timestamp not null default now()
);

create table block (
  id serial primary key,
  grid integer not null references grid (id),
  size point not null,
  properties text[ ],
  direction Direction not null
);

create table node (
  id serial not null primary key,
  block integer not null references block (id),
  kind NodeType not null,
  size point not null,
  location point not null,
  attributes jsonb
);

create table geometry (
  id serial not null primary key,
  node integer not null references node (id),
  left_face integer[ ][ ] not null,
  top_face integer[ ][ ] not null,
  right_face integer[ ][ ] not null,
  bottom_face integer[ ][ ] not null,
  front_face integer[ ][ ] not null,
  back_face integer[ ][ ] not null,
  bezel integer[ ][ ]
);


text:
package org.springframework.core;

import java.lang.reflect.Method;
import java.lang.reflect.Type;

import junit.framework.TestCase;

/**
 * @author Serge Bogatyrjov
 */
public abstract class AbstractGenericsTests extends TestCase {

	protected Class<?> targetClass;

	protected String methods[];

	protected Type expectedResults[];

	protected void executeTest() throws NoSuchMethodException {
		String methodName = getName().substring(4);
		methodName = methodName.substring(0, 1).toLowerCase() + methodName.substring(1);
		for (int i = 0; i < this.methods.length; i++) {
			if (methodName.equals(this.methods[i])) {
				Method method = this.targetClass.getMethod(methodName);
				Type type = getType(method);
				assertEquals(this.expectedResults[i], type);
				return;
			}
		}
		throw new IllegalStateException("Bad test data");
	}

	protected abstract Type getType(Method method);

}


text:
import { Injectable } from '@angular/core';
import { ToastController } from 'ionic-angular';

@Injectable()
export class ToastProvider {
  constructor(private toastCtrl: ToastController) {}

  public info(message: string) {
    this.toastCtrl.create({ message, duration: 3000 }).present();
  }

  public error(message: string) {
    this.toastCtrl.create({ message, duration: 3000 }).present();
  }
}


text:
package com.yuzhouwan.hacker.enums

object Enums extends Enumeration {
  type enums = Value
  val E, N, U, M, OTHER = Value

  def main(args: Array[String]): Unit = {
    assert(convert2Enums("E").getOrElse(Enums.OTHER).equals(Enums.E))
    assert(convert2Enums2("N").getOrElse(Enums.OTHER).equals(Enums.N))
    assert(convert2Enums3("U").getOrElse(Enums.OTHER).equals(Enums.U))
    assert(convert2Enums4("M").getOrElse(Enums.OTHER).equals(Enums.M))
  }

  // normal
  // equals 方法检查的是:值是否相等
  def convert2Enums(enums: String): Option[enums] = {
    Enums.values.find(x => x.toString.equals(enums))
  }

  // bad
  def convert2Enums2(enums: String): Option[enums] = {
    Enums.values.find(_.toString.equals(enums))
  }

  // better
  def convert2Enums3(enums: String): Option[enums] = {
    Enums.values.find(_.toString eq enums)
  }

  // same as `eq`
  // eq 和 == 检查的是:引用是否相同
  def convert2Enums4(enums: String): Option[enums] = {
    Enums.values.find(_.toString == enums)
  }
}


text:
import installGlobalHook from '../../backend/utils/installGlobalHook';

const script = document.createElement('script');
script.textContent = `;(${installGlobalHook.toString()}(window))`;
document.documentElement.appendChild(script);
script.parentNode.removeChild(script);

// if (__DEV__) {
window.addEventListener('test-open-mobx-devtools-window', () => {
  console.log('test-open-mobx-devtools-window'); // eslint-disable-line no-console
  chrome.runtime.sendMessage({ eventName: 'open-mobx-devtools-window' });
});
// }


text:
@protocol CACameraSessionDelegate <NSObject>

@optional - (void)didCaptureImage:(UIImage *)image;
@optional - (void)didCaptureImageWithData:(NSData *)imageData;
@optional - (void)didTapDismiss;

@end

@interface CameraSessionView : UIView

//Delegate Property
@property (nonatomic, weak) id <CACameraSessionDelegate> delegate;

//API Functions
- (void)setTopBarColor:(UIColor *)topBarColor;
- (void)hideFlashButton;
- (void)hideCameraToogleButton;
- (void)hideDismissButton;

@end


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>SpTree</title>
<meta name="date" content="2016-09-19">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.deeplearning4j.clustering.sptree

Class SpTree

java.lang.Object

org.deeplearning4j.clustering.sptree.SpTree

All Implemented Interfaces:

java.io.Serializable

public class SpTree
extends java.lang.Object
implements java.io.Serializable

See Also:

Serialized Form

Field Summary

Fields

Modifier and Type
Field and Description

static int
NODE_RATIO

Constructor Summary

Constructors

Constructor and Description

SpTree(INDArray data)

SpTree(INDArray data,
      java.util.Set<INDArray> indices)

SpTree(INDArray data,
      java.util.Set<INDArray> indices,
      java.lang.String similarityFunction)

SpTree(SpTree parent,
      INDArray data,
      INDArray corner,
      INDArray width,
      java.util.Set<INDArray> indices)

SpTree(SpTree parent,
      INDArray data,
      INDArray corner,
      INDArray width,
      java.util.Set<INDArray> indices,
      java.lang.String similarityFunction)

Method Summary

All Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

void
computeEdgeForces(INDArray rowP,
                 INDArray colP,
                 INDArray valP,
                 int N,
                 INDArray posF)

Compute edge forces using barns hut

void
computeNonEdgeForces(int pointIndex,
                    double theta,
                    INDArray negativeForce,
                    com.google.common.util.concurrent.AtomicDouble sumQ)

Compute non edge forces using barnes hut

int
depth()

The depth of the node

Cell
getBoundary()

INDArray
getCenterOfMass()

SpTree[]
getChildren()

int
getCumSize()

int
getD()

int[]
getIndex()

int
getNumChildren()

boolean
isCorrect()

Verifies the structure of the tree (does bounds checking on each node)

boolean
isLeaf()

void
setCumSize(int cumSize)

void
setNumChildren(int numChildren)

void
subDivide()

Subdivide the node in to
 4 children

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

NODE_RATIO

public static final int NODE_RATIO

See Also:

Constant Field Values

Constructor Detail

SpTree

public SpTree(SpTree parent,
              INDArray data,
              INDArray corner,
              INDArray width,
              java.util.Set<INDArray> indices,
              java.lang.String similarityFunction)

SpTree

public SpTree(INDArray data,
              java.util.Set<INDArray> indices,
              java.lang.String similarityFunction)

SpTree

public SpTree(SpTree parent,
              INDArray data,
              INDArray corner,
              INDArray width,
              java.util.Set<INDArray> indices)

SpTree

public SpTree(INDArray data,
              java.util.Set<INDArray> indices)

SpTree

public SpTree(INDArray data)

Method Detail

subDivide

public void subDivide()

Subdivide the node in to
 4 children

computeNonEdgeForces

public void computeNonEdgeForces(int pointIndex,
                                 double theta,
                                 INDArray negativeForce,
                                 com.google.common.util.concurrent.AtomicDouble sumQ)

Compute non edge forces using barnes hut

Parameters:

pointIndex -

theta -

negativeForce -

sumQ -

computeEdgeForces

public void computeEdgeForces(INDArray rowP,
                              INDArray colP,
                              INDArray valP,
                              int N,
                              INDArray posF)

Compute edge forces using barns hut

Parameters:

rowP - a vector

colP -

valP -

N - the number of elements

posF - the positive force

isLeaf

public boolean isLeaf()

isCorrect

public boolean isCorrect()

Verifies the structure of the tree (does bounds checking on each node)

Returns:

true if the structure of the tree
 is correct.

depth

public int depth()

The depth of the node

Returns:

the depth of the node

getChildren

public SpTree[] getChildren()

getD

public int getD()

getCenterOfMass

public INDArray getCenterOfMass()

getBoundary

public Cell getBoundary()

getIndex

public int[] getIndex()

getCumSize

public int getCumSize()

setCumSize

public void setCumSize(int cumSize)

getNumChildren

public int getNumChildren()

setNumChildren

public void setNumChildren(int numChildren)

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
using System;
using System.Data;
using System.Windows.Forms;
using dbFactory;
using DevExpress.XtraEditors;

namespace Productos
{
    public partial class frmProductos : Form
    {
        public frmProductos()
        {
            InitializeComponent();
            scBuscar.Client = gridProductos;

        }

        private void btnNuevo_Click(object sender, EventArgs e)
        {
            frmNuevoProducto nuevo = new frmNuevoProducto();
            if(nuevo.ShowDialog() == DialogResult.OK)
            {
                loadData();
            }
        }

        private void btnCategorias_Click(object sender, EventArgs e)
        {
            frmCategorias cat = new frmCategorias();
            cat.ShowDialog();
        }

        private void frmProductos_Load(object sender, EventArgs e)
        {
            loadData();
            gridViewProductos.Columns[0].AppearanceCell.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
            gridViewProductos.Columns[1].AppearanceCell.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
            gridViewProductos.Columns[2].AppearanceCell.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
            gridViewProductos.Columns[3].AppearanceCell.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
            gridViewProductos.Columns[0].AppearanceHeader.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
            gridViewProductos.Columns[1].AppearanceHeader.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
            gridViewProductos.Columns[2].AppearanceHeader.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
            gridViewProductos.Columns[3].AppearanceHeader.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
            gridViewProductos.Appearance.HeaderPanel.Font = new System.Drawing.Font("Segoe UI", 10.5F, System.Drawing.FontStyle.Bold);
            this.MdiParent.Cursor = DefaultCursor;
        }

        private void btnEliminar_Click(object sender, EventArgs e)
        {
            this.eliminarProducto();
        }

        private void btnEditar_Click(object sender, EventArgs e)
        {
            DataRow datos = gridViewProductos.GetFocusedDataRow();
            if(new frmNuevoProducto(datos).ShowDialog() == DialogResult.OK)
            {
                loadData();
            }

        }

        private void gridViewProductos_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyValue == 46)
            {
                this.eliminarProducto();
            }
        }

        private void eliminarProducto()
        {
            if (XtraMessageBox.Show("Esta a punto de eliminar este registro!\nDesea Continuar?", "Advertencia!", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
            {
                if (db.connect())
                {
                    DataRow datos = gridViewProductos.GetFocusedDataRow();
                    if (db.executeNonQuery("delete from productos where nombre=@nombre AND presentacion=@presentacion;", new String[] { "@nombre", "@presentacion" }, new object[] { datos.ItemArray[0].ToString(), datos.ItemArray[2].ToString() }) != -1)
                    {
                        loadData();
                        return;
                    }
                }
                XtraMessageBox.Show("Error al intentar borrar el registro!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void loadData()
        {
            if (db.connect())
            {
                gridProductos.DataSource = db.executeQuery("select p.nombre,pc.descripcion as categoria,p.presentacion,p.cantidad_lote as 'Cantidad por Lote' from productos p, producto_categoria pc where p.id_categoria = pc.id_categoria order by p.nombre") ?? new DataTable();
            }
        }

    }
}


text:
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}

module Deserializer
( parseTMachine
) where

import qualified Data.ByteString.Lazy as BS
import Data.HashMap.Lazy ( HashMap(..)
                         , fromList
                         , toList
                         )
import Data.Aeson
import qualified Turing as T

data TransitionInput = TransitionInput { action ::String
                                       , read' :: String
                                       , toState :: String
                                       , write :: String
                                       } deriving (Show)

data MachineInput = MachineInput { name :: String
                                 , alphabet :: [String]
                                 , blank :: String
                                 , states :: [String]
                                 , initial :: String
                                 , finals :: [String]
                                 , transitions :: HashMap String [TransitionInput]
                                 } deriving (Show)

instance FromJSON TransitionInput where
    parseJSON = withObject "TransitionInput" $ \o -> do
        { action <- o .: "action"
        ; read' <- o .: "read"
        ; toState <- o .: "to_state"
        ; write <- o .: "write"
        ; return TransitionInput{..}
        }

instance FromJSON MachineInput where
    parseJSON = withObject "MachineInput" $ \o -> do
        { name <- o .: "name"
        ; alphabet <- o .: "alphabet"
        ; blank <- o .: "blank"
        ; states <- o .: "states"
        ; initial <- o .: "initial"
        ; finals <- o .: "finals"
        ; transitions' <- o .: "transitions"
        ; transitions <- parseJSON transitions'
        ; return MachineInput{..}
        }

-- Turn a string into an Action
stringToAction :: String -> T.Action
stringToAction "LEFT" = T.MoveLeft
stringToAction "RIGHT" = T.MoveRight
stringToAction _ = error "Unknown action"

-- Turn a TransitionInput into a TransitionAction
inputToAction :: TransitionInput -> T.TransitionAction
inputToAction (TransitionInput taction tread ttoState twrite)
    = T.TransitionAction ttoState (head twrite) (stringToAction taction)

inputToTransitions1 :: String -> TransitionInput -> ((String, Char), T.TransitionAction)
inputToTransitions1 s input = ((s, (head . read') input), inputToAction input)

inputToTransitions2 :: (String, [TransitionInput]) -> [((String, Char), T.TransitionAction)]
inputToTransitions2 (s, xs) = fmap (inputToTransitions1 s) xs

inputToTransitions :: HashMap String [TransitionInput] -> HashMap (String, Char) T.TransitionAction
inputToTransitions = fromList . concat . (fmap inputToTransitions2) . toList

-- Return a TuringMachine for a MachineInput
inputToTMachine :: MachineInput -> T.TuringMachine
inputToTMachine (MachineInput mname malpha mblank mstates minit mfinals mtransitions)
    = T.TuringMachine mname (concat malpha) (head mblank) mstates minit
                      mfinals (inputToTransitions mtransitions)

-- Parse a Turing Machine from a ByteString
parseTMachine :: BS.ByteString -> Maybe T.TuringMachine
parseTMachine = (fmap inputToTMachine) . decode


text:
extern NSString *const BKAssertFailureTitleString;

@interface BKAssertFailHandler : BKAssertHandler

// Default fail hanlder will do the default action based on the BKAssertMode.
// If you sub-class this class, call this class method to invoke the proper fail (eg. abort, exception, breakpoint, etc)
+ (void)defaultFailActionHandler:(BKAssertMode)mode description:(NSString *)description;

- (void)handleFailureWithCondition:(NSString *)condition function:(NSString *)function file:(NSString *)file line:(NSInteger)line description:(NSString *)format arguments:(va_list)arguments backtrace:(NSArray *)backtrace;

@end


text:
{% extends "layout.html" %}

{% block page_title %}
Upload pattern
{% endblock %}

{% block head %}
{% include "includes/head.html" %}
{% include "includes/scripts.html" %}
{% endblock %}

{% import "templates/button.html" as button %}

{% block content %}

    {% include "includes/phase_banner_beta.html" %}
    {% include "includes/buttons/back.html" %}

Upload pattern

            <form class="form" onsubmit="return false;">

                    <fieldset>
                        <legend class="visuallyhidden">Upload keeper evidence</legend>

Tell the user what to upload here

                                    Choose a file to upload

                                <input id="fileInput" type="file" name="multiple-vehicles" accept="">

Accepted file types: zip, doc, docx, jpg, png, gif, pdf, xls, xlsx, csv
Maximum file size: 5MB

                            {{ button.input(id='continue', name='continue', class='button margin-top-1', type='button', value='Upload and continue') }}

                    </fieldset>

            </form>

{% endblock %}


text:
<ion-modal-view>
  <ion-header-bar>

Submit Comment on Dish

      <button class="button button-clear button-positive" ng-click="closeAddCommentForm()">Close</button>

  </ion-header-bar>
  <ion-content>
    <form ng-submit="doAddComment()">

          Rating
          <select ng-model="mycomment.rating">
            <option ng-repeat="n in [1,2,3,4,5]" value="{{n}}">{{n}}</option>
          </select>

          Your Name
          <input type="text" ng-model="mycomment.author">

          Your Comment
          <input type="text" ng-model="mycomment.comment">

          <button class="button button-block button-positive" type="submit">Submit</button>

    </form>
  </ion-content>
</ion-modal-view>