code
stringlengths
4
1.01M
<?php namespace Doctrine\Bundle\DoctrineBundle\Tests\DependencyInjection; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Loader\YamlFileLoader; use Symfony\Component\Config\FileLocator; class YamlDoctrineExtensionTest extends AbstractDoctrineExtensionTest { protected function loadFromFile(ContainerBuilder $container, $file) { $loadYaml = new YamlFileLoader($container, new FileLocator(__DIR__.'/Fixtures/config/yml')); $loadYaml->load($file.'.yml'); } }
<?php namespace Moeketsi\AclAdminControlPanel\Http\Controllers; use Illuminate\Foundation\Bus\DispatchesJobs; use Illuminate\Routing\Controller as BaseController; use Illuminate\Foundation\Validation\ValidatesRequests; use Illuminate\Foundation\Auth\Access\AuthorizesRequests; class Controller extends BaseController { use AuthorizesRequests, DispatchesJobs, ValidatesRequests; }
#!/usr/bin/env python # A Raspberry Pi GPIO based relay device import RPi.GPIO as GPIO from common.adafruit.Adafruit_MCP230xx.Adafruit_MCP230xx import Adafruit_MCP230XX class Relay(object): _mcp23017_chip = {} # Conceivably, we could have up to 8 of these as there are a possibility of 8 MCP chips on a bus. def __init__(self, mcp_pin, i2c_address=0x27): """ Initialize a relay :param mcp_pin: BCM gpio number that is connected to a relay :return: """ self.ON = 0 self.OFF = 1 self._i2c_address = i2c_address self._mcp_pin = mcp_pin if GPIO.RPI_REVISION == 1: i2c_busnum = 0 else: i2c_busnum = 1 if not self._mcp23017_chip.has_key(self._i2c_address): self._mcp23017_chip[self._i2c_address] = Adafruit_MCP230XX(busnum=i2c_busnum, address=self._i2c_address, num_gpios=16) self._relay = self._mcp23017_chip[self._i2c_address] self._relay.config(self._mcp_pin, self._relay.OUTPUT) self._relay.output(self._mcp_pin, self.OFF) self.state = self.OFF def set_state(self, state): """ Set the state of the relay. relay.ON, relay.OFF :param state: :return: """ if state == self.ON: self._relay.output(self._mcp_pin, self.ON) self.state = self.ON elif state == self.OFF: self._relay.output(self._mcp_pin, self.OFF) self.state = self.OFF def toggle(self): """ Toggle the state of a relay :return: """ if self.state == self.ON: self._relay.output(self._mcp_pin, self.OFF) self.state = self.OFF else: self._relay.output(self._mcp_pin, self.ON) self.state = self.ON def get_state(self): return self.state if __name__ == '__main__': import time pause = .15 for pin in range(16): print("Pin: %s" % pin) r = Relay(pin) r.set_state(r.ON) time.sleep(pause) r.set_state(r.OFF) time.sleep(pause) r.toggle() time.sleep(pause) r.toggle() time.sleep(pause) r1 = Relay(10) r2 = Relay(2) r3 = Relay(15) r1.set_state(r1.ON) print(r1._mcp_pin) r2.set_state(r2.ON) print(r2._mcp_pin) r3.set_state(r3.ON) print(r3._mcp_pin) time.sleep(1) r1.set_state(r1.OFF) r2.set_state(r2.OFF) r3.set_state(r3.OFF)
var accessToken="i7LM4k7JcSKs4ucCpxpgNPcs3i1kRbNKyUE8aPGKZzZWASagz9uZiuLgmgDgBJzY"; $(window).load(function() { $('#pseudo_submit').click(function() { NProgress.start(); $.ajax({ type: "POST", url: "../db-app/signdown.php", dataType: 'text', data: { password: $("#basic_pass").val() }, complete: function(xhr, statusText){ NProgress.done(); }, success: function (res) { console.log(res); if(res.indexOf("ERR")==-1) { delete_schedule(res); } else { new PNotify({ title: 'Error :(', text: "Something went wrong", type: 'error', styling: 'bootstrap3' }); } } }); }); }); function delete_schedule(id) { NProgress.start(); var del_url = "https://api.whenhub.com/api/schedules/"+id+"?access_token="+accessToken; $.ajax({ type: "DELETE", url: del_url, complete: function(xhr, statusText){ NProgress.done(); console.log(xhr.status+" "+statusText); }, success: function (data) { console.log(data); window.location.href = "account_deleted.php"; }, error: function(xhr, statusText, err){ console.log(xhr); console.log(statusText); console.log(err); } }); }
package net.glowstone.io.entity; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.UUID; import java.util.stream.Collectors; import net.glowstone.entity.AttributeManager; import net.glowstone.entity.AttributeManager.Property; import net.glowstone.entity.GlowLivingEntity; import net.glowstone.entity.objects.GlowLeashHitch; import net.glowstone.io.nbt.NbtSerialization; import net.glowstone.util.InventoryUtil; import net.glowstone.util.nbt.CompoundTag; import org.bukkit.Location; import org.bukkit.attribute.AttributeModifier; import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; import org.bukkit.entity.LeashHitch; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; import org.bukkit.inventory.EntityEquipment; import org.bukkit.inventory.ItemStack; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; public abstract class LivingEntityStore<T extends GlowLivingEntity> extends EntityStore<T> { public LivingEntityStore(Class<T> clazz, String type) { super(clazz, type); } public LivingEntityStore(Class<T> clazz, EntityType type) { super(clazz, type); } // these tags that apply to living entities only are documented as global: // - short "Air" // - string "CustomName" // - bool "CustomNameVisible" // todo: the following tags // - float "AbsorptionAmount" // - short "HurtTime" // - int "HurtByTimestamp" // - short "DeathTime" // - bool "PersistenceRequired" // on ActiveEffects, bool "ShowParticles" @Override public void load(T entity, CompoundTag compound) { super.load(entity, compound); compound.readShort("Air", entity::setRemainingAir); compound.readString("CustomName", entity::setCustomName); compound.readBoolean("CustomNameVisible", entity::setCustomNameVisible); if (!compound.readFloat("HealF", entity::setHealth)) { compound.readShort("Health", entity::setHealth); } compound.readShort("AttackTime", entity::setNoDamageTicks); compound.readBoolean("FallFlying", entity::setFallFlying); compound.iterateCompoundList("ActiveEffects", effect -> { // should really always have every field, but be forgiving if possible if (!effect.isByte("Id") || !effect.isInt("Duration")) { return; } PotionEffectType type = PotionEffectType.getById(effect.getByte("Id")); int duration = effect.getInt("Duration"); if (type == null || duration < 0) { return; } final int amplifier = compound.tryGetInt("Amplifier").orElse(0); boolean ambient = compound.getBoolean("Ambient", false); // bool "ShowParticles" entity.addPotionEffect(new PotionEffect(type, duration, amplifier, ambient), true); }); EntityEquipment equip = entity.getEquipment(); if (equip != null) { loadEquipment(entity, equip, compound); } compound.readBoolean("CanPickUpLoot", entity::setCanPickupItems); AttributeManager am = entity.getAttributeManager(); compound.iterateCompoundList("Attributes", tag -> { if (!tag.isString("Name") || !tag.isDouble("Base")) { return; } List<AttributeModifier> modifiers = new ArrayList<>(); tag.iterateCompoundList("Modifiers", modifierTag -> { if (modifierTag.isDouble("Amount") && modifierTag.isString("Name") && modifierTag.isInt("Operation") && modifierTag.isLong("UUIDLeast") && modifierTag.isLong("UUIDMost")) { modifiers.add(new AttributeModifier( new UUID(modifierTag.getLong("UUIDLeast"), modifierTag.getLong("UUIDMost")), modifierTag.getString("Name"), modifierTag.getDouble("Amount"), AttributeModifier.Operation.values()[modifierTag.getInt("Operation")])); } }); AttributeManager.Key key = AttributeManager.Key.fromName(tag.getString("Name")); am.setProperty(key, tag.getDouble("Base"), modifiers); }); Optional<CompoundTag> maybeLeash = compound.tryGetCompound("Leash"); if (maybeLeash.isPresent()) { CompoundTag leash = maybeLeash.get(); if (!leash.readUuid("UUIDMost", "UUIDLeast", entity::setLeashHolderUniqueId) && leash.isInt("X") && leash.isInt("Y") && leash.isInt("Z")) { int x = leash.getInt("X"); int y = leash.getInt("Y"); int z = leash.getInt("Z"); LeashHitch leashHitch = GlowLeashHitch .getLeashHitchAt(new Location(entity.getWorld(), x, y, z).getBlock()); entity.setLeashHolder(leashHitch); } } else { compound.readBoolean("Leashed", leashSet -> { if (leashSet) { // We know that there was something leashed, but not what entity it was // This can happen, when for example Minecart got leashed // We still have to make sure that we drop a Leash Item entity.setLeashHolderUniqueId(UUID.randomUUID()); } }); } } private void loadEquipment(T entity, EntityEquipment equip, CompoundTag compound) { // Deprecated since 15w31a, left here for compatibilty for now compound.readCompoundList("Equipment", list -> { equip.setItemInMainHand(getItem(list, 0)); equip.setBoots(getItem(list, 1)); equip.setLeggings(getItem(list, 2)); equip.setChestplate(getItem(list, 3)); equip.setHelmet(getItem(list, 4)); }); // Deprecated since 15w31a, left here for compatibilty for now compound.readFloatList("DropChances", list -> { equip.setItemInMainHandDropChance(getOrDefault(list, 0, 1f)); equip.setBootsDropChance(getOrDefault(list, 1, 1f)); equip.setLeggingsDropChance(getOrDefault(list, 2, 1f)); equip.setChestplateDropChance(getOrDefault(list, 3, 1f)); equip.setHelmetDropChance(getOrDefault(list, 4, 1f)); }); compound.readCompoundList("HandItems", list -> { equip.setItemInMainHand(getItem(list, 0)); equip.setItemInOffHand(getItem(list, 1)); }); compound.readCompoundList("ArmorItems", list -> { equip.setBoots(getItem(list, 0)); equip.setLeggings(getItem(list, 1)); equip.setChestplate(getItem(list, 2)); equip.setHelmet(getItem(list, 3)); }); // set of dropchances on a player throws an UnsupportedOperationException if (!(entity instanceof Player)) { compound.readFloatList("HandDropChances", list -> { equip.setItemInMainHandDropChance(getOrDefault(list, 0, 1f)); equip.setItemInOffHandDropChance(getOrDefault(list, 1, 1f)); }); compound.readFloatList("ArmorDropChances", list -> { equip.setBootsDropChance(getOrDefault(list, 0, 1f)); equip.setLeggingsDropChance(getOrDefault(list, 1, 1f)); equip.setChestplateDropChance(getOrDefault(list, 2, 1f)); equip.setHelmetDropChance(getOrDefault(list, 3, 1f)); }); } } private ItemStack getItem(List<CompoundTag> list, int index) { if (list == null) { return InventoryUtil.createEmptyStack(); } if (index >= list.size()) { return InventoryUtil.createEmptyStack(); } return NbtSerialization.readItem(list.get(index)); } private float getOrDefault(List<Float> list, int index, float defaultValue) { if (list == null) { return defaultValue; } if (index >= list.size()) { return defaultValue; } return list.get(index); } @Override public void save(T entity, CompoundTag tag) { super.save(entity, tag); tag.putShort("Air", entity.getRemainingAir()); if (entity.getCustomName() != null && !entity.getCustomName().isEmpty()) { tag.putString("CustomName", entity.getCustomName()); tag.putBool("CustomNameVisible", entity.isCustomNameVisible()); } tag.putFloat("HealF", entity.getHealth()); tag.putShort("Health", (int) entity.getHealth()); tag.putShort("AttackTime", entity.getNoDamageTicks()); tag.putBool("FallFlying", entity.isFallFlying()); Map<String, Property> properties = entity.getAttributeManager().getAllProperties(); if (!properties.isEmpty()) { List<CompoundTag> attributes = new ArrayList<>(properties.size()); properties.forEach((key, property) -> { CompoundTag attribute = new CompoundTag(); attribute.putString("Name", key); attribute.putDouble("Base", property.getValue()); Collection<AttributeModifier> modifiers = property.getModifiers(); if (modifiers != null && !modifiers.isEmpty()) { List<CompoundTag> modifierTags = modifiers.stream().map(modifier -> { CompoundTag modifierTag = new CompoundTag(); modifierTag.putDouble("Amount", modifier.getAmount()); modifierTag.putString("Name", modifier.getName()); modifierTag.putInt("Operation", modifier.getOperation().ordinal()); UUID uuid = modifier.getUniqueId(); modifierTag.putLong("UUIDLeast", uuid.getLeastSignificantBits()); modifierTag.putLong("UUIDMost", uuid.getMostSignificantBits()); return modifierTag; }).collect(Collectors.toList()); attribute.putCompoundList("Modifiers", modifierTags); } attributes.add(attribute); }); tag.putCompoundList("Attributes", attributes); } List<CompoundTag> effects = new LinkedList<>(); for (PotionEffect effect : entity.getActivePotionEffects()) { CompoundTag effectTag = new CompoundTag(); effectTag.putByte("Id", effect.getType().getId()); effectTag.putByte("Amplifier", effect.getAmplifier()); effectTag.putInt("Duration", effect.getDuration()); effectTag.putBool("Ambient", effect.isAmbient()); effectTag.putBool("ShowParticles", true); effects.add(effectTag); } tag.putCompoundList("ActiveEffects", effects); EntityEquipment equip = entity.getEquipment(); if (equip != null) { tag.putCompoundList("HandItems", Arrays.asList( NbtSerialization.writeItem(equip.getItemInMainHand(), -1), NbtSerialization.writeItem(equip.getItemInOffHand(), -1) )); tag.putCompoundList("ArmorItems", Arrays.asList( NbtSerialization.writeItem(equip.getBoots(), -1), NbtSerialization.writeItem(equip.getLeggings(), -1), NbtSerialization.writeItem(equip.getChestplate(), -1), NbtSerialization.writeItem(equip.getHelmet(), -1) )); tag.putFloatList("HandDropChances", Arrays.asList( equip.getItemInMainHandDropChance(), equip.getItemInOffHandDropChance() )); tag.putFloatList("ArmorDropChances", Arrays.asList( equip.getBootsDropChance(), equip.getLeggingsDropChance(), equip.getChestplateDropChance(), equip.getHelmetDropChance() )); } tag.putBool("CanPickUpLoot", entity.getCanPickupItems()); tag.putBool("Leashed", entity.isLeashed()); if (entity.isLeashed()) { Entity leashHolder = entity.getLeashHolder(); CompoundTag leash = new CompoundTag(); // "Non-living entities excluding leashes will not persist as leash holders." // The empty Leash tag is still persisted tough if (leashHolder instanceof LeashHitch) { Location location = leashHolder.getLocation(); leash.putInt("X", location.getBlockX()); leash.putInt("Y", location.getBlockY()); leash.putInt("Z", location.getBlockZ()); } else if (leashHolder instanceof LivingEntity) { leash.putLong("UUIDMost", entity.getUniqueId().getMostSignificantBits()); leash.putLong("UUIDLeast", entity.getUniqueId().getLeastSignificantBits()); } tag.putCompound("Leash", leash); } } }
module TNorms #using Debug using ..Norms.TNorm type AlgebraicProduct <: TNorm end type BoundedDifference <: TNorm end type DrasticProduct <: TNorm end type EinsteinProduct <: TNorm end type HamacherProduct <: TNorm end type Minimum <: TNorm end end
<?php switch ($page){ case 'psd-files': $subtitle = ' - PSD files included'; break; case 'changelog': $subtitle = ' - Changelog'; break; case 'assets': $subtitle = ' - Assets'; break; default: $subtitle = ''; } ?> <!DOCTYPE HTML> <html> <head> <title>My Heaven - Online Booking PSD Template<?php echo $subtitle; ?></title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta name="description" content="My Heaven is a clean and complete booking PSD template ideal for hotels, guest houses, villas and more." /> <meta name="keywords" content="availability, book, booking, calendar, holiday, hostel, hotel, rate, rent, reservation, room, schedule, travel, vacation, villa" /> <?php include_once('../libraries/php/assets.php'); ?> <?php include_once('../libraries/php/google-analytics.php'); ?> </head> <body> <div id="wrapper"> <div id="header"> <h1>My Heaven - Online Booking PSD Template</h1> </div>
/*********************************************************************** Copyright (c) 2008, 2009, Memo Akten, www.memo.tv, Douglas Edric Stanley, www.abstractmachine.net * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of MSA Visuals nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * * ***********************************************************************/ #pragma once #include <Availability.h> #ifdef __IPHONE_3_0 #include "ofMain.h" #include <MapKit/MapKit.h> #include "ofxiPhoneMapKitListener.h" #include <list> // these are the types you can set for the map enum ofxiPhoneMapKitType { OFXIPHONE_MAPKIT_MAP = MKMapTypeStandard, OFXIPHONE_MAPKIT_SATELLITE = MKMapTypeSatellite, OFXIPHONE_MAPKIT_HYRBID = MKMapTypeHybrid }; // this is a type, similar to ofPoint, but with better precision for storing latitude and longitude typedef CLLocationCoordinate2D ofxMapKitLocation; class ofxiPhoneMapKit : public ofxiPhoneMapKitListener { public: ofxiPhoneMapKit(); ~ofxiPhoneMapKit(); // open the mapview void open(); // hide the mapview void close(); // latitude is south/north (-90...90) // longitude is east/west (-180...180) // set center (latitude,longitude) of map void setCenter(double latitude, double longitude, bool animated = true); // set span of map (in degrees) void setSpan(double latitudeDelta, double longitudeDelta, bool animated = true); // set span of map (in meters) void setSpanWithMeters(double metersLatitude, double metersLongitude, bool animated = true); // set center (latidude, longitude) and span (in degrees) void setRegion(double latitude, double longitude, double latitudeDelta, double longitudeDelta, bool animated = true); // set center (latidude, longitude) and span (in meters) void setRegionWithMeters(double latitude, double longitude, double metersLatitude, double metersLongitude, bool animated = true); // set the map type (see ofxiPhoneMapKitType above) void setType(ofxiPhoneMapKitType type = OFXIPHONE_MAPKIT_MAP); // set whether user location is visible on the map (as a blue dot) void setShowUserLocation(bool b); // enable/disable user interaction // if user interaction is not allowed, setAllowZoom / setAllowScroll are ignored // if user interaction is allowed, testApp::touchXXXX events will not be called void setAllowUserInteraction(bool b); // set whether user is allowed to zoom in or not void setAllowZoom(bool b); // set whether user is allowed to scroll the view or not void setAllowScroll(bool b); // returns whether the user location is visible in the current map region bool isUserOnScreen(); // return current center of map (latitude, longitude) ofxMapKitLocation getCenterLocation(); // convert location (latitude, longitude) to screen coordinates (i.e. pixels) ofPoint getScreenCoordinatesForLocation(double latitude, double longitude); // convert screen coordinates (i.e. pixels) to location (latitude, longitude) ofxMapKitLocation getLocationForScreenCoordinates(float x, float y); // convert location (latitude, longitude) and span (in degrees) to screen coordinates (i.e. pixels) ofRectangle getScreenRectForRegion(double latitude, double latitudeDelta, double longitudeDelta); // convert location (latitude, longitude) and span (in meters) to screen coordinates (i.e. pixels) ofRectangle getScreenRectForRegionWithMeters(double latitude, double longitude, double metersLatitude, double metersLongitude); // returns whether the map is open or not bool isOpen(); void addListener(ofxiPhoneMapKitListener* l); void removeListener(ofxiPhoneMapKitListener* l); void regionWillChange(bool animated); void regionDidChange(bool animated); void willStartLoadingMap(); void didFinishLoadingMap(); void errorLoadingMap(string errorDescription); // return instance to MKMapView MKMapView *getMKMapView(); protected: MKMapView *mapView; std::list<ofxiPhoneMapKitListener*> listeners; CLLocationCoordinate2D makeCLLocation(double latitude, double longitude); MKCoordinateSpan makeMKCoordinateSpan(double latitudeDelta, double longitudeDelta); void _setRegion(CLLocationCoordinate2D center, MKCoordinateSpan span, bool animated); }; #endif
<?php /* * Copyright (c) 2012, Christoph Mewes, http://www.xrstf.de/ * * This file is released under the terms of the MIT license. You can find the * complete text in the attached LICENSE file or online at: * * http://www.opensource.org/licenses/mit-license.php */ /** * Generated result class for `hg root` * * @generated * @see http://selenic.com/hg/help/root * @package libhg.Command.Root */ class libhg_Command_Root_Result { /** * command output * * @var string */ public $output; /** * command return code * * @var int */ public $code; /** * Constructor * * @param string $output command's output * @param int $code command's return code */ public function __construct($output, $code) { $this->output = $output; $this->code = $code; } }
// ----------------------------------------------------------------------- // <copyright file="BasePartnerComponent{TContext}.java" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // ----------------------------------------------------------------------- package com.microsoft.store.partnercenter; /** * Holds common partner component properties and behavior. All components should inherit from this class. The context * object type. */ public abstract class BasePartnerComponent<TContext> implements IPartnerComponent<TContext> { /** * Initializes a new instance of the {@link #BasePartnerComponent{TContext}} class. * * @param rootPartnerOperations The root partner operations that created this component. * @param componentContext A component context object to work with. */ protected BasePartnerComponent( IPartner rootPartnerOperations, TContext componentContext ) { if ( rootPartnerOperations == null ) { throw new NullPointerException( "rootPartnerOperations null" ); } this.setPartner( rootPartnerOperations ); this.setContext( componentContext ); } /** * Gets a reference to the partner operations instance that generated this component. */ private IPartner __Partner; @Override public IPartner getPartner() { return __Partner; } private void setPartner( IPartner value ) { __Partner = value; } /** * Gets the component context object. */ private TContext __Context; @Override public TContext getContext() { return __Context; } private void setContext( TContext value ) { __Context = value; } }
#!/bin/bash # Generate barebones groovy/gradle project # Author: Pawel Slusarz @pslusarz # License: MIT if [ -n "$1" ] then project_name=$1 else project_name="new-project" # Default, if not specified on command-line. fi language="groovy" mkdir -p "$project_name/src/main/$language/org/sw7d" mkdir -p "$project_name/src/test/$language/org/sw7d" main_file="$project_name/src/main/$language/org/sw7d/Main.$language" echo "package org.sw7d" >> $main_file echo "class Main {" >> $main_file echo " static void main(args) {" >> $main_file echo " println 'hello barebones groovy'" >> $main_file echo " }" >> $main_file echo "}" >> $main_file build_file="$project_name/build.gradle" echo "apply plugin: '$language'" >> $build_file echo "apply plugin: 'idea'" >> $build_file echo "apply plugin: 'eclipse'" >> $build_file echo "apply plugin: 'application'" >> $build_file echo "" >> $build_file echo "mainClassName = 'org.sw7d.Main'" >> $build_file echo "" >> $build_file echo "repositories {" >> $build_file echo " mavenCentral()" >> $build_file echo "}" >> $build_file echo "" >> $build_file echo "dependencies {" >> $build_file echo " compile 'org.codehaus.groovy:groovy-all:2.4.11'" >> $build_file echo "}" >> $build_file echo "task wrapper(type: Wrapper) {" >> $build_file echo " gradleVersion = '4.0.1'" >> $build_file echo "}" >> $build_file gitignore_file="$project_name/.gitignore" echo ".gradle/" >> $gitignore_file echo "build/" >> $gitignore_file #idea project files echo "*.iml" >> $gitignore_file echo "*.ipr" >> $gitignore_file echo "*.iws" >> $gitignore_file echo ".idea/" >> $gitignore_file echo "classes/" >> $gitignore_file #eclipse project files echo ".settings/" >> $gitignore_file echo ".classpath" >> $gitignore_file echo ".project" >> $gitignore_file
import React from 'react'; import IconBase from '@suitejs/icon-base'; function MdFlashOn(props) { return ( <IconBase viewBox="0 0 48 48" {...props}> <polygon points="14 4 14 26 20 26 20 44 34 20 26 20 34 4" /> </IconBase> ); } export default MdFlashOn;
/**************************************************************************** * ¹¦ ÄÜ£ºÒôƵÎļþ²Ù×÷Àà * * Ìí ¼Ó ÈË£ºÐ¡¿É * * Ìí¼Óʱ¼ä£º2015.01.17 12£º27 * * °æ±¾ÀàÐÍ£º³õʼ°æ±¾ * * ÁªÏµ·½Ê½£ºQQ-1035144170 * ****************************************************************************/ #include "StdAfx.h" #include "MusicOperat.h" CMusicOpreat::CMusicOpreat(HWND m_PWnd) { m_ParenhWnd=m_PWnd; nIndex=0; //²¥·ÅË÷Òý hStream=NULL; //²¥·ÅÁ÷ m_pBassMusic=NULL; m_pMainState=NULL; //²âÊÔ£º CLrcParse lrcPar; lrcPar.ReadFile(""); } CMusicOpreat::~CMusicOpreat(void) { if (hStream) { BASS_ChannelStop(hStream); hStream=NULL; } } //CMusicOpreat * CMusicOpreat::GetInstance() //{ // static CMusicOpreat _Instance; // // return &_Instance; //} void CMusicOpreat::InitDatas() { //³õʼ»¯ÉùÒô×é¼þ m_pBassMusic = CBassMusicEngine::GetInstance(); if ( m_pBassMusic == NULL ) { if ( SMessageBox(NULL,TEXT("ÉùÒôÒýÇæ³õʼ»¯Ê§°Ü"),_T("¾¯¸æ"),MB_OK|MB_ICONEXCLAMATION) == IDOK ) { PostQuitMessage(0); } } m_pBassMusic->Init(m_hWnd,this); } void CMusicOpreat::InsertMapInfo(int nNum, CString strPath, tagMusicInfo &pMuInfo) { //¼ÓÔØÎļþ HSTREAM hStream = m_pBassMusic->LoadFile(strPath); if ( hStream == -1 ) return; //»ñȡýÌå±êÇ© tagMusicInfo *pInfo = m_pBassMusic->GetInfo(hStream); //ͨ¹ýmapºÍListBox½áºÏ£¬Ò»Æð¹ÜÀí²¥·ÅÁбí tagMusicInfo *pMusicInfo = new tagMusicInfo; pMusicInfo->dwTime = pInfo->dwTime; pMusicInfo->hStream = pInfo->hStream; lstrcpyn(pMusicInfo->szArtist,pInfo->szArtist,CountArray(pMusicInfo->szArtist)); lstrcpyn(pMusicInfo->szTitle,pInfo->szTitle,CountArray(pMusicInfo->szTitle)); pMuInfo=*pMusicInfo; m_MusicManager.insert(pair<int,tagMusicInfo*>(nNum,pMusicInfo)); } void CMusicOpreat::OnButPrev() // ÉÏÒ»Çú { m_pBassMusic->Stop(hStream); nIndex--; if (nIndex<0) { nIndex=m_MusicManager.size()-1; } CMusicManagerMap::iterator iter = m_MusicManager.find(nIndex); if ( iter == m_MusicManager.end() ) return; hStream = iter->second->hStream; if( m_pBassMusic->Play(hStream,true) ) { int i=0; } } void CMusicOpreat::OnButPlay() // ²¥·Å { m_pBassMusic->Stop(hStream); CMusicManagerMap::iterator iter = m_MusicManager.find(nIndex); if ( iter == m_MusicManager.end() ) { return; }else { hStream = iter->second->hStream; if( m_pBassMusic->Play(hStream,/*(++nIndex!= nIndex) ? false : true)*/true )) { int i=0; } } } void CMusicOpreat::OnButPause() // ÔÝÍ£ { if ( m_pBassMusic->IsPlaying(hStream) == FALSE ) return; if( m_pBassMusic->Pause(hStream) ) { int i=0; } } void CMusicOpreat::OnButPlayNext() // ÏÂÒ»Çú { m_pBassMusic->Stop(hStream); nIndex++; if (nIndex>=m_MusicManager.size()) { nIndex=0; } CMusicManagerMap::iterator iter = m_MusicManager.find(nIndex); if ( iter == m_MusicManager.end() ) return; hStream = iter->second->hStream; if( m_pBassMusic->Play(hStream,true) ) { int i=0; } } void CMusicOpreat::OnStop() { //×Ô¶¯Çл»ÏÂÒ»Ê׸è OnButPlayNext(); //::PostMessage(GetContainer()->GetHostHwnd(), MSG_USER_SEARCH_DMTASKDLG, 0, 0); ::PostMessage(m_ParenhWnd,MSG_USER_REDRAW,0,0); }
// Copyright (c) 2017-2018 The DigiByte Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef DIGIBYTE_INDEX_TXINDEX_H #define DIGIBYTE_INDEX_TXINDEX_H #include <chain.h> #include <index/base.h> #include <txdb.h> /** * TxIndex is used to look up transactions included in the blockchain by hash. * The index is written to a LevelDB database and records the filesystem * location of each transaction by transaction hash. */ class TxIndex final : public BaseIndex { protected: class DB; private: const std::unique_ptr<DB> m_db; protected: /// Override base class init to migrate from old database. bool Init() override; bool WriteBlock(const CBlock& block, const CBlockIndex* pindex) override; BaseIndex::DB& GetDB() const override; const char* GetName() const override { return "txindex"; } public: /// Constructs the index, which becomes available to be queried. explicit TxIndex(size_t n_cache_size, bool f_memory = false, bool f_wipe = false); // Destructor is declared because this class contains a unique_ptr to an incomplete type. virtual ~TxIndex() override; /// Look up a transaction by hash. /// /// @param[in] tx_hash The hash of the transaction to be returned. /// @param[out] block_hash The hash of the block the transaction is found in. /// @param[out] tx The transaction itself. /// @return true if transaction is found, false otherwise bool FindTx(const uint256& tx_hash, uint256& block_hash, CTransactionRef& tx) const; }; /// The global transaction index, used in GetTransaction. May be null. extern std::unique_ptr<TxIndex> g_txindex; #endif // DIGIBYTE_INDEX_TXINDEX_H
/**************************************************************************** ** Meta object code from reading C++ file 'cookiejar.h' ** ** Created: Fri May 7 07:20:45 2010 ** by: The Qt Meta Object Compiler version 62 (Qt 4.6.2) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "../cookiejar.h" #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'cookiejar.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 62 #error "This file was generated using the moc from 4.6.2. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE static const uint qt_meta_data_CookieJar[] = { // content: 4, // revision 0, // classname 0, 0, // classinfo 4, 14, // methods 5, 34, // properties 2, 49, // enums/sets 0, 0, // constructors 0, // flags 1, // signalCount // signals: signature, parameters, type, tag, flags 11, 10, 10, 10, 0x05, // slots: signature, parameters, type, tag, flags 28, 10, 10, 10, 0x0a, 36, 10, 10, 10, 0x0a, 51, 10, 10, 10, 0x08, // properties: name, type, flags 71, 58, 0x0009510b, 95, 84, 0x0009510b, 118, 106, 0x0b095103, 133, 106, 0x0b095103, 148, 106, 0x0b095103, // enums: name, flags, count, data 58, 0x0, 3, 57, 84, 0x0, 3, 63, // enum data: key, value 171, uint(CookieJar::AcceptAlways), 184, uint(CookieJar::AcceptNever), 196, uint(CookieJar::AcceptOnlyFromSitesNavigatedTo), 227, uint(CookieJar::KeepUntilExpire), 243, uint(CookieJar::KeepUntilExit), 257, uint(CookieJar::KeepUntilTimeLimit), 0 // eod }; static const char qt_meta_stringdata_CookieJar[] = { "CookieJar\0\0cookiesChanged()\0clear()\0" "loadSettings()\0save()\0AcceptPolicy\0" "acceptPolicy\0KeepPolicy\0keepPolicy\0" "QStringList\0blockedCookies\0allowedCookies\0" "allowForSessionCookies\0AcceptAlways\0" "AcceptNever\0AcceptOnlyFromSitesNavigatedTo\0" "KeepUntilExpire\0KeepUntilExit\0" "KeepUntilTimeLimit\0" }; const QMetaObject CookieJar::staticMetaObject = { { &QNetworkCookieJar::staticMetaObject, qt_meta_stringdata_CookieJar, qt_meta_data_CookieJar, 0 } }; #ifdef Q_NO_DATA_RELOCATION const QMetaObject &CookieJar::getStaticMetaObject() { return staticMetaObject; } #endif //Q_NO_DATA_RELOCATION const QMetaObject *CookieJar::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject; } void *CookieJar::qt_metacast(const char *_clname) { if (!_clname) return 0; if (!strcmp(_clname, qt_meta_stringdata_CookieJar)) return static_cast<void*>(const_cast< CookieJar*>(this)); return QNetworkCookieJar::qt_metacast(_clname); } int CookieJar::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QNetworkCookieJar::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { switch (_id) { case 0: cookiesChanged(); break; case 1: clear(); break; case 2: loadSettings(); break; case 3: save(); break; default: ; } _id -= 4; } #ifndef QT_NO_PROPERTIES else if (_c == QMetaObject::ReadProperty) { void *_v = _a[0]; switch (_id) { case 0: *reinterpret_cast< AcceptPolicy*>(_v) = acceptPolicy(); break; case 1: *reinterpret_cast< KeepPolicy*>(_v) = keepPolicy(); break; case 2: *reinterpret_cast< QStringList*>(_v) = blockedCookies(); break; case 3: *reinterpret_cast< QStringList*>(_v) = allowedCookies(); break; case 4: *reinterpret_cast< QStringList*>(_v) = allowForSessionCookies(); break; } _id -= 5; } else if (_c == QMetaObject::WriteProperty) { void *_v = _a[0]; switch (_id) { case 0: setAcceptPolicy(*reinterpret_cast< AcceptPolicy*>(_v)); break; case 1: setKeepPolicy(*reinterpret_cast< KeepPolicy*>(_v)); break; case 2: setBlockedCookies(*reinterpret_cast< QStringList*>(_v)); break; case 3: setAllowedCookies(*reinterpret_cast< QStringList*>(_v)); break; case 4: setAllowForSessionCookies(*reinterpret_cast< QStringList*>(_v)); break; } _id -= 5; } else if (_c == QMetaObject::ResetProperty) { _id -= 5; } else if (_c == QMetaObject::QueryPropertyDesignable) { _id -= 5; } else if (_c == QMetaObject::QueryPropertyScriptable) { _id -= 5; } else if (_c == QMetaObject::QueryPropertyStored) { _id -= 5; } else if (_c == QMetaObject::QueryPropertyEditable) { _id -= 5; } else if (_c == QMetaObject::QueryPropertyUser) { _id -= 5; } #endif // QT_NO_PROPERTIES return _id; } // SIGNAL 0 void CookieJar::cookiesChanged() { QMetaObject::activate(this, &staticMetaObject, 0, 0); } static const uint qt_meta_data_CookieModel[] = { // content: 4, // revision 0, // classname 0, 0, // classinfo 1, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount // slots: signature, parameters, type, tag, flags 13, 12, 12, 12, 0x08, 0 // eod }; static const char qt_meta_stringdata_CookieModel[] = { "CookieModel\0\0cookiesChanged()\0" }; const QMetaObject CookieModel::staticMetaObject = { { &QAbstractTableModel::staticMetaObject, qt_meta_stringdata_CookieModel, qt_meta_data_CookieModel, 0 } }; #ifdef Q_NO_DATA_RELOCATION const QMetaObject &CookieModel::getStaticMetaObject() { return staticMetaObject; } #endif //Q_NO_DATA_RELOCATION const QMetaObject *CookieModel::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject; } void *CookieModel::qt_metacast(const char *_clname) { if (!_clname) return 0; if (!strcmp(_clname, qt_meta_stringdata_CookieModel)) return static_cast<void*>(const_cast< CookieModel*>(this)); return QAbstractTableModel::qt_metacast(_clname); } int CookieModel::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QAbstractTableModel::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { switch (_id) { case 0: cookiesChanged(); break; default: ; } _id -= 1; } return _id; } static const uint qt_meta_data_CookiesDialog[] = { // content: 4, // revision 0, // classname 0, 0, // classinfo 0, 0, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount 0 // eod }; static const char qt_meta_stringdata_CookiesDialog[] = { "CookiesDialog\0" }; const QMetaObject CookiesDialog::staticMetaObject = { { &QDialog::staticMetaObject, qt_meta_stringdata_CookiesDialog, qt_meta_data_CookiesDialog, 0 } }; #ifdef Q_NO_DATA_RELOCATION const QMetaObject &CookiesDialog::getStaticMetaObject() { return staticMetaObject; } #endif //Q_NO_DATA_RELOCATION const QMetaObject *CookiesDialog::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject; } void *CookiesDialog::qt_metacast(const char *_clname) { if (!_clname) return 0; if (!strcmp(_clname, qt_meta_stringdata_CookiesDialog)) return static_cast<void*>(const_cast< CookiesDialog*>(this)); if (!strcmp(_clname, "Ui_CookiesDialog")) return static_cast< Ui_CookiesDialog*>(const_cast< CookiesDialog*>(this)); return QDialog::qt_metacast(_clname); } int CookiesDialog::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QDialog::qt_metacall(_c, _id, _a); if (_id < 0) return _id; return _id; } static const uint qt_meta_data_CookieExceptionsModel[] = { // content: 4, // revision 0, // classname 0, 0, // classinfo 0, 0, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount 0 // eod }; static const char qt_meta_stringdata_CookieExceptionsModel[] = { "CookieExceptionsModel\0" }; const QMetaObject CookieExceptionsModel::staticMetaObject = { { &QAbstractTableModel::staticMetaObject, qt_meta_stringdata_CookieExceptionsModel, qt_meta_data_CookieExceptionsModel, 0 } }; #ifdef Q_NO_DATA_RELOCATION const QMetaObject &CookieExceptionsModel::getStaticMetaObject() { return staticMetaObject; } #endif //Q_NO_DATA_RELOCATION const QMetaObject *CookieExceptionsModel::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject; } void *CookieExceptionsModel::qt_metacast(const char *_clname) { if (!_clname) return 0; if (!strcmp(_clname, qt_meta_stringdata_CookieExceptionsModel)) return static_cast<void*>(const_cast< CookieExceptionsModel*>(this)); return QAbstractTableModel::qt_metacast(_clname); } int CookieExceptionsModel::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QAbstractTableModel::qt_metacall(_c, _id, _a); if (_id < 0) return _id; return _id; } static const uint qt_meta_data_CookiesExceptionsDialog[] = { // content: 4, // revision 0, // classname 0, 0, // classinfo 4, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount // slots: signature, parameters, type, tag, flags 25, 24, 24, 24, 0x08, 33, 24, 24, 24, 0x08, 41, 24, 24, 24, 0x08, 64, 59, 24, 24, 0x08, 0 // eod }; static const char qt_meta_stringdata_CookiesExceptionsDialog[] = { "CookiesExceptionsDialog\0\0block()\0" "allow()\0allowForSession()\0text\0" "textChanged(QString)\0" }; const QMetaObject CookiesExceptionsDialog::staticMetaObject = { { &QDialog::staticMetaObject, qt_meta_stringdata_CookiesExceptionsDialog, qt_meta_data_CookiesExceptionsDialog, 0 } }; #ifdef Q_NO_DATA_RELOCATION const QMetaObject &CookiesExceptionsDialog::getStaticMetaObject() { return staticMetaObject; } #endif //Q_NO_DATA_RELOCATION const QMetaObject *CookiesExceptionsDialog::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject; } void *CookiesExceptionsDialog::qt_metacast(const char *_clname) { if (!_clname) return 0; if (!strcmp(_clname, qt_meta_stringdata_CookiesExceptionsDialog)) return static_cast<void*>(const_cast< CookiesExceptionsDialog*>(this)); if (!strcmp(_clname, "Ui_CookiesExceptionsDialog")) return static_cast< Ui_CookiesExceptionsDialog*>(const_cast< CookiesExceptionsDialog*>(this)); return QDialog::qt_metacast(_clname); } int CookiesExceptionsDialog::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QDialog::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { switch (_id) { case 0: block(); break; case 1: allow(); break; case 2: allowForSession(); break; case 3: textChanged((*reinterpret_cast< const QString(*)>(_a[1]))); break; default: ; } _id -= 4; } return _id; } QT_END_MOC_NAMESPACE
# HippoPlayer This repository contains the source code for HippoPlayer, a module player for the classic Amigas with OS 1.3 or higher. Binary distribution is available here: http://aminet.net/mus/play/hippoplayer.lha Tools used in development: * Amiga 1200 with kickstart 3.0, Amiga 500 with kickstart 1.3 * ASM-One v1.28 * fimp file compressor, available here: http://aminet.net/util/pack/imploder-4.0.lzh * Gadget's Editor by Stefano Crimì (included without permission) Or you can compile it with vasm You need a newer vasm then one If your going to compile under 680x0. Default assembler is a cross compiler for AmigaOS4. * fimp file compressor, available here: http://aminet.net/util/pack/imploder-4.0.lzh NB! under AmigaOS 4.x, you need to run fimp under UAE, don't use the JIT version of UAE it crashed for me, when trying to save the file. # Files and directories * puu016.s: The main very small source file * keyfile0.s: Keyfile generator * playergroup0.s: HippoPlayer.group data generator, this file includes the compressed binaries for replay routines * regtext.s: Possibly important file related to calculating checksums, see notes below * kpl14.s: Protracker replay routine source * kpl: Protracker replay routine binary * gadgets: Gadget's Editor files for the user interface * pl: Replay routines for different module types and compressed binaries for each * scopes: External scopes and related stuff * Include: Some needed include files. * gfx: The hippo logo # new Build instructions for vasm make all Create all executables and modules. make clean Deletes all the executables and modules. Edit the makefile to make adjustments. To build individual replay routines, assemble one in the _pl_-directory, write out the binary and compress it with fimp, then re-create the group file. # Build instructions for ASMPro The standard include files will be searched from _include:_ directory, these are not included. Some custom includes and some others are included. Tested to compile with ASM-One v1.28 and ASM-Pro v1.17. Compile the file _puu016.s_ to get the main binary. It should start if you have _reqtools.library_ available. To build the player group file, read the _playergroup0.s_ and assemble, it will create a binary bundle out of the files in the _pl_-dir. To build the Protracker replay routine, assemble the file _kpl14.s_ and write out the binary to _kpl_. To build individual replay routines, assemble one in the _pl_-directory, write out the binary and compress it with fimp, then re-create the group file. # Notes There is a checksum macro _check_ in the main source file which is called at certain points. This checks if the application strings have been altered, making the app exit if the check fails. There is a CRC checksum check in the file _Hippo_PS3M.s_ which does the same as the simpler check mentioned above. It will jump into a busy loop and display colors on screen if the check fails.
<?php namespace Webiny\Component\Validation\Validators; use Webiny\Component\Validation\ValidationException; use Webiny\Component\Validation\ValidatorInterface; class Number implements ValidatorInterface { public function getName() { return 'number'; } public function validate($value, $params = [], $throw = false) { if (is_numeric($value)) { return true; } $message = 'Value must be a number'; if ($throw) { throw new ValidationException($message); } return $message; } }
C * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * C * * C * copyright (c) 2011 by UCAR * C * * C * University Corporation for Atmospheric Research * C * * C * all rights reserved * C * * C * FFTPACK version 5.1 * C * * C * A Fortran Package of Fast Fourier * C * * C * Subroutines and Example Programs * C * * C * by * C * * C * Paul Swarztrauber and Dick Valent * C * * C * of * C * * C * the National Center for Atmospheric Research * C * * C * Boulder, Colorado (80307) U.S.A. * C * * C * which is sponsored by * C * * C * the National Science Foundation * C * * C * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * C SUBROUTINE C1FGKB (IDO,IP,L1,LID,NA,CC,CC1,IN1, 1 CH,CH1,IN2,WA) REAL CH(IN2,L1,IDO,IP) ,CC(IN1,L1,IP,IDO), 1 CC1(IN1,LID,IP) ,CH1(IN2,LID,IP) , 2 WA(IDO,IP-1,2) C C FFTPACK 5.1 auxiliary routine C IPP2 = IP+2 IPPH = (IP+1)/2 DO 110 KI=1,LID CH1(1,KI,1) = CC1(1,KI,1) CH1(2,KI,1) = CC1(2,KI,1) 110 CONTINUE DO 111 J=2,IPPH JC = IPP2-J DO 112 KI=1,LID CH1(1,KI,J) = CC1(1,KI,J)+CC1(1,KI,JC) CH1(1,KI,JC) = CC1(1,KI,J)-CC1(1,KI,JC) CH1(2,KI,J) = CC1(2,KI,J)+CC1(2,KI,JC) CH1(2,KI,JC) = CC1(2,KI,J)-CC1(2,KI,JC) 112 CONTINUE 111 CONTINUE DO 118 J=2,IPPH DO 117 KI=1,LID CC1(1,KI,1) = CC1(1,KI,1)+CH1(1,KI,J) CC1(2,KI,1) = CC1(2,KI,1)+CH1(2,KI,J) 117 CONTINUE 118 CONTINUE DO 116 L=2,IPPH LC = IPP2-L DO 113 KI=1,LID CC1(1,KI,L) = CH1(1,KI,1)+WA(1,L-1,1)*CH1(1,KI,2) CC1(1,KI,LC) = WA(1,L-1,2)*CH1(1,KI,IP) CC1(2,KI,L) = CH1(2,KI,1)+WA(1,L-1,1)*CH1(2,KI,2) CC1(2,KI,LC) = WA(1,L-1,2)*CH1(2,KI,IP) 113 CONTINUE DO 115 J=3,IPPH JC = IPP2-J IDLJ = MOD((L-1)*(J-1),IP) WAR = WA(1,IDLJ,1) WAI = WA(1,IDLJ,2) DO 114 KI=1,LID CC1(1,KI,L) = CC1(1,KI,L)+WAR*CH1(1,KI,J) CC1(1,KI,LC) = CC1(1,KI,LC)+WAI*CH1(1,KI,JC) CC1(2,KI,L) = CC1(2,KI,L)+WAR*CH1(2,KI,J) CC1(2,KI,LC) = CC1(2,KI,LC)+WAI*CH1(2,KI,JC) 114 CONTINUE 115 CONTINUE 116 CONTINUE IF(IDO.GT.1 .OR. NA.EQ.1) GO TO 136 DO 120 J=2,IPPH JC = IPP2-J DO 119 KI=1,LID CHOLD1 = CC1(1,KI,J)-CC1(2,KI,JC) CHOLD2 = CC1(1,KI,J)+CC1(2,KI,JC) CC1(1,KI,J) = CHOLD1 CC1(2,KI,JC) = CC1(2,KI,J)-CC1(1,KI,JC) CC1(2,KI,J) = CC1(2,KI,J)+CC1(1,KI,JC) CC1(1,KI,JC) = CHOLD2 119 CONTINUE 120 CONTINUE RETURN 136 DO 137 KI=1,LID CH1(1,KI,1) = CC1(1,KI,1) CH1(2,KI,1) = CC1(2,KI,1) 137 CONTINUE DO 135 J=2,IPPH JC = IPP2-J DO 134 KI=1,LID CH1(1,KI,J) = CC1(1,KI,J)-CC1(2,KI,JC) CH1(1,KI,JC) = CC1(1,KI,J)+CC1(2,KI,JC) CH1(2,KI,JC) = CC1(2,KI,J)-CC1(1,KI,JC) CH1(2,KI,J) = CC1(2,KI,J)+CC1(1,KI,JC) 134 CONTINUE 135 CONTINUE IF (IDO .EQ. 1) RETURN DO 131 I=1,IDO DO 130 K=1,L1 CC(1,K,1,I) = CH(1,K,I,1) CC(2,K,1,I) = CH(2,K,I,1) 130 CONTINUE 131 CONTINUE DO 123 J=2,IP DO 122 K=1,L1 CC(1,K,J,1) = CH(1,K,1,J) CC(2,K,J,1) = CH(2,K,1,J) 122 CONTINUE 123 CONTINUE DO 126 J=2,IP DO 125 I=2,IDO DO 124 K=1,L1 CC(1,K,J,I) = WA(I,J-1,1)*CH(1,K,I,J) 1 -WA(I,J-1,2)*CH(2,K,I,J) CC(2,K,J,I) = WA(I,J-1,1)*CH(2,K,I,J) 1 +WA(I,J-1,2)*CH(1,K,I,J) 124 CONTINUE 125 CONTINUE 126 CONTINUE RETURN END
#!/usr/bin/env bash GCC_VERSION=11.2.0 make DESTDIR="$DESTDIR" install rm -rfv "$DESTDIR"/usr/lib/gcc/"$(gcc -dumpmachine)"/$GCC_VERSION/include-fixed/bits/ # symlink required by FHS ln -srv /usr/bin/cpp "$DESTDIR/usr/lib" # symlinks for link time optimization install -v -dm755 "$DESTDIR"/usr/lib/bfd-plugins ln -sfv ../../libexec/gcc/"$(gcc -dumpmachine)"/$GCC_VERSION/liblto_plugin.so "$DESTDIR"/usr/lib/bfd-plugins/ # misplaced file mkdir -pv "$DESTDIR"/usr/share/gdb/auto-load/usr/lib mv -v "$DESTDIR"/usr/lib/*gdb.py "$DESTDIR"/usr/share/gdb/auto-load/usr/lib
<?php /*-------------------------------------------------------+ | PHP-Fusion Content Management System | Copyright © 2002 - 2008 Nick Jones | http://www.php-fusion.co.uk/ +--------------------------------------------------------+ | Filename: user_sig_include.php | Author: Digitanium +--------------------------------------------------------+ | This program is released as free software under the | Affero GPL license. You can redistribute it and/or | modify it under the terms of this license which you | can read by viewing the included agpl.txt or online | at www.gnu.org/licenses/agpl.html. Removal of this | copyright header is strictly prohibited without | written permission from the original author(s). +--------------------------------------------------------*/ if (!defined("IN_FUSION")) { die("Access Denied"); } if ($profile_method == "input") { require_once INCLUDES."bbcode_include.php"; echo "<tr>\n"; echo "<td valign='top' class='tbl'>".$locale['uf_sig']."</td>\n"; echo "<td class='tbl'><textarea name='user_sig' cols='60' rows='5' class='textbox' style='width:295px'>".(isset($user_data['user_sig']) ? $user_data['user_sig'] : "")."</textarea><br />\n"; echo display_bbcodes("300px", "user_sig", "inputform", "smiley|b|i|u||center|small|url|mail|img|color")."</td>\n"; echo "</tr>\n"; } elseif ($profile_method == "display") { // Not shown in profile } elseif ($profile_method == "validate_insert") { $db_fields .= ", user_sig"; $db_values .= ", '".(isset($_POST['user_sig']) ? stripinput(trim($_POST['user_sig'])) : "")."'"; } elseif ($profile_method == "validate_update") { $db_values .= ", user_sig='".(isset($_POST['user_sig']) ? stripinput(trim($_POST['user_sig'])) : "")."'"; } ?>
using System; namespace EFLikeDemo.Models { public class ErrorViewModel { public string RequestId { get; set; } public bool ShowRequestId => !string.IsNullOrEmpty(RequestId); } }
# poicreator Create POIs ``` img ├── 01.jpg ├── 21.jpg └── 22.jpg ``` A(01.jpg): ![](http://gnat.qiniudn.com/pano/01.jpg?imageView2/2/h/200) B(21.jpg): ![](http://gnat.qiniudn.com/pano/21.jpg?imageView2/2/h/200) C(22.jpg): ![](http://gnat.qiniudn.com/pano/22.jpg?imageView2/2/h/200) ``` ^ y | +---+---+---+ | | | C | +---+---+---+ | A | | B | +---+---+---+ | | | | (0,0) +---+---+---+--> x ``` ### [Image Processing](https://zybuluo.com/gnat-xj/note/92390) ``` http://gnat.qiniudn.com/pano/01.jpg?imageView2/2/h/200 ``` ### img http://gnat.qiniudn.com/pano.jpg # Compressing Off wired. # Compressing On ➜ ~ curl http://localhost:8000/gridfs/level0-12000x6000.jpg > /dev/null % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 100 9195k 0 9195k 0 0 54.7M 0 --:--:-- --:--:-- --:--:-- 54.7M ➜ ~ curl http://localhost:8000/gridfs/level0-12000x6000.jpg > /dev/null % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 100 9195k 0 9195k 0 0 40.5M 0 --:--:-- --:--:-- --:--:-- 40.6M ➜ ~ curl -H "Accept-Encoding:gzip" http://localhost:8000/gridfs/level0-12000x6000.jpg > /dev/null % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 100 9195k 0 9195k 0 0 44.5M 0 --:--:-- --:--:-- --:--:-- 44.6M ➜ ~ curl -H "Accept-Encoding:gzip" http://localhost:8000/gridfs/level0-12000x6000.jpg > /dev/null % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 100 9195k 0 9195k 0 0 47.8M 0 --:--:-- --:--:-- --:--:-- 48.0M ➜ ~ curl -H "Accept-Encoding:gzip" http://localhost:8000/gridfs/level0-12000x6000.jpg > /dev/null % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 100 9195k 0 9195k 0 0 43.7M 0 --:--:-- --:--:-- --:--:-- 43.8M ➜ ~ curl -H "Accept-Encoding:gzip" http://localhost:8000/gridfs/level0-12000x6000.jpg > /dev/null % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 100 9195k 0 9195k 0 0 47.7M 0 --:--:-- --:--:-- --:--:-- 47.7M ➜ ~ curl http://localhost:8000/gridfs/level0-12000x6000.jpg > /dev/null % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 100 9195k 0 9195k 0 0 41.8M 0 --:--:-- --:--:-- --:--:-- 41.9M
#!/bin/sh set -e echo "mkdir -p ${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" mkdir -p "${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" SWIFT_STDLIB_PATH="${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" install_framework() { if [ -r "${BUILT_PRODUCTS_DIR}/$1" ]; then local source="${BUILT_PRODUCTS_DIR}/$1" elif [ -r "${BUILT_PRODUCTS_DIR}/$(basename "$1")" ]; then local source="${BUILT_PRODUCTS_DIR}/$(basename "$1")" elif [ -r "$1" ]; then local source="$1" fi local destination="${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" if [ -L "${source}" ]; then echo "Symlinked..." source="$(readlink "${source}")" fi # use filter instead of exclude so missing patterns dont' throw errors echo "rsync -av --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${destination}\"" rsync -av --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${destination}" local basename basename="$(basename -s .framework "$1")" binary="${destination}/${basename}.framework/${basename}" if ! [ -r "$binary" ]; then binary="${destination}/${basename}" fi # Strip invalid architectures so "fat" simulator / device frameworks work on device if [[ "$(file "$binary")" == *"dynamically linked shared library"* ]]; then strip_invalid_archs "$binary" fi # Resign the code if required by the build settings to avoid unstable apps code_sign_if_enabled "${destination}/$(basename "$1")" # Embed linked Swift runtime libraries. No longer necessary as of Xcode 7. if [ "${XCODE_VERSION_MAJOR}" -lt 7 ]; then local swift_runtime_libs swift_runtime_libs=$(xcrun otool -LX "$binary" | grep --color=never @rpath/libswift | sed -E s/@rpath\\/\(.+dylib\).*/\\1/g | uniq -u && exit ${PIPESTATUS[0]}) for lib in $swift_runtime_libs; do echo "rsync -auv \"${SWIFT_STDLIB_PATH}/${lib}\" \"${destination}\"" rsync -auv "${SWIFT_STDLIB_PATH}/${lib}" "${destination}" code_sign_if_enabled "${destination}/${lib}" done fi } # Signs a framework with the provided identity code_sign_if_enabled() { if [ -n "${EXPANDED_CODE_SIGN_IDENTITY}" -a "${CODE_SIGNING_REQUIRED}" != "NO" -a "${CODE_SIGNING_ALLOWED}" != "NO" ]; then # Use the current code_sign_identitiy echo "Code Signing $1 with Identity ${EXPANDED_CODE_SIGN_IDENTITY_NAME}" echo "/usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} --preserve-metadata=identifier,entitlements \"$1\"" /usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} --preserve-metadata=identifier,entitlements "$1" fi } # Strip invalid architectures strip_invalid_archs() { binary="$1" # Get architectures for current file archs="$(lipo -info "$binary" | rev | cut -d ':' -f1 | rev)" stripped="" for arch in $archs; do if ! [[ "${VALID_ARCHS}" == *"$arch"* ]]; then # Strip non-valid architectures in-place lipo -remove "$arch" -output "$binary" "$binary" || exit 1 stripped="$stripped $arch" fi done if [[ "$stripped" ]]; then echo "Stripped $binary of architectures:$stripped" fi } if [[ "$CONFIGURATION" == "Debug" ]]; then install_framework "Pods-Then_Tests/Then.framework" fi if [[ "$CONFIGURATION" == "Release" ]]; then install_framework "Pods-Then_Tests/Then.framework" fi
package ExercicioPOO; public class TestaAgenda { public static void main(String[] args) { Agenda agenda = new Agenda(2); Pessoa p1 = new Pessoa(); p1.setNome("Emiliano"); p1.setIdade(43); p1.setAltura(1.82); Pessoa p2 = new Pessoa(); p2.setNome("Carvalho"); p2.setIdade(34); p2.setAltura(1.82); agenda.armazenaPessoa(p1.getNome(), p1.getIdade(), p1.getAltura()); agenda.armazenaPessoa(p2.getNome(), p2.getIdade(), p2.getAltura()); agenda.imprimePessoa(0); agenda.imprimeAgenda(); } }
import os from flask import Flask from flask.ext.sqlalchemy import SQLAlchemy from flask.ext.bcrypt import Bcrypt from flask_sockets import Sockets app = Flask(__name__, static_folder="../static/dist", template_folder="../static") if os.environ.get('PRODUCTION'): app.config.from_object('config.ProductionConfig') else: app.config.from_object('config.TestingConfig') db = SQLAlchemy(app) bcrypt = Bcrypt(app) sockets = Sockets(app)
<?php /** * The MIT License (MIT) * * Copyright 2015 Anatoliy Bereznyak * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ namespace Workers; /** * Class Worker * @package Bezk * @author Анатолий Березняк <bereznyak@me.com> * @homepage http://unrealmac.ru * @link https://github.com/Bezk/Workers */ final class Worker { /** * @const string номер версии скрипта */ const VERSION = '1.0.0-beta'; /** * @var int PID текущего процесса */ private $iPID; /** * @var int PID родительского процесса */ private $iParentPID; /** * @var int PID процесса, при завершении которого сработает * родительский деструктор */ private $iParentDestructorPID; /** * @var string путь к временной директории */ private $sTempDirectory; /** * @var string путь к директории для логов */ private $sLogsDirectory; /** * @var int приоритет процесса */ private $iWorkerPriority = 0; /** * @var string путь к PID файлу */ private $sPIDFilePath; /** * @var string префикс технических файлов (PID, логи) */ private $sFilesBasename; /** * @var int максимальное количество одновременно работающих процессов */ private $iNumberOfWorkers = 1; /** * @var int лимит на время исполнения дочернего процесса (в секундах) */ private $iMaxExecutionTimeInSeconds = 0; /** * @var bool флаг остановки демона */ private $bIsStop = false; /** * @var array массив работающих воркеров */ private $aInstances = array(); /** * @var callable функция с программой воркера */ private $cExecutingFunction = null; /** * @var callable функция с деструктором родительского процесса */ private $cDestructorFunction = null; /** * @var callable функция с деструктором воркера */ private $cWorkerDestructorFunction = null; /** * @var callable функция выполняемая по завершению родительского процесса */ private $cShutdownFunction = null; /** * @var int время первичной задержки для асинхронного запуска в секундах */ private $iFirstDelayBetweenLaunch = 0; /** * @var int номер процесса */ private $iNumberWorker = 0; /** * @var int порядковый номер процесса */ private $iSerialNumberWorker = 0; /** * @var int время задержки между попытками запуска новых воркеров * в милисекундах * (при достижении максимального количества работающих воркеров) */ private $iDelayBetweenLaunch = 1000; /** * @var array массив с данными для воркеров */ private $aWorkers = array(); /** * @var array ключи воркеров */ private $aWorkersNames = array(); /** * @var array данные воркеров */ private $aWorkersData = array(); /** * @var bool флаг цикличной работы */ private $bIsLooped = true; /** * @var bool флаг привязки к консоли */ private $bHookedConsole = false; /** * @var bool флаг вывода в консоль */ private $bSTDInConsole = false; /** * @var bool флаг подробного вывода */ private $bVerbose = false; /** * @var bool флаг последовательной (один за одним) работы */ private $bInSequence = false; /** * @var array массив мета информации процессов */ private $aMeta = array(); /** * @var mixed переменная с данными, которые могут использоваться в воркере */ private $mInstanceData = null; /** * @var bool флаг "запущенности" скрипта */ private $bIsActive = false; /** * @var bool флаг первичного запуска метода run */ private $bIsFirstRun = true; /** * @var bool флаг быстрого запуска */ private $bFastRun = true; /** * @var bool флаг запуска метода run */ private $bIsRun = false; /** * @var array массив воркеров завершивших работу */ private $aStopped = array(); /** * @var array массив воркеров завершивших работу */ private $bVerboseInOUT = false; /** * @var array ключ воркера */ private $sInstanceName = null; /** * @var array массив с ресурсами на потоки ввода/вывода */ private $STD = array( 'IN' => STDIN, 'OUT' => STDOUT, 'ERR' => STDERR ); final public function __construct( $bFastRun = null, $aWorkersData = null, callable $cExecutingFunction = null, callable $cDestructorFunction = null, callable $cWorkerDestructorFunction = null, callable $cShutdownFunction = null, $sTempDirectory = null, $sLogsDirectory = null, $iNumberOfWorkers = null, $iWorkerPriority = null, $iMaxExecutionTimeInSeconds = null, $iFirstDelayBetweenLaunch = null, $iDelayBetweenLaunch = null, $bIsLooped = null, $bInSequence = null, $bHookedConsole = null, $bSTDInConsole = null, $bVerbose = null, $bVerboseInOUT = null ) { declare(ticks=1); if (isset($bInSequence)) $this->bInSequence = (bool) $bInSequence; if ($cExecutingFunction) $this->cExecutingFunction = (string) $cExecutingFunction; $this->iPID = getmypid(); $this->iParentPID = $this->iPID; $this->sTempDirectory = $sTempDirectory ? (string) $sTempDirectory : sys_get_temp_dir(); $this->sLogsDirectory = $sLogsDirectory ? (string) $sLogsDirectory : $this->sTempDirectory; if ($iFirstDelayBetweenLaunch) $this->iFirstDelayBetweenLaunch = $iFirstDelayBetweenLaunch; $this->sFilesBasename = basename($_SERVER['PHP_SELF']); $this->sPIDFilePath = $this->sTempDirectory . DIRECTORY_SEPARATOR . $this->sFilesBasename . '.pid'; if (isset($bHookedConsole)) $this->bHookedConsole = (bool) $bHookedConsole; if (isset($bSTDInConsole)) $this->bSTDInConsole = (bool) $bSTDInConsole; if (isset($bIsLooped)) $this->bIsLooped = (bool) $bIsLooped; if ($cDestructorFunction) $this->cDestructorFunction = (string) $cDestructorFunction; if ($cWorkerDestructorFunction) $this->cWorkerDestructorFunction = (string) $cWorkerDestructorFunction; if ($cShutdownFunction) $this->cShutdownFunction = (string) $cShutdownFunction; if ($iMaxExecutionTimeInSeconds) $this->iMaxExecutionTimeInSeconds = (int) $iMaxExecutionTimeInSeconds; if ($iWorkerPriority) $this->iWorkerPriority = (int) $iWorkerPriority; if (isset($bVerbose)) $this->bVerbose = (bool) $bVerbose; if ($iDelayBetweenLaunch) $this->iDelayBetweenLaunch = (int) $iDelayBetweenLaunch; $this->bIsActive = $this->isActive(); if ($aWorkersData) { // выставляем количество воркеров $this->iNumberOfWorkers = count((array) $aWorkersData); // массив имен демонов => значений для воркеров $this->aWorkers = (array) $aWorkersData; // массив имен демонов $this->aWorkersNames = array_keys((array) $aWorkersData); // массив значений для воркеров $this->aWorkersData = array_values((array) $aWorkersData); } if ($iNumberOfWorkers) { if ($aWorkersData) { $this->writeInLog( $this->STD['OUT'], 'Ignore option "The numbers of processes" because set up' . ' option "Workers data"' ); } else { $this->iNumberOfWorkers = (int) $iNumberOfWorkers; for ($i = 1; $i <= $this->iNumberOfWorkers; $i++) $this->aWorkers[] = null; // массив имен демонов $this->aWorkersNames = array_keys((array) $this->aWorkers); // массив значений для воркеров $this->aWorkersData = array_values((array) $this->aWorkers); } } if (isset($bVerboseInOUT)) $this->bVerboseInOUT = (bool) $bVerboseInOUT; if (isset($bFastRun)) $this->bFastRun = $bFastRun; $this->rVerboseStream = $this->bVerboseInOUT ? $this->STD['OUT'] : $this->STD['ERR']; $this->aStopped = $this->getInstancesKeys($this->aWorkersNames); // быстрый старт if ($this->bFastRun) $this->run(); } /** * Деструкторы родительского и дочернего процессов * * @return void */ final public function __destruct() { switch (getmypid()) { // деструктор родительского процесса case $this->iParentDestructorPID: $this->setStopMeta(); $this->writeInLog($this->rVerboseStream, 'Stopped'); if ($this->bVerbose) $this->writeMeta(); $this->writeInLog( $this->rVerboseStream, '-----------------------------------------' ); if ($this->cDestructorFunction) call_user_func($this->cDestructorFunction); unlink($this->sPIDFilePath); break; case $this->iParentPID: break; // деструктор дочерних процессов default: $sContent = $this->getOutput(ob_get_contents()); ob_end_clean(); echo $sContent; $this->setStopMeta(); if ($this->bVerbose) { $this->writeInLog($this->rVerboseStream, 'Stopped'); $this->writeMeta(); $this->writeInLog( $this->rVerboseStream, '-----------------------------------------' ); } if ($this->cWorkerDestructorFunction) call_user_func($this->cWorkerDestructorFunction); } } /** * Класс запрещено клонировать * * @return void */ final private function __clone() { } /** * Выводит дебаг-инфо * * @return array */ public function __debugInfo() { return array( 'instance' => array( 'name' => $this->sInstanceName, 'data' => $this->mInstanceData, 'meta' => $this->aMeta, 'serial number worker' => $this->iSerialNumberWorker, 'number worker' => $this->iNumberWorker, 'PID' => $this->iPID, 'parent PID' => $this->iParentPID ), 'common' => array( 'version' => self::VERSION, 'parent PID' => $this->iParentPID, 'parent PID in file' => $this->getPIDFromFile(), 'PID file' => realpath($this->sPIDFilePath), 'fast run' => $this->bFastRun, 'workers' => $this->aWorkers, 'workers names' => $this->aWorkersNames, 'workers data' => $this->aWorkersData, 'meta' => $this->aMeta, 'workers program function' => $this->cExecutingFunction, 'parent destructor function' => $this->cDestructorFunction, 'worker destructor function' => $this->cWorkerDestructorFunction, 'shutdown function' => $this->cShutdownFunction, 'files prefix' => $this->sFilesBasename, 'temporary directory' => realpath($this->sTempDirectory), 'logs directory' => realpath($this->sLogsDirectory), 'numbers of workers' => $this->iNumberOfWorkers, 'worker priority' => $this->iWorkerPriority, 'maximum execution time limit' => $this->iMaxExecutionTimeInSeconds, 'first delay between launch workers' => $this->iFirstDelayBetweenLaunch, 'delay between attempts launch workers' => $this->iDelayBetweenLaunch, 'looped mode' => $this->bIsLooped, 'in sequence mode' => $this->bInSequence, 'is unhook console' => !$this->bHookedConsole, 'IO in console' => $this->bSTDInConsole, 'IO' => $this->STD, 'verbose mode' => $this->bVerbose, 'is verbose in out stream' => $this->bVerboseInOUT ) ); } /** * Запускает работу демона (если объект вызывается как функция) * * @return void */ public function __invoke() { $this->run(); } /** * Приостанавливает работу демона * * @return void */ public function __sleep() { $this->iNumberOfWorkers = 0; foreach ($this->aInstances as $iPID => $sValue) { pcntl_waitpid($iPID, $iStatus); if ($iStatus === 0) { $this->aStopped[$this->aInstances[$iPID]] = $this->aInstances[$iPID]; unset($this->aInstances[$iPID]); } } pcntl_sigwaitinfo(array(SIGCONT), $aInfo); $this->iNumberOfWorkers = count($this->aWorkers); } /** * Возобновляет работу демона после остановки * * @return void */ public function __wakeup() { $this->bIsStop = false; $this->iNumberOfWorkers = count($this->aWorkers); } /** * Возвращает строковое представление объекта * * @return string */ public function __toString() { return (string) $this->sFilesBasename; } /** * Отвязывает демона от консоли * * @return boolean */ private function unhookConsole() { if ($this->bVerbose) { $this->writeInLog( $this->rVerboseStream, 'Unhook console: Fork process and kill parent, set up children' . ' as parent...' ); } $iChildPID = pcntl_fork(); if ($iChildPID === -1) { $this->writeInLog($this->STD['ERR'], 'Fork ended with error'); return false; } // выходим из родительского (привязанного к консоли) процесса if ($iChildPID) exit(0); // продолжим работу после завершения родительского процесса $bResult = true; while ($bResult) $bResult = posix_kill($this->iPID, 0); // делаем дочерний процесс основным $bResult = posix_setsid(); if ($bResult === -1) throw new WorkerException( 'Set up current process a session leader ended with error' ); if ($this->bVerbose) $this->writeInLog($this->rVerboseStream, "\t done"); return true; } /** * Запускает работу демона * * @return void */ public function run() { $this->aMeta['time']['start'] = round(microtime(true), 2); // проверка окружения $this->checkWorkflow(); $this->writeInLog( $this->STD['OUT'], $this->bIsLooped ? 'Looped mode' : 'One-off mode' ); $this->bIsRun = true; $this->bIsFirstRun = false; // установка кастомных потоков IO $this->setStreamsIO(); // отвязываемся от консоли if (!$this->bHookedConsole) $this->unhookConsole(); // назначаем функцию завершения if ($this->cShutdownFunction) register_shutdown_function($this->cShutdownFunction); // необходимо обновить данные после отвязки от консоли $this->iPID = getmypid(); $this->iParentPID = $this->iPID; $this->iParentDestructorPID = $this->iPID; // помечаем родительский процесс if (function_exists('cli_set_process_title') && $_SERVER['TERM_PROGRAM'] !== 'Apple_Terminal' ) { cli_set_process_title($this->sFilesBasename . '.parent'); } if ($this->bVerbose) $this->writeInLog($this->rVerboseStream, 'Write PID...'); // фиксируем PID $this->writePIDInFile($this->iPID); if ($this->bVerbose) $this->writeInLog($this->rVerboseStream, "\t write PID " . $this->iPID); if ($this->bVerbose) $this->writeInLog($this->rVerboseStream, 'Set up signal handler...'); // устанавливаем обработку сигналов $this->setSignalHandlers(); if ($this->bVerbose) $this->writeInLog($this->rVerboseStream, "\t set"); while (!$this->bIsStop) { $this->iSerialNumberWorker++; $this->iNumberWorker++; if ($this->iNumberWorker > $this->iNumberOfWorkers) { // если демон не зациклен, выход if (!$this->bIsLooped) break; // сбрасываем порядковый номер дочернего процесса $this->iNumberWorker = 1; } // запущено максимальное количество дочерних процессов, ждем завершения while(count($this->aStopped) === 0) usleep($this->iDelayBetweenLaunch); $this->sInstanceName = array_values($this->aStopped)[0]; unset($this->aStopped[$this->sInstanceName]); // распределяем деление, чтобы не грузить процессор if ( ($this->iSerialNumberWorker > 1 && $this->iSerialNumberWorker <= $this->iNumberOfWorkers) && $this->iFirstDelayBetweenLaunch ) { if ($this->bVerbose) { $this->writeInLog( $this->rVerboseStream, 'Delay between launching instances: ' . $this->iFirstDelayBetweenLaunch . ' seconds' ); } sleep($this->iFirstDelayBetweenLaunch); } $iChildPID = pcntl_fork(); if ($iChildPID === -1) { throw new WorkerException('Create new instance ended with error'); } elseif ($iChildPID) { if ($this->bInSequence) pcntl_wait($sStatus); if ($this->bVerbose) { $this->writeInLog( $this->rVerboseStream, 'New instance: ' . $this->sInstanceName . ' PID: ' . $iChildPID ); } unset($this->aStopped[$this->sInstanceName]); $this->aInstances[$iChildPID] = $this->sInstanceName; } else { $this->worker(); } // выходим из цикла в дочернем процессе if ($this->iPID !== $this->iParentPID) break; $this->checkZombie(); } if ($this->iPID === $this->iParentPID) { if ($this->bVerbose) $this->writeInLog($this->rVerboseStream, 'No work. Stopping'); if ($this->bVerbose) $this->writeInLog($this->rVerboseStream, ' waiting…'); while (count($this->aInstances)) usleep($this->iDelayBetweenLaunch); $this->stop(); // не будем продолжать работу родительского процесса exit(0); } } private function stop() { $this->bIsStop = true; while ($this->aInstances) { foreach ($this->aInstances as $iPID => $mValue) { $iPID = pcntl_waitpid($iPID, $iStatus, WNOHANG|WUNTRACED); if ($iPID > 0) { if (isset($this->aInstances[$iPID])) { if ($this->bVerbose) { $this->writeInLog( $this->rVerboseStream, 'End instance: ' . $this->aInstances[$iPID] . ' PID: ' . $iPID ); } $this->aStopped[$this->aInstances[$iPID]] = $this->aInstances[$iPID]; unset($this->aInstances[$iPID]); } } } } } /** * Выполняет отлов зомби-процессов * * @return void */ private function checkZombie() { foreach ($this->aInstances as $iPID => $mValue) { $iPID = pcntl_waitpid($iPID, $iStatus, WNOHANG|WUNTRACED); if ($iPID > 0) { if (isset($this->aInstances[$iPID])) { if ($this->bVerbose) { $this->writeInLog( $this->rVerboseStream, 'End instance: ' . $this->aInstances[$iPID] . ' PID: ' . $iPID ); } $this->aStopped[$this->aInstances[$iPID]] = $this->aInstances[$iPID]; unset($this->aInstances[$iPID]); } } } } /** * Выполняет проверку окружения * * @return void */ public function checkWorkflow() { // процесс не должен запускаться в нескольких экземплярах if ($this->bIsActive) throw new WorkerException('Already running'); // нельзя дважды запускать метод run if (!$this->bIsFirstRun) throw new WorkerException('Method "run" called only once'); if (!function_exists('pcntl_fork')) { throw new WorkerException( 'PCNTL: Process control doesn\'t support.' . ' Compile PHP with --enable-pcntl' ); } if (!function_exists('pcntl_wait') && $this->bInSequence) { throw new WorkerException( 'PCNTL: Function pcntl_wait doesn\'t support.' . ' Function "In sequence" don\'t work' ); } if (function_exists('pcntl_fork') && !function_exists('pcntl_sigwaitinfo')) { $this->writeInLog( $this->STD['OUT'], 'PCNTL: OS X doesn\'t support function pcntl_sigwaitinfo.' . ' Send SIGTSTP or SIGSTOP return error of undefined function' ); } if ($this->iWorkerPriority < -20 || $this->iWorkerPriority > 20) { throw new WorkerException( 'Incorrect value for option "workers priority".' . ' Set value range from -20 to 20.'); } if (!is_dir($this->sTempDirectory) || !is_writable($this->sTempDirectory)) { throw new WorkerException( 'Incorrect value for option "temp directory" or directory' . ' not allowed write.' ); } if (!is_dir($this->sLogsDirectory) || !is_writable($this->sLogsDirectory)) { throw new WorkerException( 'Incorrect value for option "logs directory" or directory' . ' not allowed write.' ); } } /** * Выполняет работу воркера * * @return void */ private function worker() { $this->iPID = getmypid(); $this->aMeta['time']['start'] = round(microtime(true), 2); // ключ для вызова в функции пользовательской $this->mInstanceData = (bool) $this->aWorkersData ? $this->aWorkersData[$this->iNumberWorker - 1] : null; if (function_exists('cli_set_process_title') && isset($_SERVER['TERM_PROGRAM']) && $_SERVER['TERM_PROGRAM'] !== 'Apple_Terminal' ) { cli_set_process_title($this->sFilesBasename . '.' . $this->sInstanceName); } $this->setStreamsIO($this->sInstanceName); if ($this->bVerbose) $this->writeInLog($this->rVerboseStream, 'PID: ' . $this->iPID); // установка приоритета на процесс if ($this->iWorkerPriority) { if ($this->bVerbose) { $this->writeInLog( $this->rVerboseStream, 'Set process priority equal ' . $this->iWorkerPriority ); } $this->setPriority($this->iWorkerPriority); } // лимит на время исполнения дочернего процесса if ($this->iMaxExecutionTimeInSeconds) { if ($this->bVerbose) { $this->writeInLog( $this->rVerboseStream, 'Set process lifetime ' . $this->iMaxExecutionTimeInSeconds . ' seconds' ); } // считает время работы скрипта set_time_limit($this->iMaxExecutionTimeInSeconds); // считает время исполнения вне скрипта (потоки, коннекты, sleep, etc) pcntl_alarm($this->iMaxExecutionTimeInSeconds); } if ($this->bVerbose) $this->writeInLog($this->rVerboseStream, 'Started'); // перехватываем вывод ob_start(); // запускаем функцию if ($this->cExecutingFunction) { call_user_func($this->cExecutingFunction, $this->mInstanceData); // успешно выходим exit(0); } } /** * Обработчик сигналов * * @param integer $iSignalNumber * @param integer $iPID * @param integer $iPID * @return void */ public function sigHandler($iSignalNumber, $iPID = null, $iStatus = null) { switch($iSignalNumber) { // при получении сигнала завершения работы устанавливаем флаг case SIGTERM: case SIGHUP: case SIGINT; $this->stop(); break; // сигнал от дочернего процесса case SIGCHLD: $iPID = pcntl_waitpid(-1, $iStatus, WNOHANG|WUNTRACED); if ($iPID == -1) { $this->writeInLog( $this->STD['ERR'], 'Error receive ' . SIGCHLD . ' (sigchld) signal' ); return true; } // юниксовый код выхода $iExitCode = pcntl_wexitstatus($iStatus); // закончим всю работу, если воркеры выходят с фатальной ошибкой if ($iExitCode === 255) $this->stop(); if (isset($this->aInstances[$iPID])) { if ($this->bVerbose) { $this->writeInLog( $this->rVerboseStream, 'End instance: ' . $this->aInstances[$iPID] . ' PID: ' . $iPID ); } $this->aStopped[$this->aInstances[$iPID]] = $this->aInstances[$iPID]; unset($this->aInstances[$iPID]); } break; case SIGALRM: case SIGVTALRM: // код выхода дочернего процесса exit(1); echo 'Child exit on timeout' . PHP_EOL; break; case SIGTSTP: case SIGSTOP: $this->__sleep(); break; case SIGCONT: $this->__wakeup(); break; } return true; } /** * Возвращает флаг, является ли PID записанный в файле активным процессом * * @return boolean */ private function isActive() { // очищаем файловый кеш для PID файла clearstatcache(true, $this->sPIDFilePath); if (file_exists($this->sPIDFilePath) && is_readable($this->sPIDFilePath)) { $iPID = $this->getPIDFromFile(); return (is_numeric($iPID) && posix_kill($iPID, 0) === true) ? true : false; } return false; } /** * Возвращает флаг, является ли массив ассоциативным * * @param array $aArray * @return boolean */ private function isAssoc(array $aArray) { return array_keys($aArray) !== range(0, count($aArray) - 1); } /** * Записывает в файл PID процесса * * @param integer $iPID * @return boolean */ private function writePIDInFile($iPID) { return file_put_contents($this->sPIDFilePath, $iPID, LOCK_EX); } /** * Записывает строку в файл, возвращает количество записанных байт * * @param resource $rLog * @param string $sMessage * @return integer */ public function writeInLog($rLog, $sMessage) { return fwrite( $rLog, '[' . date('d-M-Y H:i:s e') . '] ' . $sMessage . PHP_EOL ); } /** * Пишет в лог мета-информацию * * @return void */ private function writeMeta() { $this->writeInLog( $this->rVerboseStream, 'Execution time: ' . round($this->aMeta['execution_time'], 2) . ' seconds' ); $this->writeInLog($this->rVerboseStream, 'Load average: ' . round($this->aMeta['load_average'][0], 2) . ', ' . round($this->aMeta['load_average'][1], 2) . ', ' . round($this->aMeta['load_average'][2], 2) ); } /** * Устанавливает флаг привязки к консоли * * @return boolean */ public function setUnhookConsole($bHookedConsole) { if ($this->bIsRun) { $this->writeInLog( $this->STD['OUT'], 'Ignore option "unhook console" because workers already run' ); return false; } $this->bHookedConsole = (bool) !$bHookedConsole; return true; } /** * Устанавливает флаг цикличности * * @return boolean */ public function setLoopedMode($bIsLooped) { $this->bIsLooped = (bool) $bIsLooped; return true; } /** * Устанавливает задержку для асинхронного запуска * * @return boolean */ public function setLaunchInstancesDelay($iFirstDelayBetweenLaunch) { $this->iFirstDelayBetweenLaunch = $iFirstDelayBetweenLaunch; return true; } /** * Устанавливает задержку между повторными попытками запуска новых воркеров * * @return boolean */ public function setDelayBetweenLaunchAttempts($iDelayBetweenLaunch) { $this->iDelayBetweenLaunch = $iDelayBetweenLaunch; return true; } /** * Устанавливает максимальное время работы воркеров в секундах * * @return boolean */ public function setMaxExecutionTime($iMaxExecutionTimeInSeconds) { $this->iMaxExecutionTimeInSeconds = $iMaxExecutionTimeInSeconds; return true; } /** * Устанавливает мод подробного вывода * * @return boolean */ public function setVerboseMode($bVerbose) { $this->bVerbose = $bVerbose; return true; } /** * Устанавливает количество воркеров * * @return boolean */ public function setNumberOfWorkers($iWorkers) { if ($this->aWorkers) { $this->writeInLog( $this->STD['OUT'], 'Ignore option "The numbers of processes" because set up option' . ' "Workers data"' ); return false; } else { $this->iNumberOfWorkers = (int) $iWorkers; for ($i = 1; $i <= $this->iNumberOfWorkers; $i++) $this->aWorkers[] = null; // массив имен демонов $this->aWorkersNames = array_keys((array) $this->aWorkers); // массив значений для воркеров $this->aWorkersData = array_values((array) $this->aWorkers); $this->aStopped = $this->getInstancesKeys($this->aWorkersNames); return true; } } /** * Устанавливает данные для проброса в воркер * * @return boolean */ public function setWorkersData($aWorkersData) { if ($this->bIsRun) { $this->writeInLog( $this->STD['OUT'], 'Ignore option "workers data" because workers already run' ); return false; } if ($this->iNumberOfWorkers) $this->writeInLog( $this->STD['OUT'], 'Ignore option "The numbers of processes" because set up option' . ' "Workers data"' ); // выставляем количество воркеров $this->iNumberOfWorkers = count((array) $aWorkersData); // массив имен демонов => значений для воркеров $this->aWorkers = (array) $aWorkersData; // массив имен демонов $this->aWorkersNames = array_keys((array) $aWorkersData); // массив значений для воркеров $this->aWorkersData = array_values((array) $aWorkersData); $this->aStopped = $this->getInstancesKeys($this->aWorkersNames); return true; } /** * Устанавливает функцию, в которой находится программа воркеров * * @return void */ public function setWorkersFunction(callable $cExecutingFunction) { if ($this->bIsRun) { $this->writeInLog( $this->STD['OUT'], 'Ignore option "workers function" because workers already run' ); return false; } $this->cExecutingFunction = (string) $cExecutingFunction; return true; } /** * Устанавливает функцию деструктора родительского процесса * * @return void */ public function setDestructorFunction($cDestructorFunction) { if ($this->bIsRun) { $this->writeInLog( $this->STD['OUT'], 'Ignore option "destructor function" because workers already run' ); return false; } $this->cDestructorFunction = (string) $cDestructorFunction; return true; } /** * Устанавливает функцию деструктора дочерних процессов * * @return void */ public function setWorkercDestructorFunction($cWorkerDestructorFunction) { if ($this->bIsRun) { $this->writeInLog( $this->STD['OUT'], 'Ignore option "workers destructor function" because workers' . ' already run' ); return false; } $this->cWorkerDestructorFunction = (string) $cWorkerDestructorFunction; return true; } /** * Устанавливает вывод потоков ввода/вывода в консоль * * @return void */ public function setIOInConsole($bSTDInConsole) { if ($this->bIsRun) { $this->writeInLog( $this->STD['OUT'], 'Ignore option "set IO in console" because workers already run' ); return false; } $this->bSTDInConsole = (bool) $bSTDInConsole; } /** * Устанавливает временную директорию * * @return boolean */ public function setTempDirectory($sTempDirectory) { if ($this->bIsRun) { $this->writeInLog( $this->STD['OUT'], 'Ignore option "set temp directory" because workers already run' ); return false; } $this->sTempDirectory = $sTempDirectory; $this->sPIDFilePath = $this->sTempDirectory . DIRECTORY_SEPARATOR . $this->sFilesBasename . '.pid'; return true; } /** * Устанавливает директорию логов * * @return boolean */ public function setLogsDirectory($sLogsDirectory) { if ($this->bIsRun) { $this->writeInLog( $this->STD['OUT'], 'Ignore option "set logs directory" because workers already run' ); return false; } $this->sLogsDirectory = $sLogsDirectory; return true; } /** * Устанавливает приоритет для воркерных процессов * * @return void */ public function setWorkersPriority($iWorkerPriority) { if ($this->bIsRun) { $this->writeInLog( $this->STD['OUT'], 'Ignore option "set workers priority" because workers already run' ); return false; } $this->iWorkerPriority = (int) $iWorkerPriority; return true; } /** * Устанавливает обработчики сигналов * * @return void */ private function setSignalHandlers() { pcntl_signal(SIGTERM, array(&$this, "sigHandler")); // сигнал завершения работы pcntl_signal(SIGHUP, array(&$this, "sigHandler")); // закрытия консоли pcntl_signal(SIGINT, array(&$this, "sigHandler")); // ctrl-c c консоли pcntl_signal(SIGALRM, array(&$this, "sigHandler")); // alarm pcntl_signal(SIGVTALRM, array(&$this, "sigHandler")); // alarm pcntl_signal(SIGCHLD, array(&$this, "sigHandler")); // сигналы завершения дочернего процессв pcntl_signal(SIGTSTP, array(&$this, "sigHandler")); // сигналы остановки с консоли ctrl-z pcntl_signal(SIGCONT, array(&$this, "sigHandler")); // продолжение работы } /** * Переопределяет потоки ввода/вывода * * @param $sInstanceName * @return void */ private function setStreamsIO($sInstanceName = null) { if (!$this->bSTDInConsole) { if (!$sInstanceName) $this->writeInLog($this->STD['OUT'], 'Reassignment STD streams'); ini_set('display_errors', 'off'); ini_set( 'error_log', $this->sLogsDirectory . DIRECTORY_SEPARATOR . $this->sFilesBasename . '.error.log' ); $sInstanceName = ($sInstanceName) ? '.' . $sInstanceName : null; // закрываем потоки fclose($this->STD['IN']); fclose($this->STD['OUT']); fclose($this->STD['ERR']); // переопределяем $this->STD['IN'] = fopen( '/dev/null', 'r' ); $this->STD['OUT'] = fopen( $this->sLogsDirectory . DIRECTORY_SEPARATOR . $this->sFilesBasename . $sInstanceName . '.application.log', 'ab' ); $this->STD['ERR'] = fopen( $this->sLogsDirectory . DIRECTORY_SEPARATOR . $this->sFilesBasename . $sInstanceName . '.daemon.log', 'ab' ); // переобпределяем зависимое свойство $this->rVerboseStream = $this->bVerboseInOUT ? $this->STD['OUT'] : $this->STD['ERR']; } } /** * Устанавливает приоритет для дочерних процессов * * @param integer $iWorkerPriority * @return boolean */ private function setPriority($iWorkerPriority) { return $iWorkerPriority ? pcntl_setpriority($iWorkerPriority) : false; } /** * Записывает начальную мета-информацию * * @return void */ private function setStartMeta() { $this->aMeta['time']['start'] = round(microtime(true), 2); } /** * Записывает конечную мета-информацию * * @return void */ private function setStopMeta() { $this->aMeta['time']['stop'] = round(microtime(true), 2); $this->aMeta['execution_time'] = $this->aMeta['time']['stop'] - $this->aMeta['time']['start']; $this->aMeta['load_average'] = sys_getloadavg(); } /** * Возвращает имена инстансов * * @return array */ private function getInstancesKeys() { $bIsAssoc = $this->isAssoc($this->aWorkers); $aKeys = array(); foreach ($this->aWorkersNames as $mKey) $aKeys[$bIsAssoc ? $mKey : $mKey + 1] = $bIsAssoc ? $mKey : $mKey + 1; return $aKeys; } /** * Обрабатывает строки, добавляя дату в начало строки * * @param string $sMessage * @return string */ private function getOutput($sMessage) { $aOutput = explode(PHP_EOL, $sMessage); $aOUT = array(); foreach ($aOutput as $sRow) { $aOUT[] = '[' . date('d-M-Y H:i:s e') . '] ' . rtrim($sRow); } return implode(PHP_EOL, $aOUT) . PHP_EOL; } /** * Возвращает PID из файла * * @return integer */ private function getPIDFromFile() { return (int) trim(file_get_contents($this->sPIDFilePath)); } /** * Возвращает PID родительского процесса * * @return integer */ private function getPID() { return (int) $this->iParentPID; } /** * Возвращает данные для использования в воркере * * @return mixed */ public function getWorkerData() { return $this->mInstanceData; } /** * Возвращает путь к каталогу временных файлов * * @return string */ public function getTempDirectory() { return $this->sTempDirectory; } /** * Возвращает путь к каталогу логов * * @return string */ public function getLogsDirectory() { return $this->sLogsDirectory; } /** * Возвращает префикс файлов (имя скрипта в котором работает демон) * * @return string */ public function getFilesBasename() { return $this->sFilesBasename; } /** * Возвращает путь к PID файлу * * @return string */ public function getPIDFilePath() { return $this->sPIDFilePath; } }
#ifndef _EASYEDITOR_SHAPES_CONTAINER_H_ #define _EASYEDITOR_SHAPES_CONTAINER_H_ #include "DataContainer.h" #include "ObjectVector.h" #include "Shape.h" namespace ee { class ShapesContainer : public DataContainer<ee::Shape> { public: virtual ~ShapesContainer(); // // DataContainer interface // virtual void Traverse(RefVisitor<ee::Shape>& visitor, bool order = true) const override; virtual void Traverse(RefVisitor<ee::Shape>& visitor, DataTraverseType type = DT_ALL, bool order = true) const override; virtual bool Remove(const ee::ShapePtr& shape) override; virtual bool Insert(const ee::ShapePtr& shape) override; virtual bool Insert(const ee::ShapePtr& shape, int idx) override; virtual bool Clear() override; virtual bool ResetOrder(const ee::ShapeConstPtr& shape, bool up) override; virtual bool ResetOrderMost(const ee::ShapeConstPtr& shape, bool up) override; private: ObjectVector<Shape> m_shapes; }; // ShapesContainer } #endif // _EASYEDITOR_SHAPES_CONTAINER_H_
using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; using TcpConnectionsViewer.Models; namespace Tests.Converters { [TestClass] public class IpTests { [TestMethod] public void Ip_IsLocalIpTest() { var localAddrs = Dns.GetHostEntry(Dns.GetHostName()).AddressList.Select(x => x).ToList(); localAddrs.Add(IPAddress.Parse("127.0.0.1")); localAddrs.Add(IPAddress.Parse("0.0.0.0")); for (int i = 0; i < localAddrs.Count; i++) { Assert.IsTrue(Ip.Instance.IsLocal(localAddrs[i])); } } } }
<?php namespace Mincer\Errors { class ClassNotRegisteredException extends \Exception { } }
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>jQuery Mobile Docs - Collapsible Content</title> <link rel="stylesheet" href="../../css/themes/default/jquery.mobile.css" /> <link rel="stylesheet" href="../_assets/css/jqm-docs.css"/> <script src="../../js/jquery.js"></script> <script src="../../docs/_assets/js/jqm-docs.js"></script> <script src="../../js/"></script> </head> <body> <div data-role="page" class="type-interior"> <div data-role="header" data-theme="f"> <h1>Collapsible</h1> <a href="../../" data-icon="home" data-iconpos="notext" data-direction="reverse">Home</a> <a href="../nav.html" data-icon="search" data-iconpos="notext" data-rel="dialog" data-transition="fade">Search</a> </div><!-- /header --> <div data-role="content"> <div class="content-primary"> <h2>Collapsible content</h2> <ul data-role="controlgroup" data-type="horizontal" class="localnav"> <li><a href="content-collapsible.html" data-role="button" data-transition="fade">Basics</a></li> <li><a href="content-collapsible-options.html" data-role="button" data-transition="fade">Options</a></li> <li><a href="content-collapsible-methods.html" data-role="button" data-transition="fade">Methods</a></li> <li><a href="content-collapsible-events.html" data-role="button" data-transition="fade" class="ui-btn-active">Events</a></li> </ul> <p>Bind events directly to the container, typically a <code>div</code> element. Use jQuery Mobile's <a href="../api/events.html">virtual events</a>, or bind standard JavaScript events, like change, focus, blur, etc.:</p> <pre><code> $( ".selector" ).bind( "collapse", function(event, ui) { ... }); </code></pre> <p>The collapsible plugin has the following custom events:</p> <dl> <dt><code>create</code> triggered when a collapsible is created</dt> <dd> <pre><code> $( ".selector" ).collapsible({ create: function(event, ui) { ... } }); </code></pre> </dd> <dt><code>collapse</code> triggered when a collapsible is collapsed</dt> <dd> <pre><code> $( ".selector" ).collapsible({ collapse: function(event, ui) { ... } }); </code></pre> </dd> <dt><code>expand</code> triggered when a collapsible is expanded</dt> <dd> <pre><code> $( ".selector" ).collapsible({ expand: function(event, ui) { ... } }); </code></pre> </dd> </dl> </div><!--/content-primary --> <div class="content-secondary"> <div data-role="collapsible" data-collapsed="true" data-theme="b" data-content-theme="d"> <h3>More in this section</h3> <ul data-role="listview" data-theme="c" data-dividertheme="d"> <li data-role="list-divider">Content Formatting</li> <li><a href="content-html.html">Basic HTML styles</a></li> <li><a href="content-grids.html">Layout grids (columns)</a></li> <li><a href="content-grids-responsive.html">Responsive grids</a></li> <li data-theme="a"><a href="content-collapsible.html">Collapsible content blocks</a></li> <li><a href="content-collapsible-set.html">Collapsible sets (accordions)</a></li> <li><a href="content-themes.html">Theming content</a></li> </ul> </div> </div> </div><!-- /content --> <div data-role="footer" class="footer-docs" data-theme="c"> <p class="jqm-version"></p> <p>&copy; 2012 jQuery Foundation and other contributors</p> </div> </div><!-- /page --> </body> </html>
// Copyright Sigurdur Gunnarsson. All Rights Reserved. // Licensed under the MIT License. See LICENSE file in the project root for full license information. // Example cylinder mesh #pragma once #include "CoreMinimal.h" #include "RuntimeMeshActor.h" #include "SimpleCylinderActor.generated.h" UCLASS() class PROCEDURALMESHES_API ASimpleCylinderActor : public ARuntimeMeshActor { GENERATED_BODY() public: ASimpleCylinderActor(); UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Procedural Parameters") float Radius = 10; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Procedural Parameters") float Height = 100; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Procedural Parameters") int32 RadialSegmentCount = 10; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Procedural Parameters") bool bCapEnds = true; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Procedural Parameters") bool bDoubleSided = false; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Procedural Parameters") bool bSmoothNormals = true; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Procedural Parameters") UMaterialInterface* Material; virtual void OnConstruction(const FTransform& Transform) override; virtual void PostLoad() override; protected: UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Transient) URuntimeMeshProviderStatic* StaticProvider; private: void GenerateMesh(); static void GenerateCylinder(TArray<FVector>& InVertices, TArray<int32>& InTriangles, TArray<FVector>& InNormals, TArray<FRuntimeMeshTangent>& InTangents, TArray<FVector2D>& InTexCoords, const float InHeight, const float InWidth, const int32 InCrossSectionCount, const bool bInCapEnds = false, const bool bInDoubleSided = false, const bool bInSmoothNormals = true); // Mesh buffers void SetupMeshBuffers(); UPROPERTY(Transient) TArray<FVector> Positions; UPROPERTY(Transient) TArray<int32> Triangles; UPROPERTY(Transient) TArray<FVector> Normals; UPROPERTY(Transient) TArray<FRuntimeMeshTangent> Tangents; UPROPERTY(Transient) TArray<FVector2D> TexCoords; };
#map { height: 100vh; }
# homebridge-platform-cec A Homebridge Plugin to Control Devices over HDMI-CEC ## Deprecated See [homebridge-cec-accessory](https://github.com/jbree/homebridge-cec-accessory) instead. ## About homebridge-platform-cec was written with Raspberry Pi in mind. I wanted the ability to control my receiver's mute and volume level. After getting the proof-of-concept working, I thought I'd grow the scope a little bit to control other devices, so I refactored the prototype to make it more extendable(extensible?). Currently, the plugin adds a Power and a Volume accessory to homebridge, both in the form of, "Light," accessories. The volume is controlled by adjusting the brightness of the light. Mute is controlled by turning off the "Light." Eventually, I'd like to have the platform auto-discover devices and available services, and make them available dynamically based on whether or not the device is powered on. Bug reports, feature requests, and pull requests welcome. ## Installation ### On a Raspberry Pi 1. Follow [these instructions](https://github.com/nfarina/homebridge/wiki/Running-HomeBridge-on-a-Raspberry-Pi) to install and run homebridge on Raspberry Pi. Don't give up. Hang in there. 2. Install cec-utils using package manager: `apt-get install cec-utils` 3. Install homebridge-platform-cec: `npm install -g homebridge-platform-cec` 4. Open an issue if you run into problems. ## Configuration Your `~/.homebridge/config.json` file must include homebridge-platform-cec listed in the platforms section: ``` "platforms": [ { "platform": "CecPlatform", "name": "CecPlatform" } ] ```
/* ** GENEREATED FILE - DO NOT MODIFY ** */ package com.wilutions.mslib.uccollaborationlib; import com.wilutions.com.*; /** * IRoomJoinStateChangedEventData. * IRoomJoinStateChangedEventData Interface */ @CoInterface(guid="{4D120020-CE64-43C5-9F84-7A7B2360388F}") public interface IRoomJoinStateChangedEventData extends IDispatch { static boolean __typelib__loaded = __TypeLib.load(); @DeclDISPID(1610743808) public RoomJoinState getJoinState() throws ComException; }
package leetcode; /** * https://leetcode.com/problems/convert-1d-array-into-2d-array/ */ public class Problem2022 { public int[][] construct2DArray(int[] original, int m, int n) { if (m * n != original.length) { return new int[][]{}; } int[][] answer = new int[m][n]; int index = 0; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { answer[i][j] = original[index++]; } } return answer; } }
var UI = require('ui'); var ajax = require('ajax'); var Vector2 = require('vector2'); var webserver = decodeURIComponent(localStorage.getItem('webserver') ? localStorage.getItem('webserver') : 'webserver'); var qvserver = localStorage.getItem('qvserver') ? localStorage.getItem('qvserver') : 'qvserver'; var files = localStorage.getItem('files') ? localStorage.getItem('files') : 'files'; // Show splash screen while waiting for data var splashWindow = new UI.Window(); // Text element to inform user var text = new UI.Text({ position: new Vector2(0, 0), size: new Vector2(144, 168), text:'Downloading data...', font:'GOTHIC_28_BOLD', color:'black', textOverflow:'wrap', textAlign:'center', backgroundColor:'white' }); // Add to splashWindow and show splashWindow.add(text); splashWindow.show(); // Make request to the nodejs app //, webserver: test ajax( { url: webserver + '/getdata', method: 'post', data: {server: qvserver, files: files, webserver: webserver}, crossDomain: true }, function(data) { try { var items = []; data = JSON.parse(data); var areas = data.data; for(var i = 0; i < areas.length; i++) { items.push({ title:areas[i].name //,subtitle:time }); } var resultsMenu = new UI.Menu({ sections: [{ title: 'Areas', items: items }] }); resultsMenu.on('select', function(e) { var innerData = data.data[e.itemIndex].areadata; var title = data.data[e.itemIndex].name; var details = []; for(var d = 0; d < innerData.length; d++) { details.push({ title: innerData[d].category, subtitle: innerData[d].value }); } var detailsMenu = new UI.Menu({ sections: [{ title: title, items: details}] }); detailsMenu.show(); }); // Show the Menu, hide the splash resultsMenu.show(); splashWindow.hide(); } catch (err) { var text = new UI.Text({ position: new Vector2(0, 0), size: new Vector2(144, 168), text:'Error parsing the data', font:'GOTHIC_28_BOLD', color:'black', textOverflow:'wrap', textAlign:'center', backgroundColor:'white' }); // Add to splashWindow and show splashWindow.add(text); splashWindow.show(); } }, function(error) { var text = new UI.Text({ position: new Vector2(0, 0), size: new Vector2(144, 168), text:'Download failed :(', font:'GOTHIC_28_BOLD', color:'black', textOverflow:'wrap', textAlign:'center', backgroundColor:'white' }); // Add to splashWindow and show splashWindow.add(text); splashWindow.show(); }); Pebble.addEventListener('showConfiguration', function(e) { console.log("Showing configuration"); Pebble.openURL('https://googledrive.com/host/0BxjGsOE_3VoOU2RPQ3BjTlBfX0E'); }); Pebble.addEventListener('webviewclosed', function(e) { var options = JSON.parse(decodeURIComponent(e.response)); qvserver = encodeURIComponent(options.qvserver); webserver = encodeURIComponent(options.webserver); files = encodeURIComponent(options.files); if(qvserver == 'undefined') { qvserver = 'http://localhost:4799/QMS/Service'; } localStorage.setItem('qvserver', qvserver); localStorage.setItem('webserver', webserver); localStorage.setItem('files', files); //console.log("Configuration window returned: ", JSON.stringify(options)); }); //Send a string to Pebble var dict = { QVSERVER : qvserver, WEBSERVER: webserver, FILES: files }; Pebble.sendAppMessage(dict, function(e) { console.log("Send successful."); }, function(e) { console.log("Send failed!"); });
import Ember from 'ember'; var PluginsPopularRoute = Ember.Route.extend({ titleToken: 'Popular' }); export default PluginsPopularRoute;
using System; using System.Web; using System.Web.UI; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.Owin; using Owin; using WebApplication2.Models; namespace WebApplication2.Account { public partial class ForgotPassword : Page { protected void Page_Load(object sender, EventArgs e) { } protected void Forgot(object sender, EventArgs e) { if (IsValid) { // Validate the user's email address var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>(); ApplicationUser user = manager.FindByName(Email.Text); if (user == null || !manager.IsEmailConfirmed(user.Id)) { FailureText.Text = "The user either does not exist or is not confirmed."; ErrorMessage.Visible = true; return; } // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771 // Send email with the code and the redirect to reset password page //string code = manager.GeneratePasswordResetToken(user.Id); //string callbackUrl = IdentityHelper.GetResetPasswordRedirectUrl(code, Request); //manager.SendEmail(user.Id, "Reset Password", "Please reset your password by clicking <a href=\"" + callbackUrl + "\">here</a>."); loginForm.Visible = false; DisplayEmail.Visible = true; } } } }
/** * Created by Hernandes on 21/04/2016. */ function PessoaModel(m){ var self = this; var base = new BaseModel(); ko.utils.extend(self,base); self.PessoaID = ko.observable().defaultValue(0).extend({required:true}); self.Nome = ko.observable('').extend({required:true,editable:true}); self.Email = ko.observable('').extend({required:true,editable:true}); self.Enderecos = ko.observableArray([]).typeOf(EnderecoBaseModel); self.assignProperties(m); } define('pessoa-model',function() { return PessoaModel; });
package net.nextpulse.jadmin.dao; import com.google.common.base.Joiner; import net.nextpulse.jadmin.ColumnDefinition; import net.nextpulse.jadmin.FormPostEntry; import org.apache.commons.dbutils.BasicRowProcessor; import org.apache.commons.lang3.StringUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import javax.sql.DataSource; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; /** * DAO implementation for resources backed by a SQL database. * * @author yholkamp */ public class GenericSQLDAO extends AbstractDAO { private static final Logger logger = LogManager.getLogger(); private final String tableName; private DataSource dataSource; public GenericSQLDAO(DataSource dataSource, String tableName) { this.dataSource = dataSource; this.tableName = tableName; } /** * @param keys primary key(s) * @return either an empty optional or one holding a DatabaseEntry matching the keys * @throws DataAccessException if an error occurs while accessing the database. */ @Override public Optional<DatabaseEntry> selectOne(Object[] keys) throws DataAccessException { logger.trace("Selecting one {}", tableName); Map<String, Object> editedObject = null; try(Connection conn = dataSource.getConnection()) { String conditions = resourceSchemaProvider.getKeyColumns().stream() .map(x -> String.format("%s = ?", x.getName())) .reduce((s, s2) -> s + " AND " + s2) .orElseThrow(() -> new DataAccessException("Could not generate SQL condition")); PreparedStatement statement = conn.prepareStatement(String.format("SELECT * FROM %s WHERE %s LIMIT 1", tableName, conditions)); for(int i = 1; i <= resourceSchemaProvider.getKeyColumns().size(); i++) { ColumnDefinition columnDefinition = resourceSchemaProvider.getKeyColumns().get(i - 1); setValue(statement, i, (String) keys[i - 1], columnDefinition, columnDefinition.getName()); } logger.debug("Executing statement {}", statement.toString()); ResultSet results = statement.executeQuery(); if(results.next()) { editedObject = new BasicRowProcessor().toMap(results); } } catch(SQLException e) { logger.error("Exception occurred while executing"); throw new DataAccessException(e); } return editedObject == null ? Optional.empty() : Optional.of(DatabaseEntry.buildFrom(editedObject)); } /** * @param offset number of objects to skip * @param count number of objects to retrieve * @param sortColumn column to sort the values by * @param sortDirection direction to sort, true for ascending, false for descending * @return list of entries of up to count long * @throws DataAccessException if an error occurs while accessing the database. */ @Override public List<DatabaseEntry> selectMultiple(long offset, long count, String sortColumn, boolean sortDirection) throws DataAccessException { logger.trace("Selecting multiple {}, {} offset, {} count", tableName, offset, count); List<DatabaseEntry> rows = new ArrayList<>(); try(Connection conn = dataSource.getConnection()) { // TODO: only select columns that are displayed or part of the primary key String sorting = sortDirection ? "asc" : "desc"; String query = String.format("SELECT * FROM %s ORDER BY %s %s LIMIT %d OFFSET %d", tableName, sortColumn, sorting, count, offset); logger.trace("Formatted selectMultiple query: {}", query); PreparedStatement statement = conn.prepareStatement(query); ResultSet results = statement.executeQuery(); while(results.next()) { Map<String, Object> row = new BasicRowProcessor().toMap(results); rows.add(DatabaseEntry.buildFrom(row)); } } catch(SQLException e) { throw new DataAccessException(e); } return rows; } /** * @param postEntry unfiltered user submitted data, must be used with caution * @throws DataAccessException if an error occurs while accessing the database. */ @Override public void insert(FormPostEntry postEntry) throws DataAccessException { logger.trace("Inserting a new {}", tableName); try(Connection conn = dataSource.getConnection()) { // construct the SQL query String query = createInsertStatement(postEntry); PreparedStatement statement = conn.prepareStatement(query); int index = 1; for(String columnName : postEntry.getKeyValues().keySet()) { setValue(statement, index++, postEntry.getKeyValues().get(columnName), getColumnDefinitions().get(columnName), columnName); } for(String columnName : postEntry.getValues().keySet()) { setValue(statement, index++, postEntry.getValues().get(columnName), getColumnDefinitions().get(columnName), columnName); } logger.debug("Prepared statement SQL: {}", query); int updatedRows = statement.executeUpdate(); if(updatedRows != 1) { throw new SQLException("Updated " + updatedRows + ", expected 1"); } } catch(SQLException e) { throw new DataAccessException(e); } } /** * @param postEntry unfiltered user submitted data, must be used with caution * @throws DataAccessException if an error occurs while accessing the database. */ @Override public void update(FormPostEntry postEntry) throws DataAccessException { logger.trace("Updating an existing {}", tableName); try(Connection conn = dataSource.getConnection()) { // construct the SQL query String query = createUpdateQuery(postEntry); logger.debug("Prepared statement SQL: {}", query); PreparedStatement statement = conn.prepareStatement(query); int index = 1; // first bind the SET field = ? portion for(String columnName : postEntry.getValues().keySet()) { setValue(statement, index++, postEntry.getValues().get(columnName), getColumnDefinitions().get(columnName), columnName); } // and next the WHERE field = ? part for(String columnName : postEntry.getKeyValues().keySet()) { setValue(statement, index++, postEntry.getKeyValues().get(columnName), getColumnDefinitions().get(columnName), columnName); } logger.debug("Query: {}", statement.toString()); int updatedRows = statement.executeUpdate(); if(updatedRows != 1) { throw new SQLException("Updated " + updatedRows + ", expected 1"); } } catch(SQLException e) { throw new DataAccessException(e); } } /** * Returns the number of entries in the database of the resource. * * @return number of entries * @throws DataAccessException if an SQL exception occurred */ @Override public int count() throws DataAccessException { try(Connection conn = dataSource.getConnection()) { PreparedStatement statement = conn.prepareStatement(String.format("SELECT COUNT(*) FROM %s", tableName)); ResultSet results = statement.executeQuery(); results.next(); return results.getInt(1); } catch(SQLException e) { throw new DataAccessException(e); } } @Override public void delete(Object... keys) throws DataAccessException { logger.trace("Updating an existing {}", tableName); try(Connection conn = dataSource.getConnection()) { // construct the SQL query String conditions = resourceSchemaProvider.getKeyColumns().stream() .map(x -> String.format("%s = ?", x.getName())) .reduce((s, s2) -> s + " AND " + s2) .orElseThrow(() -> new DataAccessException("Could not generate SQL condition")); PreparedStatement statement = conn.prepareStatement(String.format("DELETE FROM %s WHERE %s", tableName, conditions)); for(int i = 1; i <= resourceSchemaProvider.getKeyColumns().size(); i++) { ColumnDefinition columnDefinition = resourceSchemaProvider.getKeyColumns().get(i - 1); setValue(statement, i, (String) keys[i - 1], columnDefinition, columnDefinition.getName()); } logger.debug("Executing statement {}", statement.toString()); boolean results = statement.execute(); } catch(SQLException e) { throw new DataAccessException(e); } } /** * Creates an SQL update query for the provided postEntry. * * @param postEntry object to construct the update query for * @return update query with unbound parameters */ protected String createUpdateQuery(FormPostEntry postEntry) { String wherePortion = postEntry.getKeyValues().keySet().stream() .map(x -> x + " = ?") .reduce((s, s2) -> s + " AND " + s2).orElse(""); String setPortion = postEntry.getValues().keySet().stream() .map(x -> x + " = ?") .reduce((s, s2) -> s + "," + s2).orElse(""); return String.format("UPDATE %s SET %s WHERE %s", tableName, setPortion, wherePortion); } /** * Creates an SQL insert query for the provided postEntry. * * @param postEntry object to construct the insert query for * @return insert query with unbound parameters */ protected String createInsertStatement(FormPostEntry postEntry) { // obtain a list of all resource columns present in the post data List<String> columnSet = new ArrayList<>(postEntry.getKeyValues().keySet()); columnSet.addAll(postEntry.getValues().keySet()); String parameters = Joiner.on(",").join(Collections.nCopies(columnSet.size(), "?")); String parameterString = Joiner.on(",").join(columnSet); return String.format("INSERT INTO %s (%s) VALUES (%s)", tableName, parameterString, parameters); } /** * Query updater that attempts to use the most specific setX method based on the provided input. * * @param statement statement to fill * @param index index of the parameter to configure * @param value user-provided value * @param columnDefinition column definition, used to obtain type information * @param columnName name of the column being set * @throws DataAccessException exception that may be thrown by {@link PreparedStatement#setObject(int, Object)} and others */ protected void setValue(PreparedStatement statement, int index, String value, ColumnDefinition columnDefinition, String columnName) throws DataAccessException { if(columnDefinition == null) { throw new DataAccessException("Found no column definition for column " + columnName + ", value " + value); } try { if(StringUtils.isEmpty(value)) { // TODO: use setNull here logger.trace("Setting null for column {}", columnDefinition.getName()); statement.setObject(index, null); } else { switch(columnDefinition.getType()) { case integer: statement.setInt(index, Integer.valueOf(value)); break; case bool: statement.setBoolean(index, Boolean.valueOf(value)); break; case datetime: // TODO: handle input-to-date conversion SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); try { Date date = format.parse(value); statement.setDate(index, new java.sql.Date(date.getTime())); } catch(ParseException e) { logger.error("Could not parse the provided datetime string: {}", value, e); } break; case string: case text: statement.setString(index, value); break; default: logger.error("Unsupported column definition type {} found, setting without type checking", columnDefinition.getType()); statement.setObject(index, value); break; } } } catch(SQLException e) { logger.error("Could not set {}.{} (type {}) to {}", tableName, columnDefinition.getName(), columnDefinition.getType(), value); throw new DataAccessException(e); } } }
goog.provide('ol.DeviceOrientation'); goog.provide('ol.DeviceOrientationProperty'); goog.require('goog.events'); goog.require('goog.math'); goog.require('ol.Object'); goog.require('ol.has'); /** * @enum {string} */ ol.DeviceOrientationProperty = { ALPHA: 'alpha', BETA: 'beta', GAMMA: 'gamma', HEADING: 'heading', TRACKING: 'tracking' }; /** * @classdesc * The ol.DeviceOrientation class provides access to DeviceOrientation * information and events, see the [HTML 5 DeviceOrientation Specification]( * http://www.w3.org/TR/orientation-event/) for more details. * * Many new computers, and especially mobile phones * and tablets, provide hardware support for device orientation. Web * developers targetting mobile devices will be especially interested in this * class. * * Device orientation data are relative to a common starting point. For mobile * devices, the starting point is to lay your phone face up on a table with the * top of the phone pointing north. This represents the zero state. All * angles are then relative to this state. For computers, it is the same except * the screen is open at 90 degrees. * * Device orientation is reported as three angles - `alpha`, `beta`, and * `gamma` - relative to the starting position along the three planar axes X, Y * and Z. The X axis runs from the left edge to the right edge through the * middle of the device. Similarly, the Y axis runs from the bottom to the top * of the device through the middle. The Z axis runs from the back to the front * through the middle. In the starting position, the X axis points to the * right, the Y axis points away from you and the Z axis points straight up * from the device lying flat. * * The three angles representing the device orientation are relative to the * three axes. `alpha` indicates how much the device has been rotated around the * Z axis, which is commonly interpreted as the compass heading (see note * below). `beta` indicates how much the device has been rotated around the X * axis, or how much it is tilted from front to back. `gamma` indicates how * much the device has been rotated around the Y axis, or how much it is tilted * from left to right. * * For most browsers, the `alpha` value returns the compass heading so if the * device points north, it will be 0. With Safari on iOS, the 0 value of * `alpha` is calculated from when device orientation was first requested. * ol.DeviceOrientation provides the `heading` property which normalizes this * behavior across all browsers for you. * * It is important to note that the HTML 5 DeviceOrientation specification * indicates that `alpha`, `beta` and `gamma` are in degrees while the * equivalent properties in ol.DeviceOrientation are in radians for consistency * with all other uses of angles throughout OpenLayers. * * @see http://www.w3.org/TR/orientation-event/ * * @constructor * @extends {ol.Object} * @fires change Triggered when the device orientation changes. * @param {olx.DeviceOrientationOptions=} opt_options Options. * @api */ ol.DeviceOrientation = function(opt_options) { goog.base(this); var options = goog.isDef(opt_options) ? opt_options : {}; /** * @private * @type {goog.events.Key} */ this.listenerKey_ = null; goog.events.listen(this, ol.Object.getChangeEventType(ol.DeviceOrientationProperty.TRACKING), this.handleTrackingChanged_, false, this); this.setTracking(goog.isDef(options.tracking) ? options.tracking : false); }; goog.inherits(ol.DeviceOrientation, ol.Object); /** * @inheritDoc */ ol.DeviceOrientation.prototype.disposeInternal = function() { this.setTracking(false); goog.base(this, 'disposeInternal'); }; /** * @private * @param {goog.events.BrowserEvent} browserEvent Event. */ ol.DeviceOrientation.prototype.orientationChange_ = function(browserEvent) { var event = /** @type {DeviceOrientationEvent} */ (browserEvent.getBrowserEvent()); if (goog.isDefAndNotNull(event.alpha)) { var alpha = goog.math.toRadians(event.alpha); this.set(ol.DeviceOrientationProperty.ALPHA, alpha); // event.absolute is undefined in iOS. if (goog.isBoolean(event.absolute) && event.absolute) { this.set(ol.DeviceOrientationProperty.HEADING, alpha); } else if (goog.isDefAndNotNull(event.webkitCompassHeading) && goog.isDefAndNotNull(event.webkitCompassAccuracy) && event.webkitCompassAccuracy != -1) { var heading = goog.math.toRadians(event.webkitCompassHeading); this.set(ol.DeviceOrientationProperty.HEADING, heading); } } if (goog.isDefAndNotNull(event.beta)) { this.set(ol.DeviceOrientationProperty.BETA, goog.math.toRadians(event.beta)); } if (goog.isDefAndNotNull(event.gamma)) { this.set(ol.DeviceOrientationProperty.GAMMA, goog.math.toRadians(event.gamma)); } this.dispatchChangeEvent(); }; /** * @return {number|undefined} The euler angle in radians of the device from the * standard Z axis. * @observable * @api */ ol.DeviceOrientation.prototype.getAlpha = function() { return /** @type {number|undefined} */ ( this.get(ol.DeviceOrientationProperty.ALPHA)); }; goog.exportProperty( ol.DeviceOrientation.prototype, 'getAlpha', ol.DeviceOrientation.prototype.getAlpha); /** * @return {number|undefined} The euler angle in radians of the device from the * planar X axis. * @observable * @api */ ol.DeviceOrientation.prototype.getBeta = function() { return /** @type {number|undefined} */ ( this.get(ol.DeviceOrientationProperty.BETA)); }; goog.exportProperty( ol.DeviceOrientation.prototype, 'getBeta', ol.DeviceOrientation.prototype.getBeta); /** * @return {number|undefined} The euler angle in radians of the device from the * planar Y axis. * @observable * @api */ ol.DeviceOrientation.prototype.getGamma = function() { return /** @type {number|undefined} */ ( this.get(ol.DeviceOrientationProperty.GAMMA)); }; goog.exportProperty( ol.DeviceOrientation.prototype, 'getGamma', ol.DeviceOrientation.prototype.getGamma); /** * @return {number|undefined} The heading of the device relative to north, in * radians, normalizing for different browser behavior. * @observable * @api */ ol.DeviceOrientation.prototype.getHeading = function() { return /** @type {number|undefined} */ ( this.get(ol.DeviceOrientationProperty.HEADING)); }; goog.exportProperty( ol.DeviceOrientation.prototype, 'getHeading', ol.DeviceOrientation.prototype.getHeading); /** * Are we tracking the device's orientation? * @return {boolean} The status of tracking changes to alpha, beta and gamma. * If true, changes are tracked and reported immediately. * @observable * @api */ ol.DeviceOrientation.prototype.getTracking = function() { return /** @type {boolean} */ ( this.get(ol.DeviceOrientationProperty.TRACKING)); }; goog.exportProperty( ol.DeviceOrientation.prototype, 'getTracking', ol.DeviceOrientation.prototype.getTracking); /** * @private */ ol.DeviceOrientation.prototype.handleTrackingChanged_ = function() { if (ol.has.DEVICE_ORIENTATION) { var tracking = this.getTracking(); if (tracking && goog.isNull(this.listenerKey_)) { this.listenerKey_ = goog.events.listen(goog.global, 'deviceorientation', this.orientationChange_, false, this); } else if (!tracking && !goog.isNull(this.listenerKey_)) { goog.events.unlistenByKey(this.listenerKey_); this.listenerKey_ = null; } } }; /** * Enable or disable tracking of DeviceOrientation events. * @param {boolean} tracking The status of tracking changes to alpha, beta and * gamma. If true, changes are tracked and reported immediately. * @observable * @api */ ol.DeviceOrientation.prototype.setTracking = function(tracking) { this.set(ol.DeviceOrientationProperty.TRACKING, tracking); }; goog.exportProperty( ol.DeviceOrientation.prototype, 'setTracking', ol.DeviceOrientation.prototype.setTracking);
var send = require("./index") module.exports = sendJson /* sendJson := (HttpRequest, HttpResponse, Value | { body: Value, headers?: Object<String, String>, statusCode?: Number }) */ function sendJson(req, res, value, replacer, space) { if (!value || (!value.statusCode && !value.headers)) { value = { body: value } } value.headers = value.headers || {} value.body = JSON.stringify(value.body, replacer, space) value.headers["Content-Type"] = "application/json" send(req, res, value) }
package moltin.example_moltin.activities; import android.content.Context; import android.content.Intent; import android.graphics.Point; import android.graphics.Typeface; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v7.app.ActionBar; import android.view.Display; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu; import com.jeremyfeinstein.slidingmenu.lib.app.SlidingFragmentActivity; import org.json.JSONObject; import java.util.ArrayList; import moltin.android_sdk.Moltin; import moltin.android_sdk.utilities.Constants; import moltin.example_moltin.R; import moltin.example_moltin.data.CartItem; import moltin.example_moltin.data.CollectionItem; import moltin.example_moltin.data.TotalCartItem; import moltin.example_moltin.fragments.CartFragment; import moltin.example_moltin.fragments.CollectionFragment; public class CollectionActivity extends SlidingFragmentActivity implements CollectionFragment.OnCollectionFragmentPictureDownloadListener, CartFragment.OnFragmentUpdatedListener, CartFragment.OnFragmentChangeListener, CollectionFragment.OnCollectionFragmentInteractionListener { private Moltin moltin; private ArrayList<CollectionItem> items; private ArrayList<CartItem> itemsForCart; private TotalCartItem cart; public static CollectionActivity instance = null; private SlidingMenu menu; private android.app.Fragment mContent; private CartFragment menuFragment; private Point screenSize; private int position=0; private LinearLayout layIndex; private int currentOffset=0; private int limit=20; private boolean endOfList=false; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); instance = this; moltin = new Moltin(this); menu = getSlidingMenu(); menu.setShadowWidth(20); menu.setBehindWidth(getListviewWidth()-50); menu.setTouchModeBehind(SlidingMenu.TOUCHMODE_FULLSCREEN); menu.setMode(SlidingMenu.RIGHT); menu.setFadeEnabled(false); menu.setBehindScrollScale(0.5f); setSlidingActionBarEnabled(true); currentOffset=0; endOfList=false; items=new ArrayList<CollectionItem>(); if (savedInstanceState != null) mContent = getFragmentManager().getFragment(savedInstanceState, "mContentCollection"); if (mContent == null) { mContent = CollectionFragment.newInstance(items,getListviewWidth(),currentOffset); } setContentView(R.layout.activity_collection); getFragmentManager() .beginTransaction() .replace(R.id.container, mContent) .commit(); itemsForCart=new ArrayList<CartItem>(); cart=new TotalCartItem(new JSONObject()); cart.setItems(itemsForCart); setBehindContentView(R.layout.cart_content_frame); menuFragment = CartFragment.newInstance(cart, getApplicationContext()); getFragmentManager() .beginTransaction() .replace(R.id.cart_content_frame, menuFragment) .commit(); ((TextView)findViewById(R.id.txtActivityTitle)).setTypeface(Typeface.createFromAsset(getResources().getAssets(), getString(R.string.font_regular))); ((TextView)findViewById(R.id.txtActivityTitleCart)).setTypeface(Typeface.createFromAsset(getResources().getAssets(), getString(R.string.font_regular))); try { moltin.authenticate(getString(R.string.moltin_api_key), new Handler.Callback() { @Override public boolean handleMessage(Message msg) { if (msg.what == Constants.RESULT_OK) { try { getCollections(); } catch (Exception e) { e.printStackTrace(); } return true; } else { return false; } } }); } catch (Exception e) { e.printStackTrace(); } } public void setInitialPosition() { layIndex = (LinearLayout)findViewById(R.id.layIndex); if(((LinearLayout) layIndex).getChildCount() > 0) ((LinearLayout) layIndex).removeAllViews(); for(int i=0;i<items.size();i++) { ImageView img=new ImageView(this); if(position==i) img.setImageDrawable(getResources().getDrawable(R.drawable.circle_active)); else img.setImageDrawable(getResources().getDrawable(R.drawable.circle_inactive)); final float scale = getApplicationContext().getResources().getDisplayMetrics().density; ViewGroup.MarginLayoutParams params = new ViewGroup.MarginLayoutParams( (int)(12*scale + 0.5f), (int)(12*scale + 0.5f)); params.leftMargin = (int)(5*scale + 0.5f); params.rightMargin = (int)(5*scale + 0.5f); params.topMargin = (int)(5*scale + 0.5f); params.bottomMargin = (int)(40*scale + 0.5f); img.setLayoutParams(params); layIndex.addView(img); } } public void setPosition(int newPosition) { if(newPosition!=position) { if(((LinearLayout) layIndex).getChildCount() > 0) { ((ImageView)layIndex.getChildAt(position)).setImageDrawable(getResources().getDrawable(R.drawable.circle_inactive)); ((ImageView)layIndex.getChildAt(newPosition)).setImageDrawable(getResources().getDrawable(R.drawable.circle_active)); position=newPosition; } } } public void getNewPage(int currentNumber) { currentOffset=currentNumber; try { getCollections(); } catch (Exception e) { e.printStackTrace(); } } private int getListviewWidth() { Display display = getWindowManager().getDefaultDisplay(); screenSize = new Point(); display.getSize(screenSize); return screenSize.x; } public void onItemClickHandler(View view) { try { Intent intent = new Intent(this, ProductActivity.class); intent.putExtra("ID",view.getTag(R.id.txtDescription).toString()); intent.putExtra("COLLECTION",view.getTag(R.id.txtCollectionName).toString()); startActivity(intent); } catch (Exception e) { e.printStackTrace(); } } public void onClickHandler(View view) { try { switch (view.getId()) { case R.id.btnPlus: ((LinearLayout)findViewById(R.id.layLoading)).setVisibility(View.VISIBLE); moltin.cart.update(menuFragment.cart.getItems().get((int)view.getTag()).getItemIdentifier(),new String[][]{{"quantity",""+(menuFragment.cart.getItems().get((int)view.getTag()).getItemQuantity()+1)}}, new Handler.Callback() {//"wf60kt82vtzkjIMslZ1FmDyV8WUWNQlLxUiRVLS4", new Handler.Callback() { @Override public boolean handleMessage(Message msg) { menuFragment.refresh(); if (msg.what == Constants.RESULT_OK) { try { } catch (Exception e) { e.printStackTrace(); } return true; } else { ((LinearLayout)findViewById(R.id.layLoading)).setVisibility(View.GONE); return false; } } }); break; case R.id.btnMinus: ((LinearLayout)findViewById(R.id.layLoading)).setVisibility(View.VISIBLE); moltin.cart.update(menuFragment.cart.getItems().get((int)view.getTag()).getItemIdentifier(),new String[][]{{"quantity",""+(menuFragment.cart.getItems().get((int)view.getTag()).getItemQuantity()-1)}}, new Handler.Callback() {//"wf60kt82vtzkjIMslZ1FmDyV8WUWNQlLxUiRVLS4", new Handler.Callback() { @Override public boolean handleMessage(Message msg) { menuFragment.refresh(); if (msg.what == Constants.RESULT_OK) { try { } catch (Exception e) { e.printStackTrace(); } return true; } else { ((LinearLayout)findViewById(R.id.layLoading)).setVisibility(View.GONE); return false; } } }); break; case R.id.btnDelete: ((LinearLayout)findViewById(R.id.layLoading)).setVisibility(View.VISIBLE); moltin.cart.remove(menuFragment.cart.getItems().get((int)view.getTag()).getItemIdentifier(), new Handler.Callback() {//"wf60kt82vtzkjIMslZ1FmDyV8WUWNQlLxUiRVLS4", new Handler.Callback() { @Override public boolean handleMessage(Message msg) { menuFragment.refresh(); if (msg.what == Constants.RESULT_OK) { try { } catch (Exception e) { e.printStackTrace(); } return true; } else { ((LinearLayout)findViewById(R.id.layLoading)).setVisibility(View.GONE); return false; } } }); break; case R.id.btnCheckout: if(menuFragment.cart!=null && menuFragment.cart.getItemTotalNumber()!=null && menuFragment.cart.getItemTotalNumber()>0) { Intent intent = new Intent(this, BillingActivity.class); intent.putExtra("JSON",menuFragment.cart.getItemJson().toString()); startActivity(intent); } else { Toast.makeText(getApplicationContext(), getString(R.string.alert_cart_is_empty), Toast.LENGTH_LONG).show(); } break; case R.id.btnMenu: onHomeClicked(); break; case R.id.btnCart: onHomeClicked(); break; } } catch (Exception e) { e.printStackTrace(); } } public void onHomeClicked() { toggle(); } private void getCollections() throws Exception { if(endOfList) return; ((LinearLayout)findViewById(R.id.layMainLoading)).setVisibility(View.VISIBLE); moltin.collection.listing(new String[][]{{"limit",Integer.toString(limit)},{"offset",Integer.toString(currentOffset)}},new Handler.Callback() { @Override public boolean handleMessage(Message msg) { if (msg.what == Constants.RESULT_OK) { try { JSONObject json=(JSONObject)msg.obj; if(json.has("status") && json.getBoolean("status") && json.has("result") && json.getJSONArray("result").length()>0) { for(int i=0;i<json.getJSONArray("result").length();i++) { items.add(new CollectionItem(json.getJSONArray("result").getJSONObject(i))); } } if(items.size()==json.getJSONObject("pagination").getInt("total")) endOfList=true; else endOfList=false; if(currentOffset>0) { onCollectionFragmentPictureDownloadListener(); } ((CollectionFragment)mContent).customRecyclerView.getAdapter().notifyDataSetChanged(); setInitialPosition(); } catch (Exception e) { e.printStackTrace(); } return true; } else { return false; } } }); } @Override public void onFragmentInteractionForCollectionItem(String itemId) { } @Override protected void onDestroy() { try { instance=null; } catch (Exception e) { e.printStackTrace(); } super.onDestroy(); } @Override protected void onResume() { try { menuFragment.refresh(); } catch (Exception e) { e.printStackTrace(); } super.onResume(); } @Override public void onFragmentChangeForCartItem(TotalCartItem cart) { ((TextView)findViewById(R.id.txtTotalPrice)).setText(cart.getItemTotalPrice()); } @Override public void onFragmentUpdatedForCartItem() { ((LinearLayout)findViewById(R.id.layLoading)).setVisibility(View.GONE); } @Override public void onCollectionFragmentPictureDownloadListener() { try { ((LinearLayout) findViewById(R.id.layMainLoading)).setVisibility(View.GONE); } catch (Exception e) { e.printStackTrace(); } } }
//--------------------------------------------------------------------------- // // <copyright file="CanExecuteChangedEventManager.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. // </copyright> // // Description: Manager for the CanExecuteChanged event in the "weak event listener" // pattern. See WeakEventTable.cs for an overview. // //--------------------------------------------------------------------------- using System; using System.Collections; using System.Collections.Generic; using System.Runtime.CompilerServices; // ConditionalWeakTable using System.Windows; // WeakEventManager using MS.Internal; // NamedObject namespace System.Windows.Input { /// <summary> /// Manager for the ICommand.CanExecuteChanged event. /// </summary> public class CanExecuteChangedEventManager : WeakEventManager { #region Constructors // // Constructors // private CanExecuteChangedEventManager() { } #endregion Constructors #region Public Methods // // Public Methods // /// <summary> /// Add a handler for the given source's event. /// </summary> public static void AddHandler(ICommand source, EventHandler<EventArgs> handler) { if (source == null) throw new ArgumentNullException("source"); if (handler == null) throw new ArgumentNullException("handler"); CurrentManager.PrivateAddHandler(source, handler); } /// <summary> /// Remove a handler for the given source's event. /// </summary> public static void RemoveHandler(ICommand source, EventHandler<EventArgs> handler) { if (source == null) throw new ArgumentNullException("source"); if (handler == null) throw new ArgumentNullException("handler"); CurrentManager.PrivateRemoveHandler(source, handler); } #endregion Public Methods #region Protected Methods // // Protected Methods // /// <summary> /// Listen to the given source for the event. /// </summary> protected override void StartListening(object source) { // never called } /// <summary> /// Stop listening to the given source for the event. /// </summary> protected override void StopListening(object source) { // never called } protected override bool Purge(object source, object data, bool purgeAll) { ICommand command = source as ICommand; List<HandlerSink> list = data as List<HandlerSink>; List<HandlerSink> toRemove = null; bool foundDirt = false; bool removeList = purgeAll || source == null; // find dead entries to be removed from the list if (!removeList) { foreach (HandlerSink sink in list) { if (sink.IsInactive) { if (toRemove == null) { toRemove = new List<HandlerSink>(); } toRemove.Add(sink); } } removeList = (toRemove != null && toRemove.Count == list.Count); } if (removeList) { toRemove = list; } foundDirt = (toRemove != null); // if the whole list is going away, remove the data (unless parent table // is already doing that for us - purgeAll=true) if (removeList && !purgeAll && source != null) { Remove(source); } // remove and detach the dead entries if (foundDirt) { foreach (HandlerSink sink in toRemove) { EventHandler<EventArgs> handler = sink.Handler; sink.Detach(); if (!removeList) // if list is going away, no need to remove from it { list.Remove(sink); } if (handler != null) { RemoveHandlerFromCWT(handler, _cwt); } } } return foundDirt; } #endregion Protected Methods #region Private Properties // // Private Properties // // get the event manager for the current thread private static CanExecuteChangedEventManager CurrentManager { get { Type managerType = typeof(CanExecuteChangedEventManager); CanExecuteChangedEventManager manager = (CanExecuteChangedEventManager)GetCurrentManager(managerType); // at first use, create and register a new manager if (manager == null) { manager = new CanExecuteChangedEventManager(); SetCurrentManager(managerType, manager); } return manager; } } #endregion Private Properties #region Private Methods // // Private Methods // private void PrivateAddHandler(ICommand source, EventHandler<EventArgs> handler) { // get the list of sinks for this source, creating if necessary List<HandlerSink> list = (List<HandlerSink>)this[source]; if (list == null) { list = new List<HandlerSink>(); this[source] = list; } // add a new sink to the list HandlerSink sink = new HandlerSink(this, source, handler); list.Add(sink); // keep the handler alive AddHandlerToCWT(handler, _cwt); } private void PrivateRemoveHandler(ICommand source, EventHandler<EventArgs> handler) { // get the list of sinks for this source List<HandlerSink> list = (List<HandlerSink>)this[source]; if (list != null) { HandlerSink sinkToRemove = null; bool foundDirt = false; // look for the given sink on the list foreach (HandlerSink sink in list) { if (sink.Matches(source, handler)) { sinkToRemove = sink; break; } else if (sink.IsInactive) { foundDirt = true; } } // remove the sink (outside the loop, to avoid re-entrancy issues) if (sinkToRemove != null) { list.Remove(sinkToRemove); sinkToRemove.Detach(); RemoveHandlerFromCWT(handler, _cwt); } // if we noticed any stale sinks, schedule a purge if (foundDirt) { ScheduleCleanup(); } } } // add the handler to the CWT - this keeps the handler alive throughout // the lifetime of the target, without prolonging the lifetime of // the target void AddHandlerToCWT(Delegate handler, ConditionalWeakTable<object, object> cwt) { object value; object target = handler.Target; if (target == null) target = StaticSource; if (!cwt.TryGetValue(target, out value)) { // 99% case - the target only listens once cwt.Add(target, handler); } else { // 1% case - the target listens multiple times // we store the delegates in a list List<Delegate> list = value as List<Delegate>; if (list == null) { // lazily allocate the list, and add the old handler Delegate oldHandler = value as Delegate; list = new List<Delegate>(); list.Add(oldHandler); // install the list as the CWT value cwt.Remove(target); cwt.Add(target, list); } // add the new handler to the list list.Add(handler); } } void RemoveHandlerFromCWT(Delegate handler, ConditionalWeakTable<object, object> cwt) { object value; object target = handler.Target; if (target == null) target = StaticSource; if (_cwt.TryGetValue(target, out value)) { List<Delegate> list = value as List<Delegate>; if (list == null) { // 99% case - the target is removing its single handler _cwt.Remove(target); } else { // 1% case - the target had multiple handlers, and is removing one list.Remove(handler); if (list.Count == 0) { _cwt.Remove(target); } } } } #endregion Private Methods #region Private Data ConditionalWeakTable<object, object> _cwt = new ConditionalWeakTable<object, object>(); static readonly object StaticSource = new NamedObject("StaticSource"); #endregion Private Data #region HandlerSink // Some sources delegate their CanExecuteChanged event to another event // on a different object. For example, RoutedCommands delegate to // CommandManager.RequerySuggested, as do some custom commands (dev11 281808). // Similarly, some 3rd-party commands delegate to a custom class (dev11 449384). // The standard weak-event pattern won't work in these cases. It registers // the source at AddHandler-time, and uses the 'sender' argument at event-delivery // time to look up the relevant information; if these are different, we won't find // the information and therefore won't deliver the event to the intended listeners. // // To cope with this, we use the HandlerSink class. Each call to AddHandler // creates a new HandlerSink, in which we record the original source and // handler, and register a local listener. When the event is raised to a // sink's local listener, the sink merely passes the event along to the original // handler. With judicious use of WeakReference and ConditionalWeakTable, // we can do this without extending the lifetime of the original source or // listener, and without leaking any of the internal data structures. // Here's a diagram illustrating a Button listening to CanExecuteChanged from // a Command that delegates to some other event Proxy.Foo. // // Button --*--> OriginalHandler <---o--- Sink --------o------------> Command // ^ | ^ ^ // --------------------- | | // List ------- ----> LocalHandler <---- Proxy.Foo // Table: (Command) ---^ // // Legend: Weak reference: --o--> // CWT reference: --*--> // Strong reference: -----> // // For each source (i.e. Command), the Manager stores a list of Sinks pertaining // to that Command. Each Sink remembers (weakly) its original source and handler, // and registers for the Command.CanExecuteChanged event in the normal way. // The event may be raised from a different place (Proxy.Foo), but the Sink // knows to pass the event along to the original handler. The Manager uses a // ConditionalWeakTable to keep the original handlers alive, and the Sink // keeps its local handler alive with a local strong reference. // The internal data structures (Sink, List entry, LocalHandler) can be purged // when either the Button or the Command is GC'd. Both conditions are // testable by querying the Sink's weak references. private class HandlerSink { public HandlerSink(CanExecuteChangedEventManager manager, ICommand source, EventHandler<EventArgs> originalHandler) { _manager = manager; _source = new WeakReference(source); _originalHandler = new WeakReference(originalHandler); // In WPF 4.0, elements with commands (Button, Hyperlink, etc.) listened // for CanExecuteChanged and also stored a strong reference to the handler // (in an uncommon field). Some third-party commands relied on this // undocumented implementation detail by storing a weak reference to // the handler. (One such example is Win8 Server Manager's DelegateCommand - // Microsoft.Management.UI.DelegateCommand<T> - see Win8 Bugs 588129.) // // Commands that do this won't work with normal listeners: the listener // simply calls command.CanExecuteChanged += new EventHandler(MyMethod); // the command stores a weak-ref to the handler, no one has a strong-ref // so the handler is soon GC'd, after which the event doesn't get // delivered to the listener. // // In WPF 4.5, Button et al. use this weak event manager to listen to // CanExecuteChanged, indirectly. Only the manager actually listens // directly to the command's event. For compat, the manager stores a // strong reference to its handler. The only reason for this is to // support those commands that relied on the 4.0 implementation. _onCanExecuteChangedHandler = new EventHandler(OnCanExecuteChanged); // BTW, the reason commands used weak-references was to avoid leaking // the Button - see Dev11 267916. This is fixed in 4.5, precisely // by using the weak-event pattern. Commands can now implement // the CanExecuteChanged event the default way - no need for any // fancy weak-reference tricks (which people usually get wrong in // general, as in the case of DelegateCommand<T>). // register the local listener source.CanExecuteChanged += _onCanExecuteChangedHandler; } public bool IsInactive { get { return _source == null || !_source.IsAlive || _originalHandler == null || !_originalHandler.IsAlive; } } public EventHandler<EventArgs> Handler { get { return (_originalHandler != null) ? (EventHandler<EventArgs>)_originalHandler.Target : null; } } public bool Matches(ICommand source, EventHandler<EventArgs> handler) { return (_source != null && (ICommand)_source.Target == source) && (_originalHandler != null && (EventHandler<EventArgs>)_originalHandler.Target == handler); } public void Detach() { if (_source != null) { ICommand source = (ICommand)_source.Target; if (source != null) { source.CanExecuteChanged -= _onCanExecuteChangedHandler; } _source = null; _originalHandler = null; } } void OnCanExecuteChanged(object sender, EventArgs e) { // this protects against re-entrancy: a purge happening // while a CanExecuteChanged event is being delivered if (_source == null) return; // if the sender is our own CommandManager, the original // source delegated is CanExecuteChanged event to // CommandManager.RequerySuggested. We use the original // source as the sender when passing the event along, so that // listeners can distinguish which command is changing. // We could do that for 3rd-party commands that delegate as // well, but we don't for compat with 4.0. if (sender is CommandManager) { sender = _source.Target; } // pass the event along to the original listener EventHandler<EventArgs> handler = (EventHandler<EventArgs>)_originalHandler.Target; if (handler != null) { handler(sender, e); } else { // listener has been GC'd - schedule a purge _manager.ScheduleCleanup(); } } CanExecuteChangedEventManager _manager; WeakReference _source; WeakReference _originalHandler; EventHandler _onCanExecuteChangedHandler; // see remarks in the constructor } #endregion HandlerSink } }
process.env.NODE_ENV = 'production' var ora = require('ora') var rm = require('rimraf') var path = require('path') var chalk = require('chalk') var webpack = require('webpack') var config = require('../config') var webpackConfig = require('./webpack.prod.conf') var spinner = ora('building for production...') spinner.start() rm(path.join(config.build.assetsRoot, config.build.assetsSubDirectory), err => { if (err) throw err webpack(webpackConfig, function (err, stats) { spinner.stop() if (err) throw err process.stdout.write(stats.toString({ colors: true, modules: false, children: false, chunks: false, chunkModules: false }) + '\n\n') console.log(chalk.cyan(' Build complete.\n')) console.log(chalk.yellow( ' Tip: built files are meant to be served over an HTTP server.\n' + ' Opening index.html over file:// won\'t work.\n' )) }) })
#include <stdlib.h> #ifndef NEWSTATE #error "NEWSTATE not specified" #endif #ifndef WRITESTRING #error "WRITESTRING not specified" #endif extern void * NEWSTATE(void (*f)(void), void * ud); void *lua_newstate( void (*f)(void), void * ud) { return NEWSTATE(f,ud); } extern size_t WRITESTRING(char *s, size_t l); size_t galua_writestring( char * s, size_t l ) { return WRITESTRING(s, l); }
/* Revise Listing 3.8, Lottery.java, to generate a lottery of a three-digit number. The program prompts the user to enter a three-digit number and determines whether the user wins according to the following rules: 1. If the user input matches the lottery number in the exact order, the award is $10,000. 2. If all digits in the user input match all digits in the lottery number, the award is $3,000. 3. If one digit in the user input matches a digit in the lottery number, the award is $1,000. */ import java.util.Scanner; public class E3_15 { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter a three-digit number: "); String numString = input.nextLine(); displayLotteryOutcome(numString); } private static void displayLotteryOutcome(String numString) { int a = Integer.parseInt(numString.charAt(0) + ""); int b = Integer.parseInt(numString.charAt(1) + ""); int c = Integer.parseInt(numString.charAt(2) + ""); int x = generateLottery(); int y = generateLottery(); int z = generateLottery(); StringBuilder output = new StringBuilder(); if (a == x && b == y && c == z) { output.append("Matched exact order: you win $10,000"); } else if ((a == x && c == y && b == z) || (b == x && c == y && a == z) || (b == x && a == y && c == z) || (c == x && a == y && b == z) || (c == x && b == y && a == z)) { output.append("All digits match: you win $3,000"); } else if ((a == x || a == y || a == z) || (b == x || b == y || b == z) || (c == x || c == y || c == z)) { output.append("At least one digit matches: you win $1,000"); } else { output.append("Too bad! You win nothing!"); } System.out.println("Lottery: " + x + y + z); System.out.println(output); } private static int generateLottery() { return (int)(Math.random() * 10); } }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Jan Kuhl</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <link href="/stylesheets/style.css" rel="stylesheet" type="text/css" /> <link href="/feed/atom.xml" rel="alternate" type="application/atom+xml" /> <script src="/javascripts/css_browser_selector.js" type="text/javascript"></script> </head> <body> <div id="header"> <div class="inside"> <h2><a href="/">Jan Kuhl</a></h2> <p class="description">Geschenk-, Schul- und Kinderbuchautor</p> </div> </div> <div id="primary" class="single-post"> <div class="inside"> <div class="secondary"> <div class="featured"> <dl> <dt>Erstmals veröffentlicht:</dt> <dd>05.10.05</dd> </dl> <dl> <dt>Updated:</dt> <dd>14.11.07</dd> </dl> <dl> <dt>Kategorien:</dt> <dd> <a href="/pressestimmen">Pressestimmen</a> </dd> </dl> <dl> <dt>Tags:</dt> <dd> <a href="/tags/König-Fittipaldi" rel="tag">König-Fittipaldi</a> <a href="/tags/Presse" rel="tag">Presse</a> <a href="/tags/Schreiben-mit-Kindern" rel="tag">Schreiben-mit-Kindern</a> </dd> </dl> </div> </div> <hr class="hide" /> <div class="primary story"> <h1><a href="/2005/10/5/geschichten-von-koenig-fittipaldi-lassen-kinderherzen-hoeher-schlagen">Geschichten von &quot;König Fittipaldi&quot; lassen Kinderherzen höher schlagen</a></h1> <p><img src="/assets/2007/11/7/Scan10018.jpg" alt="jan" title="jan"/></p> </div> <div class="clear"></div> </div> </div> <!-- [END] #primary --> <!-- Comments --> <hr class="hide" /> <div id="ancillary"> <div class="inside"> <div class="block first"> <h2>Zur Person</h2> <img src="/images/jankuhl.png" align=left height=120> <p>Jan Kuhl ist Geschenk-, Schul- und Kinderbuchautor. Im Rahmen der Leseförderung an Grundschulen führt er regelmäßig gemeinsam mit SchülerInnen Kinderbuchprojekte durch. Er ist Träger des Marburger Literaturpreises Regio 2005.</p> </div> <div class="block"> <h2>Weitere aktuelle Themen</h2> <ul class="dates"> <li> <a href="/2008/6/1/neu-neu-neu"> <span class="date"> 01.06. </span> Neu! Neu! Neu! </a> </li> <li> <a href="/2008/5/31/ein-blick-durch-die-rosarote-brille"> <span class="date"> 31.05. </span> Ein Blick durch die rosarote Brille... </a> </li> <li> <a href="/2008/5/31/jan-kuhl-referiert-auf-dem-jako-o-familienkongress-2008"> <span class="date"> 31.05. </span> Jan Kuhl referiert auf dem JAKO-O-Familienkongress 2008 </a> </li> <li> <a href="/2008/5/28/harry-sucht-sally-auf-der-frankfurter-buchmesse"> <span class="date"> 28.05. </span> "Harry sucht Sally" auf der Frankfurter Buchmesse </a> </li> <li> <a href="/2007/11/18/meine-neue-website-ist-online"> <span class="date"> 18.11. </span> Neue Webseite ist online! </a> </li> <li><a href="/feed/atom.xml"> <img src="/images/feed_icon32x32.png" align=right height=16> Abonniere Feed</a></li> </ul> </div> <div class="block"> <h2>Konkrete Informationen zu</h2> <ul class="counts"> <li><a href="http://astore.amazon.de/jankuhl-21">Online Shop</a> </li> <li><a class="selected" href="/profil">Profil</a></li> <li><a href="/buecher">Buchveröffentlichungen</a></li> <li><a href="/projekte">Projekte</a></li> <li><a href="/gedanken-zu-schule-und-lernen">Gedanken zu Schule und Lernen</a></li> <li><a href="/mein-leben-als-autor">Mein Leben als Autor</a></li> <li><a href="/auszeichnungen-und-preise">Auszeichnungen und Preise</a></li> <li><a href="/fotogalarie">Fotogalerie</a></li> <li><a href="/pressestimmen">Pressestimmen</a></li> </ul> </div> <div class="block"> <!-- tagcloud --> <h2>Suche nach Stichworten/ Tagcloud</h2> <p style="overflow:hidden" class="tagcloud"> <span style='font-size: 1.18em'><a title='Auszeichnung (6)' href='/tags/Auszeichnung'>Auszeichnung</a></span>/ <span style='font-size: 1.04em'><a title='Buchmesse (2)' href='/tags/Buchmesse'>Buchmesse</a></span>/ <span style='font-size: 1.07em'><a title='Jan-Kuhl (3)' href='/tags/Jan-Kuhl'>Jan-Kuhl</a></span>/ <span style='font-size: 1.15em'><a title='König-Fittipaldi (5)' href='/tags/König-Fittipaldi'>König-Fittipaldi</a></span>/ <span style='font-size: 1.18em'><a title='Literaturpreis (6)' href='/tags/Literaturpreis'>Literaturpreis</a></span>/ <span style='font-size: 1.00em'><a title='Neue ars edition Reihen 2008 (1)' href='/tags/Neue ars edition Reihen 2008'>Neue ars edition Reihen 2008</a></span>/ <span style='font-size: 1.41em'><a title='Presse (12)' href='/tags/Presse'>Presse</a></span>/ <span style='font-size: 1.11em'><a title='Projekt:Kinderbuch (4)' href='/tags/Projekt:Kinderbuch'>Kinderbuch</a></span>/ <span style='font-size: 1.15em'><a title='Projekt:König-Fittipaldi (5)' href='/tags/Projekt:König-Fittipaldi'>König-Fittipaldi</a></span>/ <span style='font-size: 1.04em'><a title='Projekt:Lesung (2)' href='/tags/Projekt:Lesung'>Lesung</a></span>/ <span style='font-size: 1.07em'><a title='Schreiben-mit-Kindern (3)' href='/tags/Schreiben-mit-Kindern'>Schreiben-mit-Kindern</a></span>/ <span style='font-size: 1.70em'><a title='Teaser:Geschenkbuch (20)' href='/tags/Teaser:Geschenkbuch'>Geschenkbuch</a></span>/ <span style='font-size: 1.00em'><a title='Teaser:Kinderbuch (1)' href='/tags/Teaser:Kinderbuch'>Kinderbuch</a></span>/ <span style='font-size: 1.00em'><a title='Teaser:Schulbuch (1)' href='/tags/Teaser:Schulbuch'>Schulbuch</a></span>/ <span style='font-size: 1.00em'><a title='Teaser:Unterrichtsmaterialien (1)' href='/tags/Teaser:Unterrichtsmaterialien'>Unterrichtsmaterialien</a></span>/ </p> <!-- search --> <div id="search" class="search"> <form action="/search" id="sform" method="get" name="sform"> <p> <input type="text" id="q" name="q" tag="Warten" value="Stichworte eingeben und bestätigen" /> </p> </form> </div> </div> <div class="clear"></div> </div> </div> <hr class="hide" /> <div id="footer"> <div class="inside"> <p>Copyright &copy; 2004-2008 Jan Kuhl. All rights reserved.</p> <p><a href="/profil/impressum">Impressum</a></p> </div> </div> <!-- [END] #footer --> </body> </html>
.request-loading { display:none; position: absolute; opacity: 0.8; color: #333; left: 50%; } .resource-area { background-color: rgba(0, 0, 0, 0.1); padding: 20px; } .background-thumbnail-area { width: 80px; height: auto; max-width: 80px; max-height: 80px; margin: 1px auto; padding: 1px; float: left; vertical-align: middle; text-align: center; } .sprite-thumbnail-area { width: 300px; height: auto; max-width: 300px; max-height: 300px; margin: 1px auto; padding: 1px; float: left; vertical-align: middle; text-align: center; } .audio-thumbnail-area { width: 30px; height: auto; max-width: 30px; max-height: 30px; margin: 1px auto; padding: 1px; float: left; vertical-align: middle; text-align: center; } .resource-thumbnail { width: auto; height: auto; max-width: 100%; max-height: 100%; } .resource-property { margin: 5px 10px; } .background-media { background-color: #ddffff; margin: 5px; padding: 10px; font-size: 0.7em; } .sprite-media { background-color: #B9E5FF; margin: 5px; padding: 10px; font-size: 0.7em; } .resourcechange-notification { position: fixed; z-index: 3; top: 15%; right: 5%; } .resourceremove-notification { position: fixed; z-index: 3; top: 15%; right: 5%; } .audio-inline-form { display: inline-block; } .audio-player-area { display:inline-block; vertical-align: middle; } /*smaller input size*/ .input-xs { height: 22px; padding: 2px 5px; font-size: 12px; line-height: 1.5; border-radius: 3px; } /*customize table border style*/ table td { border-top-width: 1px !important; border-top-color: #FF8989 !important; } /*remove first border line on table*/ .table > tbody > tr:first-child > td { border: none; } .audio-player { width: 200px; } .bar { height: 18px; /*background: #00FF00;*/ } #dropshade { background: rgba(255, 255, 255, 0); width: 600px; height: 400px; position: absolute; line-height: 50px; text-align: center; z-index: 0; } #dropshade.in { width: 800px; height: 500px; line-height: 200px; } #dropshade.hover { background: lawngreen; opacity: 0.4; } #dropshade.fade { -webkit-transition: all 0.3s ease-out; -moz-transition: all 0.3s ease-out; -ms-transition: all 0.3s ease-out; -o-transition: all 0.3s ease-out; transition: all 0.3s ease-out; opacity: 1; } .sprite-input-append { margin: 10px; } .resource-navbar { margin-bottom: 5px!important; } .error-notification { position: fixed; z-index: 3; top: 15%; right: 5%; } .page-header { margin: 5px 0; }
var duplex = require('duplexer') var through = require('through') module.exports = function (counter) { var countries = {} function count(input) { countries[input.country] = (countries[input.country] || 0) + 1 } function end() { counter.setCounts(countries) } return duplex(through(count, end), counter) }
<?php /** * Entity factory * * @package Walmart API PHP Client * @author Piotr Gadzinski <dev@gadoma.com> * @copyright Copyright (c) 2016 * @license MIT * @since 05/04/2016 */ namespace WalmartApiClient\Factory; class EntityFactory implements EntityFactoryInterface { /** * {@inheritdoc} */ public function instance($className, array $entityData = []) { if (!class_exists($className)) { throw new \InvalidArgumentException("Class $className does not exist."); } $reflector = new \ReflectionClass($className); return $reflector->newInstanceArgs([$entityData]); } }
// Copyright (c) Christophe Gondouin (CGO Conseils). All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System; namespace XrmFramework { [AttributeUsage(AttributeTargets.Field)] public class ExternalValueAttribute : Attribute { public ExternalValueAttribute(string externalValue) { ExternalValue = externalValue; } public string ExternalValue { get; } } }
/* * * This CSS file is based on: * - CSS Dice: An Experiment by Jonathan Sampson - @jonathansampson http://sampsonblog.com/289/of-dice-dabblet-and-css * - normalize.css v3.0.3 https://github.com/necolas/normalize.css Copyright (c) Nicolas Gallagher and Jonathan Neal * - "Simpliste" template and "Simple" skin by Renat Rafikov http://cssr.ru/simpliste/ Copyright (c) 2012 Renat Rafikov * */ /* CSS Reset: Based on normalize.css v3.0.3 https://github.com/necolas/normalize.css Copyright (c) Nicolas Gallagher and Jonathan Neal */ html { font-family: Verdana,sans-serif; -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%; } body { margin: 0; background: #f2f2f2; } footer,header,section { display: block; } [hidden]{ display: none; } a { background-color: transparent; } a { color: #2f2; text-decoration: none; } a:active,a:hover { outline: 0; } b,strong { font-weight: bold; } img { border: 0; } button,input { color: inherit; font: inherit; margin: 0; } button { overflow: visible; text-transform: none; -webkit-appearance: button; cursor: pointer; } button[disabled] { cursor: default; } button::-moz-focus-inner,input::-moz-focus-inner { border: 0; padding: 0; } input { line-height: normal; } table { border-collapse: collapse;border-spacing: 0; } td,th { padding: 0; } ul { list-style:none } ul li { padding:0 0 0.4em 0; } h1 { font-size: 2em; margin: 0.67em 0; } h1,h2,h3 { font-weight:normal; } /* End CSS Reset */ /* CSS Dice: An Experiment by Jonathan Sampson - @jonathansampson http://sampsonblog.com/tag/web-design */ .die.one .dot { box-shadow: 0 .2em 0 #fff } .die.two .dot { background: transparent; box-shadow: -2.3em -2.3em 0 #345, 2.3em 2.3em 0 #345, -2.3em -2.3em 0 #fff, 2.3em 2.4em 0 #fff } .die.three .dot { box-shadow: -2.3em -2.3em 0 #345, 2.3em 2.3em 0 #345, -2.3em -2.3em 0 #fff, 2.3em 2.4em 0 #fff, 0 .2em 0 #fff } .die.four .dot { background: transparent; box-shadow: -2.3em -2.3em 0 #345, 2.3em 2.3em 0 #345, -2.3em 2.3em 0 #345, 2.3em -2.3em 0 #345, -2.3em -2.3em 0 #fff, 2.3em 2.4em 0 #fff, -2.3em 2.4em 0 #fff, 2.3em -2.3em 0 #fff } .die.five .dot { box-shadow: -2.3em -2.3em 0 #345, 2.3em 2.3em 0 #345, -2.3em 2.3em 0 #345, 2.3em -2.3em 0 #345, -2.3em -2.2em 0 #fff, 2.3em -2.2em 0 #fff, 2.3em 2.4em 0 #fff, -2.3em 2.4em 0 #fff, 0 .2em 0 #fff } .die.six .dot { background: transparent; box-shadow: -2.3em -2.3em 0 #345, -2.3em 0 0 #345, -2.3em 2.3em 0 #345, 2.3em -2.3em 0 #345, 2.3em 0 0 #345, 2.3em 2.3em 0 #345, -2.3em -2.1em 0 #fff, -2.3em .2em 0 #fff, -2.3em 2.4em 0 #fff, 2.3em 2.4em 0 #fff, 2.3em .2em 0 #fff, 2.3em -2.1em 0 #fff } .die { border-top: 1px solid #f1f1f1; width: 50px; height: 50px; border-radius: 10px; position: relative; margin: 10px; font-size: 6px; display: inline-block; box-shadow: 0px 5px 0 #CCC, 0 6px 3px #444, 0 10px 5px #333; background-image: -webkit-radial-gradient(#fefefe, #f0f0f0); background-image: radial-gradient(#fefefe, #f0f0f0); background-color: #fafafa; } .dot { width: 20%; height: 20%; left: 50%; top: 50%; margin: -10%; background: #345; border-radius: 50%; display: block; position: absolute; } /* End CSS Dice */ /* Theme: Based on "Simpliste" template and "Simple" skin by Renat Rafikov http://cssr.ru/simpliste Copyright (c) 2012 Renat Rafikov */ /**** Helper classes ****/ .hideme{ display:none; } .img { max-width:100%;height:auto } /**** Page ****/ .container { max-width:1300px; margin:0 auto; } .header { margin:1px 0 3em 0; padding:2em 2% 0 2%; } .logo { float:left; display:inline-block; padding:0 0 1em; font-size:18px; color:#333; } .info { padding:0 1% 1em 1%; } .board { background: #070; border-radius: 5px; box-shadow: 0 0 9px 3px #333 inset, 0 0 50px #111 inset, 0 30px 30px -20px #333 inset; padding: 15px 0 15px 2%; margin: 0 0 2% 0; color: #fafafa; } .footer { padding:1em 3% 3em 3%; color:#717171; font-size:12px; } /* .clearfix:before, .clearfix:after { content:""; display:table; } .clearfix:after { clear:both; } */ /* Columns */ .col_25 { width:23%; margin:0 2% 0 0; float:left; } .col_33 { width:31%; margin:0 2% 0 0; float:left; } .col_40 { width:38%; float:left; } .col_50 { width:48%; margin:0 2% 0 0; float:left; } .grid-column { margin:0 16px 8px 0; display:inline-block; box-sizing: border-box; } /**** Region ****/ .region { margin: 0 12px 6px 3px; } .side-region { float: left; margin:0 10px 5px 0; } /* .modal_LOADER { background-color: rgba(51, 51, 51, 0.3); cursor: wait; height: 100%; left: 0; position: fixed; top: 0; width: 100%; z-index: 9999; } .modal_LOADER img { cursor: wait; left: 48%; position: relative; top: 34%; } */ /**** Message ****/ .warning { border:1px solid #ec252e; color:#fff; padding:8px 14px; background:#ea0000; border-radius:8px; } .success { border:1px solid #399f16; color:#fff; background:#399f16; padding:8px 14px; border-radius:8px; } .message { border:1px solid #f1edcf; color:#000; background:#fbf8e3; padding:8px 14px; border-radius:8px; } .message > a { color: #004dd9 } .messages { position: absolute; width: 100%; top: 0; margin: 0; padding: 0; z-index: 9999; } .messages > div { width: 60%; margin: 0 auto; border-radius: 0 0 8px 8px; position: relative; } /**** Button ****/ .button { background-color: #ccc; box-shadow: 0 0 3px 2px #eee inset, 0 3px 3px #333; border: 1px solid #888; color: #333; text-shadow: 1px 1px 1px #ddd; border-radius: 15px; text-align:center; text-decoration:none; padding:10px 20px; display:inline-block; margin: 3px; } .button:hover { background-color: #aaa; border-color: #666; box-shadow: 0 0 3px 2px #ccc inset, 0 3px 3px #111; } .button.hot { background-color: #2c2; border: 1px solid #282; box-shadow: 0 0 3px 2px #2e2 inset, 0 3px 3px #333; color: #f1f1f1; text-shadow:1px 1px 1px #333; margin: 3px; } .button.hot:hover { background-color: #2a2; border-color: #262; box-shadow: 0 0 3px 2px #2c2 inset, 0 3px 3px #111; } /**** Item ****/ .text_field { background-color: #fafafa; border: 1px solid #c0c0c0; border-radius: 3px; box-shadow: 3px 3px 3px #333; box-sizing: border-box; color: #333; height: 100%; padding: 2px 5px; margin: 3px; } /**** Dice item plugin ****/ .die-container { width: 70px; height: 80px; border-radius: 8px; margin: 0 0 8px 8px } .hold-die { background-color: #00bb00; box-shadow: 0 0 1px 1px #2d2 inset; } /**** Label ****/ span.label-error { color: #ec252e; display: block; margin: 0 3px 3px; } label.label-optional { display: block; margin: 12px 3px 3px; } /**** Report ****/ .paper { margin-right: 6px; margin-bottom: 18px; background-color: #fefefe; border-radius: 1px; letter-spacing: -1px; color: #666; width:100%; font-size:1.4em; text-align: center; box-shadow: 0 0 30px rgba(0, 0, 0, 0.1) inset, 1px 1px 0 rgba(0,0,0,0.100), 3px 3px 0 rgba(240,240,240, 1.0), 4px 4px 0 rgba(0,0,0,0.125), 6px 6px 0 rgba(240,240,240,1.0), 7px 7px 0 rgba(0,0,0,0.150), 9px 9px 0 rgba(240,240,240,1.0), 10px 10px 0 rgba(0,0,0,0.175), 10px 12px 4px #333; } .paper td { border-top:1px solid #91d1d3; color:#333; } .paper th { font-weight: bold; } .score-card { width: auto; font-size:0.8em; margin-bottom: 12px; } .score-card td.cell1 { border-left: 1px solid #91d1d3; padding-left: 8px; text-align: left; } .score-card td.cell2 { padding: 1px 8px; text-align: right; } .score-card td.top-border { border-top: 2px solid #666; } .score-card td.side > div { float: left; margin: 0; padding: 0; bottom: 0; left: 0; overflow: visible; white-space: nowrap; -webkit-transform: rotate(-90deg); -ms-transform: rotate(-90deg); transform: rotate(-90deg); width: 20px; } .score-card td.score-box { height: 28px; width: 48px; } .score-card td.score-box > a { background-color: #fafafa; border: 1px solid #c0c0c0; border-radius: 3px; box-sizing: border-box; color: #333; display: block; font-weight: bold; padding: 0 5px; width: 100%; height: 100%; box-shadow: 0 0 1px #333 inset; } .score-card td.score-box > a > span { margin-right: 3px; } .score-card tr:first-child td { border-top: none; } .score-card tr:last-child td { font-weight: bold; padding-top: 2px; padding-bottom: 2px; } /**** responsive ****/ @media only screen and (max-width:750px) { /* Tablet */ .col_25, .col_33, .col_40, .col_50 { width:98%; float:none; } .messages { position: static; } } @media only screen and (max-width:480px) { /* Smartphone */ .header { margin-bottom:0; } .logo{ display:block; float:none; text-align:center; } .board { padding-top: 1%; padding-left: 1%; } } /* End CSS Theme */
module Keisan module Functions class ExpressionFunction < Function attr_reader :arguments, :expression def initialize(name, arguments, expression, transient_definitions) super(name, arguments.count) if expression.is_a?(::String) @expression = AST::parse(expression) else @expression = expression.deep_dup end @arguments = arguments @transient_definitions = transient_definitions end def freeze @arguments.freeze @expression.freeze super end def call(context, *args) validate_arguments!(args.count) local = local_context_for(context) arguments.each.with_index do |arg_name, i| local.register_variable!(arg_name, args[i]) end expression.value(local) end def value(ast_function, context = nil) validate_arguments!(ast_function.children.count) context ||= Context.new argument_values = ast_function.children.map {|child| child.value(context)} call(context, *argument_values) end def evaluate(ast_function, context = nil) validate_arguments!(ast_function.children.count) context ||= Context.new local = local_context_for(context) argument_values = ast_function.children.map {|child| child.evaluate(context)} arguments.each.with_index do |arg_name, i| local.register_variable!(arg_name, argument_values[i].evaluate(context)) end expression.evaluated(local) end def simplify(ast_function, context = nil) validate_arguments!(ast_function.children.count) ast_function.instance_variable_set( :@children, ast_function.children.map {|child| child.evaluate(context)} ) if ast_function.children.all? {|child| child.is_a?(AST::ConstantLiteral)} value(ast_function, context).to_node.simplify(context) else ast_function end end # Multi-argument functions work as follows: # Given f(x, y), in general we will take the derivative with respect to t, # and x = x(t), y = y(t). For instance d/dt f(2*t, t+1). # In this case, chain rule gives derivative: # dx(t)/dt * f_x(x(t), y(t)) + dy(t)/dt * f_y(x(t), y(t)), # where f_x and f_y are the x and y partial derivatives respectively. def differentiate(ast_function, variable, context = nil) validate_arguments!(ast_function.children.count) local = local_context_for(context) argument_values = ast_function.children.map {|child| child.evaluated(local)} argument_derivatives = ast_function.children.map do |child| child.differentiated(variable, context) end partial_derivatives = calculate_partial_derivatives(context) AST::Plus.new( argument_derivatives.map.with_index {|argument_derivative, i| partial_derivative = partial_derivatives[i] argument_variables.each.with_index {|argument_variable, j| partial_derivative = partial_derivative.replaced(argument_variable, argument_values[j]) } AST::Times.new([argument_derivative, partial_derivative]) } ) end private def argument_variables arguments.map {|argument| AST::Variable.new(argument)} end def calculate_partial_derivatives(context) argument_variables.map.with_index do |variable, i| partial_derivative = expression.differentiated(variable, context) end end def local_context_for(context = nil) context ||= Context.new context.spawn_child(definitions: @transient_definitions, shadowed: @arguments, transient: true) end end end end
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package zmarkdown.javaeditor; import org.python.util.PythonInterpreter; import org.python.core.*; /** * * @author firm1 */ public class EMarkdown{ PythonInterpreter interp; public EMarkdown() { interp = new PythonInterpreter(); interp.exec("from markdown import Markdown"); interp.exec("from markdown.extensions.zds import ZdsExtension"); interp.exec("from smileys_definition import smileys"); } public String html(String chaine) { interp.set("text", chaine); interp.exec("render = Markdown(extensions=(ZdsExtension({'inline': False, 'emoticons': smileys}),),safe_mode = 'escape', enable_attributes = False, tab_length = 4, output_format = 'html5', smart_emphasis = True, lazy_ol = True).convert(text)"); PyString render = interp.get("render", PyString.class); return render.toString(); } }
using System; using NetOffice; using NetOffice.Attributes; namespace NetOffice.OfficeApi.Enums { /// <summary> /// SupportByVersion Office 12, 14, 15, 16 /// </summary> ///<remarks> MSDN Online Documentation: <see href="https://docs.microsoft.com/en-us/office/vba/api/Office.SignatureType"/> </remarks> [SupportByVersion("Office", 12,14,15,16)] [EntityType(EntityType.IsEnum)] public enum SignatureType { /// <summary> /// SupportByVersion Office 12, 14, 15, 16 /// </summary> /// <remarks>0</remarks> [SupportByVersion("Office", 12,14,15,16)] sigtypeUnknown = 0, /// <summary> /// SupportByVersion Office 12, 14, 15, 16 /// </summary> /// <remarks>1</remarks> [SupportByVersion("Office", 12,14,15,16)] sigtypeNonVisible = 1, /// <summary> /// SupportByVersion Office 12, 14, 15, 16 /// </summary> /// <remarks>2</remarks> [SupportByVersion("Office", 12,14,15,16)] sigtypeSignatureLine = 2, /// <summary> /// SupportByVersion Office 12, 14, 15, 16 /// </summary> /// <remarks>3</remarks> [SupportByVersion("Office", 12,14,15,16)] sigtypeMax = 3 } }
export default function() { let directive = { restrict: 'E', replace: true, scope: { ad: '=' }, templateUrl: './directives/adCard/template.html', controller: ['$scope', ($scope) => { if ($scope.ad.thumbnail) { $scope.ad.previewImg = `${$scope.ad.thumbnail.base_url}/card/${$scope.ad.thumbnail.path}`; } else { $scope.ad.previewImg = '/src/images/car2.png'; } if (120 <= $scope.ad.body.length) { $scope.ad.shortBody = `${$scope.ad.body.slice(0, 119).trim()}...`; } else { $scope.ad.shortBody = $scope.ad.body; } }] }; return directive; }
<?php /** * Get Partial * Get and render a partial template file. * * @since 1.0.0 * * $part: (string) name of the partial, relative to * the _templates/partials directory. */ function get_partial( $part ) { # Get theme object global $_theme; return $_theme->get_partial($part); } /** * Get Header * Get header partial. * * @since 1.0.0 * * $name: (string) name of custom header file. */ function get_header( $name = 'header' ) { return get_partial($name); } /** * Get Footer * Get footer partial. * * @since 1.0.0 * * $name: (string) name of custom footer file. */ function get_footer( $name = 'footer' ) { return get_partial($name); } /** * Get Sidebar * Get sidebar partial. * * @since 1.0.0 * * $name: (string) name of custom sidebar file. */ function get_sidebar( $name = 'sidebar' ) { return get_partial($name); } /** * Theme Add Meta * * @since 1.0.1 * * $meta: (array) meta tags to add (key => value) */ function theme_add_meta( array $meta = array() ) { # Get Page Array $page = get('page'); # Merge New Data $page = array_merge($page, $meta); # Update Page Array set('page', $page); # Return updated array return $page; } /** * Theme Remove Meta * * @since 1.0.1 * * $key: (string) key of the meta data to remove */ function theme_remove_meta( $key ) { # Get Page Array $page = get('page'); # Protected Keys $protected = array( 'is_home', 'path', 'slug' ); # Check Key is not protected if ( in_array($key, $protected) ) { return false; } # Check Key exists if ( isset($page[$key]) ) { # Remove value unset($page[$key]); # Update Page Array set('page', $page); return $page; } return false; } /** * Assets Dir * Return location of assets relative to * the ROOT_DIR. * * @since 1.0.1 * * $prefix: (string) string to prepend to the returned value. * $print: (bool) print the value to the screen */ function assets_dir( $prefix = '/', $print = true ) { # Get Theme global $_theme; # Get Current Theme Location $location = $_theme->prop('dir'); if ( $print === true ) { echo $prefix . $location . '/assets'; } else { return $prefix . $location . '/assets'; } }
var app = require('app'); // Module to control application life. var BrowserWindow = require('browser-window'); // Module to create native browser window. // Report crashes to our server. require('crash-reporter').start(); // Keep a global reference of the window object, if you don't, the window will // be closed automatically when the JavaScript object is garbage collected. var mainWindow = null; // Quit when all windows are closed. app.on('window-all-closed', function() { 'use strict'; // On OS X it is common for applications and their menu bar // to stay active until the user quits explicitly with Cmd + Q if (process.platform !== 'darwin') { app.quit(); } }); // This method will be called when Electron has finished // initialization and is ready to create browser windows. app.on('ready', function() { 'use strict'; // Create the browser window. mainWindow = new BrowserWindow({ width: 1024, height: 768, title: 'Build & Deploy', 'auto-hide-menu-bar': true }); // and load the index.html of the app. mainWindow.loadUrl('file://' + __dirname + '/index.html'); // Emitted when the window is closed. mainWindow.on('closed', function() { // Dereference the window object, usually you would store windows // in an array if your app supports multi windows, this is the time // when you should delete the corresponding element. mainWindow = null; }); });
using System.Collections.Generic; using System.Linq; using ThoughtWorks.ConferenceTrackManager.Models; namespace ThoughtWorks.ConferenceTrackManager.App { public interface ITalkDistributor { bool DistributeTalksAcrossSessions(IList<IConferenceSession> sessions, IList<ITalk> allTalks); } public class TalkDistributor : ITalkDistributor { public bool DistributeTalksAcrossSessions(IList<IConferenceSession> sessions, IList<ITalk> talks) { var successfullyDistributedTalks = true; var sortedTalks = talks.OrderByDescending(t => t.LengthInMinutes).ToList(); var talkIndex = 0; while (talkIndex < sortedTalks.Count()) { var successfullyAddedTalkToSession = false; foreach (var session in sessions) { successfullyAddedTalkToSession = session.TryIncludeTalkInSession(sortedTalks[talkIndex]); if (successfullyAddedTalkToSession) { talkIndex = talkIndex + 1; } } if (!successfullyAddedTalkToSession) { successfullyDistributedTalks = false; talkIndex = talkIndex + 1; } } return successfullyDistributedTalks; } } }
#ifndef DW_RAYTRACER_RAY_H #define DW_RAYTRACER_RAY_H #include "Vector3.h" namespace raytracer { class Ray { public: inline Ray() { } inline Ray(const Vector3& rOrigin, const Vector3& rDirection) { setOrigin(rOrigin); setDirection(rDirection); } inline Vector3 pointAtParameter(float t) const { return rOrigin + (t * rDirection); } inline const Vector3& origin() const { return rOrigin; } inline const Vector3& direction() const { return rDirection; } inline const Vector3& inverseDirection() const { return rInverseDirection; } inline void setOrigin(const Vector3& newOrigin) { rOrigin = newOrigin; } inline void setDirection(const Vector3& newDirection) { rDirection = newDirection; // Compute inverse of ray direction rInverseDirection = Vector3(1.0f / rDirection.x, 1.0f / rDirection.y, 1.0f / rDirection.z); // Update ray direction sings directionSigns[0] = (rDirection.x > 0 ? 0 : 1); directionSigns[1] = (rDirection.y > 0 ? 0 : 1); directionSigns[2] = (rDirection.z > 0 ? 0 : 1); } // Sign of (X, Y, Z) components of directions. // These values are pre-computed so efficient bounding box // intersections can be performed. This strategy was taken // from the book Realistic Raytracing (Shirley, Morley) int directionSigns[3]; private: Vector3 rOrigin; Vector3 rDirection; // The ray's INVERSE direction is also pre-computed for efficiency Vector3 rInverseDirection; }; } #endif
import React from 'react'; import styled from 'styled-components'; import Item from './Item'; import parchment from '../assets/parchment.png'; import chest from '../assets/chest.png'; const Container = styled.div` background: url(${parchment}); position: relative; height: 286px; width: 303px; align-self: center; margin: 10px; `; const Items = styled.div` position: absolute; display: flex; flex-direction: row; flex-wrap: wrap; align-items: center; top: 78px; left: 130px; width: 108px; `; const Chest = styled.div` position: absolute; background: url(${chest}); image-rendering: pixelated; width: 92px; height: 92px; top: 138px; left: 34px; `; const Clue = ({ rewards, className, style }) => ( <Container className={className} style={style}> <Items> {rewards.map(reward => ( <Item key={reward.id} id={reward.id} amount={reward.amount} /> ))} </Items> <Chest /> </Container> ); export default Clue;
var config = this.window ? {} : module.exports; config.Rjs = { environment: "browser", rootPath: "../", sources: [ "build/Reality.combined.replaced.js", ], tests: [ "test/**/*.js" ] };
/*========================================================================= Program: Visualization Toolkit Module: vtkCellTypes.h Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ // .NAME vtkCellTypes - object provides direct access to cells in vtkCellArray and type information // .SECTION Description // This class is a supplemental object to vtkCellArray to allow random access // into cells as well as representing cell type information. The "location" // field is the location in the vtkCellArray list in terms of an integer // offset. An integer offset was used instead of a pointer for easy storage // and inter-process communication. The type information is defined in the // file vtkCellType.h. // // .SECTION Caveats // Sometimes this class is used to pass type information independent of the // random access (i.e., location) information. For example, see // vtkDataSet::GetCellTypes(). If you use the class in this way, you can use // a location value of -1. // // .SECTION See Also // vtkCellArray vtkCellLinks #ifndef vtkCellTypes_h #define vtkCellTypes_h #include "vtkCommonDataModelModule.h" // For export macro #include "vtkObject.h" #include "vtkIntArray.h" // Needed for inline methods #include "vtkUnsignedCharArray.h" // Needed for inline methods #include "vtkCellType.h" // Needed for VTK_EMPTY_CELL class VTKCOMMONDATAMODEL_EXPORT vtkCellTypes : public vtkObject { public: static vtkCellTypes *New(); vtkTypeMacro(vtkCellTypes,vtkObject); void PrintSelf(ostream& os, vtkIndent indent); // Description: // Allocate memory for this array. Delete old storage only if necessary. int Allocate(int sz=512, int ext=1000); // Description: // Add a cell at specified id. void InsertCell(int id, unsigned char type, int loc); // Description: // Add a cell to the object in the next available slot. vtkIdType InsertNextCell(unsigned char type, int loc); // Description: // Specify a group of cell types. void SetCellTypes(int ncells, vtkUnsignedCharArray *cellTypes, vtkIntArray *cellLocations); // Description: // Return the location of the cell in the associated vtkCellArray. vtkIdType GetCellLocation(int cellId) { return this->LocationArray->GetValue(cellId);}; // Description: // Delete cell by setting to NULL cell type. void DeleteCell(vtkIdType cellId) { this->TypeArray->SetValue(cellId, VTK_EMPTY_CELL);}; // Description: // Return the number of types in the list. vtkIdType GetNumberOfTypes() { return (this->MaxId + 1);}; // Description: // Return 1 if type specified is contained in list; 0 otherwise. int IsType(unsigned char type); // Description: // Add the type specified to the end of the list. Range checking is performed. vtkIdType InsertNextType(unsigned char type){return this->InsertNextCell(type,-1);}; // Description: // Return the type of cell. unsigned char GetCellType(int cellId) { return this->TypeArray->GetValue(cellId);}; // Description: // Reclaim any extra memory. void Squeeze(); // Description: // Initialize object without releasing memory. void Reset(); // Description: // Return the memory in kilobytes consumed by this cell type array. // Used to support streaming and reading/writing data. The value // returned is guaranteed to be greater than or equal to the memory // required to actually represent the data represented by this object. // The information returned is valid only after the pipeline has // been updated. unsigned long GetActualMemorySize(); // Description: // Standard DeepCopy method. Since this object contains no reference // to other objects, there is no ShallowCopy. void DeepCopy(vtkCellTypes *src); // Description: // Given an int (as defined in vtkCellType.h) identifier for a class // return it's classname. static const char* GetClassNameFromTypeId(int typeId); // Description: // Given a data object classname, return it's int identified (as // defined in vtkCellType.h) static int GetTypeIdFromClassName(const char* classname); // Description: // This convenience method is a fast check to determine if a cell type // represents a linear or nonlinear cell. This is generally much more // efficient than getting the appropriate vtkCell and checking its IsLinear // method. static int IsLinear(unsigned char type); protected: vtkCellTypes(); ~vtkCellTypes(); vtkUnsignedCharArray *TypeArray; // pointer to types array vtkIntArray *LocationArray; // pointer to array of offsets vtkIdType Size; // allocated size of data vtkIdType MaxId; // maximum index inserted thus far vtkIdType Extend; // grow array by this point private: vtkCellTypes(const vtkCellTypes&); // Not implemented. void operator=(const vtkCellTypes&); // Not implemented. }; //---------------------------------------------------------------------------- inline int vtkCellTypes::IsType(unsigned char type) { int numTypes=this->GetNumberOfTypes(); for (int i=0; i<numTypes; i++) { if ( type == this->GetCellType(i)) { return 1; } } return 0; } //----------------------------------------------------------------------------- inline int vtkCellTypes::IsLinear(unsigned char type) { return ( (type <= 20) || (type == VTK_CONVEX_POINT_SET) || (type == VTK_POLYHEDRON) ); } #endif
/* cryptr is a simple aes-256-gcm encrypt and decrypt module for node.js Copyright (c) 2014 Maurice Butler Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ const crypto = require("crypto"); const algorithm = "aes-256-gcm"; const ivLength = 16; const saltLength = 64; const tagLength = 16; const tagPosition = saltLength + ivLength; const encryptedPosition = tagPosition + tagLength; function Cryptr(secret) { if (!secret || typeof secret !== "string") { throw new Error("Cryptr: secret must be a non-0-length string"); } function getKey(salt) { return crypto.pbkdf2Sync(secret, salt, 100000, 32, "sha512"); } this.encrypt = function encrypt(value) { if (value == null) { throw new Error("value must not be null or undefined"); } const iv = crypto.randomBytes(ivLength); const salt = crypto.randomBytes(saltLength); const key = getKey(salt); const cipher = crypto.createCipheriv(algorithm, key, iv); const encrypted = Buffer.concat([cipher.update(String(value), "utf8"), cipher.final()]); const tag = cipher.getAuthTag(); return Buffer.concat([salt, iv, tag, encrypted]).toString("hex"); }; this.decrypt = function decrypt(value) { if (value == null) { throw new Error("value must not be null or undefined"); } const stringValue = Buffer.from(String(value), "hex"); const salt = stringValue.slice(0, saltLength); const iv = stringValue.slice(saltLength, tagPosition); const tag = stringValue.slice(tagPosition, encryptedPosition); const encrypted = stringValue.slice(encryptedPosition); const key = getKey(salt); const decipher = crypto.createDecipheriv(algorithm, key, iv); decipher.setAuthTag(tag); return decipher.update(encrypted) + decipher.final("utf8"); }; } module.exports = Cryptr;
module Travis::Addons::GithubCheckStatus::Output TEMPLATES = { name: 'Travis CI - {{build_info.name}}', summary: { queued: '{{build_link(state,details_url, "The build")}} is currently waiting in the build queue for a VM to be ready.', running: '{{build_link(state,details_url, "The build")}} is currently running.', changed: '{{build_link(state,details_url, "The build")}} **{{state}}**. This is a change from the previous build, which **{{previous_state}}**.', unchanged: '{{build_link(state,details_url, "The build")}} **{{state}}**, just like the previous build.', no_previous: '{{build_link(state,details_url, "The build")}} **{{state}}**.' }, matrix_description: { without_stages: 'This build has **{{number jobs.size}} jobs**, running in parallel.', with_stages: 'This build has **{{number jobs.size}} jobs**, running in **{{number stages.size}} sequential stages**.' }, allow_failure: "This job is <a href='https://docs.travis-ci.com/user/customizing-the-build#Rows-that-are-Allowed-to-Fail'>allowed to fail</a>.", stage_description: <<-MARKDOWN, ### Stage {{stage[:number]}}: {{escape stage[:name]}} This stage **{{state stage[:state]}}**. MARKDOWN text: <<-MARKDOWN, {{build_info.description}} ## Jobs and Stages {{job_info_text}} ## Build Configuration Build Option | Setting -----------------|-------------- Language | {{language}} Operating System | {{os_description}} {{language_info}} <details> <summary>Build Configuration</summary> {{code :yaml, config_display_text}} </details> MARKDOWN jobs_table: <<-HTML, <table> <thead> {{ table_head.rstrip }} </thead> <tbody> {{ table_body.rstrip }} </tbody> </table> HTML } end
'use strict'; /* global Parse */ angular.module('main').factory('ParseFile', function ($q) { return { upload: function (base64) { var defer = $q.defer(); var parseFile = new Parse.File('image.jpg', { base64: base64 }); parseFile.save({ success: function (savedFile) { defer.resolve(savedFile); }, error: function (error) { defer.reject(error); } }); return defer.promise; }, uploadFile: function (file) { var defer = $q.defer(); var parseFile = new Parse.File('image.jpg', file); parseFile.save({ success: function (savedFile) { defer.resolve(savedFile); }, error: function (error) { defer.reject(error); } }); return defer.promise; }, }; });
### Image Color Analysis This color analysis tool was built to support a data visual analytics method for the study of national Webs. It was initially used to analyze the changing colors of the former Yugoslav domain, .yu, during the Kosovo War. For more information please refer to: Ben-David, A., Amram, A., & Bekkerman, R. (in press). [The Colors of the National Web: Visual Data Analysis of the Historical Yugoslav Web Domain](https://www.academia.edu/30508702/The_colors_of_the_national_Web_visual_data_analysis_of_the_historical_Yugoslav_Web_domain._Int_J_Digit_Libr_2016_._doi_10.1007_s00799-016-0202-6). *Internation Journal on Digital Libraries*. The method can be readily applied to any other national Web (or Web archive), and, in fact, to any folder of images. The following is a tutorial for using the tool on a given folder of images. We will compare the color histogram of Google images results to "Donald Trump" and "Hillary Clinton" (as of November 2016). Two demo folders are included in this tutorial. #### Preparations 1. Please Download and install [Anaconda, version Python 2.7](https://www.continuum.io/downloads). 2. Please 'download zip' the project folders from [Github](https://github.com/omilab/image-color-analysis/archive/master.zip). 3. Unzip the folder #### A Step by Step Guide for using the tool 1. In Anaconda, open "Jupyter Notebook". 2. When notebook opens - it automatically opens your default browser and shows your file directory. 3. Open your downloaded and extracted folder. 4. Open the file "image_color_analysis.ipynb". #### Now, let's have some fun! The script in the file you just opened is divided into three sections: 1. Building a collage from all the images. 2. Fitting a K-Means clustering model (identifying clusters of colors in the images). 3. Creating a color histogram that summarizes the color histogram of the images. Although the code is annotated, below is an explanation of each section. ##### Part 1: Creating a collage In this section, we first specify the location of an images folder and load the images. Then, we create a collage from all the images. This is done by calculating the maximal width of all images and the sum of the heights of all images. Finally, it creates a new image with an alpha channel. That is, all images are arranged one below the other, and the empty spaces between them are marked as transparent. Click the 'run' button to start this procedure. When it's done, it prints the time it took to build the collage (this give a good indication of the process when analyzing a large corpus). The generated collage pops up. You may want to view or save it. ##### Part 2: Building a K-Means model and running it on the collage In order to calculate and identify clusters of colors in the dataset, we first need to convert the images into a numerical representation - a color array. The array has four dimensions: Red, Green, Blue (RGB) and Alpha (the transparent color we added to mark the empty spaces in the previous section). Subsequently, the collage is represented as a matrix of the total height * total width * 4(that is, RGB+A). Since KMeans does not work on a matrix, we need to transform it into a continuous, one-dimensional layer. For example, if the maximum height of the collage is 100, and the maximum width is 400, instead of representing the collage as a 100 * 400 * 4, it is represented as one line of the sum: 160,000. Finally, we remove all transparent colors, as they are not necessary for the calculation, and we fit the model. In the code, we specify 5 clusters, but this number can be changed. Click the 'run' button to start this procedure. When it's done, it prints the time it took to build the collage. (The larger your collage is and the larger the number of clusters, the longer it will take to complete). ##### Part 3: Generating the color histogram This section calculates the proportion of colors for each section. Then, it normalizes the histogram, so that the proportions sum to 1. Finally, it generates an image that puts the width of each color in a histogram. 1.for each cluster, calculate the proportion of each color. Click the 'run' button to start this procedure. The resulting histogram that pops up summarizes the color composition of your corpus! ##### N.B. this is the bit of code where you may change the name of the demo folder to your own folder of images: folder = 'YOUR FOLDER' This is the bit of code where you may change the number of clusters (=colors in the histogram): kmeans_model = KMeans(n_clusters=YOUR NUMBER)
--- layout: post title: Tekton Pipelines in Jenkins X - Part 2 Add Steps Before/After a Stage Lifecycle Or Build Your Own Pipeline subtitle: Override an entire pipeline | Append or prepend additional steps to a defined Stage. image: 'https://avatars0.githubusercontent.com/u/47602533?s=400&v=4' share-img: http://sharepointoscar.com/img/tekton-part-2/tekton_append_steps_to_pipeline.png published: true author: Oscar Medina date: 2019-05-30 tags: - Docker - CI/CD Pipeline - Jenkins X - Tekton - K8s - GKE - Kubernetes Secrets --- ![Tekton in Action](/img/tekton-part-2/tekton_append_steps_to_pipeline.png) In [Part 1](http://sharepointoscar.com/2019-04-22-using-tekton-pipelines-in-jenkins-x-part-1/) of our multi-part post, I walked you through adding custom steps to a Tekton pipeline. In this post I'll show you how you can append custom steps to a defined Stage. I will also show you how to override an entire Build-Pack defined pipeline (the ones that come out of the box in Jenkins X), including the ability to specify your own Builder Docker Image. **Bonus** I show you how to retrieve Kubernetes Secret values and store them as a variable within the pipeline. For details on the Jenkins X Pipelines that use Build-Packs (which are the default), take a look at [Customizing Pipelines](https://jenkins-x.io/architecture/jenkins-x-pipelines/#customising-the-pipelines) I won't go into details as to what Tekton is, as I provided an overview in Part 1. This post builds on top of what we did on Part 1, please read it as many typical commands are ommited on this post (viewing jx logs etc.) # Scenario I previously installed Jenkins X Serverless on GKE and all is running. I have an existing NodeJS application that has MochaJS tests, and I've already ran it through Jenkins X CI/CD. My app tests ran, and I did absolutely nothing, as Jenkins X detected the NodeJS language, and used the appropriate **Builder**. The app current version is in our staging environent. However, I want to further have control over the Jenkins X pipelines which use the `build-packs`. I also want to see how I can completely build my own pipeline without relying on the ones provided by Jenkins X. ## What you will learn In the second part of this series, I will walk you through the following: 1. Append an additional two steps to the given built-in Release pipeline, within the Build Stage. Adding a step before and after the build occurs. 2. Override the entire `Build-Pack` built-in pipeline with my own definition. (this of course means more work for me) So let's get started! # Append Steps To The Release Pipeline Build Stage First, I will modify the `jenkins-x.yaml` file. In order to do that, I will execute a `jx` command as follows: {% highlight bash %} > $ jx create step {% endhighlight %} I answer the questions related to where I want to add the step. The last prompt is actually a `shell` command. But I just type whatever as I need to properly define it later. Once finished, the `jenkins-x.yaml` file is immediately modified. It should look like the following: {% highlight yaml %} buildPack: javascript pipelineConfig: pipelines: overrides: - pipeline: release stage: build type: after steps: - sh: echo ====================================== APPENDING Release Pipeline, Build Stage, Before execution of default stuff ====================================== name: sposcar-appending-step {% endhighlight %} You can add additional steps as well, as the `steps` node is an array. You may also opt to add another step at a diffrent time, perhaps in the `type: before` vs the `type: after` as I did and below is the final `yaml` {% highlight yaml %} buildPack: javascript pipelineConfig: pipelines: overrides: - pipeline: release stage: build type: before steps: - sh: echo ====================================== PREPENDING Release Pipeline, Build Stage, before execution of default stuff ====================================== name: sposcar-prepending-step - pipeline: release stage: build type: after steps: - sh: echo ====================================== APPENDING Release Pipeline, Build Stage, after execution of default stuff ====================================== name: sposcar-appending-step {% endhighlight %} ## Checking the build logs Once I run the pipeline, the custom steps should be executed, and should appear in the output as shown below. ![Appending and prepending tekton pipeline steps](/img/tekton-part-2/appending_steps.png) # Replacing the built-in Pipeline Because Jenkins X uses `build-packs` to build an app based on the language, it automatically detects this when you import your existing app. Therefore, the first line already containted `buildPack: javascript`. Jenkins X added this for me automatically. However, in this scenario, I do not want to use the buil-in pipeline, nor do I need to overwrite any steps. I want to completely define my own pipeline. This step shows you an example of what that may look like. The `yaml` for the entire replacement looks like the following: {% highlight yaml %} buildPack: none pipelineConfig: pipelines: release: pipeline: options: containerOptions: resources: limits: cpu: 0.2 memory: 128Mi requests: cpu: 0.1 memory: 64Mi agent: image: sharepointoscar/node:8 stages: - name: Oscar Build Stage steps: - name: Get Node Version command: node args: - --version - name: NPM Installar Por Favor command: npm args: - install options: containerOptions: resources: limits: cpu: 0.4 memory: 256Mi requests: cpu: 0.2 memory: 128Mi - name: Oscar Test Stage steps: - name: Run MochaJS Tests command: npm args: - test options: containerOptions: resources: limits: cpu: 0.4 memory: 256Mi requests: cpu: 0.2 memory: 128Mi {% endhighlight %} Lots going on here. First, you will notice that the first line, tells Jenkins X to *not* use a `buildPack`. You might notice that I specified container properties and modified them. I am telling Jenkins X that I need specific `cpu` and `memory` for the containers it spins up to run the `Tekton` pipeline. Another noteworthy item, is that I'm using a custom `Docker` image, in this scenario my app required a specific version of NodeJS, and it was not available in the existing Jenkins X repo (a common scenario), therefore the `agent.image` allows me to point to an image (this one is publicly available) and I host it at [Docker Hub](https://hub.docker.com) ## Working With Secrets and Private Registries If your registry is private (most are), then you will need to first create a Secret in Kubernetes. I prefer using a command similar to the following: `kubectl create secret generic my-registry --from-literal=username=userarealname--from-literal=apikey=passwordOrAPIKey --namespace jx` Once this is created, you can use use the pipeline `env` node to set values from the secret stored in Kubernetes, which you retrieve as shown below. **NOTE** the sample `yaml` below is not the same as the complete pipeline I defined above. I am merely showing you, how you may retrieve `secrets` and use them within the pipeline. {% highlight yaml %} buildPack: javascript pipelineConfig: env: - name: MY_REGISTRY_USERNAME valueFrom: secretKeyRef: key: username name: my-registry - name: MY_REGISTRY_APIKEY valueFrom: secretKeyRef: key: apikey name: my-registry pipelines: overrides: - pipeline: release stage: build type: before steps: - sh: echo ====================================== MY_REGISTRY_USERNAME= ${MY_REGISTRY_USERNAME} ====================================== name: sposcar-echo-username - sh: echo ====================================== MY_REGISTRY_APIKEY= ${MY_REGISTRY_APIKEY} ====================================== name: sposcar-echo-apikey {% endhighlight %} You will also notice that my steps have unique names. This is helpful when looking at logs to quickly spot them. For example, if I vew the app activities using `jx get activities -f skiapp -w`, or if you use `jx get build logs` at the time the pipeline is executing, this proves to be really helpful. --- **NOTE** Many people are confused when they execute `jx get build logs` and see a message like the following: **error: no Tekton pipelines have been triggered which match the current filter** This just means, the pipeline either has not started or never started. I tend to forget to do a Pull Requests to kick it off. Another thing you can do, is check other logs by using `jx logs` and picking an item such as the `pipelinerunner` or `pipeline` which tend to have more insight as to what happened when you ran it. --- # Part 3 and 4? There are pipelines in Jenkinx X that are not based on `Build-Packs`. We have not covered those. If you show enough interest via Twitter _(Retweets and Likes)_ when this blog is posted, I'll take the time to write a **Part 3** and **Part 4** which show you how to work with these other type of Pipelines. # Conclusion In Part 2 of of the *Tekton Pipelines in Jenkins X* blog post series, we learned how to add steps and augment the NodeJS build-pack Stages and Steps. We also completely replaced the pipeline with our own definition, and even added a custom builder docker image. I hope you found this helpful. Do you want to ensure you don't miss posts like this? [Sign up](https://jenkins-x.us7.list-manage.com/subscribe?u=d0c128ac1f69ba2bb20742976&id=84d053b0a0) for the Jenkins X Newsletter! More soon, @SharePointOscar
package com.sparta.is.entity.driveables.types; import java.util.ArrayList; import java.util.HashMap; public class TypeFile { public EnumType type; public String name, contentPack; public ArrayList<String> lines; public static HashMap<EnumType, ArrayList<TypeFile>> files; private int readerPosition = 0; static { files = new HashMap<EnumType, ArrayList<TypeFile>>(); for(EnumType type: EnumType.values()) { files.put(type, new ArrayList<TypeFile>()); } } public TypeFile(String contentPack, EnumType t, String s) { this(contentPack, t, s, true); } public TypeFile(String contentPack, EnumType t, String s, boolean addToTypeFileList) { type = t; name = s; this.contentPack = contentPack; lines = new ArrayList<String>(); if(addToTypeFileList) { files.get(type).add(this); } } public String readLine() { if(readerPosition == lines.size()) { return null; } return lines.get(readerPosition++); } }
package com.google.common.collect; import java.util.Collection; import java.util.Map; import java.util.SortedSet; import java.util.SortedMap; import java.util.Comparator; class TestCollect { String taint() { return "tainted"; } void sink(Object o) {} <T> T element(Collection<T> c) { return c.iterator().next(); } <K,V> K mapKey(Map<K,V> m) { return element(m.keySet()); } <K,V> V mapValue(Map<K,V> m) { return element(m.values()); } <K,V> K multimapKey(Multimap<K,V> m) { return element(m.keySet()); } <K,V> V multimapValue(Multimap<K,V> m) { return element(m.values()); } <R,C,V> R tableRow(Table<R,C,V> t) { return element(t.rowKeySet()); } <R,C,V> C tableColumn(Table<R,C,V> t) { return element(t.columnKeySet()); } <R,C,V> V tableValue(Table<R,C,V> t) { return element(t.values()); } void test1() { String x = taint(); ImmutableSet<String> xs = ImmutableSet.of(x, "y", "z"); sink(element(xs.asList())); // $numValueFlow=1 ImmutableSet<String> ys = ImmutableSet.of("a", "b", "c"); sink(element(Sets.filter(Sets.union(xs, ys), y -> true))); // $numValueFlow=1 sink(element(Sets.newHashSet("a", "b", "c", "d", x))); // $numValueFlow=1 } void test2() { sink(element(ImmutableList.of(taint(), taint(), taint(), taint(),taint(), taint(), taint(), taint(),taint(), taint(), taint(), taint(),taint(), taint(), taint(), taint()))); // $numValueFlow=16 sink(element(ImmutableSet.of(taint(), taint(), taint(), taint(),taint(), taint(), taint(), taint(),taint(), taint(), taint(), taint(),taint(), taint(), taint(), taint()))); // $numValueFlow=16 sink(mapKey(ImmutableMap.of(taint(), taint(), taint(), taint()))); // $numValueFlow=2 sink(mapValue(ImmutableMap.of(taint(), taint(), taint(), taint()))); // $numValueFlow=2 sink(multimapKey(ImmutableMultimap.of(taint(), taint(), taint(), taint()))); // $numValueFlow=2 sink(multimapValue(ImmutableMultimap.of(taint(), taint(), taint(), taint()))); // $numValueFlow=2 sink(tableRow(ImmutableTable.of(taint(), taint(), taint()))); // $numValueFlow=1 sink(tableColumn(ImmutableTable.of(taint(), taint(), taint()))); // $numValueFlow=1 sink(tableValue(ImmutableTable.of(taint(), taint(), taint()))); // $numValueFlow=1 } void test3() { String x = taint(); ImmutableList.Builder<String> b = ImmutableList.builder(); b.add("a"); sink(b); b.add(x); sink(element(b.build())); // $numValueFlow=1 b = ImmutableList.builder(); b.add("a").add(x); sink(element(b.build())); // $numValueFlow=1 sink(ImmutableList.builder().add("a").add(x).build().toArray()[0]); // $numValueFlow=1 ImmutableMap.Builder<String, String> b2 = ImmutableMap.builder(); b2.put(x,"v"); sink(mapKey(b2.build())); // $numValueFlow=1 b2.put("k",x); sink(mapValue(b2.build())); // $numValueFlow=1 } void test4(Table<String, String, String> t1, Table<String, String, String> t2, Table<String, String, String> t3) { String x = taint(); t1.put(x, "c", "v"); sink(tableRow(t1)); // $numValueFlow=1 t1.put("r", x, "v"); sink(tableColumn(t1)); // $numValueFlow=1 t1.put("r", "c", x); sink(tableValue(t1)); // $numValueFlow=1 sink(mapKey(t1.row("r"))); // $numValueFlow=1 sink(mapValue(t1.row("r"))); // $numValueFlow=1 t2.putAll(t1); for (Table.Cell<String,String,String> c : t2.cellSet()) { sink(c.getValue()); // $numValueFlow=1 } sink(t1.remove("r", "c")); // $numValueFlow=1 t3.row("r").put("c", x); sink(tableValue(t3)); // $ MISSING:numValueFlow=1 // depends on aliasing } void test5(Multimap<String, String> m1, Multimap<String, String> m2, Multimap<String, String> m3, Multimap<String, String> m4, Multimap<String, String> m5){ String x = taint(); m1.put("k", x); sink(multimapValue(m1)); // $numValueFlow=1 sink(element(m1.get("k"))); // $numValueFlow=1 m2.putAll("k", ImmutableList.of("a", x, "b")); sink(multimapValue(m2)); // $numValueFlow=1 m3.putAll(m1); sink(multimapValue(m3)); // $numValueFlow=1 m4.replaceValues("k", m1.replaceValues("k", ImmutableList.of("a"))); for (Map.Entry<String, String> e : m4.entries()) { sink(e.getValue()); // $numValueFlow=1 } m5.asMap().get("k").add(x); sink(multimapValue(m5)); // $ MISSING:numValueFlow=1 // depends on aliasing } void test6(Comparator<String> comp, SortedSet<String> sorS, SortedMap<String, String> sorM) { ImmutableSortedSet<String> s = ImmutableSortedSet.of(taint()); sink(element(s)); // $numValueFlow=1 sink(element(ImmutableSortedSet.copyOf(s))); // $numValueFlow=1 sink(element(ImmutableSortedSet.copyOf(comp, s))); // $numValueFlow=1 sorS.add(taint()); sink(element(ImmutableSortedSet.copyOfSorted(sorS))); // $numValueFlow=1 sink(element(ImmutableList.sortedCopyOf(s))); // $numValueFlow=1 sink(element(ImmutableList.sortedCopyOf(comp, s))); // $numValueFlow=1 ImmutableSortedMap<String, String> m = ImmutableSortedMap.of("k", taint()); sink(mapValue(m)); // $numValueFlow=1 sink(mapValue(ImmutableSortedMap.copyOf(m))); // $numValueFlow=1 sink(mapValue(ImmutableSortedMap.copyOf(m, comp))); // $numValueFlow=1 sorM.put("k", taint()); sink(mapValue(ImmutableSortedMap.copyOfSorted(sorM))); // $numValueFlow=1 } }
using NAudio.Wave; using NAudio.WindowsMediaFormat; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WavToWma.WindowsMediaFormat { internal static class FromProfileGuid { internal static WmaWriter BuildWmaWriter(FileStream wmaFileStream, WaveFormat waveFormat) { // Get system profile GUID, then load profile Guid WMProfile_V80_288MonoAudio = new Guid("{7EA3126D-E1BA-4716-89AF-F65CEE0C0C67}"); Guid wmaSystemProfileGuid = WMProfile_V80_288MonoAudio; IWMProfile wmaProfile = null; WM.ProfileManager.LoadProfileByID(ref wmaSystemProfileGuid, out wmaProfile); try { WmaWriter wmaWriter = new WmaWriter(wmaFileStream, waveFormat, wmaProfile); return wmaWriter; } catch (Exception ex) { throw; } } } }
import { Component, Input, ContentChild, ViewChildren, QueryList } from 'angular2/core'; import template from './card-list.html!text'; import { CardHeader } from './header/card-header'; import { CardBody } from './body/card-body'; import { Card } from './card/card'; export { CardHeader, CardBody }; @Component({ selector: 'conf-card-list', template: template, directives: [Card], }) export class CardList { @Input() source: any[]; @ContentChild(CardHeader) head: CardHeader; @ContentChild(CardBody) body: CardBody; @ViewChildren(Card) cards: QueryList<Card>; collapseAll() { this.cards.map((card: Card) => card.close()); } }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <title>Dictionnaire: Pages associées</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/search.js"></script> <script type="text/javascript"> $(document).ready(function() { searchBox.OnSelectItem(0); }); </script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td id="projectlogo"><img alt="Logo" src="logo-univ-nantes.png"/></td> <td style="padding-left: 0.5em;"> <div id="projectname">Dictionnaire &#160;<span id="projectnumber">1.0</span> </div> <div id="projectbrief">Implémentation d&#39;un dictionnaire avec table de hachage et arbre.</div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Généré par Doxygen 1.8.1.2 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Recherche'); </script> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Page&#160;principale</span></a></li> <li class="current"><a href="pages.html"><span>Pages&#160;associées</span></a></li> <li><a href="annotated.html"><span>Classes</span></a></li> <li><a href="files.html"><span>Fichiers</span></a></li> <li> <div id="MSearchBox" class="MSearchBoxInactive"> <span class="left"> <img id="MSearchSelect" src="search/mag_sel.png" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" alt=""/> <input type="text" id="MSearchField" value="Recherche" accesskey="S" onfocus="searchBox.OnSearchFieldFocus(true)" onblur="searchBox.OnSearchFieldFocus(false)" onkeyup="searchBox.OnSearchFieldChange(event)"/> </span><span class="right"> <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a> </span> </div> </li> </ul> </div> </div><!-- top --> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> <a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(0)"><span class="SelectionMark">&#160;</span>Tout</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(1)"><span class="SelectionMark">&#160;</span>Classes</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(2)"><span class="SelectionMark">&#160;</span>Fichiers</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(3)"><span class="SelectionMark">&#160;</span>Fonctions</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(4)"><span class="SelectionMark">&#160;</span>Énumérations</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(5)"><span class="SelectionMark">&#160;</span>Pages</a></div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div class="header"> <div class="headertitle"> <div class="title">Pages associées</div> </div> </div><!--header--> <div class="contents"> <div class="textblock">Liste de toutes les pages de documentation associées :</div><div class="directory"> <table class="directory"> <tr id="row_0_" class="even"><td class="entry"><img src="ftv2lastnode.png" alt="\" width="16" height="22" /><a class="el" href="deprecated.html" target="_self">Liste des éléments obsolètes</a></td><td class="desc"></td></tr> </table> </div><!-- directory --> </div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Généré le Vendredi Avril 25 2014 22:38:57 pour Dictionnaire par &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.1.2 </small></address> </body> </html>
// Type definitions for react-particles-js v3.0.0 // Project: https://github.com/wufe/react-particles-js // Definitions by: Simone Bembi <https://github.com/wufe> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// <reference types="react" /> import { ComponentClass } from "react"; import { Container } from "tsparticles/Core/Container"; import { ISourceOptions } from "tsparticles"; export type IParticlesParams = ISourceOptions; export * from 'tsparticles/Enums'; export * from "tsparticles/Plugins/Absorbers/Enums"; export * from "tsparticles/Plugins/Emitters/Enums"; export * from "tsparticles/Plugins/PolygonMask/Enums"; export interface ParticlesProps { width?: string; height?: string; params?: IParticlesParams; style?: any; className?: string; canvasClassName?: string; particlesRef?: React.RefObject<Container>; } type Particles = ComponentClass<ParticlesProps>; declare const Particles: Particles; export default Particles;
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_72) on Sat Nov 22 10:02:39 EST 2014 --> <title>F-Index</title> <meta name="date" content="2014-11-22"> <link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="F-Index"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../overview-summary.html">Overview</a></li> <li>Package</li> <li>Class</li> <li>Use</li> <li><a href="../overview-tree.html">Tree</a></li> <li><a href="../deprecated-list.html">Deprecated</a></li> <li class="navBarCell1Rev">Index</li> <li><a href="../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="index-4.html">Prev Letter</a></li> <li><a href="index-6.html">Next Letter</a></li> </ul> <ul class="navList"> <li><a href="../index.html?index-filesindex-5.html" target="_top">Frames</a></li> <li><a href="index-5.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="contentContainer"><a href="index-1.html">A</a>&nbsp;<a href="index-2.html">C</a>&nbsp;<a href="index-3.html">D</a>&nbsp;<a href="index-4.html">E</a>&nbsp;<a href="index-5.html">F</a>&nbsp;<a href="index-6.html">G</a>&nbsp;<a href="index-7.html">H</a>&nbsp;<a href="index-8.html">I</a>&nbsp;<a href="index-9.html">J</a>&nbsp;<a href="index-10.html">K</a>&nbsp;<a href="index-11.html">M</a>&nbsp;<a href="index-12.html">N</a>&nbsp;<a href="index-13.html">P</a>&nbsp;<a href="index-14.html">Q</a>&nbsp;<a href="index-15.html">R</a>&nbsp;<a href="index-16.html">S</a>&nbsp;<a href="index-17.html">T</a>&nbsp;<a href="index-18.html">U</a>&nbsp;<a href="index-19.html">W</a>&nbsp;<a name="_F_"> <!-- --> </a> <h2 class="title">F</h2> <dl> <dt><a href="../mapr/master/FileInfo.html" title="class in mapr.master"><span class="strong">FileInfo</span></a> - Class in <a href="../mapr/master/package-summary.html">mapr.master</a></dt> <dd> <div class="block">Encapsulates all metadata (excluding name) of a file on DFS, including its replica locations, partitioning rules, etc.</div> </dd> <dt><span class="strong"><a href="../mapr/master/FileInfo.html#FileInfo(int,%20int)">FileInfo(int, int)</a></span> - Constructor for class mapr.master.<a href="../mapr/master/FileInfo.html" title="class in mapr.master">FileInfo</a></dt> <dd> <div class="block">Initializes a <tt>FileInfo</tt> with certain number of partitions (chunks) and records (lines).</div> </dd> <dt><span class="strong"><a href="../mapr/master/QueuedTasks.html#finishedMap(java.lang.Integer)">finishedMap(Integer)</a></span> - Method in class mapr.master.<a href="../mapr/master/QueuedTasks.html" title="class in mapr.master">QueuedTasks</a></dt> <dd> <div class="block">Upon finishing a Mapper, remove it from the dependency list of all Sorters.</div> </dd> <dt><span class="strong"><a href="../mapr/master/RunningTasks.html#finishedMap(int)">finishedMap(int)</a></span> - Method in class mapr.master.<a href="../mapr/master/RunningTasks.html" title="class in mapr.master">RunningTasks</a></dt> <dd>&nbsp;</dd> <dt><span class="strong"><a href="../mapr/master/RunningTasks.html#finishedReduce(int)">finishedReduce(int)</a></span> - Method in class mapr.master.<a href="../mapr/master/RunningTasks.html" title="class in mapr.master">RunningTasks</a></dt> <dd>&nbsp;</dd> <dt><span class="strong"><a href="../mapr/master/QueuedTasks.html#finishedSort(java.lang.Integer)">finishedSort(Integer)</a></span> - Method in class mapr.master.<a href="../mapr/master/QueuedTasks.html" title="class in mapr.master">QueuedTasks</a></dt> <dd> <div class="block">Upon finishing a Sorter, remove it from the dependency list of all Reducers.</div> </dd> <dt><span class="strong"><a href="../mapr/master/RunningTasks.html#finishedSort(int)">finishedSort(int)</a></span> - Method in class mapr.master.<a href="../mapr/master/RunningTasks.html" title="class in mapr.master">RunningTasks</a></dt> <dd>&nbsp;</dd> </dl> <a href="index-1.html">A</a>&nbsp;<a href="index-2.html">C</a>&nbsp;<a href="index-3.html">D</a>&nbsp;<a href="index-4.html">E</a>&nbsp;<a href="index-5.html">F</a>&nbsp;<a href="index-6.html">G</a>&nbsp;<a href="index-7.html">H</a>&nbsp;<a href="index-8.html">I</a>&nbsp;<a href="index-9.html">J</a>&nbsp;<a href="index-10.html">K</a>&nbsp;<a href="index-11.html">M</a>&nbsp;<a href="index-12.html">N</a>&nbsp;<a href="index-13.html">P</a>&nbsp;<a href="index-14.html">Q</a>&nbsp;<a href="index-15.html">R</a>&nbsp;<a href="index-16.html">S</a>&nbsp;<a href="index-17.html">T</a>&nbsp;<a href="index-18.html">U</a>&nbsp;<a href="index-19.html">W</a>&nbsp;</div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../overview-summary.html">Overview</a></li> <li>Package</li> <li>Class</li> <li>Use</li> <li><a href="../overview-tree.html">Tree</a></li> <li><a href="../deprecated-list.html">Deprecated</a></li> <li class="navBarCell1Rev">Index</li> <li><a href="../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="index-4.html">Prev Letter</a></li> <li><a href="index-6.html">Next Letter</a></li> </ul> <ul class="navList"> <li><a href="../index.html?index-filesindex-5.html" target="_top">Frames</a></li> <li><a href="index-5.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
<?php class Email extends CI_Controller { public function __construct() { parent:: __construct(); $this->load->database(); $this->load->model('Emailinfo'); $this->load->library(array('session','form_validation')); $this->load->helper(array('form','url','date')); } public function index() { $data['emailInformation']=$this->Emailinfo->getEmailList($_SESSION['id']); $data['title']="Email List"; $this->load->view('templates/header', $data); $this->load->view('email_index', $data); $this->load->view('templates/footer', $data); } public function view ($id,$user) { $this->Emailinfo->update_status($id,$_SESSION['id']); $data['emailDetail']=$this->Emailinfo->getEmailDetail($id,$user); $data['title']="Email Detail"; $this->load->view('templates/header', $data); $this->load->view('email_information', $data); $this->load->view('templates/footer', $data); } public function create() { $this->load->library('form_validation'); $this->load->helper('form'); $data['title'] = 'Create a news email'; $this->form_validation->set_rules('sendTo','Email Receiver','callback_receiver_check'); $this->form_validation->set_rules('title','Email Title','required'); $this->form_validation->set_rules('content','Email Content','required'); if ($this->form_validation->run()==FALSE) { $this->load->view('templates/header', $data); $this->load->view('create_email', $_SESSION['id']); $this->load->view('templates/footer', $data); } else { $name = $this->input->post('sendTo'); $query = $this->db->get_where('IndividualUser', array('username' => $name)); $result = $query->row(); $id = $result->id; $this->Emailinfo->createEmail($_SESSION['id'],$id); redirect('Email/'); } } public function unread() { $data['emailInformation'] = $this->Emailinfo->unreadEmail($_SESSION['id']); $data['title']="Unread Email List"; $this->load->view('templates/header', $data); $this->load->view('email_index', $data); $this->load->view('templates/footer', $data); } public function receiver_check($name) { $receiver = $this->Emailinfo->receiver($name); if($receiver > 0) { return TRUE; } else{ return FALSE; } } public function sendNotification() { $data['title'] = "Send Notification"; $this->load->view('templates/header', $data); $this->load->view('send_notification'); $this->load->view('templates/footer'); } public function notificationSubmit() { $title = $_POST['title']; $content = $_POST['content']; $this->Emailinfo->addNotification($title, $content); redirect('/email'); } }
<?php require_once 'responseClasses.php'; header('Content-Type: text/html; charset=utf-8'); if ($_GET['latitude'] != null && $_GET['longitude']) { $lat = $_GET['latitude']; $long = $_GET['longitude']; } else { $lat = 0; $long = 0; } $openWeatherMapApiKey = 'd8bc1c0a60e836388802191cb80c95e8'; $url = 'http://api.openweathermap.org/data/2.5/weather?units=metric&lat='.$lat.'&lon='.$long.'&APPID='.$openWeatherMapApiKey; $json = file_get_contents( $url ); $data = json_decode($json); // var_dump($data); $weather = new Weather(); $weather->temperature = $data->main->temp; $weather->description = $data->weather[0]->description; echo json_encode($weather);
var Counter = require('./counterEvented.js'); var c = new Counter(1); c.increment(); c.on('even', function(){ console.log('even! ' + c.count); return; });
// // System.Configuration.NameValueConfigurationCollection.cs // // Authors: // Chris Toshok (toshok@ximian.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // Copyright (C) 2004 Novell, Inc (http://www.novell.com) // namespace System.Configuration { [ConfigurationCollection(typeof(NameValueConfigurationElement), AddItemName = "add", RemoveItemName = "remove", ClearItemsName = "clear", CollectionType = ConfigurationElementCollectionType.AddRemoveClearMap)] public sealed class NameValueConfigurationCollection : ConfigurationElementCollection { private static readonly ConfigurationPropertyCollection _properties; static NameValueConfigurationCollection() { _properties = new ConfigurationPropertyCollection(); } public string[] AllKeys { get { return (string[]) BaseGetAllKeys(); } } public new NameValueConfigurationElement this[string name] { get { return (NameValueConfigurationElement) BaseGet(name); } set { throw new NotImplementedException(); } } protected internal override ConfigurationPropertyCollection Properties { get { return _properties; } } public void Add(NameValueConfigurationElement nameValue) { BaseAdd(nameValue, false); } public void Clear() { BaseClear(); } protected override ConfigurationElement CreateNewElement() { return new NameValueConfigurationElement("", ""); } protected override object GetElementKey(ConfigurationElement element) { var e = (NameValueConfigurationElement) element; return e.Name; } public void Remove(NameValueConfigurationElement nameValue) { throw new NotImplementedException(); } public void Remove(string name) { BaseRemove(name); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; namespace Smart_radio_controller_windows_forms { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new main()); } } }
namespace Bike.Ast { public partial class Argument : Node { public bool ShouldExpand; public ExprNode Expression; } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>cfml: Error 🔥</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / released</a></li> <li class="active"><a href="">8.6 / cfml - 20180525</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> cfml <small> 20180525 <span class="label label-danger">Error 🔥</span> </small> </h1> <p>📅 <em><script>document.write(moment("2022-01-18 12:47:20 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-01-18 12:47:20 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-num base Num library distributed with the OCaml compiler base-threads base base-unix base camlp5 7.14 Preprocessor-pretty-printer of OCaml conf-findutils 1 Virtual package relying on findutils conf-perl 1 Virtual package relying on perl coq 8.6 Formal proof management system num 0 The Num library for arbitrary-precision integer and rational arithmetic ocaml 4.04.2 The OCaml compiler (virtual package) ocaml-base-compiler 4.04.2 Official 4.04.2 release ocaml-config 1 OCaml Switch Configuration ocamlfind 1.9.1 A library manager for OCaml # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;armael.gueneau@inria.fr&quot; authors: &quot;Arthur Charguéraud &lt;arthur.chargueraud@inria.fr&gt;&quot; synopsis: &quot;A tool for proving OCaml programs in Separation Logic&quot; homepage: &quot;https://gitlab.inria.fr/charguer/cfml&quot; bug-reports: &quot;https://gitlab.inria.fr/charguer/cfml/issues&quot; license: &quot;CeCILL-B&quot; dev-repo: &quot;git+https://gitlab.inria.fr/charguer/cfml.git&quot; build: [make &quot;-j%{jobs}%&quot;] install: [make &quot;install&quot; &quot;PREFIX=%{prefix}%&quot;] depends: [ &quot;ocaml&quot; {&gt;= &quot;4.03.0&quot; &amp; &lt; &quot;4.07.0&quot;} &quot;ocamlbuild&quot; {build} &quot;pprint&quot; &quot;base-bytes&quot; &quot;coq&quot; {&gt;= &quot;8.6&quot; &amp; &lt; &quot;8.9&quot;} &quot;coq-tlc&quot; {&gt;= &quot;20171206&quot;} ] url { src: &quot;https://gitlab.inria.fr/charguer/cfml/-/archive/20180525/archive.tar.gz&quot; checksum: &quot;sha512=ee6c62a7b7885aa9b443da97fb1b1d20e30d383d59ff2affebca7f35880c3396549b6e7c4547087e9d6eef5185b77ecf1adc78e94ced20c7c6c052db68a5caf5&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install 🏜️</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-cfml.20180525 coq.8.6</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam list; echo; ulimit -Sv 4000000; timeout 4h opam install -y --deps-only coq-cfml.20180525 coq.8.6</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>16 m 43 s</dd> </dl> <h2>Install 🚀</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam list; echo; ulimit -Sv 16000000; timeout 4h opam install -y -v coq-cfml.20180525 coq.8.6</code></dd> <dt>Return code</dt> <dd>7936</dd> <dt>Duration</dt> <dd>1 m 10 s</dd> <dt>Output</dt> <dd><pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-bytes base Bytes library distributed with the OCaml compiler base-num base Num library distributed with the OCaml compiler base-threads base base-unix base camlp5 7.14 Preprocessor-pretty-printer of OCaml conf-findutils 1 Virtual package relying on findutils conf-perl 1 Virtual package relying on perl coq 8.6 Formal proof management system coq-tlc 20181116 A general-purpose alternative to Coq&#39;s standard library dune 2.9.1 Fast, portable, and opinionated build system num 0 The Num library for arbitrary-precision integer and rational arithmetic ocaml 4.04.2 The OCaml compiler (virtual package) ocaml-base-compiler 4.04.2 Official 4.04.2 release ocaml-config 1 OCaml Switch Configuration ocaml-secondary-compiler 4.08.1-1 OCaml 4.08.1 Secondary Switch Compiler ocamlbuild 0.14.0 OCamlbuild is a build system with builtin rules to easily build most OCaml projects. ocamlfind 1.9.1 A library manager for OCaml ocamlfind-secondary 1.9.1 Adds support for ocaml-secondary-compiler to ocamlfind pprint 20220103 A pretty-printing combinator library and rendering engine [NOTE] Package coq is already installed (current version is 8.6). The following actions will be performed: - install coq-cfml 20180525 &lt;&gt;&lt;&gt; Gathering sources &gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt; Processing 1/1: [coq-cfml.20180525: http] [coq-cfml.20180525] downloaded from https://gitlab.inria.fr/charguer/cfml/-/archive/20180525/archive.tar.gz Processing 1/1: &lt;&gt;&lt;&gt; Processing actions &lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt; Processing 1/2: [coq-cfml: make] + /home/bench/.opam/opam-init/hooks/sandbox.sh &quot;build&quot; &quot;make&quot; &quot;-j4&quot; (CWD=/home/bench/.opam/ocaml-base-compiler.4.04.2/.opam-switch/build/coq-cfml.20180525) - make CFML=/home/bench/.opam/ocaml-base-compiler.4.04.2/.opam-switch/build/coq-cfml.20180525 -C lib/coq proof - rm -f generator/cfml_config.ml - make[1]: Entering directory &#39;/home/bench/.opam/ocaml-base-compiler.4.04.2/.opam-switch/build/coq-cfml.20180525/lib/coq&#39; - sed -e &#39;s|@@PREFIX@@|/home/bench/.opam/ocaml-base-compiler.4.04.2|&#39; \ - -e &#39;s|@@BINDIR@@|/home/bench/.opam/ocaml-base-compiler.4.04.2/bin|&#39; \ - -e &#39;s|@@LIBDIR@@|/home/bench/.opam/ocaml-base-compiler.4.04.2/lib/cfml|&#39; \ - generator/cfml_config.ml.in &gt; generator/cfml_config.ml - make -C generator - make[1]: Entering directory &#39;/home/bench/.opam/ocaml-base-compiler.4.04.2/.opam-switch/build/coq-cfml.20180525/generator&#39; - ocamlbuild -j 4 -classic-display -I lex -I parsing -I typing -I utils -cflags &quot;-g&quot; -lflags &quot;-g&quot; -use-ocamlfind -package pprint main.native makecmj.native - ocamlfind ocamldep -package pprint -modules main.ml &gt; main.ml.depends - ocamlfind ocamldep -package pprint -modules cfml_config.ml &gt; cfml_config.ml.depends - ocamlfind ocamldep -package pprint -modules characteristic.mli &gt; characteristic.mli.depends - ocamlfind ocamldep -package pprint -modules formula.mli &gt; formula.mli.depends - ocamlfind ocamldep -package pprint -modules coq.ml &gt; coq.ml.depends - ocamlfind ocamldep -package pprint -modules mytools.mli &gt; mytools.mli.depends - ocamlfind ocamldep -package pprint -modules parsing/location.mli &gt; parsing/location.mli.depends - ocamlfind ocamldep -package pprint -modules utils/warnings.mli &gt; utils/warnings.mli.depends - ocamlfind ocamlc -c -g -package pprint -I utils -I lex -I parsing -I typing -o utils/warnings.cmi utils/warnings.mli - ocamlfind ocamlc -c -g -package pprint -I parsing -I lex -I utils -I typing -o parsing/location.cmi parsing/location.mli - Compiling Shared... - ocamlfind ocamldep -package pprint -modules renaming.ml &gt; renaming.ml.depends - ocamlfind ocamldep -package pprint -modules utils/clflags.mli &gt; utils/clflags.mli.depends - ocamlfind ocamldep -package pprint -modules typing/ident.mli &gt; typing/ident.mli.depends - ocamlfind ocamlc -c -g -package pprint -I lex -I utils -I parsing -I typing -o mytools.cmi mytools.mli - ocamlfind ocamldep -package pprint -modules typing/path.mli &gt; typing/path.mli.depends - ocamlfind ocamlc -c -g -package pprint -I typing -I lex -I utils -I parsing -o typing/ident.cmi typing/ident.mli - ocamlfind ocamlc -c -g -package pprint -I utils -I lex -I parsing -I typing -o utils/clflags.cmi utils/clflags.mli - ocamlfind ocamlc -c -g -package pprint -I typing -I lex -I utils -I parsing -o typing/path.cmi typing/path.mli - ocamlfind ocamlc -c -g -package pprint -I lex -I utils -I parsing -I typing -o renaming.cmo renaming.ml - + ocamlfind ocamlc -c -g -package pprint -I lex -I utils -I parsing -I typing -o renaming.cmo renaming.ml - File &quot;renaming.ml&quot;, line 241, characters 4-20: - Warning 3: deprecated: String.uppercase - Use String.uppercase_ascii instead. - ocamlfind ocamlc -c -g -package pprint -I lex -I utils -I parsing -I typing -o coq.cmo coq.ml - ocamlfind ocamldep -package pprint -modules typing/typedtree.mli &gt; typing/typedtree.mli.depends - ocamlfind ocamldep -package pprint -modules parsing/asttypes.mli &gt; parsing/asttypes.mli.depends - ocamlfind ocamldep -package pprint -modules typing/env.mli &gt; typing/env.mli.depends - ocamlfind ocamldep -package pprint -modules typing/annot.mli &gt; typing/annot.mli.depends - ocamlfind ocamldep -package pprint -modules utils/consistbl.mli &gt; utils/consistbl.mli.depends - ocamlfind ocamldep -package pprint -modules parsing/longident.mli &gt; parsing/longident.mli.depends - ocamlfind ocamldep -package pprint -modules typing/types.mli &gt; typing/types.mli.depends - ocamlfind ocamlc -c -g -package pprint -I parsing -I lex -I utils -I typing -o parsing/asttypes.cmi parsing/asttypes.mli - ocamlfind ocamldep -package pprint -modules typing/primitive.mli &gt; typing/primitive.mli.depends - ocamlfind ocamlc -c -g -package pprint -I typing -I lex -I utils -I parsing -o typing/primitive.cmi typing/primitive.mli - ocamlfind ocamlc -c -g -package pprint -I typing -I lex -I utils -I parsing -o typing/annot.cmi typing/annot.mli - ocamlfind ocamlc -c -g -package pprint -I utils -I lex -I parsing -I typing -o utils/consistbl.cmi utils/consistbl.mli - ocamlfind ocamlc -c -g -package pprint -I parsing -I lex -I utils -I typing -o parsing/longident.cmi parsing/longident.mli - ocamlfind ocamlc -c -g -package pprint -I typing -I lex -I utils -I parsing -o typing/types.cmi typing/types.mli - ocamlfind ocamlc -c -g -package pprint -I typing -I lex -I utils -I parsing -o typing/env.cmi typing/env.mli - ocamlfind ocamlc -c -g -package pprint -I lex -I utils -I parsing -I typing -o formula.cmi formula.mli - ocamlfind ocamlc -c -g -package pprint -I typing -I lex -I utils -I parsing -o typing/typedtree.cmi typing/typedtree.mli - ocamlfind ocamldep -package pprint -modules formula_to_coq.mli &gt; formula_to_coq.mli.depends - ocamlfind ocamldep -package pprint -modules normalize.mli &gt; normalize.mli.depends - ocamlfind ocamldep -package pprint -modules parsing/parsetree.mli &gt; parsing/parsetree.mli.depends - ocamlfind ocamlc -c -g -package pprint -I parsing -I lex -I utils -I typing -o parsing/parsetree.cmi parsing/parsetree.mli - ocamlfind ocamldep -package pprint -modules parse_type.mli &gt; parse_type.mli.depends - ocamlfind ocamldep -package pprint -modules print_coq.mli &gt; print_coq.mli.depends - ocamlfind ocamldep -package pprint -modules print_past.mli &gt; print_past.mli.depends - ocamlfind ocamldep -package pprint -modules print_tast.mli &gt; print_tast.mli.depends - ocamlfind ocamldep -package pprint -modules settings.mli &gt; settings.mli.depends - ocamlfind ocamldep -package pprint -modules typing/typetexp.mli &gt; typing/typetexp.mli.depends - ocamlfind ocamlc -c -g -package pprint -I lex -I utils -I parsing -I typing -o cfml_config.cmo cfml_config.ml - ocamlfind ocamlc -c -g -package pprint -I lex -I utils -I parsing -I typing -o characteristic.cmi characteristic.mli - ocamlfind ocamlc -c -g -package pprint -I lex -I utils -I parsing -I typing -o formula_to_coq.cmi formula_to_coq.mli - ocamlfind ocamlc -c -g -package pprint -I lex -I utils -I parsing -I typing -o normalize.cmi normalize.mli - ocamlfind ocamlc -c -g -package pprint -I lex -I utils -I parsing -I typing -o parse_type.cmi parse_type.mli - ocamlfind ocamlc -c -g -package pprint -I lex -I utils -I parsing -I typing -o print_coq.cmi print_coq.mli - ocamlfind ocamlc -c -g -package pprint -I lex -I utils -I parsing -I typing -o print_past.cmi print_past.mli - ocamlfind ocamlc -c -g -package pprint -I lex -I utils -I parsing -I typing -o print_tast.cmi print_tast.mli - ocamlfind ocamlc -c -g -package pprint -I lex -I utils -I parsing -I typing -o settings.cmi settings.mli - ocamlfind ocamlc -c -g -package pprint -I typing -I lex -I utils -I parsing -o typing/typetexp.cmi typing/typetexp.mli - ocamlfind ocamlc -c -g -package pprint -I lex -I utils -I parsing -I typing -o main.cmo main.ml - + ocamlfind ocamlc -c -g -package pprint -I lex -I utils -I parsing -I typing -o main.cmo main.ml - File &quot;main.ml&quot;, line 94, characters 35-52: - Warning 3: deprecated: String.capitalize - Use String.capitalize_ascii instead. - File &quot;main.ml&quot;, line 99, characters 48-65: - Warning 3: deprecated: String.capitalize - Use String.capitalize_ascii instead. - ocamlfind ocamldep -package pprint -modules characteristic.ml &gt; characteristic.ml.depends - ocamlfind ocamldep -package pprint -modules utils/clflags.ml &gt; utils/clflags.ml.depends - ocamlfind ocamldep -package pprint -modules utils/config.ml &gt; utils/config.ml.depends - ocamlfind ocamldep -package pprint -modules utils/config.mli &gt; utils/config.mli.depends - ocamlfind ocamlc -c -g -package pprint -I utils -I lex -I parsing [...] truncated x formula.ml - ocamlfind ocamlopt -c -g -package pprint -I lex -I utils -I parsing -I typing -o print_tast.cmx print_tast.ml - ocamlfind ocamlopt -c -g -package pprint -I typing -I lex -I utils -I parsing -o typing/typecore.cmx typing/typecore.ml - ocamlfind ocamldep -package pprint -modules formula_to_coq.ml &gt; formula_to_coq.ml.depends - ocamlfind ocamldep -package pprint -modules normalize.ml &gt; normalize.ml.depends - ocamlfind ocamldep -package pprint -modules parse_type.ml &gt; parse_type.ml.depends - ocamlfind ocamldep -package pprint -modules utils/ccomp.ml &gt; utils/ccomp.ml.depends - ocamlfind ocamldep -package pprint -modules utils/ccomp.mli &gt; utils/ccomp.mli.depends - ocamlfind ocamlc -c -g -package pprint -I utils -I lex -I parsing -I typing -o utils/ccomp.cmi utils/ccomp.mli - ocamlfind ocamldep -package pprint -modules parsing/parse.ml &gt; parsing/parse.ml.depends - ocamlfind ocamldep -package pprint -modules parsing/parse.mli &gt; parsing/parse.mli.depends - ocamlfind ocamlc -c -g -package pprint -I parsing -I lex -I utils -I typing -o parsing/parse.cmi parsing/parse.mli - /home/bench/.opam/ocaml-base-compiler.4.04.2/bin/ocamllex.opt -q parsing/lexer.mll - ocamlfind ocamldep -package pprint -modules parsing/lexer.ml &gt; parsing/lexer.ml.depends - ocamlfind ocamldep -package pprint -modules parsing/lexer.mli &gt; parsing/lexer.mli.depends - /home/bench/.opam/ocaml-base-compiler.4.04.2/bin/ocamlyacc parsing/parser.mly - + /home/bench/.opam/ocaml-base-compiler.4.04.2/bin/ocamlyacc parsing/parser.mly - 1 rule never reduced - ocamlfind ocamldep -package pprint -modules parsing/parser.mli &gt; parsing/parser.mli.depends - ocamlfind ocamlc -c -g -package pprint -I parsing -I lex -I utils -I typing -o parsing/parser.cmi parsing/parser.mli - ocamlfind ocamlc -c -g -package pprint -I parsing -I lex -I utils -I typing -o parsing/lexer.cmi parsing/lexer.mli - ocamlfind ocamldep -package pprint -modules parsing/parser.ml &gt; parsing/parser.ml.depends - ocamlfind ocamldep -package pprint -modules parsing/syntaxerr.ml &gt; parsing/syntaxerr.ml.depends - ocamlfind ocamldep -package pprint -modules parsing/syntaxerr.mli &gt; parsing/syntaxerr.mli.depends - ocamlfind ocamlc -c -g -package pprint -I parsing -I lex -I utils -I typing -o parsing/syntaxerr.cmi parsing/syntaxerr.mli - ocamlfind ocamlopt -c -g -package pprint -I parsing -I lex -I utils -I typing -o parsing/syntaxerr.cmx parsing/syntaxerr.ml - ocamlfind ocamlopt -c -g -package pprint -I parsing -I lex -I utils -I typing -o parsing/parser.cmx parsing/parser.ml - ocamlfind ocamlopt -c -g -package pprint -I parsing -I lex -I utils -I typing -o parsing/lexer.cmx parsing/lexer.ml - ocamlfind ocamldep -package pprint -modules typing/typemod.ml &gt; typing/typemod.ml.depends - ocamlfind ocamldep -package pprint -modules typing/typemod.mli &gt; typing/typemod.mli.depends - ocamlfind ocamldep -package pprint -modules typing/includemod.mli &gt; typing/includemod.mli.depends - ocamlfind ocamldep -package pprint -modules typing/includecore.mli &gt; typing/includecore.mli.depends - ocamlfind ocamlc -c -g -package pprint -I typing -I lex -I utils -I parsing -o typing/includecore.cmi typing/includecore.mli - ocamlfind ocamlc -c -g -package pprint -I typing -I lex -I utils -I parsing -o typing/includemod.cmi typing/includemod.mli - ocamlfind ocamlc -c -g -package pprint -I typing -I lex -I utils -I parsing -o typing/typemod.cmi typing/typemod.mli - ocamlfind ocamldep -package pprint -modules typing/includemod.ml &gt; typing/includemod.ml.depends - ocamlfind ocamldep -package pprint -modules typing/includeclass.ml &gt; typing/includeclass.ml.depends - ocamlfind ocamldep -package pprint -modules typing/includeclass.mli &gt; typing/includeclass.mli.depends - ocamlfind ocamlc -c -g -package pprint -I typing -I lex -I utils -I parsing -o typing/includeclass.cmi typing/includeclass.mli - ocamlfind ocamldep -package pprint -modules typing/includecore.ml &gt; typing/includecore.ml.depends - ocamlfind ocamldep -package pprint -modules typing/mtype.ml &gt; typing/mtype.ml.depends - ocamlfind ocamldep -package pprint -modules typing/mtype.mli &gt; typing/mtype.mli.depends - ocamlfind ocamlc -c -g -package pprint -I typing -I lex -I utils -I parsing -o typing/mtype.cmi typing/mtype.mli - ocamlfind ocamlopt -c -g -package pprint -I typing -I lex -I utils -I parsing -o typing/includeclass.cmx typing/includeclass.ml - ocamlfind ocamlopt -c -g -package pprint -I typing -I lex -I utils -I parsing -o typing/includecore.cmx typing/includecore.ml - ocamlfind ocamlopt -c -g -package pprint -I typing -I lex -I utils -I parsing -o typing/mtype.cmx typing/mtype.ml - ocamlfind ocamldep -package pprint -modules typing/typeclass.ml &gt; typing/typeclass.ml.depends - ocamlfind ocamldep -package pprint -modules typing/typeclass.mli &gt; typing/typeclass.mli.depends - ocamlfind ocamlc -c -g -package pprint -I typing -I lex -I utils -I parsing -o typing/typeclass.cmi typing/typeclass.mli - ocamlfind ocamldep -package pprint -modules typing/typedecl.ml &gt; typing/typedecl.ml.depends - ocamlfind ocamldep -package pprint -modules typing/typedecl.mli &gt; typing/typedecl.mli.depends - ocamlfind ocamlc -c -g -package pprint -I typing -I lex -I utils -I parsing -o typing/typedecl.cmi typing/typedecl.mli - ocamlfind ocamlopt -c -g -package pprint -I typing -I lex -I utils -I parsing -o typing/typedecl.cmx typing/typedecl.ml - ocamlfind ocamlopt -c -g -package pprint -I typing -I lex -I utils -I parsing -o typing/includemod.cmx typing/includemod.ml - ocamlfind ocamlopt -c -g -package pprint -I typing -I lex -I utils -I parsing -o typing/typeclass.cmx typing/typeclass.ml - ocamlfind ocamlopt -c -g -package pprint -I utils -I lex -I parsing -I typing -o utils/ccomp.cmx utils/ccomp.ml - ocamlfind ocamlopt -c -g -package pprint -I parsing -I lex -I utils -I typing -o parsing/parse.cmx parsing/parse.ml - ocamlfind ocamlopt -c -g -package pprint -I typing -I lex -I utils -I parsing -o typing/typemod.cmx typing/typemod.ml - Compiling CFApp... - + ocamlfind ocamlopt -c -g -package pprint -I typing -I lex -I utils -I parsing -o typing/typemod.cmx typing/typemod.ml - File &quot;typing/typemod.ml&quot;, line 1231, characters 23-40: - Warning 3: deprecated: String.capitalize - Use String.capitalize_ascii instead. - ocamlfind ocamldep -package pprint -modules print_coq.ml &gt; print_coq.ml.depends - ocamlfind ocamldep -package pprint -modules settings.ml &gt; settings.ml.depends - ocamlfind ocamlopt -c -g -package pprint -I lex -I utils -I parsing -I typing -o cfml_config.cmx cfml_config.ml - ocamlfind ocamlopt -c -g -package pprint -I lex -I utils -I parsing -I typing -o characteristic.cmx characteristic.ml - ocamlfind ocamlopt -c -g -package pprint -I lex -I utils -I parsing -I typing -o formula_to_coq.cmx formula_to_coq.ml - ocamlfind ocamlopt -c -g -package pprint -I lex -I utils -I parsing -I typing -o normalize.cmx normalize.ml - ocamlfind ocamlopt -c -g -package pprint -I lex -I utils -I parsing -I typing -o parse_type.cmx parse_type.ml - ocamlfind ocamlopt -c -g -package pprint -I lex -I utils -I parsing -I typing -o print_coq.cmx print_coq.ml - + ocamlfind ocamlopt -c -g -package pprint -I lex -I utils -I parsing -I typing -o print_coq.cmx print_coq.ml - File &quot;print_coq.ml&quot;, line 493, characters 48-57: - Error: This expression has type PPrint.document - but an expression was expected of type - PPrintEngine.ToBuffer.document = PPrintEngine.document - Command exited with code 2. - Hint: Recursive traversal of subdirectories was not enabled for this build, - as the working directory does not look like an ocamlbuild project (no - &#39;_tags&#39; or &#39;myocamlbuild.ml&#39; file). If you have modules in subdirectories, - you should add the option &quot;-r&quot; or create an empty &#39;_tags&#39; file. - - To enable recursive traversal for some subdirectories only, you can use the - following &#39;_tags&#39; file: - - true: -traverse - &lt;dir1&gt; or &lt;dir2&gt;: traverse - - make[1]: *** [Makefile:10: all] Error 10 - make[1]: Leaving directory &#39;/home/bench/.opam/ocaml-base-compiler.4.04.2/.opam-switch/build/coq-cfml.20180525/generator&#39; - make: *** [Makefile:30: generator] Error 2 - make: *** Waiting for unfinished jobs.... - Compiling CFPrint... - Compiling CFBuiltin... - Compiling CFTactics... - Compiling CFHeader... - Compiling CFDemos... - Compiling CFLib... - Compiling CFLibCredits... - Compiling CFAsymptoticsDemos... - make[1]: Leaving directory &#39;/home/bench/.opam/ocaml-base-compiler.4.04.2/.opam-switch/build/coq-cfml.20180525/lib/coq&#39; [ERROR] The compilation of coq-cfml failed at &quot;/home/bench/.opam/opam-init/hooks/sandbox.sh build make -j4&quot;. #=== ERROR while compiling coq-cfml.20180525 ==================================# # context 2.0.5 | linux/x86_64 | ocaml-base-compiler.4.04.2 | file:///home/bench/run/opam-coq-archive/released # path ~/.opam/ocaml-base-compiler.4.04.2/.opam-switch/build/coq-cfml.20180525 # command ~/.opam/opam-init/hooks/sandbox.sh build make -j4 # exit-code 2 # env-file ~/.opam/log/coq-cfml-1576-335865.env # output-file ~/.opam/log/coq-cfml-1576-335865.out ### output ### # [...] # make[1]: Leaving directory &#39;/home/bench/.opam/ocaml-base-compiler.4.04.2/.opam-switch/build/coq-cfml.20180525/generator&#39; # make: *** [Makefile:30: generator] Error 2 # make: *** Waiting for unfinished jobs.... # Compiling CFPrint... # Compiling CFBuiltin... # Compiling CFTactics... # Compiling CFHeader... # Compiling CFDemos... # Compiling CFLib... # Compiling CFLibCredits... # Compiling CFAsymptoticsDemos... # make[1]: Leaving directory &#39;/home/bench/.opam/ocaml-base-compiler.4.04.2/.opam-switch/build/coq-cfml.20180525/lib/coq&#39; &lt;&gt;&lt;&gt; Error report &lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt; +- The following actions failed | - build coq-cfml 20180525 +- - No changes have been performed # Run eval $(opam env) to update the current shell environment &#39;opam install -y -v coq-cfml.20180525 coq.8.6&#39; failed. The middle of the output is truncated (maximum 20000 characters) </pre></dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣 </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
/** * Created by XD on 2016/7/24. */ export enum DeleteEnum{ //未删除 NotDel=0, //已删除 IsDel=1 } export function getDeleteEnumDisplayName(deleteEnum:DeleteEnum){ return { [DeleteEnum.IsDel]:'已删', [DeleteEnum.NotDel]:'未删' }[deleteEnum] } export enum CheckEnum { /// <summary> /// 未通过:2 /// </summary> UnPass = 2, /// 未审核:0 Waiting = 0, /// <summary> /// 已审核:1 /// </summary> Pass = 1, } export enum UseStateEnum { /// <summary> /// 启用1 /// </summary> Enable = 1, /// <summary> /// 停用0 /// </summary> Disable = 0 } export enum SexEnum { /// <summary> /// 未知0 /// </summary> Unknown = 0, /// <summary> /// 男1 // / </summary> Man = 1, /// <summary> /// 女2 /// </summary> Woman = 2 } export enum FormsRole { /// <summary> /// 管理员 /// </summary> Admin=0, /// <summary> /// 网站用户 /// </summary> Member=1 }
--- uid: SolidEdgeAssembly.AssemblyFilletWeld.Faces(SolidEdgeGeometry.FeatureTopologyQueryTypeConstants) summary: Returns a collection of faces of a specified type that belong to a model, a feature, or a topology object. The result of the Faces property is a topology collection. This topology collection is a temporary collection and is overwritten the next time the Edges, Faces, or FacesByRay property is used. remarks: By default, the Faces property returns all faces for the object. The topology collection can be restricted to a specified type of face by supplying a value (from the FeatureTopologyQueryTypeConstants constant set) for the FaceType argument for the feature objects only. For example, this property can be set to return all faces that are spheres. ---
//数据的视觉映射 // 数据可视化是 数据 到 视觉元素 的映射过程(这个过程也可称为视觉编码,视觉元素也可称为视觉通道)。 // data ----> graph //使用visualmap提供通用的视觉映射 visualmap 属性有 1.图形类别symbol 2.图像大小symbolSize 3.颜色color 4.透明度opacity 5.颜色透明度 colorAlpha // 6.颜色明暗度colorLightness 7.颜色饱和度colorSturaction 8.色调colorHue //数据和维度 // 引入 ECharts 主模块 var echarts = require('echarts/lib/echarts'); require('echarts/lib/chart/line'); require('echarts/lib/component/graphic'); require('echarts/lib/component/tooltip'); var symbolSize = 20; // 这个 data 变量在这里单独声明,在后面也会用到。 var data = [[15, 0], [-50, 10], [-56.5, 20], [-46.5, 30], [-22.1, 40]]; var myChart = echarts.init(document.getElementById('root')); myChart.setOption({ tooltip: { // 表示不使用默认的『显示』『隐藏』触发规则。 triggerOn: 'none', formatter: function (params) { return 'X: ' + params.data[0].toFixed(2) + '<br>Y: ' + params.data[1].toFixed(2); } }, xAxis: { min: -100, max: 80, type: 'value', axisLine: { onZero: false } }, yAxis: { min: -30, max: 60, type: 'value', axisLine: { onZero: false } }, series: [ { id: 'a', type: 'line', smooth: true, symbolSize: symbolSize, // 为了方便拖拽,把 symbolSize 尺寸设大了。 data: data } ] }); myChart.setOption({ // 声明一个 graphic component,里面有若干个 type 为 'circle' 的 graphic elements。 // 这里使用了 echarts.util.map 这个帮助方法,其行为和 Array.prototype.map 一样,但是兼容 es5 以下的环境。 // 用 map 方法遍历 data 的每项,为每项生成一个圆点。 graphic: echarts.util.map(data, function (dataItem, dataIndex) { return { // 'circle' 表示这个 graphic element 的类型是圆点。 type: 'circle', shape: { // 圆点的半径。 r: symbolSize / 2 }, // 用 transform 的方式对圆点进行定位。position: [x, y] 表示将圆点平移到 [x, y] 位置。 // 这里使用了 convertToPixel 这个 API 来得到每个圆点的位置,下面介绍。 position: myChart.convertToPixel('grid', dataItem), // 这个属性让圆点不可见(但是不影响他响应鼠标事件)。 invisible: true, // 这个属性让圆点可以被拖拽。 draggable: true, // 把 z 值设得比较大,表示这个圆点在最上方,能覆盖住已有的折线图的圆点。 z: 100, // 在 mouseover 的时候显示,在 mouseout 的时候隐藏。 onmousemove: echarts.util.curry(showTooltip, dataIndex), onmouseout: echarts.util.curry(hideTooltip, dataIndex), // 此圆点的拖拽的响应事件,在拖拽过程中会不断被触发。下面介绍详情。 // 这里使用了 echarts.util.curry 这个帮助方法,意思是生成一个与 onPointDragging // 功能一样的新的函数,只不过第一个参数永远为此时传入的 dataIndex 的值。 ondrag: echarts.util.curry(onPointDragging, dataIndex) }; }) }); // 拖拽某个圆点的过程中会不断调用此函数。 // 此函数中会根据拖拽后的新位置,改变 data 中的值,并用新的 data 值,重绘折线图,从而使折线图同步于被拖拽的隐藏圆点。 function onPointDragging(dataIndex) { // 这里的 data 就是本文最初的代码块中声明的 data,在这里会被更新。 // 这里的 this 就是被拖拽的圆点。this.position 就是圆点当前的位置。 data[dataIndex] = myChart.convertFromPixel('grid', this.position); // 用更新后的 data,重绘折线图。 myChart.setOption({ series: [{ id: 'a', data: data }] }); } window.addEventListener('resize', function () { // 对每个拖拽圆点重新计算位置,并用 setOption 更新。 myChart.setOption({ graphic: echarts.util.map(data, function (item, dataIndex) { return { position: myChart.convertToPixel('grid', item) }; }) }); }); function showTooltip(dataIndex) { myChart.dispatchAction({ type: 'showTip', seriesIndex: 0, dataIndex: dataIndex }); } function hideTooltip(dataIndex) { myChart.dispatchAction({ type: 'hideTip' }); }
require 'test_helper' require 'set' class MmDraftTest < Test::Unit::TestCase context "record" do def setup Dog.accepts_nested_attributes_for(:monkey, :apes, :allow_destroy => true) Dog.collection.remove end context "A Document" do setup do @dog = Dog.create(:name => 'Rufus', :monkey_attributes => [{:name => 'Boink'}], :apes_attributes => [{:name => 'Pess'}] ) end should "accept nested attributes for embedded documents" do @dog.monkey.size.should == 1 end should "accept nested attributes for associated documents" do @dog.apes.size.should == 1 end context "which already exists" do setup do monkey = @dog.monkey.first.attributes.merge({:_destroy => true}) ape = @dog.apes.first.attributes.merge({:_destroy => true}) # @dog.update_attributes(:monkey_attributes => [monkey], :apes_attributes => [ape]) @dog.attributes = {:monkey_attributes => [monkey], :apes_attributes => [ape]} end should "not destroy associated documents until the document is saved" do @dog.apes.size.should == 1 end should "destroy embedded documents when saved" do @dog.save @dog.reload @dog.monkey.size.should == 0 end should "destroy associated documents when saved" do @dog.save @dog.reload @dog.apes.size.should == 0 end end end should "raise an ArgumentError for non existing associations" do lambda { Dog.accepts_nested_attributes_for :blah }.should raise_error(ArgumentError) end end end
/* * Generated by class-dump 3.3.4 (64 bit). * * class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2011 by Steve Nygard. */ #import "UIWindow.h" @interface UIWindow (MPAdditions) - (id)copyIOSurfaceSnapshotView:(long long)arg1; @end
<?php function connection() { // serwer $mysql_server = "127.0.0.1"; // admin $mysql_admin = "root"; // hasło $mysql_pass = ""; // nazwa baza $mysql_db = "zaklad_tapicerski"; // nawiązujemy połączenie z serwerem MySQL @mysql_connect($mysql_server, $mysql_admin, $mysql_pass) or die('Brak połączenia z serwerem MySQL.'); // łączymy się z bazą danych @mysql_select_db($mysql_db) or die('Błąd wyboru bazy danych.'); } ?>
package rodzillaa.github.io.rodzilla.utils; public class APIUtil { public static final String SERVER_URL = "http://ec2-54-174-96-216.compute-1.amazonaws.com:9000"; }
package weka.analyzers.mineData; import java.util.BitSet; /** * The Disjunction of other cached rules. * * @param <T> the type of CachedRule contained in this RuleSet */ public class CachedRuleDisjunction<T extends CachedRule> extends CachedRuleSet<T> { /** * Construct a new empty RuleDisjunction that covers all Instances. * * @param numInstances number of instances this RuleSet should cover */ public CachedRuleDisjunction(int numInstances) { super(numInstances, "OR"); } @Override protected void addBitSet(BitSet other) { covered.or(other); } }
require "spec_helper" describe LicensesController do describe "routing" do it "recognizes and generates #index" do { :get => "/licenses" }.should route_to(:controller => "licenses", :action => "index") end it "recognizes and generates #new" do { :get => "/licenses/new" }.should route_to(:controller => "licenses", :action => "new") end it "recognizes and generates #show" do { :get => "/licenses/1" }.should route_to(:controller => "licenses", :action => "show", :id => "1") end it "recognizes and generates #edit" do { :get => "/licenses/1/edit" }.should route_to(:controller => "licenses", :action => "edit", :id => "1") end it "recognizes and generates #create" do { :post => "/licenses" }.should route_to(:controller => "licenses", :action => "create") end it "recognizes and generates #update" do { :put => "/licenses/1" }.should route_to(:controller => "licenses", :action => "update", :id => "1") end it "recognizes and generates #destroy" do { :delete => "/licenses/1" }.should route_to(:controller => "licenses", :action => "destroy", :id => "1") end end end
'use strict'; var React = require('react'); var mui = require('material-ui'); var SvgIcon = mui.SvgIcon; var DeviceSignalCellularConnectedNoInternet2Bar = React.createClass({ displayName: 'DeviceSignalCellularConnectedNoInternet2Bar', render: function render() { return React.createElement( SvgIcon, this.props, React.createElement('path', { 'fillOpacity': '.3', d: 'M22 8V2L2 22h16V8z' }), React.createElement('path', { d: 'M14 22V10L2 22h12zm6-12v8h2v-8h-2zm0 12h2v-2h-2v2z' }) ); } }); module.exports = DeviceSignalCellularConnectedNoInternet2Bar;
/** * Created by tkachenko on 14.04.15. */ ATF.invoke(['$directiveProvider', 'utils', 'jQuery'], function ($directiveProvider, utils, $) { $directiveProvider.register('$On', { link: function (name, $el, scope, args, vars) { var __vars = vars||{}; if (!args[0] || !args[1]) { return $el; } var eventName = args[0]; var expr = utils.eval(args[1]); var apply = args[2]; if (eventName.toLowerCase() === 'transitionend') { eventName = 'webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend'; } $($el).on(eventName, function ($event) { __vars.$event = $event; if (args[2] || eventName === 'click') { $event.preventDefault(); } expr.call(this, scope, __vars); if (apply) { scope.$apply(); } }); return $el; } }); });
# retext-live DEPRECATED in favour of retext’s virtual object model. [See previous versions](https://github.com/wooorm/retext-live/tree/b8bf46a2466fb2bfbe2f9f8430683a479dfe131a). They can still be used.
//! Writes audio samples to files. (Reads too, this module needs a rename) //! //! ### Audacity PCM import settings //! //! * File > Import > Raw Data... //! * Signed 16-bit PCM //! * Little-endian //! * 1 Channel (Mono) //! * Sample rate: 44_100Hz (or whatever your samples generated have) use std::fs::OpenOptions; use std::io::{BufReader, Error, Read, Result, Write}; use std::path::Path; use byteorder::{BigEndian, LittleEndian, ReadBytesExt, WriteBytesExt}; /// Creates a file at `filename` and writes a bunch of `&[i16]` samples to it as a PCM file. /// See module documentation for PCM settings. /// /// ``` /// use synthrs::wave::sine_wave; /// use synthrs::writer::write_pcm_file; /// use synthrs::synthesizer::{quantize_samples, make_samples}; /// /// write_pcm_file( /// "out/sine.wav", /// &quantize_samples::<i16>(&make_samples(0.1, 44_100, sine_wave(440.0))), /// ).expect("failed to write wav"); /// ``` pub fn write_pcm_file(filename: &str, samples: &[i16]) -> Result<()> { let path = Path::new(filename); let mut f = OpenOptions::new() .write(true) .truncate(true) .create(true) .open(&path)?; write_pcm(&mut f, samples) } /// Writes a bunch of `&[i16]` samples to a `Write` as raw PCM. /// See module documentation for PCM settings. /// /// Also see `synthrs::writer::write_pcm_file`. /// /// ``` /// use std::io::Cursor; /// use synthrs::wave::sine_wave; /// use synthrs::writer::write_pcm; /// use synthrs::synthesizer::{quantize_samples, make_samples}; /// /// let mut output_buffer: Vec<u8> = Vec::new(); /// let mut output_writer = Cursor::new(output_buffer); /// /// // You can use whatever implements `Write`, such as a `File`. /// write_pcm( /// &mut output_writer, /// &quantize_samples::<i16>(&make_samples(0.1, 44_100, sine_wave(440.0))), /// ).expect("failed to write wav"); /// ``` pub fn write_pcm<W>(writer: &mut W, samples: &[i16]) -> Result<()> where W: Write, { for &sample in samples.iter() { writer.write_i16::<LittleEndian>(sample)?; } Ok(()) } /// Creates a file at `filename` and writes a bunch of `&[i16]` samples to it as a WAVE file /// ``` /// use synthrs::wave::sine_wave; /// use synthrs::writer::write_wav_file; /// use synthrs::synthesizer::{quantize_samples, make_samples}; /// /// write_wav_file( /// "out/sine.wav", /// 44_100, /// &quantize_samples::<i16>(&make_samples(0.1, 44_100, sine_wave(440.0))), /// ).expect("failed to write wav"); /// ``` pub fn write_wav_file(filename: &str, sample_rate: usize, samples: &[i16]) -> Result<()> { let path = Path::new(filename); let mut f = OpenOptions::new() .write(true) .truncate(true) .create(true) .open(&path)?; write_wav(&mut f, sample_rate, samples) } /// Writes a bunch of `&[i16]` samples to a `Write`. Also see `synthrs::writer::write_wav_file`. /// ``` /// use std::io::Cursor; /// use synthrs::wave::sine_wave; /// use synthrs::writer::write_wav; /// use synthrs::synthesizer::{quantize_samples, make_samples}; /// /// let mut output_buffer: Vec<u8> = Vec::new(); /// let mut output_writer = Cursor::new(output_buffer); /// /// // You can use whatever implements `Write`, such as a `File`. /// write_wav( /// &mut output_writer, /// 44_100, /// &quantize_samples::<i16>(&make_samples(0.1, 44_100, sine_wave(440.0))), /// ).expect("failed to write wav"); /// ``` pub fn write_wav<W>(writer: &mut W, sample_rate: usize, samples: &[i16]) -> Result<()> where W: Write, { // See: http://www-mmsp.ece.mcgill.ca/Documents/AudioFormats/WAVE/WAVE.html // Some WAV header fields let channels = 1; let bit_depth = 16; let subchunk_2_size = samples.len() * channels * bit_depth / 8; let chunk_size = 36 + subchunk_2_size as i32; let byte_rate = (sample_rate * channels * bit_depth / 8) as i32; let block_align = (channels * bit_depth / 8) as i16; writer.write_i32::<BigEndian>(0x5249_4646)?; // ChunkID, RIFF writer.write_i32::<LittleEndian>(chunk_size)?; // ChunkSize writer.write_i32::<BigEndian>(0x5741_5645)?; // Format, WAVE writer.write_i32::<BigEndian>(0x666d_7420)?; // Subchunk1ID, fmt writer.write_i32::<LittleEndian>(16)?; // Subchunk1Size, 16 for PCM writer.write_i16::<LittleEndian>(1)?; // AudioFormat, PCM = 1 (linear quantization) writer.write_i16::<LittleEndian>(channels as i16)?; // NumChannels writer.write_i32::<LittleEndian>(sample_rate as i32)?; // SampleRate writer.write_i32::<LittleEndian>(byte_rate)?; // ByteRate writer.write_i16::<LittleEndian>(block_align)?; // BlockAlign writer.write_i16::<LittleEndian>(bit_depth as i16)?; // BitsPerSample writer.write_i32::<BigEndian>(0x6461_7461)?; // Subchunk2ID, data writer.write_i32::<LittleEndian>(subchunk_2_size as i32)?; // Subchunk2Size, number of bytes in the data for sample in samples { writer.write_i16::<LittleEndian>(*sample)? } Ok(()) } // Borrowing of packed &wave.pcm is unsafe // #[repr(C, packed)] /// Representation of a WAV file. Does not contain fields for extended WAV formats. #[repr(C)] #[derive(Debug, Clone)] pub struct Wave { pub chunk_id: i32, pub chunk_size: i32, pub format: i32, pub subchunk_1_id: i32, pub subchunk_1_size: i32, /// 1 = PCM pub audio_format: i16, pub num_channels: i16, pub sample_rate: i32, pub byte_rate: i32, pub block_align: i16, pub bits_per_sample: i16, pub subchunk_2_id: i32, pub subchunk_2_size: i32, pub pcm: Vec<i16>, } /// Reads a wave file given a file path. Convenience wrapper around `crate::writer::read_wav_file`. /// ``` /// use synthrs::writer; /// /// let wave = writer::read_wav_file("./tests/assets/sine.wav").unwrap(); /// assert_eq!(wave.num_channels, 1); /// ``` pub fn read_wav_file(filename: &str) -> Result<Wave> { let path = Path::new(filename); let file = OpenOptions::new().read(true).open(&path)?; let mut reader = BufReader::new(file); read_wav(&mut reader) } /// Reads a wave file. Only supports mono 16-bit, little-endian, signed PCM WAV files /// /// ### Useful commands: /// /// * Use `ffmpeg -i .\example.wav` to inspect a wav /// * Use `ffmpeg -i "dirty.wav" -f wav -flags +bitexact -acodec pcm_s16le -ar 44100 -ac 1 "clean.wav"` to clean a WAV /// /// ``` /// use std::path::Path; /// use std::fs::OpenOptions; /// use std::io::BufReader; /// use synthrs::writer; /// /// let path = Path::new("./tests/assets/sine.wav"); /// let file = OpenOptions::new().read(true).open(&path).unwrap(); /// let mut reader = BufReader::new(file); /// /// let wave = writer::read_wav(&mut reader).unwrap(); /// assert_eq!(wave.num_channels, 1); /// ``` // For -acodec values, see https://trac.ffmpeg.org/wiki/audio%20types pub fn read_wav<R>(reader: &mut R) -> Result<Wave> where R: Read, { let chunk_id = reader.read_i32::<BigEndian>()?; // ChunkID, RIFF let chunk_size = reader.read_i32::<LittleEndian>()?; // ChunkSize let format = reader.read_i32::<BigEndian>()?; // Format, WAVE if format != 0x5741_5645 { return Err(Error::new( std::io::ErrorKind::InvalidInput, "file is not a WAV".to_string(), )); } let subchunk_1_id = reader.read_i32::<BigEndian>()?; // Subchunk1ID, fmt let subchunk_1_size = reader.read_i32::<LittleEndian>()?; // Subchunk1Size, Chunk size: 16, 18 or 40 let audio_format = reader.read_i16::<LittleEndian>()?; // AudioFormat, PCM = 1 (linear quantization) if audio_format != 1 { return Err(Error::new( std::io::ErrorKind::InvalidInput, format!( "only 16-bit little-endian signed PCM WAV supported, audio_format: {}", audio_format ), )); } let num_channels = reader.read_i16::<LittleEndian>()?; // NumChannels let sample_rate = reader.read_i32::<LittleEndian>()?; // SampleRate let byte_rate = reader.read_i32::<LittleEndian>()?; // ByteRate let block_align = reader.read_i16::<LittleEndian>()?; // BlockAlign let bits_per_sample = reader.read_i16::<LittleEndian>()?; // BitsPerSample let extra_bytes = subchunk_1_size - 16; if extra_bytes > 0 { let extension_size = reader.read_i16::<LittleEndian>()?; // Size of the extension (0 or 22) if extension_size == 22 { // TODO: Add this to `Wave` as optionals let _valid_bits_per_sample = reader.read_i16::<LittleEndian>()?; let _speaker_mask = reader.read_i16::<LittleEndian>()?; let _subformat = reader.read_i16::<BigEndian>()?; } else if extension_size != 0 { return Err(Error::new( std::io::ErrorKind::InvalidInput, format!( "unexpected fmt chunk extension size: should be 0 or 22 but got: {}", extension_size ), )); } } let subchunk_2_id = reader.read_i32::<BigEndian>()?; // Subchunk2ID, data if subchunk_2_id != 0x6461_7461 { return Err(Error::new( std::io::ErrorKind::InvalidInput, format!( "unexpected subchunk name: expecting data, got: {}", subchunk_2_id ), )); } let subchunk_2_size = reader.read_i32::<LittleEndian>()?; // Subchunk2Size, number of bytes in the data let mut pcm: Vec<i16> = Vec::with_capacity(2 * subchunk_2_size as usize); // `reader.read_into_i16(&pcm)` doesn't seem to work here due to bad input? // It just does nothing and &pcm is left empty after that. for _i in 0..subchunk_2_size { let sample = reader.read_i16::<LittleEndian>().unwrap_or(0); pcm.push(sample); } let wave = Wave { chunk_id, chunk_size, format, subchunk_1_id, subchunk_1_size, audio_format, num_channels, sample_rate, byte_rate, block_align, bits_per_sample, subchunk_2_id, subchunk_2_size, pcm, }; Ok(wave) } #[cfg(test)] mod tests { use super::*; #[test] fn test_read_wav() { // 1 second at 44,100Hz, PCM 16 (2-byte) let wave = read_wav_file("./tests/assets/sine.wav").unwrap(); assert_eq!(wave.format, 0x5741_5645); // WAVE assert_eq!(wave.audio_format, 1); assert_eq!(wave.num_channels, 1); assert_eq!(wave.sample_rate, 44_100); assert_eq!(wave.byte_rate, 88_200); assert_eq!(wave.block_align, 2); assert_eq!(wave.bits_per_sample, 16); assert_eq!(wave.subchunk_2_size, 88_200); assert_eq!(wave.pcm.len(), 88_200); } #[test] fn test_write_read_wav() { use crate::synthesizer::{make_samples, quantize_samples}; use crate::wave::sine_wave; use crate::writer::write_wav; use std::io::{Cursor, Seek, SeekFrom}; let output_buffer: Vec<u8> = Vec::new(); let mut output_writer = Cursor::new(output_buffer); write_wav( &mut output_writer, 44_100, &quantize_samples::<i16>(&make_samples(0.1, 44_100, sine_wave(440.0))), ) .unwrap(); let _ = output_writer.seek(SeekFrom::Start(0)); let wave = read_wav(&mut output_writer).unwrap(); assert_eq!(wave.format, 0x5741_5645); // WAVE assert_eq!(wave.audio_format, 1); assert_eq!(wave.num_channels, 1); assert_eq!(wave.sample_rate, 44_100); assert_eq!(wave.byte_rate, 88_200); assert_eq!(wave.block_align, 2); assert_eq!(wave.bits_per_sample, 16); assert_eq!(wave.subchunk_2_size, 8820); assert_eq!(wave.pcm.len(), 8820); } }
import Constants from '../constants'; import LinkDrawable from './link'; import SphericalPortalLinkMesh from '../mesh/spherical-portal-link'; /** * Represents a portal link that follows the surface of a sphere. * * Hooray for custom shaders, etc! */ class SphericalPortalLinkDrawable extends LinkDrawable { /** * Construct a spherical portal link * @param {Number} sphereRadius Radius of the sphere * @param {vec2} start Lat,lng of the origin portal * @param {vec2} end Lat,lng of the destination portal * @param {vec4} color Color of the link * @param {Number} startPercent Percent health of the origin portal * @param {Number} endPercent Percent health of the destination portal */ constructor(sphereRadius, start, end, color, startPercent, endPercent) { super(Constants.Program.SphericalLink, Constants.Texture.PortalLink); this.radius = sphereRadius; this.start = start; this.end = end; this.color = color; this.startPercent = startPercent; this.endPercent = endPercent; } /** * Constructs a mesh for the link, then initializes the remaining assets. * @param {AssetManager} manager AssetManager containing the program/texture * @return {Boolean} Success/failure */ init(manager) { this.mesh = new SphericalPortalLinkMesh( manager._gl, this.radius, this.start, this.end, this.color, this.startPercent, this.endPercent ); return super.init(manager); } updateView(viewProject, view, project) { super.updateView(viewProject, view, project); this.uniforms.u_model = this.model; } } export default SphericalPortalLinkDrawable;
<div class="page-content container"> <div class="col-xs-10 col-xs-offset-1"> <div class="area padding-15 text-center"> <button class="btn needs-btn" ui-sref="demand.list">前往需求列表</button> </div> <div class="area bg-white"> <h4 class="text-green font-bold"><i class="glyphicon glyphicon-list-alt"></i> 推荐阅读</h4> <p class="read-content row clearfix"> <span class="col-xs-6"> <a class="text-muted" ui-sref="reading.rules">商品发布规则</a> </span> <span class="col-xs-6"> <a class="text-muted" ui-sref="reading.iphone">购买二手iPhone注意事项</a> </span> </p> </div> <div class="area"> <div class="area-header text-center"> <h3 class="page-title-wrap"> <span class="page-title-content"><i class="iconfont icon-xin text-red page-title-icon"></i>最新上架</span> </h3> </div> <div class="row"> <div ui-sref="goods.details({id: item._id})" class="col-xs-3" ng-repeat="item in vm.recentGoods"> <img-reset img-data="item"></img-reset> </div> </div> </div> <div class="area"> <div class="area-header text-center"> <h3 class="page-title-wrap"> <span class="page-title-content"><i class="iconfont icon-shoucangjia text-red page-title-icon"></i>收藏最多</span> </h3> </div> <div class="row"> <div ui-sref="goods.details({id: item._id})" class="col-xs-3" ng-repeat="item in vm.collectedMostGoods"> <img-reset img-data="item"></img-reset> </div> </div> </div> <div class="area"> <div class="area-header text-center"> <h3 class="page-title-wrap"> <span class="page-title-content"><i class="iconfont icon-kejian text-red page-title-icon"></i>浏览最多</span> </h3> </div> <div class="row"> <div ui-sref="goods.details({id: item._id})" class="col-xs-3" ng-repeat="item in vm.pvMostGoods"> <img-reset img-data="item"></img-reset> </div> </div> </div> </div> </div>
\documentclass[12pt,a4paper]{article} \usepackage{../HBSuerDemir} \begin{document} \hPage{b1p2/262} \begin{enumerate} \item [30.] Check the consistency of the system, and solve (if possible): \begin{enumerate} \item [a)] $3x_1 + 2x_2 + x_3=7$\\ $2x_1+x_2-2x_3=4$\\ $4x_1+3x_2+4x_3=20 $ \item[b)] $2x_1+7x_3=4$\\ $x_1+x_2+2x_3=1$ \\ $2x_1+2x_2+4x_3=2$ \end{enumerate} \item [31.] Solve \begin{enumerate} \item [a)] $x+2y = 3$\\ $2x+y=0$\\ $3x-y=5$ \item[b)] $x+2y=3$\\ $2x+y=0$ \\ $x+y=2$ \end{enumerate} \item [32.] Solve \begin{enumerate} \item [a)] $x^2+5y^2-z^2=0$\\ $2x^2+3y^2-z^2=2$\\ $x^2-y^2+2z^2=21 $ \item[b)] $\frac{2}{x}+\frac{1}{y}+\frac{3}{z}=1$\\ $\frac{6}{x}-\frac{2}{y}+\frac{6}{z}=3$ \\ $\frac{1}{x}+\frac{1}{2y}-\frac{3}{z}=0$ \end{enumerate} \item [33.] Solve \begin{enumerate} \item [a)] $3x-y-z=2$\\ $4x+y+2z=7$\\ $x+2y+3z=4$ \item[b)] $s+t=2$\\ $t-u=3$ \\ $u-z=2$\\ $s-z=7$ \end{enumerate} \item [34.] If the following system have the same solution, what is the relation between a,b,c? $2x-3y+z=5$\\ $ax+y-bz=2$\\ $x-y+2z=0 $ $5x-y+2z=4$\\ $x+cy-z=0$ \item [35.] Discuss the solution of $x+a^2y+a^4z=a$\\ $x+b^2y+b^4z=b$\\ $x+c^2y+c^4z=c $ \end{enumerate} \end{document}
<link rel="import" href="../bower_components/polymer/polymer.html"> <link rel="import" href="../bower_components/core-pages/core-pages.html"> <link rel="import" href="../bower_components/paper-button/paper-button.html"> <link rel="import" href="../bower_components/facebook-login/facebook-login.html"> <!--<link rel="import" href="../bower_components/fontawesome-icon/fontawesome-icon.html">--> <link rel="import" href="claimed-controller.html"> <link rel="import" href="claimed-login.html"> <link rel="import" href="claimed-map.html"> <link rel="import" href="claimed-button.html"> <x-fontawesome></x-fontawesome> <polymer-element name="claimed-app" block> <template> <style> ::content > .core-selected { position: relative; display: block; z-index: 10; } claimed-map { position: absolute; z-index: 0; } core-pages { position: relative; z-index: 1; } claimed-button { font-size: 3em; display: inline; } </style> <claimed-controller user="{{user}}" location="{{location}}" state="{{state}}"></claimed-controller> <core-pages selected="{{state}}" fit> <claimed-login name="login" user="{{user}}" on-connected="{{state = 'map'}}" on-disconnected="{{state = 'login'}}"></claimed-login> <div name="claim" style="text-align: center;"> <div style="height: 50%; padding-top: 13em; box-sizing: border-box;"> <claimed-button icon="user"> User</claimed-button> </div> <div style="height: 50%; padding-top: 6.5em; box-sizing: border-box;"> <claimed-button icon="flag" disable="{{!location}}"> Claim</claimed-button> <br/> <template if="{{!location}}"> <span style="position:relative; top:-1.5em; color: #ffd600;"> <!--<fontawesome-icon value="fa fa-warning"></fontawesome-icon>--> Enable Geolocation to play </span> </template> </div> </div> </core-pages> <core-ajax auto url="claims/{{user.id}}" method="GET" handleAs="json" on-core-response="{{handleResponse}}"></core-ajax> <core-ajax auto url="claim/{{user.id}}" method="POST" params="{{ }}" handleAs="json" on-core-response="{{handleResponse}}"></core-ajax> <claimed-map location="{{location}}" fit class="background"></claimed-map> </template> <script> Polymer('claimed-app', { created: function () {}, ready: function () { console.dir(this); }, attached: function () {}, domReady: function () {}, detached: function () {}, attributeChanged: function (attrName, oldVal, newVal) { //var newVal = this.getAttribute(attrName); console.log(attrName, 'old: ' + oldVal, 'new:', newVal); }, }); </script> </polymer-element>