code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
package org.buildmlearn.toolkit.fragment; import android.app.Fragment; import android.content.Intent; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import org.buildmlearn.toolkit.R; import org.buildmlearn.toolkit.activity.TemplateActivity; /** * @brief Fragment displayed on the home screen. */ public class HomeFragment extends Fragment { /** * {@inheritDoc} */ @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_home, container, false); view.findViewById(R.id.button_template).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { startActivity(new Intent(getActivity(), TemplateActivity.class)); } }); return view; } }
vishwesh3/BuildmLearn-Toolkit-Android
source-code/app/src/main/java/org/buildmlearn/toolkit/fragment/HomeFragment.java
Java
bsd-3-clause
1,033
package com.xeiam.xchange.btcchina; import java.io.IOException; import javax.ws.rs.Consumes; import javax.ws.rs.DefaultValue; import javax.ws.rs.GET; import javax.ws.rs.HeaderParam; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import si.mazi.rescu.ParamsDigest; import si.mazi.rescu.SynchronizedValueFactory; import com.xeiam.xchange.btcchina.dto.account.request.BTCChinaGetAccountInfoRequest; import com.xeiam.xchange.btcchina.dto.account.request.BTCChinaGetDepositsRequest; import com.xeiam.xchange.btcchina.dto.account.request.BTCChinaGetWithdrawalRequest; import com.xeiam.xchange.btcchina.dto.account.request.BTCChinaGetWithdrawalsRequest; import com.xeiam.xchange.btcchina.dto.account.request.BTCChinaRequestWithdrawalRequest; import com.xeiam.xchange.btcchina.dto.account.response.BTCChinaGetAccountInfoResponse; import com.xeiam.xchange.btcchina.dto.account.response.BTCChinaGetDepositsResponse; import com.xeiam.xchange.btcchina.dto.account.response.BTCChinaGetWithdrawalResponse; import com.xeiam.xchange.btcchina.dto.account.response.BTCChinaGetWithdrawalsResponse; import com.xeiam.xchange.btcchina.dto.account.response.BTCChinaRequestWithdrawalResponse; import com.xeiam.xchange.btcchina.dto.marketdata.BTCChinaDepth; import com.xeiam.xchange.btcchina.dto.marketdata.BTCChinaTicker; import com.xeiam.xchange.btcchina.dto.marketdata.BTCChinaTrade; import com.xeiam.xchange.btcchina.dto.trade.request.BTCChinaBuyIcebergOrderRequest; import com.xeiam.xchange.btcchina.dto.trade.request.BTCChinaBuyOrderRequest; import com.xeiam.xchange.btcchina.dto.trade.request.BTCChinaBuyStopOrderRequest; import com.xeiam.xchange.btcchina.dto.trade.request.BTCChinaCancelIcebergOrderRequest; import com.xeiam.xchange.btcchina.dto.trade.request.BTCChinaCancelOrderRequest; import com.xeiam.xchange.btcchina.dto.trade.request.BTCChinaCancelStopOrderRequest; import com.xeiam.xchange.btcchina.dto.trade.request.BTCChinaGetIcebergOrderRequest; import com.xeiam.xchange.btcchina.dto.trade.request.BTCChinaGetIcebergOrdersRequest; import com.xeiam.xchange.btcchina.dto.trade.request.BTCChinaGetMarketDepthRequest; import com.xeiam.xchange.btcchina.dto.trade.request.BTCChinaGetOrderRequest; import com.xeiam.xchange.btcchina.dto.trade.request.BTCChinaGetOrdersRequest; import com.xeiam.xchange.btcchina.dto.trade.request.BTCChinaGetStopOrderRequest; import com.xeiam.xchange.btcchina.dto.trade.request.BTCChinaGetStopOrdersRequest; import com.xeiam.xchange.btcchina.dto.trade.request.BTCChinaSellIcebergOrderRequest; import com.xeiam.xchange.btcchina.dto.trade.request.BTCChinaSellOrderRequest; import com.xeiam.xchange.btcchina.dto.trade.request.BTCChinaSellStopOrderRequest; import com.xeiam.xchange.btcchina.dto.trade.request.BTCChinaTransactionsRequest; import com.xeiam.xchange.btcchina.dto.trade.response.BTCChinaBooleanResponse; import com.xeiam.xchange.btcchina.dto.trade.response.BTCChinaGetIcebergOrderResponse; import com.xeiam.xchange.btcchina.dto.trade.response.BTCChinaGetIcebergOrdersResponse; import com.xeiam.xchange.btcchina.dto.trade.response.BTCChinaGetMarketDepthResponse; import com.xeiam.xchange.btcchina.dto.trade.response.BTCChinaGetOrderResponse; import com.xeiam.xchange.btcchina.dto.trade.response.BTCChinaGetOrdersResponse; import com.xeiam.xchange.btcchina.dto.trade.response.BTCChinaGetStopOrderResponse; import com.xeiam.xchange.btcchina.dto.trade.response.BTCChinaGetStopOrdersResponse; import com.xeiam.xchange.btcchina.dto.trade.response.BTCChinaIntegerResponse; import com.xeiam.xchange.btcchina.dto.trade.response.BTCChinaTransactionsResponse; @Path("/") @Produces(MediaType.APPLICATION_JSON) public interface BTCChina { @GET @Path("data/ticker") BTCChinaTicker getTicker(@QueryParam("market") String market) throws IOException; /** * Returns all the open orders from the specified {@code market}. * * @param market the market could be {@code btccny}, {@code ltccny}, {@code ltcbtc}. * @return the order book. * @throws IOException indicates I/O exception. * @see #getOrderBook(String, int) */ @GET @Path("data/orderbook") BTCChinaDepth getFullDepth(@QueryParam("market") String market) throws IOException; /** * Order book default contains all open ask and bid orders. Set 'limit' parameter to specify the number of records fetched per request. * <p> * Bid orders are {@code limit} orders with highest price while ask with lowest, and orders are descendingly sorted by price. * </p> * * @param market market could be {@code btccny}, {@code ltccny}, {@code ltcbtc}. * @param limit number of records fetched per request. * @return the order book. * @throws IOException indicates I/O exception. * @see #getFullDepth(String) */ @GET @Path("data/orderbook") BTCChinaDepth getOrderBook(@QueryParam("market") String market, @QueryParam("limit") int limit) throws IOException; /** * Returns last 100 trade records. */ @GET @Path("data/historydata") BTCChinaTrade[] getHistoryData(@QueryParam("market") String market) throws IOException; /** * Returns last {@code limit} trade records. * * @param market * @param limit the range of limit is [0,5000]. * @throws IOException */ @GET @Path("data/historydata") BTCChinaTrade[] getHistoryData(@QueryParam("market") String market, @QueryParam("limit") int limit) throws IOException; /** * Returns 100 trade records starting from id {@code since}. * * @param market * @param since the starting trade ID(exclusive). * @throws IOException */ @GET @Path("data/historydata") BTCChinaTrade[] getHistoryData(@QueryParam("market") String market, @QueryParam("since") long since) throws IOException; /** * Returns {@code limit} trades starting from id {@code since} * * @param market * @param since the starting trade ID(exclusive). * @param limit the range of limit is [0,5000]. * @throws IOException */ @GET @Path("data/historydata") BTCChinaTrade[] getHistoryData(@QueryParam("market") String market, @QueryParam("since") long since, @QueryParam("limit") int limit) throws IOException; @GET @Path("data/historydata") BTCChinaTrade[] getHistoryData(@QueryParam("market") String market, @QueryParam("since") long since, @QueryParam("limit") int limit, @QueryParam("sincetype") @DefaultValue("id") String sincetype) throws IOException; @POST @Path("api_trade_v1.php") @Consumes(MediaType.APPLICATION_JSON) BTCChinaGetAccountInfoResponse getAccountInfo(@HeaderParam("Authorization") ParamsDigest authorization, @HeaderParam("Json-Rpc-Tonce") SynchronizedValueFactory<Long> jsonRpcTonce, BTCChinaGetAccountInfoRequest getAccountInfoRequest) throws IOException; @POST @Path("api_trade_v1.php") @Consumes(MediaType.APPLICATION_JSON) BTCChinaGetDepositsResponse getDeposits(@HeaderParam("Authorization") ParamsDigest authorization, @HeaderParam("Json-Rpc-Tonce") SynchronizedValueFactory<Long> jsonRpcTonce, BTCChinaGetDepositsRequest getDepositsRequest) throws IOException; /** * Get the complete market depth. Returns all open bid and ask orders. */ @POST @Path("api_trade_v1.php") @Consumes(MediaType.APPLICATION_JSON) BTCChinaGetMarketDepthResponse getMarketDepth(@HeaderParam("Authorization") ParamsDigest authorization, @HeaderParam("Json-Rpc-Tonce") SynchronizedValueFactory<Long> jsonRpcTonce, BTCChinaGetMarketDepthRequest request) throws IOException; @POST @Path("api_trade_v1.php") @Consumes(MediaType.APPLICATION_JSON) BTCChinaGetWithdrawalResponse getWithdrawal(@HeaderParam("Authorization") ParamsDigest authorization, @HeaderParam("Json-Rpc-Tonce") SynchronizedValueFactory<Long> jsonRpcTonce, BTCChinaGetWithdrawalRequest request) throws IOException; @POST @Path("api_trade_v1.php") @Consumes(MediaType.APPLICATION_JSON) BTCChinaGetWithdrawalsResponse getWithdrawals(@HeaderParam("Authorization") ParamsDigest authorization, @HeaderParam("Json-Rpc-Tonce") SynchronizedValueFactory<Long> jsonRpcTonce, BTCChinaGetWithdrawalsRequest request) throws IOException; @POST @Path("api_trade_v1.php") @Consumes(MediaType.APPLICATION_JSON) BTCChinaRequestWithdrawalResponse requestWithdrawal(@HeaderParam("Authorization") ParamsDigest authorization, @HeaderParam("Json-Rpc-Tonce") SynchronizedValueFactory<Long> jsonRpcTonce, BTCChinaRequestWithdrawalRequest requestWithdrawalRequest) throws IOException; @POST @Path("api_trade_v1.php") @Consumes(MediaType.APPLICATION_JSON) BTCChinaGetOrderResponse getOrder(@HeaderParam("Authorization") ParamsDigest authorization, @HeaderParam("Json-Rpc-Tonce") SynchronizedValueFactory<Long> jsonRpcTonce, BTCChinaGetOrderRequest getOrderRequest) throws IOException; @POST @Path("api_trade_v1.php") @Consumes(MediaType.APPLICATION_JSON) BTCChinaGetOrdersResponse getOrders(@HeaderParam("Authorization") ParamsDigest authorization, @HeaderParam("Json-Rpc-Tonce") SynchronizedValueFactory<Long> jsonRpcTonce, BTCChinaGetOrdersRequest getOrdersRequest) throws IOException; @POST @Path("api_trade_v1.php") @Consumes(MediaType.APPLICATION_JSON) BTCChinaBooleanResponse cancelOrder(@HeaderParam("Authorization") ParamsDigest authorization, @HeaderParam("Json-Rpc-Tonce") SynchronizedValueFactory<Long> jsonRpcTonce, BTCChinaCancelOrderRequest cancelOrderRequest) throws IOException; @POST @Path("api_trade_v1.php") @Consumes(MediaType.APPLICATION_JSON) BTCChinaIntegerResponse buyOrder2(@HeaderParam("Authorization") ParamsDigest authorization, @HeaderParam("Json-Rpc-Tonce") SynchronizedValueFactory<Long> jsonRpcTonce, BTCChinaBuyOrderRequest buyOrderRequest) throws IOException; @POST @Path("api_trade_v1.php") @Consumes(MediaType.APPLICATION_JSON) BTCChinaIntegerResponse sellOrder2(@HeaderParam("Authorization") ParamsDigest authorization, @HeaderParam("Json-Rpc-Tonce") SynchronizedValueFactory<Long> jsonRpcTonce, BTCChinaSellOrderRequest sellOrderRequest) throws IOException; @POST @Path("api_trade_v1.php") @Consumes(MediaType.APPLICATION_JSON) BTCChinaTransactionsResponse getTransactions(@HeaderParam("Authorization") ParamsDigest authorization, @HeaderParam("Json-Rpc-Tonce") SynchronizedValueFactory<Long> jsonRpcTonce, BTCChinaTransactionsRequest transactionRequest) throws IOException; /** * Place a buy iceberg order. This method will return an iceberg order id. */ @POST @Path("api_trade_v1.php") @Consumes(MediaType.APPLICATION_JSON) BTCChinaIntegerResponse buyIcebergOrder(@HeaderParam("Authorization") ParamsDigest authorization, @HeaderParam("Json-Rpc-Tonce") SynchronizedValueFactory<Long> jsonRpcTonce, BTCChinaBuyIcebergOrderRequest request) throws IOException; /** * Place a sell iceberg order. This method will return an iceberg order id. */ @POST @Path("api_trade_v1.php") @Consumes(MediaType.APPLICATION_JSON) BTCChinaIntegerResponse sellIcebergOrder(@HeaderParam("Authorization") ParamsDigest authorization, @HeaderParam("Json-Rpc-Tonce") SynchronizedValueFactory<Long> jsonRpcTonce, BTCChinaSellIcebergOrderRequest request) throws IOException; /** * Get an iceberg order, including the orders placed. */ @POST @Path("api_trade_v1.php") @Consumes(MediaType.APPLICATION_JSON) BTCChinaGetIcebergOrderResponse getIcebergOrder(@HeaderParam("Authorization") ParamsDigest authorization, @HeaderParam("Json-Rpc-Tonce") SynchronizedValueFactory<Long> jsonRpcTonce, BTCChinaGetIcebergOrderRequest request) throws IOException; /** * Get iceberg orders, including the orders placed inside each iceberg order. */ @POST @Path("api_trade_v1.php") @Consumes(MediaType.APPLICATION_JSON) BTCChinaGetIcebergOrdersResponse getIcebergOrders(@HeaderParam("Authorization") ParamsDigest authorization, @HeaderParam("Json-Rpc-Tonce") SynchronizedValueFactory<Long> jsonRpcTonce, BTCChinaGetIcebergOrdersRequest request) throws IOException; /** * Cancels an open iceberg order. Fails if iceberg order is already cancelled or closed. The related order with the iceberg order will also be * cancelled. */ @POST @Path("api_trade_v1.php") @Consumes(MediaType.APPLICATION_JSON) BTCChinaBooleanResponse cancelIcebergOrder(@HeaderParam("Authorization") ParamsDigest authorization, @HeaderParam("Json-Rpc-Tonce") SynchronizedValueFactory<Long> jsonRpcTonce, BTCChinaCancelIcebergOrderRequest request) throws IOException; /** * Place a buy stop order. This method will return a stop order id. */ @POST @Path("api_trade_v1.php") @Consumes(MediaType.APPLICATION_JSON) BTCChinaIntegerResponse buyStopOrder(@HeaderParam("Authorization") ParamsDigest authorization, @HeaderParam("Json-Rpc-Tonce") SynchronizedValueFactory<Long> jsonRpcTonce, BTCChinaBuyStopOrderRequest request) throws IOException; /** * Place a sell stop order. This method will return an stop order id. */ @POST @Path("api_trade_v1.php") @Consumes(MediaType.APPLICATION_JSON) BTCChinaIntegerResponse sellStopOrder(@HeaderParam("Authorization") ParamsDigest authorization, @HeaderParam("Json-Rpc-Tonce") SynchronizedValueFactory<Long> jsonRpcTonce, BTCChinaSellStopOrderRequest request) throws IOException; /** * Get a stop order. */ @POST @Path("api_trade_v1.php") @Consumes(MediaType.APPLICATION_JSON) BTCChinaGetStopOrderResponse getStopOrder(@HeaderParam("Authorization") ParamsDigest authorization, @HeaderParam("Json-Rpc-Tonce") SynchronizedValueFactory<Long> jsonRpcTonce, BTCChinaGetStopOrderRequest request) throws IOException; /** * Get stop orders. */ @POST @Path("api_trade_v1.php") @Consumes(MediaType.APPLICATION_JSON) BTCChinaGetStopOrdersResponse getStopOrders(@HeaderParam("Authorization") ParamsDigest authorization, @HeaderParam("Json-Rpc-Tonce") SynchronizedValueFactory<Long> jsonRpcTonce, BTCChinaGetStopOrdersRequest request) throws IOException; /** * Cancels an open stop order. Fails if stop order is already cancelled or closed. */ @POST @Path("api_trade_v1.php") @Consumes(MediaType.APPLICATION_JSON) BTCChinaBooleanResponse cancelStopOrder(@HeaderParam("Authorization") ParamsDigest authorization, @HeaderParam("Json-Rpc-Tonce") SynchronizedValueFactory<Long> jsonRpcTonce, BTCChinaCancelStopOrderRequest request) throws IOException; }
cinjoff/XChange-1
xchange-btcchina/src/main/java/com/xeiam/xchange/btcchina/BTCChina.java
Java
mit
14,863
<?php namespace Test\TestBundle\DependencyInjection; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; /** * This is the class that validates and merges configuration from your app/config files * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class} */ class Configuration implements ConfigurationInterface { /** * {@inheritDoc} */ public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root('test_test'); // Here you should define the parameters that are allowed to // configure your bundle. See the documentation linked above for // more information on that topic. return $treeBuilder; } }
max05/bootstrap
src/Test/TestBundle/DependencyInjection/Configuration.php
PHP
mit
873
package gforms // Generate password input field: <input type="password" ...> func PasswordInputWidget(attrs map[string]string) Widget { w := new(textInputWidget) w.Type = "password" if attrs == nil { attrs = map[string]string{} } w.Attrs = attrs return w }
gernest/gforms
passwordinputwidget.go
GO
mit
266
/* Copyright (c) 2003-2018, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license */ CKEDITOR.plugins.setLang( 'colorbutton', 'bs', { auto: 'Automatska', bgColorTitle: 'Boja pozadine', colors: { '000': 'Black', '800000': 'Maroon', '8B4513': 'Saddle Brown', '2F4F4F': 'Dark Slate Gray', '008080': 'Teal', '000080': 'Navy', '4B0082': 'Indigo', '696969': 'Dark Gray', B22222: 'Fire Brick', A52A2A: 'Brown', DAA520: 'Golden Rod', '006400': 'Dark Green', '40E0D0': 'Turquoise', '0000CD': 'Medium Blue', '800080': 'Purple', '808080': 'Gray', F00: 'Red', FF8C00: 'Dark Orange', FFD700: 'Gold', '008000': 'Green', '0FF': 'Cyan', '00F': 'Blue', EE82EE: 'Violet', A9A9A9: 'Dim Gray', FFA07A: 'Light Salmon', FFA500: 'Orange', FFFF00: 'Yellow', '00FF00': 'Lime', AFEEEE: 'Pale Turquoise', ADD8E6: 'Light Blue', DDA0DD: 'Plum', D3D3D3: 'Light Grey', FFF0F5: 'Lavender Blush', FAEBD7: 'Antique White', FFFFE0: 'Light Yellow', F0FFF0: 'Honeydew', F0FFFF: 'Azure', F0F8FF: 'Alice Blue', E6E6FA: 'Lavender', FFF: 'White', '1ABC9C': 'Strong Cyan', // MISSING '2ECC71': 'Emerald', // MISSING '3498DB': 'Bright Blue', // MISSING '9B59B6': 'Amethyst', // MISSING '4E5F70': 'Grayish Blue', // MISSING 'F1C40F': 'Vivid Yellow', // MISSING '16A085': 'Dark Cyan', // MISSING '27AE60': 'Dark Emerald', // MISSING '2980B9': 'Strong Blue', // MISSING '8E44AD': 'Dark Violet', // MISSING '2C3E50': 'Desaturated Blue', // MISSING 'F39C12': 'Orange', // MISSING 'E67E22': 'Carrot', // MISSING 'E74C3C': 'Pale Red', // MISSING 'ECF0F1': 'Bright Silver', // MISSING '95A5A6': 'Light Grayish Cyan', // MISSING 'DDD': 'Light Gray', // MISSING 'D35400': 'Pumpkin', // MISSING 'C0392B': 'Strong Red', // MISSING 'BDC3C7': 'Silver', // MISSING '7F8C8D': 'Grayish Cyan', // MISSING '999': 'Dark Gray' // MISSING }, more: 'Više boja...', panelTitle: 'Colors', textColorTitle: 'Boja teksta' } );
zweidner/hubzero-cms
core/plugins/editors/ckeditor/assets/plugins/colorbutton/lang/bs.js
JavaScript
mit
2,069
# encoding: utf-8 # require 'spec_helper' describe 'country descriptions' do def self.it_splits number, expected it { Phony.split(number).should == expected } end describe 'regression' do it_splits '33630588659', ["33", "6", "30", "58", "86", "59"] end describe 'splitting' do describe 'Ascension Island' do it_splits '2473551', ['247', false, '3551'] end describe 'Afghanistan' do it_splits '93201234567', ['93', '20', '1234567'] # Kabul end describe 'Algeria' do it_splits '213211231234', ['213', '21', '123', '1234'] # Algiers it_splits '213331231234', ['213', '33', '123', '1234'] # Batna end describe 'Argentina' do it_splits '541112345678', ['54', '11', '1234', '5678'] it_splits '542911234567', ['54', '291', '123', '4567'] it_splits '542965123456', ['54', '2965', '12', '3456'] it_splits '5491112345678', ['54', '911', '1234', '5678'] it_splits '5492201234567', ['54', '9220', '123', '4567'] it_splits '5492221123456', ['54', '92221', '12', '3456'] it_splits '548001234567', ['54', '800', '123', '4567'] end describe 'Austria' do it_splits '43198110', %w( 43 1 98110 ) # Vienna it_splits '4310000000', %w( 43 1 0000000 ) # Vienna it_splits '43800123456789', %w( 43 800 123456789 ) # Free it_splits '4368100000000', %w( 43 681 0000 0000 ) # Mobile it_splits '436880000000', %w( 43 688 0000 000 ) # Mobile it_splits '4366900000000', %w( 43 669 0000 0000 ) # Mobile it_splits '433161234567891', %w( 43 316 1234567891 ) # Graz it_splits '432164123456789', %w( 43 2164 123456789 ) # Rohrau # mobile numbers can have from 7 to 10 digits in the subscriber number it_splits '436641234567', %w( 43 664 1234 567 ) it_splits '4366412345678', %w( 43 664 1234 5678 ) it_splits '43664123456789', %w( 43 664 1234 56789 ) it_splits '436641234567890', %w( 43 664 1234 567890 ) end describe 'Australia' do it_splits '61512341234', ['61', '5', '1234', '1234'] # Landline it_splits '61423123123', ['61', '423', '123', '123'] # Mobile end describe 'Bahrain' do it_splits '97312345678', ['973', false, '1234', '5678'] end describe 'Bangladesh' do it_splits '88021234567', %w(880 2 1234567) it_splits '8805112345', %w(880 51 12345) it_splits '88031123456', %w(880 31 123456) it_splits '88032112345', %w(880 321 12345) it_splits '8804311234567', %w(880 431 1234567) it_splits '880902012345', %w(880 9020 12345) end describe 'Belarus' do it_splits '375152123456', %w(375 152 123456) it_splits '375151512345', %w(375 1515 12345) it_splits '375163423456', %w(375 163 423456) it_splits '375163112345', %w(375 1631 12345) it_splits '375291234567', %w(375 29 1234567) it_splits '375800123', %w(375 800 123) it_splits '3758001234', %w(375 800 1234) it_splits '3758001234567', %w(375 800 1234567) it_splits '37582012345678', %w(375 820 12345678) end describe 'Belgium' do it_splits '3235551212', ['32', '3', '555', '12', '12'] # Antwerpen it_splits '3250551212', ['32', '50', '55', '12', '12'] # Brugge it_splits '3225551212', ['32', '2', '555', '12', '12'] # Brussels it_splits '3295551914', ['32', '9', '555', '19', '14'] # Gent it_splits '3245551414', ['32', '4', '555', '14', '14'] # Liège it_splits '3216473200', ['32', '16', '47', '32', '00'] # Leuven it_splits '32475279584', ['32', '475', '27', '95', '84'] # mobile it_splits '32468279584', ['32', '468', '27', '95', '84'] # mobile (Telenet) it_splits '3270123123', ['32', '70', '123', '123'] # Bus Service? end describe 'Belize' do it_splits '5012051234', %w(501 205 1234) end describe 'Benin' do it_splits '22912345678', ['229', false, '1234', '5678'] end describe 'Bolivia' do it_splits '59122772266', %w(591 2 277 2266) end describe 'Botswana' do it_splits '26780123456', %w(267 80 123 456) it_splits '2672956789', %w(267 29 567 89) it_splits '2674634567', %w(267 463 4567) it_splits '2675812345', %w(267 58 123 45) it_splits '26776712345', %w(267 7 6712 345) it_splits '26781234567', %w(267 8 1234 567) end describe 'Brazil' do it_splits '551112341234', ['55', '11', '1234', '1234'] it_splits '5511981231234', ['55', '11', '98123', '1234'] # São Paulo's 9 digits mobile it_splits '552181231234', ['55', '21', '8123', '1234'] it_splits '5521981231234', ['55', '21', '98123', '1234'] # Rio de Janeiro's 9 digits mobile it_splits '551931311234', ['55', '19', '3131', '1234'] # Rio de Janeiro's 9 digits mobile it_splits '5519991311234', ['55', '19', '99131', '1234'] # Rio de Janeiro's 9 digits mobile context "special states with 9 in mobile" do %w{ 11 12 13 14 15 16 17 18 19 21 22 24 27 28 81 82 83 84 85 86 87 88 89 91 92 93 94 95 96 97 98 99}.each do |state_code| it_splits "55#{state_code}993051123", ['55', state_code, '99305', '1123'] end end context "special numbers" do it_splits '5508002221234', ['55', '0800', '222', '1234'] it_splits '5530032221', ['55', '3003', '2221'] it_splits '5540209999', ['55', '4020', '9999'] it_splits '5540048999', ['55', '4004', '8999'] end context "service numbers" do it_splits '55100', ['55', '100', ""] it_splits '55199', ['55', '199', ""] end end describe 'Cambodia' do it_splits '85512236142', ["855", "12", "236", "142"] # mobile (Mobitel) it_splits '855977100872', ["855", "97", "710", "0872"] # mobile (Metfone) it_splits '855234601183', ["855", "23", "460", "1183"] # Long fixed line (Phnom Penh) it_splits '85533234567', ["855", "33", "234", "567"] # Regular fixed line (Kampot) end describe 'Chile' do it_splits '5621234567', ['56', '2', '1234567'] # Santiago it_splits '5675123456', ['56', '75', '123456'] # Curico it_splits '56912345678', ['56', '9', '12345678'] # Mobile it_splits '56137123456', ['56', '137', '123', '456'] # Service end describe 'China' do it_splits '862112345678', ['86', '21', '1234', '5678'] # Shanghai it_splits '8675582193447', ['86', '755', '8219', '3447'] # Shenzhen end describe 'Colombia' do it_splits '5711234567', ['57', '1', '123', '4567'] it_splits '573101234567', ['57', '310', '123', '4567'] # mobile end describe 'Croatia' do it_splits '38521695900', %w( 385 21 695 900 ) # Landline it_splits '38514566666', %w( 385 1 4566 666 ) # Landline (Zagreb) it_splits '385918967509', %w( 385 91 896 7509 ) # Mobile end describe 'Cuba' do it_splits '5351231234', ['53', '5123', '1234'] # Mobile it_splits '5371234567', ['53', '7', '1234567'] # Havana it_splits '5342123456', ['53', '42', '123456'] # Villa Clara end describe 'Cyprus' do it_splits '35712322123456', ['357', '123', '22', '123456'] # Voicemail it_splits '35722123456', ['357', '22', '123456'] # Fixed it_splits '35791123456', ['357', '91', '123456'] # Mobile end describe 'Denmark' do it_splits '4532121212', ['45', false, '32', '12', '12', '12'] end describe 'Egypt' do it_splits '20212345678', ['20', '2', '12345678'] it_splits '20921234567', ['20', '92', '1234567'] it_splits '20951234567', ['20', '95', '1234567'] end describe 'Equatorial Guinea' do it_splits '240222201123', ['240', false, '222', '201', '123'] it_splits '240335201123', ['240', false, '335', '201', '123'] end describe 'Estonia' do it_splits '3723212345', ['372', '321', '2345'] # Landline it_splits '37251231234', ['372', '5123', '1234'] # Mobile it_splits '3728001234', ['372', '800', '1234'] # Freephone it_splits '37281231234', ['372', '8123', '1234'] # Mobile it_splits '37282231234', ['372', '8223', '1234'] # Mobile it_splits '37252212345', ['372', '5221', '2345'] # Mobile it_splits '3725221234', ['372', '5221', '234'] # Mobile it_splits '37270121234', ['372', '7012', '1234'] # Premium end describe 'Finland' do it_splits '3589123123', ['358', '9', '123', '123'] # Helsinki it_splits '3581912312', ['358', '19', '123', '12'] # Nylandia it_splits '3585012312', ['358', '50', '123', '12'] # Mobile it_splits '358600123', ['358', '600', '123'] # Service end describe 'France' do it_splits '33112345678', ['33', '1', '12','34','56','78'] # Paris it_splits '33812345678', ['33', '8', '12','34','56','78'] # Service number end describe 'Georgia' do it_splits '99522012345', %w(995 220 123 45) it_splits '995321234567', %w(995 32 123 4567) it_splits '995342123456', %w(995 342 123 456) it_splits '995596123456', %w(995 596 123 456) end describe 'Germany' do it_splits '493038625454', ['49', '30', '386', '25454'] # Berlin it_splits '4932221764542', ['49', '32', '221', '764542'] # Non-Geographical it_splits '4922137683323', ['49', '221', '376', '83323'] # Cologne it_splits '497614767676', ['49', '761', '476', '7676'] # Freiburg im Breisgau it_splits '4921535100', ['49', '2153', '510', '0'] # Nettetal-Lobberich it_splits '493434144602', ['49', '34341', '446', '02'] # Geithain it_splits '491805878323', ['49', '180', '587', '8323'] # Service number it_splits '491815878323', ['49', '181', '587', '8323'] # Service number it_splits '498001234567', ['49', '800', '123', '4567'] # Service number it_splits '49800222340010', ['49', '800', '222', '340010'] # Service number it_splits '4915111231234', ['49', '151', '1123', '1234'] # Mobile number it_splits '4915771231234', ['49', '157', '7123', '1234'] # Mobile number it_splits '491601234567', ['49', '160', '1234', '567'] # Mobile number it_splits '4916312345678', ['49', '163', '1234', '5678'] # Mobile number it_splits '4915211231234', ['49', '1521', '123', '1234'] # Mobile number end describe 'Ghana' do it_splits '233302123456', ['233', '30', '212', '3456'] # Mobile Vodafone, Accra end describe 'Gibraltar' do it_splits '35020012345', ['350', '200', '12345'] # Fixed it_splits '35021112345', ['350', '211', '12345'] # Fixed it_splits '35022212345', ['350', '222', '12345'] # Fixed it_splits '35054123456', ['350', '54', '123456'] # Mobile it_splits '35056123456', ['350', '56', '123456'] # Mobile it_splits '35057123456', ['350', '57', '123456'] # Mobile it_splits '35058123456', ['350', '58', '123456'] # Mobile it_splits '35060123456', ['350', '60', '123456'] # Mobile it_splits '3508012', ['350', '8012', '' ] # Freephone end describe 'Greece' do it_splits '302142345678', %w(30 21 4234 5678) it_splits '302442345678', %w(30 24 4234 5678) it_splits '305034571234', %w(30 50 3457 1234) it_splits '306901234567', %w(30 690 123 4567) it_splits '307001234567', %w(30 70 0123 4567) it_splits '308001001234', %w(30 800 100 1234) it_splits '308011001234', %w(30 801 100 1234) it_splits '308071001234', %w(30 807 100 1234) it_splits '308961001234', %w(30 896 100 1234) it_splits '309011234565', %w(30 901 123 4565) it_splits '309091234565', %w(30 909 123 4565) end describe 'Haiti' do it_splits '50922121234', ['509', '22', '12', '1234'] end describe 'Hong Kong' do it_splits '85212341234', ['852', false, '1234', '1234'] # end describe 'Hungary' do it_splits'3612345678', ['36', '1', '234', '5678'] it_splits'3622123456', ['36', '22', '123', '456'] end describe 'Iceland' do it_splits '354112', ['354', false, '112'] # Emergency TODO it_splits '3544211234', ['354', false, '421', '1234'] # Keflavík it_splits '3544621234', ['354', false, '462', '1234'] # Akureyri it_splits '3545511234', ['354', false, '551', '1234'] # Reykjavík end describe 'Indonesia' do it_splits '6242323032', ["62", "4", "2323", "032"] it_splits '6285220119289', ['62', '852', '2011', '9289'] it_splits '62217815263', %w(62 21 781 5263) it_splits '6213123', %w(62 13 123) it_splits '6213123456', %w(62 13 123 456) it_splits '6217412', %w(62 174 12) it_splits '6217412345', %w(62 174 12 345) it_splits '6217712', %w(62 177 12) it_splits '6217712123456', %w(62 177 1212 3456) it_splits '62178123', %w(62 178 123) it_splits '6217812345', %w(62 178 123 45) it_splits '622112345', %w(62 21 123 45) it_splits '622112345567', %w(62 21 1234 5567) it_splits '622212345', %w(62 22 123 45) it_splits '62221234567', %w(62 22 123 4567) it_splits '624311234', %w(62 4 311 234) it_splits '62431123456', %w(62 4 3112 3456) it_splits '6262212345', %w(62 6 221 2345) it_splits '62622123456', %w(62 6 2212 3456) it_splits '6270123456', %w(62 70 123 456) it_splits '6271123456', %w(62 71 123 456) it_splits '62711234567', %w(62 71 123 4567) it_splits '62810123456', %w(62 810 123 456) it_splits '6281012345678', %w(62 810 1234 5678) it_splits '628151234567', %w(62 815 123 4567) it_splits '62820123456', %w(62 820 123 456) it_splits '628231234567', %w(62 823 123 4567) it_splits '6282312345678', %w(62 823 1234 5678) it_splits '6287012345', %w(62 870 123 45) it_splits '62877123456', %w(62 877 123 456) it_splits '62881123456', %w(62 881 123 456) it_splits '6288112345656', %w(62 881 1234 5656) it_splits '6291234567', %w(62 9 1234 567) it_splits '629123456789', %w(62 9 123 456 789) end describe 'India' do it_splits '919911182111', ['91', '99', '111', '82', '111'] # mobile it_splits '912212345678', ['91', '22', '123', '45', '678'] # New Delhi it_splits '911411234567', ['91', '141', '123', '45', '67'] # Jaipur it_splits '913525123456', ['91', '3525', '123', '456'] # DALKHOLA it_splits '914433993939', ['91', '44', '339', '93', '939'] # end describe 'Iran' do it_splits '982112341234', ['98', '21', '1234', '1234'] # Teheran it_splits '989191231234', ['98', '919', '123', '1234'] # Example Cell Phone end describe 'Ireland' do it_splits '35311234567', ['353', '1', '123', '4567'] # Dublin, 7 digit subscriber # it_splits '353539233333', ['353', '53', '923', '3333'] # Wexford, 7 digit subscriber it_splits '3532212345', ['353', '22', '12345'] # Mallow, 5 digit subscriber # it_splits '35345123456', ['353', '45', '123456'] # Naas, 6 digit subscriber # it_splits '353801234567', ['353', '80', '123', '4567'] # Mobile it_splits '353761234567', ['353', '76', '123', '4567'] # VoIP it_splits '353800123456', ['353', '800', '123456'] # Freefone it_splits '353000123456', ['353', '000', '123456'] # Default fixed 3 split for unrecognized end describe 'Israel (972)' do it_splits '972100', ['972', '1', '00'] # Police it_splits '97221231234', ['972', '2', '123', '1234'] # Jerusalem Area it_splits '97282411234', ['972', '8', '241', '1234'] # Gaza Strip (Palestine) it_splits '97291231234', ['972', '9', '123', '1234'] # Sharon Area it_splits '972501231234', ['972', '50', '123', '1234'] # Mobile (Pelephone) it_splits '972591231234', ['972', '59', '123', '1234'] # Mobile Jawwal (Palestine) it_splits '972771231234', ['972', '77', '123', '1234'] # Cable Phone Services it_splits '9721700123123', ['972', '1', '700', '123', '123'] # Cable Phone Services end describe 'Israel (970)' do it_splits '97021231234', ['970', '2', '123', '1234'] # Jerusalem Area it_splits '97082411234', ['970', '8', '241', '1234'] # Gaza Strip (Palestine) it_splits '97091231234', ['970', '9', '123', '1234'] # Sharon Area it_splits '970501231234', ['970', '50', '123', '1234'] # Mobile (Pelephone) it_splits '970591231234', ['970', '59', '123', '1234'] # Mobile Jawwal (Palestine) it_splits '970771231234', ['970', '77', '123', '1234'] # Cable Phone Services it_splits '9701700123123', ['970', '1', '700', '123', '123'] # Cable Phone Services end describe 'Italy' do it_splits '39348695281', ['39', '348', '695', '281'] # Mobile (6-digit subscriber no. - rare, but still used) it_splits '393486952812', ['39', '348', '695', '2812'] # Mobile (7-digit subscriber no. - common) it_splits '3934869528123',['39', '348', '695', '2812', '3'] # Mobile (8-digit subscriber no - new) it_splits '393357210488', ['39', '335', '721', '0488'] # Mobile it_splits '393248644272', ['39', '324', '864', '4272'] # Mobile it_splits '390612341234', ['39', '06', '1234', '1234'] # Roma it_splits '390288838883', ['39', '02', '8883', '8883'] # Milano it_splits '390141595661', ['39', '0141', '595', '661'] # Asti it_splits '3903123391', ['39', '031', '23391'] # Como it_splits '390909709511', ['39', '090', '9709511'] # Barcellona it_splits '390471811353', ['39', '0471', '811', '353'] # Bolzano end describe 'Japan' do it_splits '81312345678', %w(81 3 1234 5678) # Tokyo it_splits '81612345678', %w(81 6 1234 5678) # Osaka it_splits '81120123456', %w(81 120 123 456) # Freephone it_splits '81111234567', %w(81 11 123 4567) it_splits '81123123456', %w(81 123 12 3456) it_splits '81126712345', %w(81 1267 1 2345) it_splits '812012345678', %w(81 20 1234 5678) # Pager(Calling Party Pay) it_splits '815012345678', %w(81 50 1234 5678) # IP Telephone it_splits '816012345678', %w(81 60 1234 5678) # UPT it_splits '817012345678', %w(81 70 1234 5678) # PHS it_splits '818012345678', %w(81 80 1234 5678) # Cellular it_splits '819012345678', %w(81 90 1234 5678) # Cellular end describe 'Kenya' do it_splits '254201234567', ['254', '20', '1234567'] # Nairobi it_splits '254111234567', ['254', '11', '1234567'] # Mombasa it_splits '254723100220', ['254', '723', '100220'] # Mombasa end describe 'Kyrgyzstan' do it_splits '996312212345', %w(996 312 212 345) it_splits '996315212345', %w(996 315 212 345) it_splits '996313121234', %w(996 3131 212 34) it_splits '996394621234', %w(996 3946 212 34) it_splits '996501234567', %w(996 50 123 4567) it_splits '996521234567', %w(996 52 123 4567) it_splits '996581234567', %w(996 58 123 4567) it_splits '996800123456', %w(996 800 123 456) end describe 'Lithuania' do it_splits '37070012123', ['370', '700', '12', '123'] # Service it_splits '37061212123', ['370', '612', '12', '123'] # Mobile it_splits '37051231212', ['370', '5', '123', '12', '12'] # Vilnius it_splits '37037121212', ['370', '37', '12', '12', '12'] # Kaunas it_splits '37044011212', ['370', '440', '1', '12', '12'] # Skuodas end describe 'Luxembourg' do it_splits '352222809', ['352', '22', '28', '09'] it_splits '35226222809', ['352', '26', '22', '28', '09'] it_splits '352621123456', ['352', '621', '123', '456'] it_splits '3524123456', ['352', '4', '12', '34', '56'] it_splits '352602112345678', ['352', '6021', '12', '34', '56', '78'] it_splits '352370431', ['352', '37', '04', '31'] it_splits '35227855', ['352', '27', '85', '5'] end describe 'Malaysia' do it_splits '6082123456', ['60', '82', '123456'] # Kuching it_splits '60312345678', ['60', '3', '12345678'] # Kuala Lumpur it_splits '60212345678', ['60', '2', '12345678'] # Singapore it_splits '60111231234', ['60', '11', '123', '1234'] # Mobile it_splits '601112312345', ['60', '11', '123', '12345'] # Mobile it_splits '60800121234', ['60', '800', '12', '1234'] # Freephone # it_splits '60112', ['60', '112'] # Service end describe 'Malta' do it_splits '35621231234', ['356', '2123', '1234'] # Fixed it_splits '35677123456', ['356', '77', '123456'] # Mobile it_splits '35698123456', ['356', '98', '123456'] # Mobile it_splits '35651231234', ['356', '5123', '1234'] # Voice Mail end describe 'Mexico' do it_splits '525512121212', ['52', '55', '1212', '1212'] # Mexico City it_splits '5215512121212', ['52', '1', '55', '1212', '1212'] # Mexico City cell phone from abroad it_splits '526641231212', ['52', '664', '123', '1212'] # Tijuana it_splits '5216641231212', ['52', '1', '664', '123', '1212'] # Tijuana cell phone from abroad it_splits '520446641231212', ['52', '044', '664', '123', '1212'] # Tijuana cell phone local from landline end describe 'Monaco' do it_splits '37741123456', ['377', '41', '12', '34', '56'] # Mobile it_splits '377612345678', ['377', '6', '12', '34', '56', '78'] # Mobile end describe 'Montenegro' do it_splits '38280123456', %w(382 80 123 456) it_splits '3822012345', %w(382 20 123 45) it_splits '38220123456', %w(382 20 123 456) it_splits '38232123456', %w(382 32 123 456) it_splits '38278103456', %w(382 78 103 456) it_splits '38263123', %w(382 63 123) it_splits '382631234567890', %w(382 63 123 456 7890) it_splits '38277103456', %w(382 77 103 456) it_splits '38294103456', %w(382 94 103 456) it_splits '38288103456', %w(382 88 103 456) it_splits '3826812', %w(382 68 12) it_splits '382681212345678', %w(382 68 12 1234 5678) it_splits '38270123', %w(382 70 123) it_splits '382701234567890', %w(382 70 123 456 7890) end describe 'Morocco' do it_splits '212537718685', ['212', '53', '7718', '685'] it_splits '212612345678', ['212', '6', '12', '34', '56', '78'] end describe 'The Netherlands' do it_splits '31612345678', ['31', '6', '12', '34', '56', '78'] # mobile it_splits '31201234567', ['31', '20', '123', '4567'] it_splits '31222123456', ['31', '222', '123', '456'] end describe 'Norway' do it_splits '4721234567', ['47',false,'21','23','45','67'] it_splits '4731234567', ['47',false,'31','23','45','67'] it_splits '4741234567', ['47',false,'412','34','567'] it_splits '4751234567', ['47',false,'51','23','45','67'] it_splits '4761234567', ['47',false,'61','23','45','67'] it_splits '4771234567', ['47',false,'71','23','45','67'] it_splits '4781234567', ['47',false,'812','34','567'] it_splits '4791234567', ['47',false,'912','34','567'] end describe 'Oman' do it_splits '96824423123', %w(968 24 423 123) it_splits '96825423123', %w(968 25 423 123) end describe 'Pakistan' do it_splits '922112345678', %w(92 21 1234 5678) it_splits '92221234567', %w(92 22 1234 567) it_splits '92232123456', %w(92 232 123 456) it_splits '923012345678', %w(92 30 1234 5678) end describe 'Paraguay (Republic of)' do it_splits '59521123456', %w(595 21 123 456) it_splits '595211234567', %w(595 21 123 4567) it_splits '595345123456', %w(595 345 123 456) it_splits '595961611234', %w(595 96 161 1234) end describe 'Peru' do it_splits '51112341234', ['51', '1', '1234', '1234'] # Lima it_splits '51912341234', ['51', '9', '1234', '1234'] # mobile it_splits '51841234123', ['51', '84', '1234', '123'] # Cuzco, best effort end describe 'Philippines' do it_splits '6321234567', ['63', '2', '1234567'] it_splits '6321234567890', ['63', '2', '1234567890'] it_splits '632123456789012', ['63', '2', '123456789012'] it_splits '639121234567', ['63', '912', '1234567'] it_splits '63881234567', ['63', '88', '1234567'] end describe 'Poland' do it_splits '48123456789', ['48', '12', '345', '67', '89'] # Landline it_splits '48501123456', ['48', '501', '123', '456'] # Mobile it_splits '48800123456', ['48', '800', '123', '456'] # Free it_splits '48801123456', ['48', '801', '123', '456'] # Shared cost it_splits '48701123456', ['48', '701', '123', '456'] # Premium end describe 'Portugal' do it_splits '351211231234', ['351', '21', '123', '1234'] # Lisboa it_splits '351241123123', ['351', '241', '123', '123'] # Abrantes it_splits '351931231234', ['351', '93', '123', '1234'] # mobile end describe 'Qatar' do it_splits '9741245123456', %w(974 1245 123 456) it_splits '9742613456', %w(974 26 134 56) it_splits '97433123456', %w(974 33 123 456) it_splits '97444412456', %w(974 44 412 456) it_splits '9748001234', %w(974 800 12 34) it_splits '9749001234', %w(974 900 12 34) it_splits '97492123', %w(974 92 123) it_splits '97497123', %w(974 97 123) end describe 'Romania' do it_splits '40211231234', ['40', '21', '123', '1234'] # Bucureşti it_splits '40721231234', ['40', '72', '123', '1234'] # mobile it_splits '40791231234', ['40', '79', '123', '1234'] # mobile it_splits '40249123123', ['40', '249', '123', '123'] # Olt end describe 'Russia' do it_splits '78122345678', ['7', '812', '234', '56', '78'] # Russia 3-digit it_splits '74012771077', ['7', '4012', '77', '10', '77'] # Russia 4-digit it_splits '78402411212', ['7', '84024', '1', '12', '12'] # Russia 5-digit it_splits '79296119119', ['7', '929', '611', '91', '19'] # Russia 3-digit, Megafon Mobile. it_splits '7840121212', ['7', '840', '12', '1212'] # Abhasia it_splits '7799121212', ['7', '799', '12', '1212'] # Kazachstan it_splits '7995344121212', ['7','995344','12','1212'] # South Osetia it_splits '7209175276', ['7', '209', '17', '5276'] # Fantasy number end describe 'Rwanda' do it_splits '250781234567', ['250', '78', '1234567'] # mobile it_splits '250721234567', ['250', '72', '1234567'] # mobile it_splits '250731234567', ['250', '73', '1234567'] # mobile it_splits '250251234567', ['250', '25', '1234567'] # fixed it_splits '25006123456', ['250', '06', '123456'] # fixed end describe 'Sao Tome and Principe' do it_splits '2392220012', %w(239 2 220 012) it_splits '2399920012', %w(239 9 920 012) end describe 'South Korea' do it_splits '82212345678', ['82', '2', '1234', '5678'] # Seoul it_splits '825112345678', ['82', '51', '1234', '5678'] # Busan it_splits '821027975588', ['82', '10', '2797', '5588'] # mobile it_splits '821087971234', ['82', '10', '8797', '1234'] # mobile end describe 'Serbia' do it_splits '38163512529', ['381', '63', '512', '529'] end describe 'South Sudan' do it_splits '211123212345', ['211', '123', '212', '345'] it_splits '211973212345', ['211', '973', '212', '345'] end describe 'Sudan' do it_splits '249187171100', ['249', '18', '717', '1100'] end describe 'Thailand' do it_splits '6621231234', ['66', '2', '123', '1234'] # Bangkok it_splits '6636123123', ['66', '36', '123', '123'] # Lop Buri it_splits '66851234567', ['66', '851', '234', '567'] # Lop Buri it_splits '66921234567', ['66', '921', '234', '567'] # mobile end describe 'Tunesia' do it_splits '21611231234', ['216', '1', '123', '1234'] # Ariana it_splits '21621231234', ['216', '2', '123', '1234'] # Bizerte end describe 'Salvador (El)' do it_splits '50321121234', ['503', '2112', '1234'] # Fixed number it_splits '50361121234', ['503', '6112', '1234'] # Mobile number end describe 'Singapore' do it_splits '6561231234', ['65', false, '6123', '1234'] # Fixed line end describe 'Slovakia' do it_splits '421912123456', ['421', '912', '123456'] # Mobile it_splits '421212345678', ['421', '2', '12345678'] # Bratislava it_splits '421371234567', ['421', '37', '1234567'] # Nitra / Other end describe 'Slovenia' do it_splits '38651234567', ['386', '51', '234', '567'] # Mobile it_splits '38611234567', ['386', '1', '123', '4567'] # LJUBLJANA end describe 'Spain' do it_splits '34600123456', ['34', '600', '123', '456'] # Mobile it_splits '34900123456', ['34', '900', '123', '456'] # Special it_splits '34931234567', ['34', '93', '123', '45', '67'] # Landline large regions it_splits '34975123456', ['34', '975', '12', '34', '56'] # Landline it_splits '34123456789', ['34', '123', '456', '789'] # Default end describe 'Sri Lanka' do it_splits '94711231212', ['94', '71', '123', '12', '12'] # Mobile end describe 'Sweden' do it_splits '46812345678', ['46', '8', '123', '45', '678'] # Stockholm it_splits '46111234567', ['46', '11', '123', '45', '67'] it_splits '46721234567', ['46', '72', '123', '45', '67'] # mobile it_splits '46125123456', ['46', '125', '123', '456'] end describe 'Switzerland' do it_splits '41443643532', ['41', '44', '364', '35', '32'] # Zurich (usually) it_splits '41800334455', ['41', '800', '334', '455'] # Service number end describe 'Tanzania' do it_splits '255221231234', ['255', '22', '123', '1234'] # Dar Es Salaam it_splits '255651231234', ['255', '65', '123', '1234'] # TIGO it_splits '255861123123', ['255', '861', '123', '123'] # Special Rates end describe 'Turkey' do it_splits '903121234567', ['90', '312', '123', '4567'] # Ankara end describe 'Uganda' do it_splits '256414123456', ['256', '41', '4123456'] # Kampania it_splits '256464441234', ['256', '464', '441234'] # Mubende end describe 'The UK' do it_splits '442075671113', ['44', '20', '7567', '1113'] # [2+8] London it_splits '442920229901', ['44', '29', '2022', '9901'] # [2+8] Cardiff it_splits '441134770011', ['44', '113', '477', '0011'] # [3+7] Leeds it_splits '441412770022', ['44', '141', '277', '0022'] # [3+7] Glasgow it_splits '441204500532', ['44', '1204', '500532'] # [4+6] Bolton it_splits '44120462532', ['44', '1204', '62532'] # [4+5] Bolton it_splits '441333247700', ['44', '1333', '247700'] # [4+6] Leven (Fife) it_splits '441382229845', ['44', '1382', '229845'] # [4+6] Dundee it_splits '441420700378', ['44', '1420', '700378'] # [4+6] Alton it_splits '44142080378', ['44', '1420', '80378'] # [4+5] Alton it_splits '441475724688', ['44', '1475', '724688'] # [4+6] Greenock it_splits '441539248756', ['44', '1539', '248756'] # [4+6] Kendal (Mixed area) it_splits '441539648788', ['44', '15396', '48788'] # [5+5] Sedbergh (Mixed area) it_splits '441652757248', ['44', '1652', '757248'] # [4+6] Brigg it_splits '441664333456', ['44', '1664', '333456'] # [4+6] Melton Mowbray it_splits '441697222555', ['44', '1697', '222555'] # [4+6] Brampton (Mixed area) it_splits '441697388555', ['44', '16973', '88555'] # [5+5] Wigton (Mixed area) it_splits '441697433777', ['44', '16974', '33777'] # [5+5] Raughton Head (Mixed area) it_splits '44169772333', ['44', '16977', '2333'] # [5+4] Brampton (Mixed area) it_splits '441697744888', ['44', '16977', '44888'] # [5+5] Brampton (Mixed area) it_splits '441757850526', ['44', '1757', '850526'] # [4+6] Selby it_splits '441890234567', ['44', '1890', '234567'] # [4+6] Coldstream (ELNS area) it_splits '441890595378', ['44', '1890', '595378'] # [4+6] Ayton (ELNS area) it_splits '441931306526', ['44', '1931', '306526'] # [4+6] Shap it_splits '441946555777', ['44', '1946', '555777'] # [4+6] Whitehaven (Mixed area) it_splits '44194662888', ['44', '1946', '62888'] # [4+5] Whitehaven (Mixed area) it_splits '441946722444', ['44', '19467', '22444'] # [5+5] Gosforth (Mixed area) it_splits '441987705337', ['44', '1987', '705337'] # [4+6] Ebbsfleet it_splits '443005828323', ['44', '300', '582', '8323'] # Non-geographic (NTS) it_splits '443334253344', ['44', '333', '425', '3344'] # Non-geographic (NTS) it_splits '443437658834', ['44', '343', '765', '8834'] # Non-geographic (NTS) it_splits '443452273512', ['44', '345', '227', '3512'] # Non-geographic (NTS) it_splits '443707774444', ['44', '370', '777', '4444'] # Non-geographic (NTS) it_splits '443725247722', ['44', '372', '524', '7722'] # Non-geographic (NTS) it_splits '44500557788', ['44', '500', '557788'] # Freefone (500 + 6) it_splits '445575671113', ['44', '55', '7567', '1113'] # Corporate numbers it_splits '445644775533', ['44', '56', '4477', '5533'] # LIECS/VoIP it_splits '447020229901', ['44', '70', '2022', '9901'] # Personal numbers it_splits '447688554246', ['44', '76', '8855', '4246'] # Pager it_splits '447180605207', ['44', '7180', '605207'] # Mobile it_splits '447480605207', ['44', '7480', '605207'] # Mobile it_splits '447624605207', ['44', '7624', '605207'] # Mobile (Isle of Man) it_splits '447780605207', ['44', '7780', '605207'] # Mobile it_splits '447980605207', ['44', '7980', '605207'] # Mobile it_splits '44800557788', ['44', '800', '557788'] # Freefone (800 + 6) it_splits '448084682355', ['44', '808', '468', '2355'] # Freefone (808 + 7) it_splits '448005878323', ['44', '800', '587', '8323'] # Freefone (800 + 7), regression it_splits '448437777334', ['44', '843', '777', '7334'] # Non-geographic (NTS) it_splits '448457777334', ['44', '845', '777', '7334'] # Non-geographic (NTS) it_splits '448707777334', ['44', '870', '777', '7334'] # Non-geographic (NTS) it_splits '448727777334', ['44', '872', '777', '7334'] # Non-geographic (NTS) it_splits '449052463456', ['44', '905', '246', '3456'] # Non-geographic (PRS) it_splits '449122463456', ['44', '912', '246', '3456'] # Non-geographic (PRS) it_splits '449832463456', ['44', '983', '246', '3456'] # Non-geographic (SES) end describe 'US' do it_splits '15551115511', ['1', '555', '111', '5511'] end describe 'Venezuela' do it_splits '582121234567', ['58', '212', '1234567'] end describe 'Vietnam' do it_splits '8498123456', ['84', '98', '123456'] # Viettel Mobile it_splits '8499612345', ['84', '996', '12345'] # GTel it_splits '84412345678', ['84', '4', '1234', '5678'] # Hanoi end describe 'Zambia' do it_splits '260955123456', ['260', '955', '123456'] # mobile it_splits '260211123456', ['260', '211', '123456'] # fixed end describe 'New Zealand' do it_splits '6491234567', ['64', '9', '123', '4567'] end describe 'Bhutan (Kingdom of)' do it_splits '9759723642', %w(975 9 723 642) end describe 'Brunei Darussalam' do it_splits '6737932744', %w(673 7 932 744) end describe 'Burkina Faso' do it_splits '22667839323', ['226', false, '6783', '9323'] end describe 'Burundi' do it_splits '25712345678', ['257', false, '1234', '5678'] end describe 'Cameroon' do it_splits '23727659381', ['237', false, '2765', '9381'] end describe 'Cape Verde' do it_splits '2385494177', ['238', false, '549', '4177'] end describe 'Central African Republic' do it_splits '23612345678', ['236', false, '1234', '5678'] end describe 'Chad' do it_splits '23512345678', ['235', false, '1234', '5678'] end describe 'Comoros' do it_splits '2693901234', ['269', false, '3901', '234'] it_splits '2693401234', ['269', false, '3401', '234'] end describe 'Congo' do it_splits '242123456789', ['242', false, '1234', '56789'] end describe 'Cook Islands' do it_splits '68251475', ['682', false, '51', '475'] end describe 'Costa Rica' do it_splits '50622345678', %w(506 2 234 5678) end describe "Côte d'Ivoire" do it_splits '22507335518', ['225', '07', '33', '55', '18'] it_splits '22537335518', ['225', '37', '33', '55', '18'] end describe 'Democratic Republic of Timor-Leste' do it_splits '6701742945', ['670', false, '174', '2945'] end describe 'Democratic Republic of the Congo' do it_splits '24311995381', %w(243 1 199 5381) end describe 'Diego Garcia' do it_splits '2461234683', ['246', false, '123', '4683'] end describe 'Djibouti' do it_splits '25349828978', ['253', false, '4982', '8978'] end describe 'Ecuador' do it_splits '593445876756', %w(593 44 587 6756) end describe 'Eritrea' do it_splits '2916537192', %w(291 6 537 192) end describe 'Ethiopia' do it_splits '251721233486', %w(251 72 123 3486) end describe 'Falkland Islands (Malvinas)' do it_splits '50014963', ['500', false, '14', '963'] end describe 'Faroe Islands' do it_splits '298997986', ['298', false, '997', '986'] end describe 'Fiji (Republic of)' do it_splits '6798668123', ['679', false, '866', '8123'] end describe 'French Guiana (French Department of)' do it_splits '594594123456', %w(594 594 123 456) end describe "French Polynesia (Territoire français d'outre-mer)" do it_splits '68921988900', ['689', false, '21', '98', '89', '00'] end describe 'Gabonese Republic' do it_splits '2411834375', ['241', '1', '834', '375'] end describe 'Gambia' do it_splits '2206683355', ['220', false, '668', '3355'] end describe 'Greenland' do it_splits '299314185', ['299', '31', '4185'] it_splits '299691123', ['299', '691', '123'] end describe 'Guadeloupe (French Department of)' do it_splits '590590456789', %w(590 590 45 67 89) end describe 'Guatemala (Republic of)' do it_splits '50219123456789', ['502', '19', '123', '456', '789'] it_splits '50221234567', ['502', '2', '123', '4567'] end describe 'Guinea' do it_splits '22430311234', ['224', '3031', '12', '34'] it_splits '224662123456', ['224', '662', '12', '34', '56'] end describe 'Guinea-Bissau' do it_splits '2453837652', ['245', false, '383', '7652'] end describe 'Guyana' do it_splits '5922631234', %w(592 263 1234) end describe 'Honduras (Republic of)' do it_splits '50412961637', %w(504 12 961 637) end describe 'Iraq' do it_splits '96411234567', %w(964 1 123 4567) it_splits '96421113456', %w(964 21 113 456) it_splits '9647112345678', %w(964 71 1234 5678) end describe 'Jordan (Hashemite Kingdom of)' do it_splits '96280012345', %w(962 800 123 45) it_splits '96226201234', %w(962 2 620 1234) it_splits '962712345678', %w(962 7 1234 5678) it_splits '962746612345', %w(962 7 4661 2345) it_splits '96290012345', %w(962 900 123 45) it_splits '96285123456', %w(962 85 123 456) it_splits '96270123456', %w(962 70 123 456) it_splits '96262501456', %w(962 6250 1456) it_splits '96287901456', %w(962 8790 1456) end describe 'Kiribati (Republic of)' do it_splits '68634814', ['686', false, '34', '814'] end describe "Democratic People's Republic of Korea" do it_splits '850212345', %w(850 2 123 45) it_splits '8502123456789', %w(850 2 123 456 789) it_splits '85023812356', %w(850 2 381 2356) #it_splits '85028801123456781256', %w(850 2 8801 1234 5678 1256) it_splits '8501911234567', %w(850 191 123 4567) end describe 'Kuwait (State of)' do it_splits '96523456789', ['965', false, '2345', '6789'] it_splits '9651812345', ['965', false, '181', '2345'] end describe "Lao People's Democratic Republic" do it_splits '85697831195', %w(856 97 831 195) end describe 'Latvia' do it_splits '37180123456', %w(371 801 234 56) it_splits '37163723456', %w(371 637 234 56) it_splits '37129412345', %w(371 294 123 45) end describe 'Lebanon' do it_splits '9611123456', %w(961 1 123 456) it_splits '9614123456', %w(961 4 123 456) it_splits '9613123456', %w(961 3 123 456) it_splits '96170123456', %w(961 70 123 456) it_splits '96190123456', %w(961 90 123 456) it_splits '96181123456', %w(961 81 123 456) end describe 'Lesotho' do it_splits '26623592495', ['266', false, '2359', '2495'] end describe 'Liberia' do it_splits '23121234567', ['231', false, '2123', '4567'] it_splits '2314123456', ['231', false, '4123', '456'] it_splits '231771234567', ['231', false, '77', '123', '4567'] end describe 'Libya' do it_splits '21820512345', %w(218 205 123 45) it_splits '21822123456', %w(218 22 123 456) it_splits '218211234456', %w(218 21 1234 456) it_splits '218911234456', %w(218 91 1234 456) end describe 'Madagascar' do it_splits '26120012345678', ['261', false, '20', '012', '345', '678'] it_splits '261201243456', ['261', false, *%w(20 124 3456)] it_splits '261512345678', ['261', false, *%w(512 345 678)] end describe 'Malawi' do it_splits '2651725123', ['265', false, '1725', '123'] it_splits '265213456789',[ '265', false, '213', '456', '789'] it_splits '2659123456', ['265', false, '9123', '456'] it_splits '265991123456', ['265', false, '991', '123', '456'] end describe 'Maldives (Republic of)' do it_splits '9606568279', ['960', '656', '8279'] end describe 'Mali' do it_splits '22379249349', ['223', false, '7924', '9349'] end describe 'Marshall Islands (Republic of the)' do it_splits '6924226536', ['692', false, '422', '6536'] end describe 'Martinique (French Department of)' do it_splits '596596123456', %w(596 596 12 34 56) end describe 'Mauritania' do it_splits '22212345678', ['222', false, '1234', '5678'] end describe 'Mauritius' do it_splits '2309518919', ['230', false, '951', '8919'] end describe 'Micronesia (Federated States of)' do it_splits '6911991754', ['691', false, '199', '1754'] end describe 'Moldova' do it_splits '37380012345', %w(373 800 123 45) it_splits '37322123345', %w(373 22 123 345) it_splits '37324112345', %w(373 241 123 45) it_splits '37360512345', %w(373 605 123 45) it_splits '37380312345', %w(373 803 123 45) end describe 'Mongolia' do it_splits '9761112345', %w(976 11 123 45) it_splits '9761211234', %w(976 121 12 34) it_splits '97612112345', %w(976 121 12 345) it_splits '97670123456', %w(976 70 123 456) it_splits '97675123456', %w(976 75 123 456) it_splits '97688123456', %w(976 88 123 456) it_splits '97650123456', %w(976 50 123 456) end describe 'Mozambique' do it_splits '258600123456', %w(258 600 123 456) it_splits '25825112345', %w(258 251 123 45) it_splits '258821234456', %w(258 82 1234 456) it_splits '258712344567', %w(258 7 1234 4567) end describe 'Namibia' do it_splits '264675161324', %w(264 6751 613 24) it_splits '26467175890', %w(264 67 175 890) it_splits '26463088612345', %w(264 63 088 612 345) it_splits '264851234567', %w(264 85 1234 567) end describe 'Nauru (Republic of)' do it_splits '6741288739', ['674', false, '128', '8739'] end describe 'Nepal' do it_splits '97714345678', %w(977 1 434 5678) it_splits '97710123456', %w(977 10 123 456) it_splits '9779812345678', %w(977 98 1234 5678) end describe "New Caledonia (Territoire français d'outre-mer)" do it_splits '687747184', ['687', false, '747', '184'] end describe 'Nicaragua' do it_splits '50512345678', ['505', '12', '345', '678'] end describe 'Niger' do it_splits '22712345678', ['227', false, '1234', '5678'] end describe 'Nigeria' do it_splits '23411231234', %w(234 1 123 1234) # Lagos # mobile numbers it_splits '2347007661234', %w(234 700 766 1234) it_splits '2347017661234', %w(234 701 766 1234) it_splits '2347027661234', %w(234 702 766 1234) it_splits '2347037661234', %w(234 703 766 1234) it_splits '2347047661234', %w(234 704 766 1234) it_splits '2347057661234', %w(234 705 766 1234) it_splits '2347067661234', %w(234 706 766 1234) it_splits '2347077661234', %w(234 707 766 1234) it_splits '2347087661234', %w(234 708 766 1234) it_splits '2347097661234', %w(234 709 766 1234) it_splits '2348007661234', %w(234 800 766 1234) it_splits '2348017661234', %w(234 801 766 1234) it_splits '2348027661234', %w(234 802 766 1234) it_splits '2348037661234', %w(234 803 766 1234) it_splits '2348047661234', %w(234 804 766 1234) it_splits '2348057661234', %w(234 805 766 1234) it_splits '2348067661234', %w(234 806 766 1234) it_splits '2348077661234', %w(234 807 766 1234) it_splits '2348087661234', %w(234 808 766 1234) it_splits '2348097661234', %w(234 809 766 1234) it_splits '2349007661234', %w(234 900 766 1234) it_splits '2349017661234', %w(234 901 766 1234) it_splits '2349027661234', %w(234 902 766 1234) it_splits '2349037661234', %w(234 903 766 1234) it_splits '2349047661234', %w(234 904 766 1234) it_splits '2349057661234', %w(234 905 766 1234) it_splits '2349067661234', %w(234 906 766 1234) it_splits '2349077661234', %w(234 907 766 1234) it_splits '2349087661234', %w(234 908 766 1234) it_splits '2349097661234', %w(234 909 766 1234) it_splits '2348107661234', %w(234 810 766 1234) it_splits '2348117661234', %w(234 811 766 1234) it_splits '2348127661234', %w(234 812 766 1234) it_splits '2348137661234', %w(234 813 766 1234) it_splits '2348147661234', %w(234 814 766 1234) it_splits '2348157661234', %w(234 815 766 1234) it_splits '2348167661234', %w(234 816 766 1234) it_splits '2348177661234', %w(234 817 766 1234) it_splits '2348187661234', %w(234 818 766 1234) it_splits '2348197661234', %w(234 819 766 1234) end describe 'Niue' do it_splits '6833651', ['683', false, '3651'] end describe 'Palau (Republic of)' do it_splits '6804873653', ['680', false, '487', '3653'] end describe 'Panama (Republic of)' do it_splits '5078001234', %w(507 800 1234) it_splits '50761234567', %w(507 6 123 4567) it_splits '5072123456', %w(507 2 123 456) end describe 'Papua New Guinea' do it_splits '6753123567', %w(675 3 123 567) it_splits '6751801234', %w(675 180 1234) it_splits '67580123456', %w(675 80 123 456) it_splits '67591123456', %w(675 91 123 456) it_splits '6751612345', %w(675 16 123 45) it_splits '67518412345678', %w(675 184 1234 5678) it_splits '67517012', %w(675 170 12) it_splits '6751891', %w(675 189 1) it_splits '6752701234', %w(675 270 1234) it_splits '6752751234', %w(675 275 1234) it_splits '67527912', %w(675 279 12) it_splits '67511512345678', %w(675 115 1234 5678) end describe 'Reunion / Mayotte (new)' do it_splits '262594399265', ['262', '594', '39', '92', '65'] end describe 'Saint Helena' do it_splits '2903614', ['290', false, '3614'] end describe 'Saint Pierre and Miquelon (Collectivité territoriale de la République française)' do it_splits '508418826', ['508', false, '418', '826'] end describe 'Samoa (Independent State of)' do it_splits '685800123', ['685', false, '800', '123'] it_splits '68561123', ['685', false, '61', '123'] it_splits '6857212345', ['685', false, '721', '2345'] it_splits '685830123', ['685', false, '830', '123'] it_splits '685601234', ['685', false, '601', '234'] it_splits '6858412345', ['685', false, '841', '2345'] end describe 'San Marino' do it_splits '378800123', ['378', false, '800', '123'] it_splits '3788001234567', ['378', false, '800', '123', '4567'] it_splits '378012345', ['378', false, '012', '345'] it_splits '3780123456789', ['378', false, '012', '345', '6789'] it_splits '378512345', ['378', false, '512', '345'] it_splits '3785123456789', ['378', false, '512', '345', '6789'] end describe 'Saudi Arabia (Kingdom of)' do it_splits '9660208528423', %w(966 020 852 8423) it_splits '966506306201', %w(966 50 630 6201) end describe 'Senegal' do it_splits '221123456789', ['221', false, '1234', '56789'] end describe 'Serbia' do it_splits '38180012345', %w(381 800 123 45) it_splits '3811012345', %w(381 10 123 45) it_splits '38110123456', %w(381 10 123 456) it_splits '38111123456', %w(381 11 123 456) it_splits '381111234567', %w(381 11 123 4567) it_splits '381721234567', %w(381 72 123 4567) it_splits '38160123', %w(381 60 123) it_splits '381601234567', %w(381 60 123 4567) it_splits '38142123456', %w(381 42 123 456) it_splits '38191234567', %w(381 9 123 4567) it_splits '38160123', %w(381 60 123) it_splits '381601234567890', %w(381 60 123 456 7890) it_splits '38170123456', %w(381 70 123 456) end describe 'Sierra Leone' do it_splits '23264629769', %w(232 64 629 769) end describe 'Solomon Islands' do it_splits '67754692', ['677', false, '54', '692'] it_splits '6777546921', ['677', false, '7546', '921'] end describe 'Somali Democratic Republic' do it_splits '252103412345', %w(252 1034 123 45) it_splits '2521313123', %w(252 1313 123) it_splits '2521601234', %w(252 160 12 34) it_splits '25250012345', %w(252 500 123 45) it_splits '252671234567', %w(252 67 1234 567) end describe 'Suriname (Republic of)' do it_splits '597958434', ['597', false, '958', '434'] it_splits '597212345', ['597', false, '212', '345'] it_splits '5976123456', ['597', false, '612', '3456'] end describe 'Swaziland' do it_splits '26822071234', ['268', false, '2207', '1234'] it_splits '2685501234', ['268', false, '550', '1234'] end describe 'Syrian Arab Republic' do it_splits '963111234567', %w(963 11 123 4567) it_splits '963311234567', %w(963 31 123 4567) it_splits '96315731234', %w(963 15 731 234) it_splits '963912345678', %w(963 9 1234 5678) end describe 'Taiwan' do it_splits '88618123456', %w(886 18 123 456) it_splits '8866121234567', %w(886 612 123 4567) it_splits '886212345678', %w(886 2 1234 5678) it_splits '88631234567', %w(886 3 123 4567) it_splits '88633123456', %w(886 33 123 456) it_splits '88682712345', %w(886 827 123 45) it_splits '8864121234', %w(886 412 1234) it_splits '88690123456', %w(886 90 123 456) it_splits '886901234567', %w(886 90 123 4567) it_splits '88694991345', %w(886 94 991 345) end describe 'Togolese Republic' do it_splits '22812345678', ['228', false, '1234', '5678'] end describe 'Tajikistan' do it_splits '992313012345', %w(992 3130 123 45) it_splits '992331700123', %w(992 331700 123) it_splits '992372123345', %w(992 372 123 345) it_splits '992505123456', %w(992 505 123 456) it_splits '992973123456', %w(992 973 123 456) it_splits '992474456123', %w(992 474 456 123) end describe 'Tokelau' do it_splits '6901371', %w(690 1 371) end describe 'Tonga (Kingdom of)' do it_splits '67620123', ['676', false, '20', '123'] it_splits '67684123', ['676', false, '84', '123'] it_splits '6767712345', ['676', false, '77', '123', '45'] it_splits '6768912345', ['676', false, '89', '123', '45'] end describe 'Tuvalu' do it_splits '68893741', ['688', false, '93741'] end describe 'Turkmenistan' do it_splits '99312456789', %w(993 12 456 789) it_splits '99313145678', %w(993 131 456 78) it_splits '99313924567', %w(993 1392 4567) it_splits '99361234567', %w(993 6 123 4567) end describe 'Ukraine' do it_splits '380800123456', %w(380 800 123 456) it_splits '380312123456', %w(380 312 123 456) it_splits '380320123456', %w(380 32 0123 456) it_splits '380325912345', %w(380 3259 123 45) it_splits '380326061234', %w(380 32606 1234) it_splits '380391234567', %w(380 39 123 45 67) it_splits '380501234567', %w(380 50 123 45 67) it_splits '380631234567', %w(380 63 123 45 67) it_splits '380661234567', %w(380 66 123 45 67) it_splits '380671234567', %w(380 67 123 45 67) it_splits '380681234567', %w(380 68 123 45 67) it_splits '380911234567', %w(380 91 123 45 67) it_splits '380921234567', %w(380 92 123 45 67) it_splits '380931234567', %w(380 93 123 45 67) it_splits '380941234567', %w(380 94 123 45 67) it_splits '380951234567', %w(380 95 123 45 67) it_splits '380961234567', %w(380 96 123 45 67) it_splits '380971234567', %w(380 97 123 45 67) it_splits '380981234567', %w(380 98 123 45 67) it_splits '380991234567', %w(380 99 123 45 67) end describe 'United Arab Emirates' do it_splits '97180012', %w(971 800 12) it_splits '971800123456789', %w(971 800 12 345 6789) it_splits '97121234567', %w(971 2 123 4567) it_splits '971506412345', %w(971 50 641 2345) it_splits '971600641234', %w(971 600 641 234) it_splits '971500641234', %w(971 500 641 234) it_splits '971200641234', %w(971 200 641 234) end describe 'Uruguay (Eastern Republic of)' do it_splits '59880012345', %w(598 800 123 45) it_splits '59820123456', %w(598 2 012 3456) it_splits '59821123456', %w(598 21 123 456) it_splits '59890912345', %w(598 909 123 45) it_splits '59893123456', %w(598 93 123 456) it_splits '59890812345', %w(598 908 123 45) it_splits '59880512345', %w(598 805 123 45) end describe 'Uzbekistan (Republic of)' do it_splits '998433527869', %w(998 43 352 7869) end describe 'Vanuatu (Republic of)' do it_splits '67889683', ['678', false, '89', '683'] end describe 'Yemen' do it_splits '9671234567', %w(967 1 234 567) it_splits '96712345678', %w(967 1 234 5678) it_splits '9677234567', %w(967 7 234 567) it_splits '967771234567', %w(967 77 123 4567) it_splits '967581234', %w(967 58 1234) end describe 'Zimbabwe' do it_splits '2632582123456', %w(263 2582 123 456) it_splits '2632582123', %w(263 2582 123) it_splits '263147123456', %w(263 147 123 456) it_splits '263147123', %w(263 147 123) it_splits '263270123456', %w(263 270 123 456) it_splits '26327012345', %w(263 270 123 45) it_splits '2638612354567', %w(263 86 1235 4567) # mobile numbers (see http://www.itu.int/dms_pub/itu-t/oth/02/02/T02020000E90002PDFE.pdf, Table 4, Page 25) %w(71 73 77 78).each do |prefix| number = "263#{prefix}2345678" it_splits number, ['263', prefix, '234', '5678'] end end end end
tpena/phony
spec/lib/phony/countries_spec.rb
Ruby
mit
56,003
var http = require("http"); var url = require("url"); var server; // Diese Funktion reagiert auf HTTP Requests, // hier wird also die Web Anwendung implementiert! var simpleHTTPResponder = function(req, res) { // Routing bedeutet, anhand der URL Adresse // unterschiedliche Funktionen zu steuern. // Dazu wird zunächst die URL Adresse benötigt var url_parts = url.parse(req.url, true); // Nun erfolgt die Fallunterscheidung, // hier anhand des URL Pfads if (url_parts.pathname == "/greetme") { // HTTP Header müssen gesetzt werden res.writeHead(200, { "Content-Type": "text/html" }); // Auch URL Query Parameter können abgefragt werden var query = url_parts.query; var name = "Anonymous"; if (query["name"] != undefined) { name = query["name"]; } // HTML im Script zu erzeugen ist mühselig... res.end("<html><head><title>Greetme</title></head><body><H1>Greetings " + name + "!</H1></body></html>"); // nun folgt der zweite Fall... } else { res.writeHead(404, { "Content-Type": "text/html" }); res.end( "<html><head><title>Error</title></head><body><H1>Only /greetme is implemented.</H1></body></html>" ); } } // Webserver erzeugen, an Endpunkt binden und starten server = http.createServer(simpleHTTPResponder); var port = process.argv[2]; server.listen(port);
MaximilianKucher/vs1Lab
Beispiele/nodejs_webserver/web.js
JavaScript
mit
1,328
package engine.menu.managers; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Image; import java.util.List; import engine.dialogue.InteractionBox; import engine.gridobject.person.Player; import engine.images.ScaledImage; import engine.item.Weapon; import engine.menu.MenuInteractionMatrix; import engine.menu.nodes.WeaponInfoNode; public class WeaponManager extends MenuManager implements InteractionBox { private Player myPlayer; private MenuInteractionMatrix myMIM; private MenuManager myMenuManager; public WeaponManager(Player p, MenuManager mm, MenuInteractionMatrix mim) { super(p, null, mim); myPlayer = p; myMIM = mim; myMenuManager = mm; } @Override public void paintDisplay(Graphics2D g2d, int xSize, int ySize, int width, int height) { paintMenu(g2d, height, width); paintFeatureBox(g2d, "ImageFiles/PokemonBox.png", 17, 20, 300, 200); paintWeaponData(g2d); drawSelector(g2d, 198, 40, 280, 45, 44, myMIM); } @Override public void getNextText() { // TODO Auto-generated method stub } protected void paintFeatureBox(Graphics g2d, String imgPath, int x, int y, int width, int height) { Image img = new ScaledImage(width, height, imgPath).scaleImage(); g2d.drawImage(img, x, y, null); } protected void paintFeatureImage(Graphics g2d, Image feature, int x, int y) { g2d.drawImage(feature, x, y, null); } protected void paintFeatureName(Graphics g2d, String name, int x, int y) { g2d.drawString(name, x, y); } private void paintWeaponData(Graphics g2d) { List<Weapon> features = myPlayer.getWeaponList(); int emptySpace = 0; for (int i = 0; i < features.size(); i++) { if (i != 0) { emptySpace = 1; } else { emptySpace = 0; } Image scaledWeaponImage = features.get(i).getImage() .getScaledInstance(35, 35, Image.SCALE_SMOOTH); paintFeatureImage(g2d, scaledWeaponImage, 37, 45 + i * 40 + 5 * emptySpace); paintFeatureName(g2d, features.get(i).toString(), 80, 67 + i * 40 + 5 * emptySpace); } } public void createWeaponInfoNodes() { for (int i = 0; i < myPlayer.getWeaponList().size(); i++) { myMIM.setNode(new WeaponInfoNode(myPlayer, this, myMenuManager, i), 0, i); } } }
yomikaze/OOGASalad
src/engine/menu/managers/WeaponManager.java
Java
mit
2,233
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Composition; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Highlighting; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.KeywordHighlighting.KeywordHighlighters { [ExportHighlighter(LanguageNames.CSharp), Shared] internal class UsingStatementHighlighter : AbstractKeywordHighlighter<UsingStatementSyntax> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public UsingStatementHighlighter() { } protected override void AddHighlights(UsingStatementSyntax usingStatement, List<TextSpan> highlights, CancellationToken cancellationToken) => highlights.Add(usingStatement.UsingKeyword.Span); } }
mavasani/roslyn
src/Features/CSharp/Portable/Highlighting/KeywordHighlighters/UsingStatementHighlighter.cs
C#
mit
1,116
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.SolutionCrawler; using Microsoft.VisualStudio.IntegrationTest.Utilities.InProcess; using Microsoft.VisualStudio.LanguageServices.Telemetry; namespace Microsoft.VisualStudio.IntegrationTest.Utilities.OutOfProcess { public class VisualStudioWorkspace_OutOfProc : OutOfProcComponent { private readonly VisualStudioWorkspace_InProc _inProc; internal VisualStudioWorkspace_OutOfProc(VisualStudioInstance visualStudioInstance) : base(visualStudioInstance) { _inProc = CreateInProcComponent<VisualStudioWorkspace_InProc>(visualStudioInstance); } public void SetOptionInfer(string projectName, bool value) { _inProc.SetOptionInfer(projectName, value); WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Workspace); } public bool IsPrettyListingOn(string languageName) => _inProc.IsPrettyListingOn(languageName); public void SetPrettyListing(string languageName, bool value) => _inProc.SetPrettyListing(languageName, value); public void SetPerLanguageOption(string optionName, string feature, string language, object value) => _inProc.SetPerLanguageOption(optionName, feature, language, value); public void SetOption(string optionName, string feature, object value) => _inProc.SetOption(optionName, feature, value); public void WaitForAsyncOperations(TimeSpan timeout, string featuresToWaitFor, bool waitForWorkspaceFirst = true) => _inProc.WaitForAsyncOperations(timeout, featuresToWaitFor, waitForWorkspaceFirst); public void WaitForAllAsyncOperations(TimeSpan timeout, params string[] featureNames) => _inProc.WaitForAllAsyncOperations(timeout, featureNames); public void WaitForAllAsyncOperationsOrFail(TimeSpan timeout, params string[] featureNames) => _inProc.WaitForAllAsyncOperationsOrFail(timeout, featureNames); public void CleanUpWorkspace() => _inProc.CleanUpWorkspace(); public void ResetOptions() => _inProc.ResetOptions(); public void CleanUpWaitingService() => _inProc.CleanUpWaitingService(); public void SetImportCompletionOption(bool value) { SetGlobalOption(WellKnownGlobalOption.CompletionOptions_ShowItemsFromUnimportedNamespaces, LanguageNames.CSharp, value); SetGlobalOption(WellKnownGlobalOption.CompletionOptions_ShowItemsFromUnimportedNamespaces, LanguageNames.VisualBasic, value); } public void SetEnableDecompilationOption(bool value) { SetOption("NavigateToDecompiledSources", "FeatureOnOffOptions", value); } public void SetArgumentCompletionSnippetsOption(bool value) { SetGlobalOption(WellKnownGlobalOption.CompletionViewOptions_EnableArgumentCompletionSnippets, LanguageNames.CSharp, value); SetGlobalOption(WellKnownGlobalOption.CompletionViewOptions_EnableArgumentCompletionSnippets, LanguageNames.VisualBasic, value); } public void SetTriggerCompletionInArgumentLists(bool value) => SetGlobalOption(WellKnownGlobalOption.CompletionOptions_TriggerInArgumentLists, LanguageNames.CSharp, value); public void SetFullSolutionAnalysis(bool value) { SetPerLanguageOption( optionName: SolutionCrawlerOptions.BackgroundAnalysisScopeOption.Name, feature: SolutionCrawlerOptions.BackgroundAnalysisScopeOption.Feature, language: LanguageNames.CSharp, value: value ? BackgroundAnalysisScope.FullSolution : BackgroundAnalysisScope.Default); SetPerLanguageOption( optionName: SolutionCrawlerOptions.BackgroundAnalysisScopeOption.Name, feature: SolutionCrawlerOptions.BackgroundAnalysisScopeOption.Feature, language: LanguageNames.VisualBasic, value: value ? BackgroundAnalysisScope.FullSolution : BackgroundAnalysisScope.Default); } public void SetFileScopedNamespaces(bool value) => _inProc.SetFileScopedNamespaces(value); public void SetEnableOpeningSourceGeneratedFilesInWorkspaceExperiment(bool value) { SetGlobalOption( WellKnownGlobalOption.VisualStudioSyntaxTreeConfigurationService_EnableOpeningSourceGeneratedFilesInWorkspace, language: null, value); } public void SetFeatureOption(string feature, string optionName, string? language, string? valueString) => _inProc.SetFeatureOption(feature, optionName, language, valueString); public void SetGlobalOption(WellKnownGlobalOption option, string? language, object? value) => _inProc.SetGlobalOption(option, language, value); } }
CyrusNajmabadi/roslyn
src/VisualStudio/IntegrationTest/TestUtilities/OutOfProcess/VisualStudioWorkspace_OutOfProc.cs
C#
mit
5,369
<?php namespace SMW\Tests\SPARQLStore; use SMW\SPARQLStore\RedirectLookup; use SMW\InMemoryPoolCache; use SMW\DIWikiPage; use SMW\DIProperty; use SMW\Exporter\Escaper; use SMWExpNsResource as ExpNsResource; use SMWExpLiteral as ExpLiteral; use SMWExpResource as ExpResource; use SMWExporter as Exporter; /** * @covers \SMW\SPARQLStore\RedirectLookup * @group semantic-mediawiki * * @license GNU GPL v2+ * @since 2.0 * * @author mwjames */ class RedirectLookupTest extends \PHPUnit_Framework_TestCase { public function testCanConstruct() { $repositoryConnection = $this->getMockBuilder( '\SMW\SPARQLStore\RepositoryConnection' ) ->disableOriginalConstructor() ->getMock(); $this->assertInstanceOf( '\SMW\SPARQLStore\RedirectLookup', new RedirectLookup( $repositoryConnection ) ); } public function testRedirectTragetForBlankNode() { $repositoryConnection = $this->getMockBuilder( '\SMW\SPARQLStore\RepositoryConnection' ) ->disableOriginalConstructor() ->getMock(); $instance = new RedirectLookup( $repositoryConnection ); $expNsResource = new ExpNsResource( '', '', '', null ); $exists = null; $this->assertSame( $expNsResource, $instance->findRedirectTargetResource( $expNsResource, $exists ) ); $this->assertFalse( $exists ); } public function testRedirectTragetForDataItemWithSubobject() { $repositoryConnection = $this->getMockBuilder( '\SMW\SPARQLStore\RepositoryConnection' ) ->disableOriginalConstructor() ->getMock(); $instance = new RedirectLookup( $repositoryConnection ); $dataItem = new DIWikiPage( 'Foo', 1, '', 'beingASubobject' ); $expNsResource = new ExpNsResource( 'Foo', 'Bar', '', $dataItem ); $exists = null; $this->assertSame( $expNsResource, $instance->findRedirectTargetResource( $expNsResource, $exists ) ); $this->assertTrue( $exists ); } public function testRedirectTragetForDBLookupWithNoEntry() { $repositoryConnection = $this->createRepositoryConnectionMockToUse( false ); $instance = new RedirectLookup( $repositoryConnection ); $dataItem = new DIWikiPage( 'Foo', 1, '', '' ); $expNsResource = new ExpNsResource( 'Foo', 'Bar', '', $dataItem ); $exists = null; $this->assertSame( $expNsResource, $instance->findRedirectTargetResource( $expNsResource, $exists ) ); $this->assertFalse( $exists ); } public function testRedirectTragetForDBLookupWithSingleEntry() { $expLiteral = new ExpLiteral( 'Redirect' ); $repositoryConnection = $this->createRepositoryConnectionMockToUse( array( $expLiteral ) ); $instance = new RedirectLookup( $repositoryConnection ); $instance->reset(); $dataItem = new DIWikiPage( 'Foo', 1, '', '' ); $expNsResource = new ExpNsResource( 'Foo', 'Bar', '', $dataItem ); $exists = null; $this->assertSame( $expNsResource, $instance->findRedirectTargetResource( $expNsResource, $exists ) ); $this->assertTrue( $exists ); } public function testRedirectTragetForDBLookupWithMultipleEntries() { $expLiteral = new ExpLiteral( 'Redirect' ); $repositoryConnection = $this->createRepositoryConnectionMockToUse( array( $expLiteral, null ) ); $instance = new RedirectLookup( $repositoryConnection ); $instance->reset(); $dataItem = new DIWikiPage( 'Foo', 1, '', '' ); $expNsResource = new ExpNsResource( 'Foo', 'Bar', '', $dataItem ); $exists = null; $this->assertSame( $expNsResource, $instance->findRedirectTargetResource( $expNsResource, $exists ) ); $this->assertTrue( $exists ); } public function testRedirectTragetForDBLookupWithMultipleEntriesForcesNewResource() { $propertyPage = new DIWikiPage( 'Foo', SMW_NS_PROPERTY ); $resource = new ExpNsResource( 'Foo', Exporter::getInstance()->getNamespaceUri( 'property' ), 'property', $propertyPage ); $repositoryConnection = $this->createRepositoryConnectionMockToUse( array( $resource, $resource ) ); $instance = new RedirectLookup( $repositoryConnection ); $instance->reset(); $dataItem = new DIWikiPage( 'Foo', 1, '', '' ); $expNsResource = new ExpNsResource( 'Foo', 'Bar', '', $dataItem ); $exists = null; $targetResource = $instance->findRedirectTargetResource( $expNsResource, $exists ); $this->assertNotSame( $expNsResource, $targetResource ); $expectedResource = new ExpNsResource( Escaper::encodePage( $propertyPage ), Exporter::getInstance()->getNamespaceUri( 'wiki' ), 'wiki' ); $this->assertEquals( $expectedResource, $targetResource ); $this->assertTrue( $exists ); } public function testRedirectTragetForDBLookupWithForNonMultipleResourceEntryThrowsException() { $expLiteral = new ExpLiteral( 'Redirect' ); $repositoryConnection = $this->createRepositoryConnectionMockToUse( array( $expLiteral, $expLiteral ) ); $instance = new RedirectLookup( $repositoryConnection ); $instance->reset(); $dataItem = new DIWikiPage( 'Foo', 1, '', '' ); $expNsResource = new ExpNsResource( 'Foo', 'Bar', '', $dataItem ); $exists = null; $this->setExpectedException( 'RuntimeException' ); $instance->findRedirectTargetResource( $expNsResource, $exists ); } public function testRedirectTargetForCachedLookup() { $dataItem = new DIWikiPage( 'Foo', NS_MAIN ); $expNsResource = new ExpNsResource( 'Foo', 'Bar', '', $dataItem ); $poolCache = InMemoryPoolCache::getInstance()->getPoolCacheFor( 'sparql.store.redirectlookup' ); $poolCache->save( $expNsResource->getUri(), $expNsResource ); $repositoryConnection = $this->getMockBuilder( '\SMW\SPARQLStore\RepositoryConnection' ) ->disableOriginalConstructor() ->getMock(); $instance = new RedirectLookup( $repositoryConnection ); $exists = null; $instance->findRedirectTargetResource( $expNsResource, $exists ); $this->assertTrue( $exists ); $instance->reset(); } /** * @dataProvider nonRedirectableResourceProvider */ public function testRedirectTargetForNonRedirectableResource( $expNsResource ) { $repositoryConnection = $this->getMockBuilder( '\SMW\SPARQLStore\RepositoryConnection' ) ->disableOriginalConstructor() ->getMock(); $instance = new RedirectLookup( $repositoryConnection ); $instance->reset(); $exists = null; $instance->findRedirectTargetResource( $expNsResource, $exists ); $instance->reset(); $this->assertFalse( $exists ); } private function createRepositoryConnectionMockToUse( $listReturnValue ) { $repositoryResult = $this->getMockBuilder( '\SMW\SPARQLStore\QueryEngine\RepositoryResult' ) ->disableOriginalConstructor() ->getMock(); $repositoryResult->expects( $this->once() ) ->method( 'current' ) ->will( $this->returnValue( $listReturnValue ) ); $repositoryConnection = $this->getMockBuilder( '\SMW\SPARQLStore\RepositoryConnection' ) ->disableOriginalConstructor() ->getMock(); $repositoryConnection->expects( $this->once() ) ->method( 'select' ) ->will( $this->returnValue( $repositoryResult ) ); return $repositoryConnection; } public function nonRedirectableResourceProvider() { $provider[] = array( Exporter::getInstance()->getSpecialPropertyResource( '_INST' ) ); $provider[] = array( Exporter::getInstance()->getSpecialPropertyResource( '_SUBC' ) ); $provider[] = array( Exporter::getInstance()->getSpecialPropertyResource( '_REDI' ) ); $provider[] = array( Exporter::getInstance()->getSpecialPropertyResource( '_MDAT' ) ); $provider[] = array( Exporter::getInstance()->getSpecialPropertyResource( '_MDAT', true ) ); return $provider; } }
stuartbman/mediawiki-vagrant
mediawiki/extensions/SemanticMediaWiki/tests/phpunit/Unit/SPARQLStore/RedirectLookupTest.php
PHP
mit
7,584
<?php /* * This file is part of the Sismo utility. * * (c) Fabien Potencier <fabien@symfony.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ use Sismo\Sismo; use Sismo\BuildException; use Symfony\Component\Console\Application; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Process\ProcessBuilder; $console = new Application('Sismo', Sismo::VERSION); $console ->register('output') ->setDefinition(array( new InputArgument('slug', InputArgument::REQUIRED, 'Project slug'), )) ->setDescription('Displays the latest output for a project') ->setHelp(<<<EOF The <info>%command.name%</info> command displays the latest output for a project: <info>php %command.full_name% twig</info> EOF ) ->setCode(function (InputInterface $input, OutputInterface $output) use ($app) { $sismo = $app['sismo']; $slug = $input->getArgument('slug'); if (!$sismo->hasProject($slug)) { $output->writeln(sprintf('<error>Project "%s" does not exist.</error>', $slug)); return 1; } $project = $sismo->getProject($slug); if (!$project->getLatestCommit()) { $output->writeln(sprintf('<error>Project "%s" has never been built yet.</error>', $slug)); return 2; } $output->write($project->getLatestCommit()->getOutput()); $now = new \DateTime(); $diff = $now->diff($project->getLatestCommit()->getBuildDate()); if ($m = $diff->format('%i')) { $time = $m.' minutes'; } else { $time = $diff->format('%s').' seconds'; } $output->writeln(''); $output->writeln(sprintf('<info>This output was generated by Sismo %s ago</info>', $time)); }) ; $console ->register('projects') ->setDescription('List available projects') ->setHelp(<<<EOF The <info>%command.name%</info> command displays the available projects Sismo can build. EOF ) ->setCode(function (InputInterface $input, OutputInterface $output) use ($app) { $sismo = $app['sismo']; $projects = array(); $width = 0; foreach ($sismo->getProjects() as $slug => $project) { $projects[$slug] = $project->getName(); $width = strlen($project->getName()) > $width ? strlen($project->getName()) : $width; } $width += 2; $output->writeln(''); $output->writeln('<comment>Available projects:</comment>'); foreach ($projects as $slug => $project) { $output->writeln(sprintf(" <info>%-${width}s</info> %s", $slug, $project)); } $output->writeln(''); }) ; $console ->register('build') ->setDefinition(array( new InputArgument('slug', InputArgument::OPTIONAL, 'Project slug'), new InputArgument('sha', InputArgument::OPTIONAL, 'Commit sha'), new InputOption('force', '', InputOption::VALUE_NONE, 'Force the build'), new InputOption('local', '', InputOption::VALUE_NONE, 'Disable remote sync'), new InputOption('silent', '', InputOption::VALUE_NONE, 'Disable notifications'), new InputOption('timeout', '', InputOption::VALUE_REQUIRED, 'Time limit'), new InputOption('data-path', '', InputOption::VALUE_REQUIRED, 'The data path'), new InputOption('config-file', '', InputOption::VALUE_REQUIRED, 'The config file'), )) ->setDescription('Build projects') ->setHelp(<<<EOF Without any arguments, the <info>%command.name%</info> command builds the latest commit of all configured projects one after the other: <info>php %command.full_name%</info> The command loads project configurations from <comment>~/.sismo/config.php</comment>. Change it with the <info>--config-file</info> option: <info>php %command.full_name% --config-file=/path/to/config.php</info> Data (repository, DB, ...) are stored in <comment>~/.sismo/data/</comment>. The <info>--data-path</info> option allows you to change the default: <info>php %command.full_name% --data-path=/path/to/data</info> Pass the project slug to build a specific project: <info>php %command.full_name% twig</info> Force a specific commit to be built by passing the SHA: <info>php %command.full_name% twig a1ef34</info> Use <comment>--force</comment> to force the built even if it has already been built previously: <info>php %command.full_name% twig a1ef34 --force</info> Disable notifications with <comment>--silent</comment>: <info>php %command.full_name% twig a1ef34 --silent</info> Disable repository synchonization with <comment>--local</comment>: <info>php %command.full_name% twig a1ef34 --local</info> Limit the time (in seconds) spent by the command building projects by using the <comment>--timeout</comment> option: <info>php %command.full_name% twig --timeout 3600</info> When you use this command as a cron job, <comment>--timeout</comment> can avoid the command to be run concurrently. Be warned that this is a rough estimate as the time is only checked between two builds. When a build is started, it won't be stopped if the time limit is over. Use the <comment>--verbose</comment> option to debug builds in case of a problem. EOF ) ->setCode(function (InputInterface $input, OutputInterface $output) use ($app) { if ($input->getOption('data-path')) { $app['data.path'] = $input->getOption('data-path'); } if ($input->getOption('config-file')) { $app['config.file'] = $input->getOption('config-file'); } $sismo = $app['sismo']; if ($slug = $input->getArgument('slug')) { if (!$sismo->hasProject($slug)) { $output->writeln(sprintf('<error>Project "%s" does not exist.</error>', $slug)); return 1; } $projects = array($sismo->getProject($slug)); } else { $projects = $sismo->getProjects(); } $start = time(); $startedOut = false; $startedErr = false; $callback = null; if (OutputInterface::VERBOSITY_VERBOSE === $output->getVerbosity()) { $callback = function ($type, $buffer) use ($output, &$startedOut, &$startedErr) { if ('err' === $type) { if (!$startedErr) { $output->write("\n<bg=red;fg=white> ERR </> "); $startedErr = true; $startedOut = false; } $output->write(str_replace("\n", "\n<bg=red;fg=white> ERR </> ", $buffer)); } else { if (!$startedOut) { $output->write("\n<bg=green;fg=white> OUT </> "); $startedOut = true; $startedErr = false; } $output->write(str_replace("\n", "\n<bg=green;fg=white> OUT </> ", $buffer)); } }; } $flags = 0; if ($input->getOption('force')) { $flags = $flags | Sismo::FORCE_BUILD; } if ($input->getOption('local')) { $flags = $flags | Sismo::LOCAL_BUILD; } if ($input->getOption('silent')) { $flags = $flags | Sismo::SILENT_BUILD; } $returnValue = 0; foreach ($projects as $project) { // out of time? if ($input->getOption('timeout') && time() - $start > $input->getOption('timeout')) { break; } try { $output->writeln(sprintf('<info>Building Project "%s" (into "%s")</info>', $project, $app['builder']->getBuildDir($project))); $sismo->build($project, $input->getArgument('sha'), $flags, $callback); $output->writeln(''); } catch (BuildException $e) { $output->writeln("\n".sprintf('<error>%s</error>', $e->getMessage())); $returnValue = 1; } } return $returnValue; }) ; $console ->register('run') ->setDefinition(array( new InputArgument('address', InputArgument::OPTIONAL, 'Address:port', 'localhost:9000'), )) ->setDescription('Runs Sismo with PHP built-in web server') ->setHelp(<<<EOF The <info>%command.name%</info> command runs the embedded Sismo web server: <info>%command.full_name%</info> You can also customize the default address and port the web server listens to: <info>%command.full_name% 127.0.0.1:8080</info> EOF ) ->setCode(function (InputInterface $input, OutputInterface $output) use ($console) { if (version_compare(PHP_VERSION, '5.4.0') < 0) { throw new \Exception('This feature only runs with PHP 5.4.0 or higher.'); } $sismo = __DIR__.'/sismo.php'; while (!file_exists($sismo)) { $dialog = $console->getHelperSet()->get('dialog'); $sismo = $dialog->ask($output, sprintf('<comment>I cannot find "%s". What\'s the absoulte path of "sismo.php"?</comment> ', $sismo), __DIR__.'/sismo.php'); } $output->writeln(sprintf("Sismo running on <info>%s</info>\n", $input->getArgument('address'))); $builder = new ProcessBuilder(array(PHP_BINARY, '-S', $input->getArgument('address'), $sismo)); $builder->setWorkingDirectory(getcwd()); $builder->setTimeout(null); $builder->getProcess()->run(function ($type, $buffer) use ($output) { if (OutputInterface::VERBOSITY_VERBOSE === $output->getVerbosity()) { $output->write($buffer); } }); }) ; return $console;
druid628/Sismo
src/console.php
PHP
mit
9,948
#include "scripting/lua-bindings/manual/ui/lua_cocos2dx_experimental_video_manual.hpp" #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID || CC_TARGET_PLATFORM == CC_PLATFORM_IOS) #include "ui/UIVideoPlayer.h" #include "scripting/lua-bindings/manual/tolua_fix.h" #include "scripting/lua-bindings/manual/LuaBasicConversions.h" #include "scripting/lua-bindings/manual/CCLuaValue.h" #include "scripting/lua-bindings/manual/CCLuaEngine.h" static int lua_cocos2dx_experimental_video_VideoPlayer_addEventListener(lua_State* L) { int argc = 0; cocos2d::experimental::ui::VideoPlayer* self = nullptr; #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; if (!tolua_isusertype(L,1,"ccexp.VideoPlayer",0,&tolua_err)) goto tolua_lerror; #endif self = static_cast<cocos2d::experimental::ui::VideoPlayer*>(tolua_tousertype(L,1,0)); #if COCOS2D_DEBUG >= 1 if (nullptr == self) { tolua_error(L,"invalid 'self' in function 'lua_cocos2dx_Widget_addTouchEventListener'\n", nullptr); return 0; } #endif argc = lua_gettop(L) - 1; if (argc == 1) { #if COCOS2D_DEBUG >= 1 if (!toluafix_isfunction(L,2,"LUA_FUNCTION",0,&tolua_err)) { goto tolua_lerror; } #endif LUA_FUNCTION handler = ( toluafix_ref_function(L,2,0)); self->addEventListener([=](cocos2d::Ref* ref, cocos2d::experimental::ui::VideoPlayer::EventType eventType){ LuaStack* stack = LuaEngine::getInstance()->getLuaStack(); stack->pushObject(ref, "cc.Ref"); stack->pushInt((int)eventType); stack->executeFunctionByHandler(handler, 2); }); return 0; } luaL_error(L, "%s has wrong number of arguments: %d, was expecting %d\n ", "ccexp.VideoPlayer:addEventListener",argc, 0); return 0; #if COCOS2D_DEBUG >= 1 tolua_lerror: tolua_error(L, "#ferror in function 'lua_cocos2dx_experimental_VideoPlayer_addEventListener'.", &tolua_err); #endif return 0; } static void extendVideoPlayer(lua_State* L) { lua_pushstring(L, "ccexp.VideoPlayer"); lua_rawget(L, LUA_REGISTRYINDEX); if (lua_istable(L,-1)) { tolua_function(L, "addEventListener", lua_cocos2dx_experimental_video_VideoPlayer_addEventListener); } lua_pop(L, 1); } int register_all_cocos2dx_experimental_video_manual(lua_State* L) { if (nullptr == L) return 0; extendVideoPlayer(L); return 0; } #endif
tianxiawuzhei/cocos-quick-cpp
publibs/cocos2dx/cocos/scripting/lua-bindings/manual/ui/lua_cocos2dx_experimental_video_manual.cpp
C++
mit
2,501
/* _____ __ ___ __ ____ _ __ / ___/__ ___ _ ___ / |/ /__ ___ / /_____ __ __/ __/_______(_)__ / /_ / (_ / _ `/ ' \/ -_) /|_/ / _ \/ _ \/ '_/ -_) // /\ \/ __/ __/ / _ \/ __/ \___/\_,_/_/_/_/\__/_/ /_/\___/_//_/_/\_\\__/\_, /___/\__/_/ /_/ .__/\__/ /___/ /_/ See Copyright Notice in gmMachine.h */ #include "gmDebug.h" #include "gmConfig.h" #include "gmMachine.h" #include "gmThread.h" #if GMDEBUG_SUPPORT #define ID_mrun GM_MAKE_ID32('m','r','u','n') #define ID_msin GM_MAKE_ID32('m','s','i','n') #define ID_msou GM_MAKE_ID32('m','s','o','u') #define ID_msov GM_MAKE_ID32('m','s','o','v') #define ID_mgct GM_MAKE_ID32('m','g','c','t') #define ID_mgsr GM_MAKE_ID32('m','g','s','r') #define ID_mgsi GM_MAKE_ID32('m','g','s','i') #define ID_mgti GM_MAKE_ID32('m','g','t','i') #define ID_mgvi GM_MAKE_ID32('m','g','v','i') #define ID_msbp GM_MAKE_ID32('m','s','b','p') #define ID_mbrk GM_MAKE_ID32('m','b','r','k') #define ID_mend GM_MAKE_ID32('m','e','n','d') #define ID_dbrk GM_MAKE_ID32('d','b','r','k') #define ID_dexc GM_MAKE_ID32('d','e','x','c') #define ID_drun GM_MAKE_ID32('d','r','u','n') #define ID_dstp GM_MAKE_ID32('d','s','t','p') #define ID_dsrc GM_MAKE_ID32('d','s','r','c') #define ID_dctx GM_MAKE_ID32('d','c','t','x') #define ID_call GM_MAKE_ID32('c','a','l','l') #define ID_vari GM_MAKE_ID32('v','a','r','i') #define ID_done GM_MAKE_ID32('d','o','n','e') #define ID_dsri GM_MAKE_ID32('d','s','r','i') #define ID_srci GM_MAKE_ID32('s','r','c','i') #define ID_done GM_MAKE_ID32('d','o','n','e') #define ID_dthi GM_MAKE_ID32('d','t','h','i') #define ID_thri GM_MAKE_ID32('t','h','r','i') #define ID_done GM_MAKE_ID32('d','o','n','e') #define ID_derr GM_MAKE_ID32('d','e','r','r') #define ID_dmsg GM_MAKE_ID32('d','m','s','g') #define ID_dack GM_MAKE_ID32('d','a','c','k') #define ID_dend GM_MAKE_ID32('d','e','n','d') // // functions to handle incomming commands from a debugger // void gmMachineRun(gmDebugSession * a_session, int a_threadId); void gmMachineStepInto(gmDebugSession * a_session, int a_threadId); void gmMachineStepOver(gmDebugSession * a_session, int a_threadId); void gmMachineStepOut(gmDebugSession * a_session, int a_threadId); void gmMachineGetContext(gmDebugSession * a_session, int a_threadId, int a_callframe); void gmMachineGetSource(gmDebugSession * a_session, int a_sourceId); void gmMachineGetSourceInfo(gmDebugSession * a_session); void gmMachineGetThreadInfo(gmDebugSession * a_session); void gmMachineGetVariableInfo(gmDebugSession * a_session, int a_variableId); void gmMachineSetBreakPoint(gmDebugSession * a_session, int a_responseId, int a_sourceId, int a_lineNumber, int a_threadId, int a_enabled); void gmMachineBreak(gmDebugSession * a_session, int a_threadId); void gmMachineQuit(gmDebugSession * a_session); // // functions to package outgoing messages to a debugger // void gmDebuggerBreak(gmDebugSession * a_session, int a_threadId, int a_sourceId, int a_lineNumber); void gmDebuggerRun(gmDebugSession * a_session, int a_threadId); void gmDebuggerStop(gmDebugSession * a_session, int a_threadId); void gmDebuggerSource(gmDebugSession * a_session, int a_sourceId, const char * a_sourceName, const char * a_source); void gmDebuggerException(gmDebugSession * a_session, int a_threadId); void gmDebuggerBeginContext(gmDebugSession * a_session, int a_threadId, int a_callFrame); void gmDebuggerContextCallFrame(gmDebugSession * a_session, int a_callFrame, const char * a_functionName, int a_sourceId, int a_lineNumber, const char * a_thisSymbol, const char * a_thisValue, int a_thisId); void gmDebuggerContextVariable(gmDebugSession * a_session, const char * a_varSymbol, const char * a_varValue, int a_varId); void gmDebuggerEndContext(gmDebugSession * a_session); void gmDebuggerBeginSourceInfo(gmDebugSession * a_session); void gmDebuggerSourceInfo(gmDebugSession * a_session, int a_sourceId, const char * a_sourceName); void gmDebuggerEndSourceInfo(gmDebugSession * a_session); void gmDebuggerBeginThreadInfo(gmDebugSession * a_session); void gmDebuggerThreadInfo(gmDebugSession * a_session, int a_threadId, int a_threadState); void gmDebuggerEndThreadInfo(gmDebugSession * a_session); void gmDebuggerError(gmDebugSession * a_session, const char * a_error); void gmDebuggerMessage(gmDebugSession * a_session, const char * a_message); void gmDebuggerAck(gmDebugSession * a_session, int a_response, int a_posNeg); void gmDebuggerQuit(gmDebugSession * a_session); // // debug machine callback // enum gmdThreadFlags { TF_STEPOVER = (1 << 0), TF_STEPINTO = (1 << 1), TF_STEPOUT = (1 << 2), TF_BREAK = (1 << 3), }; // the following callbacks return true if the thread is to yield after completion of the callback. static bool LineCallback(gmThread * a_thread) { gmDebugSession * session = (gmDebugSession *) a_thread->GetMachine()->m_debugUser; GM_ASSERT(session); if(!(a_thread->m_debugFlags & TF_STEPOVER) || (a_thread->m_debugUser != ((a_thread->GetFrame()) ? a_thread->GetFrame()->m_returnBase : 0))) { int * bp = session->FindBreakPoint((void *) a_thread->GetInstruction()); if(bp == NULL) return false; if(*bp && *bp != a_thread->GetId()) return false; } a_thread->m_debugFlags = TF_BREAK; const gmFunctionObject * fn = a_thread->GetFunctionObject(); gmDebuggerBreak(session, a_thread->GetId(), fn->GetSourceId(), fn->GetLine(a_thread->GetInstruction())); return true; } static bool CallCallback(gmThread * a_thread) { gmDebugSession * session = (gmDebugSession *) a_thread->GetMachine()->m_debugUser; GM_ASSERT(session); if(a_thread->m_debugFlags & TF_STEPINTO) { a_thread->m_debugFlags = TF_BREAK; const gmFunctionObject * fn = a_thread->GetFunctionObject(); gmDebuggerBreak(session, a_thread->GetId(), fn->GetSourceId(), fn->GetLine(a_thread->GetInstruction())); return true; } return false; } static bool RetCallback(gmThread * a_thread) { gmDebugSession * session = (gmDebugSession *) a_thread->GetMachine()->m_debugUser; GM_ASSERT(session); if(((a_thread->m_debugFlags & TF_STEPOUT) && (a_thread->m_debugUser == a_thread->GetIntBase())) || ((a_thread->m_debugFlags & TF_STEPOVER) && (a_thread->m_debugUser == a_thread->GetIntBase()))) { a_thread->m_debugFlags = TF_BREAK; const gmFunctionObject * fn = a_thread->GetFunctionObject(); gmDebuggerBreak(session, a_thread->GetId(), fn->GetSourceId(), fn->GetLine(a_thread->GetInstruction())); return true; } return false; } static bool IsBrokenCallback(gmThread * a_thread) { return (a_thread->m_debugFlags & TF_BREAK) > 0; } static gmMachineCallback s_prevMachineCallback = NULL; bool GM_CDECL gmdMachineCallback(gmMachine * a_machine, gmMachineCommand a_command, const void * a_context) { gmDebugSession * session = (gmDebugSession *) a_machine->m_debugUser; const gmThread * thread = (const gmThread *) a_context; // chain callback if(s_prevMachineCallback) s_prevMachineCallback(a_machine, a_command, a_context); // do we have a debug session? if(session == NULL) return false; // command switch(a_command) { case MC_THREAD_EXCEPTION : { // send thread exception message gmDebuggerException(session, thread->GetId()); a_machine->GetLog(); bool first = true; const char * entry; while((entry = a_machine->GetLog().GetEntry(first))) { gmDebuggerError(session, entry); } return true; } case MC_THREAD_CREATE : { gmDebuggerRun(session, thread->GetId()); break; } case MC_THREAD_DESTROY : { gmDebuggerStop(session, thread->GetId()); break; } default : break; }; return false; } // // debug session // gmDebugSession::gmDebugSession() : m_breaks(32) { m_machine = NULL; } gmDebugSession::~gmDebugSession() { m_breaks.RemoveAndDeleteAll(); } void gmDebugSession::Update() { for(;;) { int len; const void * msg = m_pumpMessage(this, len); if(msg == NULL) break; m_in.Open(msg, len); // parse the message int id, pa, pb, pc, pd; Unpack(id); switch(id) { case ID_mrun : Unpack(id); gmMachineRun(this, id); break; case ID_msin : Unpack(id); gmMachineStepInto(this, id); break; case ID_msou : Unpack(id); gmMachineStepOut(this, id); break; case ID_msov : Unpack(id); gmMachineStepOver(this, id); break; case ID_mgct : Unpack(id).Unpack(pa); gmMachineGetContext(this, id, pa); break; case ID_mgsr : Unpack(id); gmMachineGetSource(this, id); break; case ID_mgsi : gmMachineGetSourceInfo(this); break; case ID_mgti : gmMachineGetThreadInfo(this); break; case ID_mgvi : Unpack(id); gmMachineGetVariableInfo(this, id); break; case ID_msbp : Unpack(pa).Unpack(pb).Unpack(pc).Unpack(id).Unpack(pd); gmMachineSetBreakPoint(this, pa, pb, pc, id, pd); break; case ID_mbrk : Unpack(id); gmMachineBreak(this, id); break; case ID_mend : gmMachineQuit(this); break; default:; } } } bool gmDebugSession::Open(gmMachine * a_machine) { Close(); m_machine = a_machine; m_machine->m_debugUser = this; m_machine->m_line = LineCallback; m_machine->m_call = CallCallback; m_machine->m_isBroken = IsBrokenCallback; m_machine->m_return = RetCallback; s_prevMachineCallback = a_machine->s_machineCallback; a_machine->s_machineCallback = gmdMachineCallback; return true; } static bool threadIterClose(gmThread * a_thread, void * a_context) { a_thread->m_debugFlags = 0; a_thread->m_debugUser = 0; return true; } bool gmDebugSession::Close() { if(m_machine && m_machine->m_debugUser == this) { gmDebuggerQuit(this); m_machine->m_debugUser = NULL; m_machine->s_machineCallback = s_prevMachineCallback; m_machine->m_line = NULL; m_machine->m_call = NULL; m_machine->m_return = NULL; m_machine->m_isBroken = NULL; m_machine->KillExceptionThreads(); m_machine->ForEachThread(threadIterClose, NULL); m_machine = NULL; m_breaks.RemoveAndDeleteAll(); m_out.ResetAndFreeMemory(); return true; } m_breaks.RemoveAndDeleteAll(); m_out.ResetAndFreeMemory(); return false; } gmDebugSession &gmDebugSession::Pack(int a_val) { m_out << a_val; return *this; } gmDebugSession &gmDebugSession::Pack(const char * a_val) { if(a_val) m_out.Write(a_val, strlen(a_val) + 1); else m_out.Write("", 1); return *this; } void gmDebugSession::Send() { m_sendMessage(this, m_out.GetData(), m_out.GetSize()); m_out.Reset(); } gmDebugSession &gmDebugSession::Unpack(int &a_val) { if(m_in.Read(&a_val, 4) != 4) a_val = 0; return *this; } gmDebugSession &gmDebugSession::Unpack(const char * &a_val) { // this is dangerous!!! a_val = &m_in.GetData()[m_in.Tell()]; int len = strlen(a_val); m_in.Seek(m_in.Tell() + len + 1); return *this; } bool gmDebugSession::AddBreakPoint(const void * a_bp, int a_threadId) { BreakPoint * bp = m_breaks.Find((void *const&)a_bp); if(bp) return false; bp = GM_NEW( BreakPoint() ); bp->m_bp = a_bp; bp->m_threadId = a_threadId; m_breaks.Insert(bp); return true; } int * gmDebugSession::FindBreakPoint(const void * a_bp) { BreakPoint * bp = m_breaks.Find((void *const&)a_bp); if(bp) { return &bp->m_threadId; } return NULL; } bool gmDebugSession::RemoveBreakPoint(const void * a_bp) { BreakPoint * bp = m_breaks.Find((void *const&)a_bp); if(bp) { m_breaks.Remove(bp); delete bp; return true; } return false; } // // implementation // void gmMachineRun(gmDebugSession * a_session, int a_threadId) { gmThread * thread = a_session->GetMachine()->GetThread(a_threadId); if(thread) { thread->m_debugFlags = 0; } } void gmMachineStepInto(gmDebugSession * a_session, int a_threadId) { gmThread * thread = a_session->GetMachine()->GetThread(a_threadId); if(thread) { thread->m_debugUser = (thread->GetFrame()) ? thread->GetFrame()->m_returnBase : 0; thread->m_debugFlags = TF_STEPINTO | TF_STEPOVER; } } void gmMachineStepOver(gmDebugSession * a_session, int a_threadId) { gmThread * thread = a_session->GetMachine()->GetThread(a_threadId); if(thread) { thread->m_debugUser = (thread->GetFrame()) ? thread->GetFrame()->m_returnBase : 0; thread->m_debugFlags = TF_STEPOVER; } } void gmMachineStepOut(gmDebugSession * a_session, int a_threadId) { gmThread * thread = a_session->GetMachine()->GetThread(a_threadId); if(thread) { thread->m_debugUser = (thread->GetFrame()) ? thread->GetFrame()->m_returnBase : 0; thread->m_debugFlags = TF_STEPOUT; } } void gmMachineGetContext(gmDebugSession * a_session, int a_threadId, int a_callframe) { const int buffSize = 256; char buff[buffSize]; // buff is used for AsString gmThread * thread = a_session->GetMachine()->GetThread(a_threadId); if(thread) { // count the number of frames on the thread int numFrames = 0; const gmStackFrame * frame = thread->GetFrame(); while(frame) { ++numFrames; frame = frame->m_prev; } // if a valid frame was requested, fill out a context. if(a_callframe >= 0 && a_callframe <= numFrames) { gmDebuggerBeginContext(a_session, a_threadId, a_callframe); // pack frames frame = thread->GetFrame(); numFrames = 0; gmVariable * base = thread->GetBase(); const gmuint8 * ip = thread->GetInstruction(); while(frame) { // get the function object gmVariable * fnVar = base - 1; if(fnVar->m_type == GM_FUNCTION) { gmFunctionObject * fn = (gmFunctionObject *) GM_MOBJECT(thread->GetMachine(), fnVar->m_value.m_ref); // this base[-2].AsStringWithType(thread->GetMachine(), buff, buffSize); gmDebuggerContextCallFrame(a_session, numFrames, fn->GetDebugName(), fn->GetSourceId(), fn->GetLine(ip), "this", buff, (base[-2].IsReference()) ? base[-2].m_value.m_ref : 0); if(numFrames == a_callframe) { // this is the active frame, fill out the variables int i; for(i = 0; i < fn->GetNumParamsLocals(); ++i) { base[i].AsStringWithType(thread->GetMachine(), buff, buffSize); gmDebuggerContextVariable(a_session, fn->GetSymbol(i), buff, (base[i].IsReference()) ? base[i].m_value.m_ref : 0); } } } else { base[-2].AsStringWithType(thread->GetMachine(), buff, buffSize); gmDebuggerContextCallFrame(a_session, numFrames, "unknown", 0, 0, "this", buff, (base[-2].IsReference()) ? base[-2].m_value.m_ref : 0); } // next call frame ++numFrames; base = thread->GetBottom() + frame->m_returnBase; ip = frame->m_returnAddress; frame = frame->m_prev; } gmDebuggerEndContext(a_session); } } } void gmMachineGetSource(gmDebugSession * a_session, int a_sourceId) { const char * source; const char * filename; if(a_session->GetMachine()->GetSourceCode(a_sourceId, source, filename)) { gmDebuggerSource(a_session, a_sourceId, filename, source); } } void gmMachineGetSourceInfo(gmDebugSession * a_session) { // todo } static bool threadIter(gmThread * a_thread, void * a_context) { gmDebugSession * session = (gmDebugSession *) a_context; int state = 0; // 0 - running, 1 - blocked, 2 - sleeping, 3 - exception, 4 - debug if(a_thread->m_debugFlags) state = 4; else if(a_thread->GetState() == gmThread::EXCEPTION) state = 3; else if(a_thread->GetState() == gmThread::RUNNING) state = 0; else if(a_thread->GetState() == gmThread::BLOCKED) state = 1; else if(a_thread->GetState() == gmThread::SLEEPING) state = 2; else state = 3; gmDebuggerThreadInfo(session, a_thread->GetId(), state); return true; } void gmMachineGetThreadInfo(gmDebugSession * a_session) { gmDebuggerBeginThreadInfo(a_session); a_session->GetMachine()->ForEachThread(threadIter, a_session); gmDebuggerEndThreadInfo(a_session); } void gmMachineGetVariableInfo(gmDebugSession * a_session, int a_variableId) { // todo } void gmMachineSetBreakPoint(gmDebugSession * a_session, int a_responseId, int a_sourceId, int a_lineNumber, int a_threadId, int a_enabled) { bool sendAck = false; // get break point const void * bp = (const void *) a_session->GetMachine()->GetInstructionAtBreakPoint(a_sourceId, a_lineNumber); if(bp) { // get to next instruction bp = (const void *) (((const char *) bp) + 4); int * id = a_session->FindBreakPoint(bp); if(id) { if(!a_enabled) { a_session->RemoveBreakPoint(bp); sendAck = true; } } else { if(a_session->AddBreakPoint(bp, a_threadId)) { sendAck = true; } } } if(sendAck) gmDebuggerAck(a_session, a_responseId, 1); else gmDebuggerAck(a_session, a_responseId, 0); } void gmMachineBreak(gmDebugSession * a_session, int a_threadId) { gmThread * thread = a_session->GetMachine()->GetThread(a_threadId); if(thread) { thread->m_debugUser = (thread->GetFrame()) ? thread->GetFrame()->m_returnBase : 0; thread->m_debugFlags = TF_STEPINTO | TF_STEPOVER; } } void gmMachineQuit(gmDebugSession * a_session) { a_session->Close(); } void gmDebuggerBreak(gmDebugSession * a_session, int a_threadId, int a_sourceId, int a_lineNumber) { a_session->Pack(ID_dbrk).Pack(a_threadId).Pack(a_sourceId).Pack(a_lineNumber).Send(); } void gmDebuggerException(gmDebugSession * a_session, int a_threadId) { a_session->Pack(ID_dexc).Pack(a_threadId).Send(); } void gmDebuggerRun(gmDebugSession * a_session, int a_threadId) { a_session->Pack(ID_drun).Pack(a_threadId).Send(); } void gmDebuggerStop(gmDebugSession * a_session, int a_threadId) { a_session->Pack(ID_dstp).Pack(a_threadId).Send(); } void gmDebuggerSource(gmDebugSession * a_session, int a_sourceId, const char * a_sourceName, const char * a_source) { a_session->Pack(ID_dsrc).Pack(a_sourceId).Pack(a_sourceName).Pack(a_source).Send(); } void gmDebuggerBeginContext(gmDebugSession * a_session, int a_threadId, int a_callFrame) { a_session->Pack(ID_dctx).Pack(a_threadId).Pack(a_callFrame); } void gmDebuggerContextCallFrame(gmDebugSession * a_session, int a_callFrame, const char * a_functionName, int a_sourceId, int a_lineNumber, const char * a_thisSymbol, const char * a_thisValue, int a_thisId) { a_session->Pack(ID_call).Pack(a_callFrame).Pack(a_functionName).Pack(a_sourceId).Pack(a_lineNumber).Pack(a_thisSymbol).Pack(a_thisValue).Pack(a_thisId); } void gmDebuggerContextVariable(gmDebugSession * a_session, const char * a_varSymbol, const char * a_varValue, int a_varId) { a_session->Pack(ID_vari).Pack(a_varSymbol).Pack(a_varValue).Pack(a_varId); } void gmDebuggerEndContext(gmDebugSession * a_session) { a_session->Pack(ID_done).Send(); } void gmDebuggerBeginSourceInfo(gmDebugSession * a_session) { a_session->Pack(ID_dsri); } void gmDebuggerSourceInfo(gmDebugSession * a_session, int a_sourceId, const char * a_sourceName) { a_session->Pack(ID_srci).Pack(a_sourceId).Pack(a_sourceName); } void gmDebuggerEndSourceInfo(gmDebugSession * a_session) { a_session->Pack(ID_done).Send(); } void gmDebuggerBeginThreadInfo(gmDebugSession * a_session) { a_session->Pack(ID_dthi); } void gmDebuggerThreadInfo(gmDebugSession * a_session, int a_threadId, int a_threadState) { a_session->Pack(ID_thri).Pack(a_threadId).Pack(a_threadState); } void gmDebuggerEndThreadInfo(gmDebugSession * a_session) { a_session->Pack(ID_done).Send(); } void gmDebuggerError(gmDebugSession * a_session, const char * a_error) { a_session->Pack(ID_derr).Pack(a_error).Send(); } void gmDebuggerMessage(gmDebugSession * a_session, const char * a_message) { a_session->Pack(ID_dmsg).Pack(a_message).Send(); } void gmDebuggerAck(gmDebugSession * a_session, int a_response, int a_posNeg) { a_session->Pack(ID_dack).Pack(a_response).Pack(a_posNeg).Send(); } void gmDebuggerQuit(gmDebugSession * a_session) { a_session->Pack(ID_dend).Send(); } // // lib binding // int GM_CDECL gmdDebug(gmThread * a_thread) { // if the machine has a debug session, attach a debug hook to the thread if(a_thread->GetMachine()->m_debugUser && a_thread->GetMachine()->GetDebugMode()) { a_thread->m_debugUser = (a_thread->GetFrame()) ? a_thread->GetFrame()->m_returnBase : 0; a_thread->m_debugFlags = TF_STEPINTO | TF_STEPOVER; } return GM_OK; } static gmFunctionEntry s_debugLib[] = { /*gm \lib gm \brief functions in the gm lib are all global scope */ /*gm \function debug \brief debug will cause a the debugger to break at this point while running. */ {"debug", gmdDebug}, }; void gmBindDebugLib(gmMachine * a_machine) { a_machine->RegisterLibrary(s_debugLib, sizeof(s_debugLib) / sizeof(s_debugLib[0])); } #endif
LothusMarque/Furnarchy
furnarchy2/furnarchyskin/gm/gmDebug.cpp
C++
mit
22,124
module Jasminerice module ApplicationHelper end end
ajacksified/restful-clients-in-rails-demo
rack-proxy/ruby/1.9.1/gems/jasminerice-0.0.8/app/helpers/jasminerice/application_helper.rb
Ruby
mit
56
goog.require('ol.Map'); goog.require('ol.View'); goog.require('ol.control'); goog.require('ol.layer.Tile'); goog.require('ol.layer.Vector'); goog.require('ol.source.GeoJSON'); goog.require('ol.source.OSM'); var map = new ol.Map({ layers: [ new ol.layer.Tile({ source: new ol.source.OSM() }), new ol.layer.Vector({ source: new ol.source.GeoJSON({ projection: 'EPSG:3857', url: 'data/geojson/countries.geojson' }) }) ], target: 'map', controls: ol.control.defaults({ attributionOptions: /** @type {olx.control.AttributionOptions} */ ({ collapsible: false }) }), view: new ol.View({ center: [0, 0], zoom: 2 }) }); var exportPNGElement = document.getElementById('export-png'); if ('download' in exportPNGElement) { exportPNGElement.addEventListener('click', function(e) { map.once('postcompose', function(event) { var canvas = event.context.canvas; exportPNGElement.href = canvas.toDataURL('image/png'); }); map.renderSync(); }, false); } else { var info = document.getElementById('no-download'); /** * display error message */ info.style.display = ''; }
buddebej/ol3-dem
ol3/examples/export-map.js
JavaScript
mit
1,180
'use strict'; angular.module('sumaAnalysis') .factory('actsLocs', function () { function calculateDepthAndTooltip (item, list, root, depth) { var parent; depth = depth || {depth: 0, tooltipTitle: item.title, ancestors: []}; if (parseInt(item.parent, 10) === parseInt(root, 10)) { return depth; } parent = _.find(list, {'id': item.parent}); depth.depth += 1; depth.tooltipTitle = parent.title + ': ' + depth.tooltipTitle; depth.ancestors.push(parent.id); return calculateDepthAndTooltip(parent, list, root, depth); } function processActivities (activities, activityGroups) { var activityList = [], activityGroupsHash; // Sort activities and activity groups activities = _.sortBy(activities, 'rank'); activityGroups = _.sortBy(activityGroups, 'rank'); activityGroupsHash = _.object(_.map(activityGroups, function (aGrp) { return [aGrp.id, aGrp.title]; })); // For each activity group, build a list of activities _.each(activityGroups, function (activityGroup) { // Add activity group metadata to activityGroupList array activityList.push({ 'id' : activityGroup.id, 'rank' : activityGroup.rank, 'title' : activityGroup.title, 'type' : 'activityGroup', 'depth' : 0, 'filter' : 'allow', 'enabled': true }); // Loop over activities and add the ones belonging to the current activityGroup _.each(activities, function (activity) { if (activity.activityGroup === activityGroup.id) { // Add activities to activityList array behind proper activityGroup activityList.push({ 'id' : activity.id, 'rank' : activity.rank, 'title' : activity.title, 'type' : 'activity', 'depth' : 1, 'activityGroup' : activityGroup.id, 'activityGroupTitle': activityGroupsHash[activityGroup.id], 'tooltipTitle' : activityGroupsHash[activityGroup.id] + ': ' + activity.title, 'altName' : activityGroupsHash[activityGroup.id] + ': ' + activity.title, 'filter' : 'allow', 'enabled' : true }); } }); }); return activityList; } function processLocations (locations, root) { return _.map(locations, function (loc, index, list) { var depth = calculateDepthAndTooltip(loc, list, root); loc.depth = depth.depth; loc.tooltipTitle = depth.tooltipTitle; loc.ancestors = depth.ancestors; loc.filter = true; loc.enabled = true; return loc; }); } return { get: function (init) { return { activities: processActivities(init.dictionary.activities, init.dictionary.activityGroups), locations: processLocations(init.dictionary.locations, init.rootLocation) }; } }; });
cazzerson/Suma
analysis/src/scripts/services/actsLocs.js
JavaScript
mit
3,247
""" kombu.transport.pyamqp ====================== pure python amqp transport. """ from __future__ import absolute_import import amqp from kombu.five import items from kombu.utils.amq_manager import get_manager from kombu.utils.text import version_string_as_tuple from . import base DEFAULT_PORT = 5672 DEFAULT_SSL_PORT = 5671 class Message(base.Message): def __init__(self, channel, msg, **kwargs): props = msg.properties super(Message, self).__init__( channel, body=msg.body, delivery_tag=msg.delivery_tag, content_type=props.get('content_type'), content_encoding=props.get('content_encoding'), delivery_info=msg.delivery_info, properties=msg.properties, headers=props.get('application_headers') or {}, **kwargs) class Channel(amqp.Channel, base.StdChannel): Message = Message def prepare_message(self, body, priority=None, content_type=None, content_encoding=None, headers=None, properties=None, _Message=amqp.Message): """Prepares message so that it can be sent using this transport.""" return _Message( body, priority=priority, content_type=content_type, content_encoding=content_encoding, application_headers=headers, **properties or {} ) def message_to_python(self, raw_message): """Convert encoded message body back to a Python value.""" return self.Message(self, raw_message) class Connection(amqp.Connection): Channel = Channel class Transport(base.Transport): Connection = Connection default_port = DEFAULT_PORT default_ssl_port = DEFAULT_SSL_PORT # it's very annoying that pyamqp sometimes raises AttributeError # if the connection is lost, but nothing we can do about that here. connection_errors = amqp.Connection.connection_errors channel_errors = amqp.Connection.channel_errors recoverable_connection_errors = \ amqp.Connection.recoverable_connection_errors recoverable_channel_errors = amqp.Connection.recoverable_channel_errors driver_name = 'py-amqp' driver_type = 'amqp' supports_heartbeats = True supports_ev = True def __init__(self, client, default_port=None, default_ssl_port=None, **kwargs): self.client = client self.default_port = default_port or self.default_port self.default_ssl_port = default_ssl_port or self.default_ssl_port def driver_version(self): return amqp.__version__ def create_channel(self, connection): return connection.channel() def drain_events(self, connection, **kwargs): return connection.drain_events(**kwargs) def establish_connection(self): """Establish connection to the AMQP broker.""" conninfo = self.client for name, default_value in items(self.default_connection_params): if not getattr(conninfo, name, None): setattr(conninfo, name, default_value) if conninfo.hostname == 'localhost': conninfo.hostname = '127.0.0.1' opts = dict({ 'host': conninfo.host, 'userid': conninfo.userid, 'password': conninfo.password, 'login_method': conninfo.login_method, 'virtual_host': conninfo.virtual_host, 'insist': conninfo.insist, 'ssl': conninfo.ssl, 'connect_timeout': conninfo.connect_timeout, 'heartbeat': conninfo.heartbeat, }, **conninfo.transport_options or {}) conn = self.Connection(**opts) conn.client = self.client return conn def verify_connection(self, connection): return connection.connected def close_connection(self, connection): """Close the AMQP broker connection.""" connection.client = None connection.close() def get_heartbeat_interval(self, connection): return connection.heartbeat def register_with_event_loop(self, connection, loop): loop.add_reader(connection.sock, self.on_readable, connection, loop) def heartbeat_check(self, connection, rate=2): return connection.heartbeat_tick(rate=rate) def qos_semantics_matches_spec(self, connection): props = connection.server_properties if props.get('product') == 'RabbitMQ': return version_string_as_tuple(props['version']) < (3, 3) return True @property def default_connection_params(self): return { 'userid': 'guest', 'password': 'guest', 'port': (self.default_ssl_port if self.client.ssl else self.default_port), 'hostname': 'localhost', 'login_method': 'AMQPLAIN', } def get_manager(self, *args, **kwargs): return get_manager(self.client, *args, **kwargs)
sunze/py_flask
venv/lib/python3.4/site-packages/kombu/transport/pyamqp.py
Python
mit
5,008
<?php defined('C5_EXECUTE') or die("Access Denied."); use Concrete\Core\Entity\Sharing\SocialNetwork\Link; use Concrete\Core\Form\Service\Form; use Concrete\Core\Sharing\SocialNetwork\Service; use Concrete\Core\Support\Facade\Application; use Concrete\Core\Support\Facade\Url; /** @var Link[] $links */ /** @var Link[] $selectedLinks */ $app = Application::getFacadeApplication(); /** @var Form $form */ $form = $app->make(Form::class); ?> <div class="form-group"> <label class="control-label form-label"> <?php echo t('Choose Social Links to Show'); ?> </label> <div id="ccm-block-social-links-list"> <?php if (0 == count($links)) { ?> <p> <?php echo t('You have not added any social links.'); ?> </p> <?php } ?> <?php foreach ($links as $link) { ?> <?php /** @var Service $service */ $service = $link->getServiceObject(); ?> <?php if ($service) { ?> <div class="form-check"> <label for="<?php echo "slID" . $link->getID(); ?>" class="form-check-label"> <?php echo $form->checkbox("socialService", $link->getID(), is_array($selectedLinks) && in_array($link, $selectedLinks), ["name" => "slID[]", "id" => "slID" . $link->getID()]); ?> <?php echo $service->getDisplayName(); ?> </label> <i class="fas fa-arrows-alt"></i> </div> <?php } ?> <?php } ?> </div> </div> <div class="alert alert-info"> <?php echo t(/*i18n: the two %s will be replaced with HTML code*/'Add social links %sin the dashboard%s', '<a href="' . (string)Url::to('/dashboard/system/basics/social') . '">' ,'</a>'); ?> </div> <!--suppress CssUnusedSymbol --> <style type="text/css"> #ccm-block-social-links-list { -webkit-user-select: none; position: relative; } #ccm-block-social-links-list .form-check { display: -webkit-box; display: -ms-flexbox; display: flex; -webkit-box-align: center; -ms-flex-align: center; align-items: center; margin-bottom: 0; padding: 6px; } #ccm-block-social-links-list .form-check:hover { background: #e7e7e7; border-radius: 4px; transition: background-color .1s linear; } #ccm-block-social-links-list .form-check.ui-sortable-helper { background: none; } #ccm-block-social-links-list i.fa-arrows-alt { display: none; color: #666; cursor: move; margin-left: auto; } #ccm-block-social-links-list div.form-check:hover i.fa-arrows-alt { display: block; } </style> <script> $(function () { $('#ccm-block-social-links-list').sortable({ axis: 'y' }); }); </script>
mlocati/concrete5
concrete/blocks/social_links/form.php
PHP
mit
2,919
#! /usr/bin/env ruby require 'spec_helper' require 'matchers/json' require 'puppet/util/instrumentation' require 'puppet/util/instrumentation/listener' describe Puppet::Util::Instrumentation::Listener do Listener = Puppet::Util::Instrumentation::Listener before(:each) do @delegate = stub 'listener', :notify => nil, :name => 'listener' @listener = Listener.new(@delegate) @listener.enabled = true end it "should indirect instrumentation_listener" do Listener.indirection.name.should == :instrumentation_listener end it "should raise an error if delegate doesn't support notify" do lambda { Listener.new(Object.new) }.should raise_error end it "should not be enabled by default" do Listener.new(@delegate).should_not be_enabled end it "should delegate notification" do @delegate.expects(:notify).with(:event, :start, {}) listener = Listener.new(@delegate) listener.notify(:event, :start, {}) end it "should not listen is not enabled" do @listener.enabled = false @listener.should_not be_listen_to(:label) end it "should listen to all label if created without pattern" do @listener.should be_listen_to(:improbable_label) end it "should listen to specific string pattern" do listener = Listener.new(@delegate, "specific") listener.enabled = true listener.should be_listen_to(:specific) end it "should not listen to non-matching string pattern" do listener = Listener.new(@delegate, "specific") listener.enabled = true listener.should_not be_listen_to(:unspecific) end it "should listen to specific regex pattern" do listener = Listener.new(@delegate, /spe.*/) listener.enabled = true listener.should be_listen_to(:specific_pattern) end it "should not listen to non matching regex pattern" do listener = Listener.new(@delegate, /^match.*/) listener.enabled = true listener.should_not be_listen_to(:not_matching) end it "should delegate its name to the underlying listener" do @delegate.expects(:name).returns("myname") @listener.name.should == "myname" end it "should delegate data fetching to the underlying listener" do @delegate.expects(:data).returns(:data) @listener.data.should == {:data => :data } end describe "when serializing to pson" do it "should return a pson object containing pattern, name and status" do @listener.should set_json_attribute('enabled').to(true) @listener.should set_json_attribute('name').to("listener") end end describe "when deserializing from pson" do it "should lookup the archetype listener from the instrumentation layer" do Puppet::Util::Instrumentation.expects(:[]).with("listener").returns(@listener) Puppet::Util::Instrumentation::Listener.from_pson({"name" => "listener"}) end it "should create a new listener shell instance delegating to the archetypal listener" do Puppet::Util::Instrumentation.expects(:[]).with("listener").returns(@listener) @listener.stubs(:listener).returns(@delegate) Puppet::Util::Instrumentation::Listener.expects(:new).with(@delegate, nil, true) Puppet::Util::Instrumentation::Listener.from_pson({"name" => "listener", "enabled" => true}) end end end
kieran-bamforth/our-boxen
vendor/bundle/ruby/2.0.0/gems/puppet-3.4.3/spec/unit/util/instrumentation/listener_spec.rb
Ruby
mit
3,283
/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2013 Torus Knot Software Ltd 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. ----------------------------------------------------------------------------- */ #include "OgreStableHeaders.h" #include "OgreCommon.h" #include "OgreWindowEventUtilities.h" #include "OgreRenderWindow.h" #include "OgreLogManager.h" #include "OgreRoot.h" #include "OgreException.h" #include "OgreStringConverter.h" #if OGRE_PLATFORM == OGRE_PLATFORM_LINUX #include <X11/Xlib.h> void GLXProc( Ogre::RenderWindow *win, const XEvent &event ); #endif //using namespace Ogre; Ogre::WindowEventUtilities::WindowEventListeners Ogre::WindowEventUtilities::_msListeners; Ogre::RenderWindowList Ogre::WindowEventUtilities::_msWindows; namespace Ogre { //--------------------------------------------------------------------------------// void WindowEventUtilities::messagePump() { #if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 // Windows Message Loop (NULL means check all HWNDs belonging to this context) MSG msg; while( PeekMessage( &msg, NULL, 0U, 0U, PM_REMOVE ) ) { TranslateMessage( &msg ); DispatchMessage( &msg ); } #elif OGRE_PLATFORM == OGRE_PLATFORM_LINUX //GLX Message Pump RenderWindowList::iterator win = _msWindows.begin(); RenderWindowList::iterator end = _msWindows.end(); Display* xDisplay = 0; // same for all windows for (; win != end; win++) { XID xid; XEvent event; if (!xDisplay) (*win)->getCustomAttribute("XDISPLAY", &xDisplay); (*win)->getCustomAttribute("WINDOW", &xid); while (XCheckWindowEvent (xDisplay, xid, StructureNotifyMask | VisibilityChangeMask | FocusChangeMask, &event)) { GLXProc(*win, event); } // The ClientMessage event does not appear under any Event Mask while (XCheckTypedWindowEvent (xDisplay, xid, ClientMessage, &event)) { GLXProc(*win, event); } } #elif OGRE_PLATFORM == OGRE_PLATFORM_APPLE && !defined __OBJC__ && !defined __LP64__ // OSX Message Pump EventRef event = NULL; EventTargetRef targetWindow; targetWindow = GetEventDispatcherTarget(); // If we are unable to get the target then we no longer care about events. if( !targetWindow ) return; // Grab the next event, process it if it is a window event while( ReceiveNextEvent( 0, NULL, kEventDurationNoWait, true, &event ) == noErr ) { // Dispatch the event SendEventToEventTarget( event, targetWindow ); ReleaseEvent( event ); } #endif } //--------------------------------------------------------------------------------// void WindowEventUtilities::addWindowEventListener( RenderWindow* window, WindowEventListener* listener ) { _msListeners.insert(std::make_pair(window, listener)); } //--------------------------------------------------------------------------------// void WindowEventUtilities::removeWindowEventListener( RenderWindow* window, WindowEventListener* listener ) { WindowEventListeners::iterator i = _msListeners.begin(), e = _msListeners.end(); for( ; i != e; ++i ) { if( i->first == window && i->second == listener ) { _msListeners.erase(i); break; } } } //--------------------------------------------------------------------------------// void WindowEventUtilities::_addRenderWindow(RenderWindow* window) { _msWindows.push_back(window); } //--------------------------------------------------------------------------------// void WindowEventUtilities::_removeRenderWindow(RenderWindow* window) { RenderWindowList::iterator i = std::find(_msWindows.begin(), _msWindows.end(), window); if( i != _msWindows.end() ) _msWindows.erase( i ); } } #if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 //--------------------------------------------------------------------------------// namespace Ogre { LRESULT CALLBACK WindowEventUtilities::_WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { if (uMsg == WM_CREATE) { // Store pointer to Win32Window in user data area SetWindowLongPtr(hWnd, GWLP_USERDATA, (LONG_PTR)(((LPCREATESTRUCT)lParam)->lpCreateParams)); return 0; } // look up window instance // note: it is possible to get a WM_SIZE before WM_CREATE RenderWindow* win = (RenderWindow*)GetWindowLongPtr(hWnd, GWLP_USERDATA); if (!win) return DefWindowProc(hWnd, uMsg, wParam, lParam); //LogManager* log = LogManager::getSingletonPtr(); //Iterator of all listeners registered to this RenderWindow WindowEventListeners::iterator index, start = _msListeners.lower_bound(win), end = _msListeners.upper_bound(win); switch( uMsg ) { case WM_ACTIVATE: { bool active = (LOWORD(wParam) != WA_INACTIVE); if( active ) { win->setActive( true ); } else { if( win->isDeactivatedOnFocusChange() ) { win->setActive( false ); } } for( ; start != end; ++start ) (start->second)->windowFocusChange(win); break; } case WM_SYSKEYDOWN: switch( wParam ) { case VK_CONTROL: case VK_SHIFT: case VK_MENU: //ALT //return zero to bypass defProc and signal we processed the message return 0; } break; case WM_SYSKEYUP: switch( wParam ) { case VK_CONTROL: case VK_SHIFT: case VK_MENU: //ALT case VK_F10: //return zero to bypass defProc and signal we processed the message return 0; } break; case WM_SYSCHAR: // return zero to bypass defProc and signal we processed the message, unless it's an ALT-space if (wParam != VK_SPACE) return 0; break; case WM_ENTERSIZEMOVE: //log->logMessage("WM_ENTERSIZEMOVE"); break; case WM_EXITSIZEMOVE: //log->logMessage("WM_EXITSIZEMOVE"); break; case WM_MOVE: //log->logMessage("WM_MOVE"); win->windowMovedOrResized(); for(index = start; index != end; ++index) (index->second)->windowMoved(win); break; case WM_DISPLAYCHANGE: win->windowMovedOrResized(); for(index = start; index != end; ++index) (index->second)->windowResized(win); break; case WM_SIZE: //log->logMessage("WM_SIZE"); win->windowMovedOrResized(); for(index = start; index != end; ++index) (index->second)->windowResized(win); break; case WM_GETMINMAXINFO: // Prevent the window from going smaller than some minimu size ((MINMAXINFO*)lParam)->ptMinTrackSize.x = 100; ((MINMAXINFO*)lParam)->ptMinTrackSize.y = 100; break; case WM_CLOSE: { //log->logMessage("WM_CLOSE"); bool close = true; for(index = start; index != end; ++index) { if (!(index->second)->windowClosing(win)) close = false; } if (!close) return 0; for(index = _msListeners.lower_bound(win); index != end; ++index) (index->second)->windowClosed(win); win->destroy(); return 0; } } return DefWindowProc( hWnd, uMsg, wParam, lParam ); } } #elif OGRE_PLATFORM == OGRE_PLATFORM_LINUX //--------------------------------------------------------------------------------// void GLXProc( Ogre::RenderWindow *win, const XEvent &event ) { //An iterator for the window listeners Ogre::WindowEventUtilities::WindowEventListeners::iterator index, start = Ogre::WindowEventUtilities::_msListeners.lower_bound(win), end = Ogre::WindowEventUtilities::_msListeners.upper_bound(win); switch(event.type) { case ClientMessage: { ::Atom atom; win->getCustomAttribute("ATOM", &atom); if(event.xclient.format == 32 && event.xclient.data.l[0] == (long)atom) { //Window closed by window manager //Send message first, to allow app chance to unregister things that need done before //window is shutdown bool close = true; for(index = start ; index != end; ++index) { if (!(index->second)->windowClosing(win)) close = false; } if (!close) return; for(index = start ; index != end; ++index) (index->second)->windowClosed(win); win->destroy(); } break; } case DestroyNotify: { if (!win->isClosed()) { // Window closed without window manager warning. for(index = start ; index != end; ++index) (index->second)->windowClosed(win); win->destroy(); } break; } case ConfigureNotify: { // This could be slightly more efficient if windowMovedOrResized took arguments: unsigned int oldWidth, oldHeight, oldDepth; int oldLeft, oldTop; win->getMetrics(oldWidth, oldHeight, oldDepth, oldLeft, oldTop); win->windowMovedOrResized(); unsigned int newWidth, newHeight, newDepth; int newLeft, newTop; win->getMetrics(newWidth, newHeight, newDepth, newLeft, newTop); if (newLeft != oldLeft || newTop != oldTop) { for(index = start ; index != end; ++index) (index->second)->windowMoved(win); } if (newWidth != oldWidth || newHeight != oldHeight) { for(index = start ; index != end; ++index) (index->second)->windowResized(win); } break; } case FocusIn: // Gained keyboard focus case FocusOut: // Lost keyboard focus for(index = start ; index != end; ++index) (index->second)->windowFocusChange(win); break; case MapNotify: //Restored win->setActive( true ); for(index = start ; index != end; ++index) (index->second)->windowFocusChange(win); break; case UnmapNotify: //Minimised win->setActive( false ); win->setVisible( false ); for(index = start ; index != end; ++index) (index->second)->windowFocusChange(win); break; case VisibilityNotify: switch(event.xvisibility.state) { case VisibilityUnobscured: win->setActive( true ); win->setVisible( true ); break; case VisibilityPartiallyObscured: win->setActive( true ); win->setVisible( true ); break; case VisibilityFullyObscured: win->setActive( false ); win->setVisible( false ); break; } for(index = start ; index != end; ++index) (index->second)->windowFocusChange(win); break; default: break; } //End switch event.type } #elif OGRE_PLATFORM == OGRE_PLATFORM_APPLE && !defined __OBJC__ && !defined __LP64__ //--------------------------------------------------------------------------------// namespace Ogre { OSStatus WindowEventUtilities::_CarbonWindowHandler(EventHandlerCallRef nextHandler, EventRef event, void* wnd) { OSStatus status = noErr; // Only events from our window should make it here // This ensures that our user data is our WindowRef RenderWindow* curWindow = (RenderWindow*)wnd; if(!curWindow) return eventNotHandledErr; //Iterator of all listeners registered to this RenderWindow WindowEventListeners::iterator index, start = _msListeners.lower_bound(curWindow), end = _msListeners.upper_bound(curWindow); // We only get called if a window event happens UInt32 eventKind = GetEventKind( event ); switch( eventKind ) { case kEventWindowActivated: curWindow->setActive( true ); for( ; start != end; ++start ) (start->second)->windowFocusChange(curWindow); break; case kEventWindowDeactivated: if( curWindow->isDeactivatedOnFocusChange() ) { curWindow->setActive( false ); } for( ; start != end; ++start ) (start->second)->windowFocusChange(curWindow); break; case kEventWindowShown: case kEventWindowExpanded: curWindow->setActive( true ); curWindow->setVisible( true ); for( ; start != end; ++start ) (start->second)->windowFocusChange(curWindow); break; case kEventWindowHidden: case kEventWindowCollapsed: curWindow->setActive( false ); curWindow->setVisible( false ); for( ; start != end; ++start ) (start->second)->windowFocusChange(curWindow); break; case kEventWindowDragCompleted: curWindow->windowMovedOrResized(); for( ; start != end; ++start ) (start->second)->windowMoved(curWindow); break; case kEventWindowBoundsChanged: curWindow->windowMovedOrResized(); for( ; start != end; ++start ) (start->second)->windowResized(curWindow); break; case kEventWindowClose: { bool close = true; for( ; start != end; ++start ) { if (!(start->second)->windowClosing(curWindow)) close = false; } if (close) // This will cause event handling to continue on to the standard handler, which calls // DisposeWindow(), which leads to the 'kEventWindowClosed' event status = eventNotHandledErr; break; } case kEventWindowClosed: curWindow->destroy(); for( ; start != end; ++start ) (start->second)->windowClosed(curWindow); break; default: status = eventNotHandledErr; break; } return status; } } #endif
uspgamedev/3D-experiment
externals/Ogre/OgreMain/src/OgreWindowEventUtilities.cpp
C++
mit
14,140
#------------------------------------------------------------------------------ # pycparser: c_generator.py # # C code generator from pycparser AST nodes. # # Copyright (C) 2008-2012, Eli Bendersky # License: BSD #------------------------------------------------------------------------------ from . import c_ast class CGenerator(object): """ Uses the same visitor pattern as c_ast.NodeVisitor, but modified to return a value from each visit method, using string accumulation in generic_visit. """ def __init__(self): self.output = '' # Statements start with indentation of self.indent_level spaces, using # the _make_indent method # self.indent_level = 0 def _make_indent(self): return ' ' * self.indent_level def visit(self, node): method = 'visit_' + node.__class__.__name__ return getattr(self, method, self.generic_visit)(node) def generic_visit(self, node): #~ print('generic:', type(node)) if node is None: return '' else: return ''.join(self.visit(c) for c in node.children()) def visit_Constant(self, n): return n.value def visit_ID(self, n): return n.name def visit_ArrayRef(self, n): arrref = self._parenthesize_unless_simple(n.name) return arrref + '[' + self.visit(n.subscript) + ']' def visit_StructRef(self, n): sref = self._parenthesize_unless_simple(n.name) return sref + n.type + self.visit(n.field) def visit_FuncCall(self, n): fref = self._parenthesize_unless_simple(n.name) return fref + '(' + self.visit(n.args) + ')' def visit_UnaryOp(self, n): operand = self._parenthesize_unless_simple(n.expr) if n.op == 'p++': return '%s++' % operand elif n.op == 'p--': return '%s--' % operand elif n.op == 'sizeof': # Always parenthesize the argument of sizeof since it can be # a name. return 'sizeof(%s)' % self.visit(n.expr) else: return '%s%s' % (n.op, operand) def visit_BinaryOp(self, n): lval_str = self._parenthesize_if(n.left, lambda d: not self._is_simple_node(d)) rval_str = self._parenthesize_if(n.right, lambda d: not self._is_simple_node(d)) return '%s %s %s' % (lval_str, n.op, rval_str) def visit_Assignment(self, n): rval_str = self._parenthesize_if( n.rvalue, lambda n: isinstance(n, c_ast.Assignment)) return '%s %s %s' % (self.visit(n.lvalue), n.op, rval_str) def visit_IdentifierType(self, n): return ' '.join(n.names) def visit_Decl(self, n, no_type=False): # no_type is used when a Decl is part of a DeclList, where the type is # explicitly only for the first delaration in a list. # s = n.name if no_type else self._generate_decl(n) if n.bitsize: s += ' : ' + self.visit(n.bitsize) if n.init: if isinstance(n.init, c_ast.InitList): s += ' = {' + self.visit(n.init) + '}' elif isinstance(n.init, c_ast.ExprList): s += ' = (' + self.visit(n.init) + ')' else: s += ' = ' + self.visit(n.init) return s def visit_DeclList(self, n): s = self.visit(n.decls[0]) if len(n.decls) > 1: s += ', ' + ', '.join(self.visit_Decl(decl, no_type=True) for decl in n.decls[1:]) return s def visit_Typedef(self, n): s = '' if n.storage: s += ' '.join(n.storage) + ' ' s += self._generate_type(n.type) return s def visit_Cast(self, n): s = '(' + self._generate_type(n.to_type) + ')' return s + ' ' + self._parenthesize_unless_simple(n.expr) def visit_ExprList(self, n): visited_subexprs = [] for expr in n.exprs: if isinstance(expr, c_ast.ExprList): visited_subexprs.append('{' + self.visit(expr) + '}') else: visited_subexprs.append(self.visit(expr)) return ', '.join(visited_subexprs) def visit_InitList(self, n): visited_subexprs = [] for expr in n.exprs: if isinstance(expr, c_ast.InitList): visited_subexprs.append('(' + self.visit(expr) + ')') else: visited_subexprs.append(self.visit(expr)) return ', '.join(visited_subexprs) def visit_Enum(self, n): s = 'enum' if n.name: s += ' ' + n.name if n.values: s += ' {' for i, enumerator in enumerate(n.values.enumerators): s += enumerator.name if enumerator.value: s += ' = ' + self.visit(enumerator.value) if i != len(n.values.enumerators) - 1: s += ', ' s += '}' return s def visit_FuncDef(self, n): decl = self.visit(n.decl) self.indent_level = 0 body = self.visit(n.body) if n.param_decls: knrdecls = ';\n'.join(self.visit(p) for p in n.param_decls) return decl + '\n' + knrdecls + ';\n' + body + '\n' else: return decl + '\n' + body + '\n' def visit_FileAST(self, n): s = '' for ext in n.ext: if isinstance(ext, c_ast.FuncDef): s += self.visit(ext) else: s += self.visit(ext) + ';\n' return s def visit_Compound(self, n): s = self._make_indent() + '{\n' self.indent_level += 2 if n.block_items: s += ''.join(self._generate_stmt(stmt) for stmt in n.block_items) self.indent_level -= 2 s += self._make_indent() + '}\n' return s def visit_EmptyStatement(self, n): return ';' def visit_ParamList(self, n): return ', '.join(self.visit(param) for param in n.params) def visit_Return(self, n): s = 'return' if n.expr: s += ' ' + self.visit(n.expr) return s + ';' def visit_Break(self, n): return 'break;' def visit_Continue(self, n): return 'continue;' def visit_TernaryOp(self, n): s = self.visit(n.cond) + ' ? ' s += self.visit(n.iftrue) + ' : ' s += self.visit(n.iffalse) return s def visit_If(self, n): s = 'if (' if n.cond: s += self.visit(n.cond) s += ')\n' s += self._generate_stmt(n.iftrue, add_indent=True) if n.iffalse: s += self._make_indent() + 'else\n' s += self._generate_stmt(n.iffalse, add_indent=True) return s def visit_For(self, n): s = 'for (' if n.init: s += self.visit(n.init) s += ';' if n.cond: s += ' ' + self.visit(n.cond) s += ';' if n.next: s += ' ' + self.visit(n.next) s += ')\n' s += self._generate_stmt(n.stmt, add_indent=True) return s def visit_While(self, n): s = 'while (' if n.cond: s += self.visit(n.cond) s += ')\n' s += self._generate_stmt(n.stmt, add_indent=True) return s def visit_DoWhile(self, n): s = 'do\n' s += self._generate_stmt(n.stmt, add_indent=True) s += self._make_indent() + 'while (' if n.cond: s += self.visit(n.cond) s += ');' return s def visit_Switch(self, n): s = 'switch (' + self.visit(n.cond) + ')\n' s += self._generate_stmt(n.stmt, add_indent=True) return s def visit_Case(self, n): s = 'case ' + self.visit(n.expr) + ':\n' for stmt in n.stmts: s += self._generate_stmt(stmt, add_indent=True) return s def visit_Default(self, n): s = 'default:\n' for stmt in n.stmts: s += self._generate_stmt(stmt, add_indent=True) return s def visit_Label(self, n): return n.name + ':\n' + self._generate_stmt(n.stmt) def visit_Goto(self, n): return 'goto ' + n.name + ';' def visit_EllipsisParam(self, n): return '...' def visit_Struct(self, n): return self._generate_struct_union(n, 'struct') def visit_Typename(self, n): return self._generate_type(n.type) def visit_Union(self, n): return self._generate_struct_union(n, 'union') def visit_NamedInitializer(self, n): s = '' for name in n.name: if isinstance(name, c_ast.ID): s += '.' + name.name elif isinstance(name, c_ast.Constant): s += '[' + name.value + ']' s += ' = ' + self.visit(n.expr) return s def _generate_struct_union(self, n, name): """ Generates code for structs and unions. name should be either 'struct' or union. """ s = name + ' ' + (n.name or '') if n.decls: s += '\n' s += self._make_indent() self.indent_level += 2 s += '{\n' for decl in n.decls: s += self._generate_stmt(decl) self.indent_level -= 2 s += self._make_indent() + '}' return s def _generate_stmt(self, n, add_indent=False): """ Generation from a statement node. This method exists as a wrapper for individual visit_* methods to handle different treatment of some statements in this context. """ typ = type(n) if add_indent: self.indent_level += 2 indent = self._make_indent() if add_indent: self.indent_level -= 2 if typ in ( c_ast.Decl, c_ast.Assignment, c_ast.Cast, c_ast.UnaryOp, c_ast.BinaryOp, c_ast.TernaryOp, c_ast.FuncCall, c_ast.ArrayRef, c_ast.StructRef, c_ast.Constant, c_ast.ID, c_ast.Typedef): # These can also appear in an expression context so no semicolon # is added to them automatically # return indent + self.visit(n) + ';\n' elif typ in (c_ast.Compound,): # No extra indentation required before the opening brace of a # compound - because it consists of multiple lines it has to # compute its own indentation. # return self.visit(n) else: return indent + self.visit(n) + '\n' def _generate_decl(self, n): """ Generation from a Decl node. """ s = '' if n.funcspec: s = ' '.join(n.funcspec) + ' ' if n.storage: s += ' '.join(n.storage) + ' ' s += self._generate_type(n.type) return s def _generate_type(self, n, modifiers=[]): """ Recursive generation from a type node. n is the type node. modifiers collects the PtrDecl, ArrayDecl and FuncDecl modifiers encountered on the way down to a TypeDecl, to allow proper generation from it. """ typ = type(n) #~ print(n, modifiers) if typ == c_ast.TypeDecl: s = '' if n.quals: s += ' '.join(n.quals) + ' ' s += self.visit(n.type) nstr = n.declname if n.declname else '' # Resolve modifiers. # Wrap in parens to distinguish pointer to array and pointer to # function syntax. # for i, modifier in enumerate(modifiers): if isinstance(modifier, c_ast.ArrayDecl): if (i != 0 and isinstance(modifiers[i - 1], c_ast.PtrDecl)): nstr = '(' + nstr + ')' nstr += '[' + self.visit(modifier.dim) + ']' elif isinstance(modifier, c_ast.FuncDecl): if (i != 0 and isinstance(modifiers[i - 1], c_ast.PtrDecl)): nstr = '(' + nstr + ')' nstr += '(' + self.visit(modifier.args) + ')' elif isinstance(modifier, c_ast.PtrDecl): if modifier.quals: nstr = '* %s %s' % (' '.join(modifier.quals), nstr) else: nstr = '*' + nstr if nstr: s += ' ' + nstr return s elif typ == c_ast.Decl: return self._generate_decl(n.type) elif typ == c_ast.Typename: return self._generate_type(n.type) elif typ == c_ast.IdentifierType: return ' '.join(n.names) + ' ' elif typ in (c_ast.ArrayDecl, c_ast.PtrDecl, c_ast.FuncDecl): return self._generate_type(n.type, modifiers + [n]) else: return self.visit(n) def _parenthesize_if(self, n, condition): """ Visits 'n' and returns its string representation, parenthesized if the condition function applied to the node returns True. """ s = self.visit(n) if condition(n): return '(' + s + ')' else: return s def _parenthesize_unless_simple(self, n): """ Common use case for _parenthesize_if """ return self._parenthesize_if(n, lambda d: not self._is_simple_node(d)) def _is_simple_node(self, n): """ Returns True for nodes that are "simple" - i.e. nodes that always have higher precedence than operators. """ return isinstance(n,( c_ast.Constant, c_ast.ID, c_ast.ArrayRef, c_ast.StructRef, c_ast.FuncCall))
bussiere/pypyjs
website/demo/home/rfk/repos/pypy/lib_pypy/cffi/_pycparser/c_generator.py
Python
mit
13,798
<?php namespace N98\Magento\Command\Developer\Theme; use N98\Magento\Command\TestCase; use Symfony\Component\Console\Tester\CommandTester; class ListCommandTest extends TestCase { public function testExecute() { $application = $this->getApplication(); $application->add(new ListCommand()); $command = $this->getApplication()->find('dev:theme:list'); $commandTester = new CommandTester($command); $commandTester->execute( array( 'command' => $command->getName(), ) ); $this->assertContains('base/default', $commandTester->getDisplay()); } }
pocallaghan/n98-magerun
tests/N98/Magento/Command/Developer/Theme/ListCommandTest.php
PHP
mit
653
//===----------------- lib/Jit/options.cpp ----------------------*- C++ -*-===// // // LLILC // // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. // See LICENSE file in the project root for full license information. // //===----------------------------------------------------------------------===// /// /// \file /// \brief Definition of the Options class that encapsulates JIT options /// extracted from CoreCLR config values. /// //===----------------------------------------------------------------------===// #include "earlyincludes.h" #include "global.h" #include "jitpch.h" #include "LLILCJit.h" #include "jitoptions.h" // Define a macro for cross-platform UTF-16 string literals. #if defined(_MSC_VER) #define UTF16(lit) L##lit #else #define UTF16(lit) u##lit #endif // For now we're always running as the altjit #define ALT_JIT 1 // These are the instantiations of the static method sets in Options.h. // This MethodSets are initialized from CLRConfig values passed through // the corinfo.h interface. MethodSet JitOptions::AltJitMethodSet; MethodSet JitOptions::AltJitNgenMethodSet; MethodSet JitOptions::ExcludeMethodSet; MethodSet JitOptions::BreakMethodSet; MethodSet JitOptions::MSILMethodSet; MethodSet JitOptions::LLVMMethodSet; MethodSet JitOptions::CodeRangeMethodSet; template <typename UTF16CharT> char16_t *getStringConfigValue(ICorJitInfo *CorInfo, const UTF16CharT *Name) { static_assert(sizeof(UTF16CharT) == 2, "UTF16CharT is the wrong size!"); return (char16_t *)LLILCJit::TheJitHost->getStringConfigValue( (const wchar_t *)Name); } template <typename UTF16CharT> void freeStringConfigValue(ICorJitInfo *CorInfo, UTF16CharT *Value) { static_assert(sizeof(UTF16CharT) == 2, "UTF16CharT is the wrong size!"); return LLILCJit::TheJitHost->freeStringConfigValue((wchar_t *)Value); } JitOptions::JitOptions(LLILCJitContext &Context) { // Set 'IsAltJit' based on environment information. IsAltJit = queryIsAltJit(Context); // Set dump level for this JIT invocation. DumpLevel = queryDumpLevel(Context); // Set optimization level for this JIT invocation. OptLevel = queryOptLevel(Context); EnableOptimization = OptLevel != ::OptLevel::DEBUG_CODE; // Set whether to use conservative GC. UseConservativeGC = queryUseConservativeGC(Context); // Set whether to insert statepoints. DoInsertStatepoints = queryDoInsertStatepoints(Context); DoSIMDIntrinsic = queryDoSIMDIntrinsic(Context); // Set whether to do tail call opt. DoTailCallOpt = queryDoTailCallOpt(Context); LogGcInfo = queryLogGcInfo(Context); // Set whether to insert failfast in exception handlers. ExecuteHandlers = queryExecuteHandlers(Context); IsExcludeMethod = queryIsExcludeMethod(Context); IsBreakMethod = queryIsBreakMethod(Context); IsMSILDumpMethod = queryIsMSILDumpMethod(Context); IsLLVMDumpMethod = queryIsLLVMDumpMethod(Context); IsCodeRangeMethod = queryIsCodeRangeMethod(Context); if (IsAltJit) { PreferredIntrinsicSIMDVectorLength = 0; } else { PreferredIntrinsicSIMDVectorLength = 32; } // Validate Statepoint and Conservative GC state. assert(DoInsertStatepoints || UseConservativeGC && "Statepoints required for precise-GC"); } bool JitOptions::queryDoTailCallOpt(LLILCJitContext &Context) { return (bool)DEFAULT_TAIL_CALL_OPT; } bool JitOptions::queryIsAltJit(LLILCJitContext &Context) { // Initial state is that we are not an alternative jit until proven otherwise; bool IsAlternateJit = false; // NDEBUG is !Debug #if !defined(NDEBUG) // DEBUG case // Get/reuse method set that contains the altjit method value. MethodSet *AltJit = nullptr; if (Context.Flags & CORJIT_FLG_PREJIT) { if (!AltJitNgenMethodSet.isInitialized()) { char16_t *NgenStr = getStringConfigValue(Context.JitInfo, UTF16("AltJitNgen")); std::unique_ptr<std::string> NgenUtf8 = Convert::utf16ToUtf8(NgenStr); AltJitNgenMethodSet.init(std::move(NgenUtf8)); freeStringConfigValue(Context.JitInfo, NgenStr); } // Set up AltJitNgen set to be used for AltJit test. AltJit = &AltJitNgenMethodSet; } else { if (!AltJitMethodSet.isInitialized()) { char16_t *JitStr = getStringConfigValue(Context.JitInfo, UTF16("AltJit")); // Move this to the UTIL code and ifdef it for platform std::unique_ptr<std::string> JitUtf8 = Convert::utf16ToUtf8(JitStr); AltJitMethodSet.init(std::move(JitUtf8)); freeStringConfigValue(Context.JitInfo, JitStr); } // Set up AltJit set to be use for AltJit test. AltJit = &AltJitMethodSet; } #ifdef ALT_JIT const char *ClassName = nullptr; const char *MethodName = nullptr; MethodName = Context.JitInfo->getMethodName(Context.MethodInfo->ftn, &ClassName); IsAlternateJit = AltJit->contains(MethodName, ClassName, Context.MethodInfo->args.pSig); #endif // ALT_JIT #else if (Context.Flags & CORJIT_FLG_PREJIT) { char16_t *NgenStr = getStringConfigValue(Context.JitInfo, UTF16("AltJitNgen")); std::unique_ptr<std::string> NgenUtf8 = Convert::utf16ToUtf8(NgenStr); if (NgenUtf8->compare("*") == 0) { IsAlternateJit = true; } } else { char16_t *JitStr = getStringConfigValue(Context.JitInfo, UTF16("AltJit")); std::unique_ptr<std::string> JitUtf8 = Convert::utf16ToUtf8(JitStr); if (JitUtf8->compare("*") == 0) { IsAlternateJit = true; } } #endif return IsAlternateJit; } ::DumpLevel JitOptions::queryDumpLevel(LLILCJitContext &Context) { ::DumpLevel JitDumpLevel = ::DumpLevel::NODUMP; char16_t *LevelWStr = getStringConfigValue(Context.JitInfo, UTF16("DUMPLLVMIR")); if (LevelWStr) { std::unique_ptr<std::string> Level = Convert::utf16ToUtf8(LevelWStr); std::transform(Level->begin(), Level->end(), Level->begin(), ::toupper); if (Level->compare("VERBOSE") == 0) { JitDumpLevel = ::DumpLevel::VERBOSE; } else if (Level->compare("SUMMARY") == 0) { JitDumpLevel = ::DumpLevel::SUMMARY; } } return JitDumpLevel; } bool JitOptions::queryIsExcludeMethod(LLILCJitContext &JitContext) { return queryMethodSet(JitContext, ExcludeMethodSet, (const char16_t *)UTF16("AltJitExclude")); } bool JitOptions::queryIsBreakMethod(LLILCJitContext &JitContext) { return queryMethodSet(JitContext, BreakMethodSet, (const char16_t *)UTF16("AltJitBreakAtJitStart")); } bool JitOptions::queryIsMSILDumpMethod(LLILCJitContext &JitContext) { return queryMethodSet(JitContext, MSILMethodSet, (const char16_t *)UTF16("AltJitMSILDump")); } bool JitOptions::queryIsLLVMDumpMethod(LLILCJitContext &JitContext) { return queryMethodSet(JitContext, LLVMMethodSet, (const char16_t *)UTF16("AltJitLLVMDump")); } bool JitOptions::queryIsCodeRangeMethod(LLILCJitContext &JitContext) { return queryMethodSet(JitContext, CodeRangeMethodSet, (const char16_t *)UTF16("AltJitCodeRangeDump")); } bool JitOptions::queryMethodSet(LLILCJitContext &JitContext, MethodSet &TheSet, const char16_t *Name) { if (!TheSet.isInitialized()) { char16_t *ConfigStr = getStringConfigValue(JitContext.JitInfo, Name); bool NeedFree = true; if (ConfigStr == nullptr) { ConfigStr = const_cast<char16_t *>((const char16_t *)UTF16("")); NeedFree = false; } std::unique_ptr<std::string> ConfigUtf8 = Convert::utf16ToUtf8(ConfigStr); TheSet.init(std::move(ConfigUtf8)); if (NeedFree) { freeStringConfigValue(JitContext.JitInfo, ConfigStr); } } const char *ClassName = nullptr; const char *MethodName = nullptr; MethodName = JitContext.JitInfo->getMethodName(JitContext.MethodInfo->ftn, &ClassName); bool IsInMethodSet = TheSet.contains(MethodName, ClassName, JitContext.MethodInfo->args.pSig); return IsInMethodSet; } bool JitOptions::queryNonNullNonEmpty(LLILCJitContext &JitContext, const char16_t *Name) { char16_t *ConfigStr = getStringConfigValue(JitContext.JitInfo, Name); return (ConfigStr != nullptr) && (*ConfigStr != 0); } // Get the GC-Scheme used by the runtime -- conservative/precise bool JitOptions::queryUseConservativeGC(LLILCJitContext &Context) { return queryNonNullNonEmpty(Context, (const char16_t *)UTF16("gcConservative")); } // Determine if GC statepoints should be inserted. bool JitOptions::queryDoInsertStatepoints(LLILCJitContext &Context) { return queryNonNullNonEmpty(Context, (const char16_t *)UTF16("INSERTSTATEPOINTS")); } // Determine if GCInfo encoding logs should be emitted bool JitOptions::queryLogGcInfo(LLILCJitContext &Context) { return queryNonNullNonEmpty(Context, (const char16_t *)UTF16("JitGCInfoLogging")); } // Determine if exception handlers should be executed. bool JitOptions::queryExecuteHandlers(LLILCJitContext &Context) { return queryNonNullNonEmpty(Context, (const char16_t *)UTF16("ExecuteHandlers")); } // Determine if SIMD intrinsics should be used. bool JitOptions::queryDoSIMDIntrinsic(LLILCJitContext &Context) { return queryNonNullNonEmpty(Context, (const char16_t *)UTF16("SIMDINTRINSIC")); } OptLevel JitOptions::queryOptLevel(LLILCJitContext &Context) { ::OptLevel JitOptLevel = ::OptLevel::BLENDED_CODE; // Currently we only check for the debug flag but this will be extended // to account for further opt levels as we move forward. if ((Context.Flags & CORJIT_FLG_DEBUG_CODE) != 0) { JitOptLevel = ::OptLevel::DEBUG_CODE; } return JitOptLevel; } JitOptions::~JitOptions() {}
dotnet/llilc
lib/Jit/jitoptions.cpp
C++
mit
9,832
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.appservice; import com.fasterxml.jackson.annotation.JsonProperty; /** * Actions which to take by the auto-heal module when a rule is triggered. */ public class AutoHealActions { /** * Predefined action to be taken. Possible values include: 'Recycle', * 'LogEvent', 'CustomAction'. */ @JsonProperty(value = "actionType") private AutoHealActionType actionType; /** * Custom action to be taken. */ @JsonProperty(value = "customAction") private AutoHealCustomAction customAction; /** * Minimum time the process must execute * before taking the action. */ @JsonProperty(value = "minProcessExecutionTime") private String minProcessExecutionTime; /** * Get the actionType value. * * @return the actionType value */ public AutoHealActionType actionType() { return this.actionType; } /** * Set the actionType value. * * @param actionType the actionType value to set * @return the AutoHealActions object itself. */ public AutoHealActions withActionType(AutoHealActionType actionType) { this.actionType = actionType; return this; } /** * Get the customAction value. * * @return the customAction value */ public AutoHealCustomAction customAction() { return this.customAction; } /** * Set the customAction value. * * @param customAction the customAction value to set * @return the AutoHealActions object itself. */ public AutoHealActions withCustomAction(AutoHealCustomAction customAction) { this.customAction = customAction; return this; } /** * Get the minProcessExecutionTime value. * * @return the minProcessExecutionTime value */ public String minProcessExecutionTime() { return this.minProcessExecutionTime; } /** * Set the minProcessExecutionTime value. * * @param minProcessExecutionTime the minProcessExecutionTime value to set * @return the AutoHealActions object itself. */ public AutoHealActions withMinProcessExecutionTime(String minProcessExecutionTime) { this.minProcessExecutionTime = minProcessExecutionTime; return this; } }
jianghaolu/azure-sdk-for-java
azure-mgmt-appservice/src/main/java/com/microsoft/azure/management/appservice/AutoHealActions.java
Java
mit
2,569
using UnityEngine; using System; using LuaInterface; using SLua; using System.Collections.Generic; public class Lua_UnityEngine_Bounds : LuaObject { [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int constructor(IntPtr l) { LuaDLL.lua_remove(l,1); UnityEngine.Bounds o; if(matchType(l,1,typeof(UnityEngine.Vector3),typeof(UnityEngine.Vector3))){ UnityEngine.Vector3 a1; checkType(l,1,out a1); UnityEngine.Vector3 a2; checkType(l,2,out a2); o=new UnityEngine.Bounds(a1,a2); pushObject(l,o); return 1; } return 0; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int SetMinMax(IntPtr l) { try{ UnityEngine.Bounds self=checkSelf<UnityEngine.Bounds>(l); UnityEngine.Vector3 a1; checkType(l,2,out a1); UnityEngine.Vector3 a2; checkType(l,3,out a2); self.SetMinMax(a1,a2); setBack(l,self); return 0; } catch(Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int Encapsulate(IntPtr l) { try{ if(matchType(l,2,typeof(UnityEngine.Vector3))){ UnityEngine.Bounds self=checkSelf<UnityEngine.Bounds>(l); UnityEngine.Vector3 a1; checkType(l,2,out a1); self.Encapsulate(a1); setBack(l,self); return 0; } else if(matchType(l,2,typeof(UnityEngine.Bounds))){ UnityEngine.Bounds self=checkSelf<UnityEngine.Bounds>(l); UnityEngine.Bounds a1; checkType(l,2,out a1); self.Encapsulate(a1); setBack(l,self); return 0; } LuaDLL.luaL_error(l,"No matched override function to call"); return 0; } catch(Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int Expand(IntPtr l) { try{ if(matchType(l,2,typeof(System.Single))){ UnityEngine.Bounds self=checkSelf<UnityEngine.Bounds>(l); System.Single a1; checkType(l,2,out a1); self.Expand(a1); setBack(l,self); return 0; } else if(matchType(l,2,typeof(UnityEngine.Vector3))){ UnityEngine.Bounds self=checkSelf<UnityEngine.Bounds>(l); UnityEngine.Vector3 a1; checkType(l,2,out a1); self.Expand(a1); setBack(l,self); return 0; } LuaDLL.luaL_error(l,"No matched override function to call"); return 0; } catch(Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int Intersects(IntPtr l) { try{ UnityEngine.Bounds self=checkSelf<UnityEngine.Bounds>(l); UnityEngine.Bounds a1; checkType(l,2,out a1); System.Boolean ret=self.Intersects(a1); pushValue(l,ret); return 1; } catch(Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int Contains(IntPtr l) { try{ UnityEngine.Bounds self=checkSelf<UnityEngine.Bounds>(l); UnityEngine.Vector3 a1; checkType(l,2,out a1); System.Boolean ret=self.Contains(a1); pushValue(l,ret); return 1; } catch(Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int SqrDistance(IntPtr l) { try{ UnityEngine.Bounds self=checkSelf<UnityEngine.Bounds>(l); UnityEngine.Vector3 a1; checkType(l,2,out a1); System.Single ret=self.SqrDistance(a1); pushValue(l,ret); return 1; } catch(Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int IntersectRay(IntPtr l) { try{ if(matchType(l,2,typeof(UnityEngine.Ray))){ UnityEngine.Bounds self=checkSelf<UnityEngine.Bounds>(l); UnityEngine.Ray a1; checkType(l,2,out a1); System.Boolean ret=self.IntersectRay(a1); pushValue(l,ret); return 1; } else if(matchType(l,2,typeof(UnityEngine.Ray),typeof(System.Single))){ UnityEngine.Bounds self=checkSelf<UnityEngine.Bounds>(l); UnityEngine.Ray a1; checkType(l,2,out a1); System.Single a2; System.Boolean ret=self.IntersectRay(a1,out a2); pushValue(l,ret); pushValue(l,a2); return 2; } LuaDLL.luaL_error(l,"No matched override function to call"); return 0; } catch(Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int op_Equality(IntPtr l) { try{ UnityEngine.Bounds a1; checkType(l,1,out a1); UnityEngine.Bounds a2; checkType(l,2,out a2); System.Boolean ret=(a1==a2); pushValue(l,ret); return 1; } catch(Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int op_Inequality(IntPtr l) { try{ UnityEngine.Bounds a1; checkType(l,1,out a1); UnityEngine.Bounds a2; checkType(l,2,out a2); System.Boolean ret=(a1!=a2); pushValue(l,ret); return 1; } catch(Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_center(IntPtr l) { UnityEngine.Bounds o = checkSelf<UnityEngine.Bounds>(l); pushValue(l,o.center); return 1; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int set_center(IntPtr l) { UnityEngine.Bounds o = checkSelf<UnityEngine.Bounds>(l); UnityEngine.Vector3 v; checkType(l,2,out v); o.center=v; setBack(l,o); return 0; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_size(IntPtr l) { UnityEngine.Bounds o = checkSelf<UnityEngine.Bounds>(l); pushValue(l,o.size); return 1; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int set_size(IntPtr l) { UnityEngine.Bounds o = checkSelf<UnityEngine.Bounds>(l); UnityEngine.Vector3 v; checkType(l,2,out v); o.size=v; setBack(l,o); return 0; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_extents(IntPtr l) { UnityEngine.Bounds o = checkSelf<UnityEngine.Bounds>(l); pushValue(l,o.extents); return 1; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int set_extents(IntPtr l) { UnityEngine.Bounds o = checkSelf<UnityEngine.Bounds>(l); UnityEngine.Vector3 v; checkType(l,2,out v); o.extents=v; setBack(l,o); return 0; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_min(IntPtr l) { UnityEngine.Bounds o = checkSelf<UnityEngine.Bounds>(l); pushValue(l,o.min); return 1; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int set_min(IntPtr l) { UnityEngine.Bounds o = checkSelf<UnityEngine.Bounds>(l); UnityEngine.Vector3 v; checkType(l,2,out v); o.min=v; setBack(l,o); return 0; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_max(IntPtr l) { UnityEngine.Bounds o = checkSelf<UnityEngine.Bounds>(l); pushValue(l,o.max); return 1; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int set_max(IntPtr l) { UnityEngine.Bounds o = checkSelf<UnityEngine.Bounds>(l); UnityEngine.Vector3 v; checkType(l,2,out v); o.max=v; setBack(l,o); return 0; } static public void reg(IntPtr l) { getTypeTable(l,"UnityEngine.Bounds"); addMember(l,SetMinMax, "SetMinMax"); addMember(l,Encapsulate, "Encapsulate"); addMember(l,Expand, "Expand"); addMember(l,Intersects, "Intersects"); addMember(l,Contains, "Contains"); addMember(l,SqrDistance, "SqrDistance"); addMember(l,IntersectRay, "IntersectRay"); addMember(l,op_Equality, "op_Equality"); addMember(l,op_Inequality, "op_Inequality"); addMember(l,get_center, "get_center"); addMember(l,set_center, "set_center"); addMember(l,get_size, "get_size"); addMember(l,set_size, "set_size"); addMember(l,get_extents, "get_extents"); addMember(l,set_extents, "set_extents"); addMember(l,get_min, "get_min"); addMember(l,set_min, "set_min"); addMember(l,get_max, "get_max"); addMember(l,set_max, "set_max"); newType(l, constructor); createTypeMetatable(l, typeof(UnityEngine.Bounds)); LuaDLL.lua_pop(l, 1); } }
idada/slua
Assets/Slua/LuaObject/Lua_UnityEngine_Bounds.cs
C#
mit
8,284
/*! * screenfull * v4.2.0 - 2019-04-01 * (c) Sindre Sorhus; MIT License */ (function () { 'use strict'; var document = typeof window !== 'undefined' && typeof window.document !== 'undefined' ? window.document : {}; var isCommonjs = typeof module !== 'undefined' && module.exports; var keyboardAllowed = typeof Element !== 'undefined' && 'ALLOW_KEYBOARD_INPUT' in Element; var fn = (function () { var val; var fnMap = [ [ 'requestFullscreen', 'exitFullscreen', 'fullscreenElement', 'fullscreenEnabled', 'fullscreenchange', 'fullscreenerror' ], // New WebKit [ 'webkitRequestFullscreen', 'webkitExitFullscreen', 'webkitFullscreenElement', 'webkitFullscreenEnabled', 'webkitfullscreenchange', 'webkitfullscreenerror' ], // Old WebKit (Safari 5.1) [ 'webkitRequestFullScreen', 'webkitCancelFullScreen', 'webkitCurrentFullScreenElement', 'webkitCancelFullScreen', 'webkitfullscreenchange', 'webkitfullscreenerror' ], [ 'mozRequestFullScreen', 'mozCancelFullScreen', 'mozFullScreenElement', 'mozFullScreenEnabled', 'mozfullscreenchange', 'mozfullscreenerror' ], [ 'msRequestFullscreen', 'msExitFullscreen', 'msFullscreenElement', 'msFullscreenEnabled', 'MSFullscreenChange', 'MSFullscreenError' ] ]; var i = 0; var l = fnMap.length; var ret = {}; for (; i < l; i++) { val = fnMap[i]; if (val && val[1] in document) { for (i = 0; i < val.length; i++) { ret[fnMap[0][i]] = val[i]; } return ret; } } return false; })(); var eventNameMap = { change: fn.fullscreenchange, error: fn.fullscreenerror }; var screenfull = { request: function (elem) { return new Promise(function (resolve) { var request = fn.requestFullscreen; var onFullScreenEntered = function () { this.off('change', onFullScreenEntered); resolve(); }.bind(this); elem = elem || document.documentElement; // Work around Safari 5.1 bug: reports support for // keyboard in fullscreen even though it doesn't. // Browser sniffing, since the alternative with // setTimeout is even worse. if (/ Version\/5\.1(?:\.\d+)? Safari\//.test(navigator.userAgent)) { elem[request](); } else { elem[request](keyboardAllowed ? Element.ALLOW_KEYBOARD_INPUT : {}); } this.on('change', onFullScreenEntered); }.bind(this)); }, exit: function () { return new Promise(function (resolve) { if (!this.isFullscreen) { resolve(); return; } var onFullScreenExit = function () { this.off('change', onFullScreenExit); resolve(); }.bind(this); document[fn.exitFullscreen](); this.on('change', onFullScreenExit); }.bind(this)); }, toggle: function (elem) { return this.isFullscreen ? this.exit() : this.request(elem); }, onchange: function (callback) { this.on('change', callback); }, onerror: function (callback) { this.on('error', callback); }, on: function (event, callback) { var eventName = eventNameMap[event]; if (eventName) { document.addEventListener(eventName, callback, false); } }, off: function (event, callback) { var eventName = eventNameMap[event]; if (eventName) { document.removeEventListener(eventName, callback, false); } }, raw: fn }; if (!fn) { if (isCommonjs) { module.exports = false; } else { window.screenfull = false; } return; } Object.defineProperties(screenfull, { isFullscreen: { get: function () { return Boolean(document[fn.fullscreenElement]); } }, element: { enumerable: true, get: function () { return document[fn.fullscreenElement]; } }, enabled: { enumerable: true, get: function () { // Coerce to boolean in case of old WebKit return Boolean(document[fn.fullscreenEnabled]); } } }); if (isCommonjs) { module.exports = screenfull; // TODO: remove this in the next major version module.exports.default = screenfull; } else { window.screenfull = screenfull; } })();
quindar/quindar-ux
public/scripts/screenfull.js
JavaScript
mit
4,129
class ExitStatus < Spinach::FeatureSteps feature "Exit status" include Integration::SpinachRunner Given "I have a feature that has no error or failure" do @feature = Integration::FeatureGenerator.success_feature end Given "I have a feature that has a failure" do @feature = Integration::FeatureGenerator.failure_feature end When "I run it" do run_feature @feature end Then "the exit status should be 0" do @last_exit_status.success?.must_equal true end Then "the exit status should be 1" do @last_exit_status.success?.must_equal false end end
alkuzad/spinach
features/steps/exit_status.rb
Ruby
mit
594
require 'rails/version' require 'rails/generators/rails/scaffold_controller/scaffold_controller_generator' module Rails module Generators class StrongParametersControllerGenerator < ScaffoldControllerGenerator argument :attributes, :type => :array, :default => [], :banner => "field:type field:type" source_root File.expand_path("../templates", __FILE__) if ::Rails::VERSION::STRING < '3.1' def module_namespacing yield if block_given? end end end end end
begriffs/strong_parameters
lib/generators/rails/strong_parameters_controller_generator.rb
Ruby
mit
520
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ package org.apache.poi.hssf.usermodel; /** * Represents a simple shape such as a line, rectangle or oval. * * @author Glen Stampoultzis (glens at apache.org) */ public class HSSFSimpleShape extends HSSFShape { // The commented out ones haven't been tested yet or aren't supported // by HSSFSimpleShape. public final static short OBJECT_TYPE_LINE = 1; public final static short OBJECT_TYPE_RECTANGLE = 2; public final static short OBJECT_TYPE_OVAL = 3; // public final static short OBJECT_TYPE_ARC = 4; // public final static short OBJECT_TYPE_CHART = 5; // public final static short OBJECT_TYPE_TEXT = 6; // public final static short OBJECT_TYPE_BUTTON = 7; public final static short OBJECT_TYPE_PICTURE = 8; // public final static short OBJECT_TYPE_POLYGON = 9; // public final static short OBJECT_TYPE_CHECKBOX = 11; // public final static short OBJECT_TYPE_OPTION_BUTTON = 12; // public final static short OBJECT_TYPE_EDIT_BOX = 13; // public final static short OBJECT_TYPE_LABEL = 14; // public final static short OBJECT_TYPE_DIALOG_BOX = 15; // public final static short OBJECT_TYPE_SPINNER = 16; // public final static short OBJECT_TYPE_SCROLL_BAR = 17; // public final static short OBJECT_TYPE_LIST_BOX = 18; // public final static short OBJECT_TYPE_GROUP_BOX = 19; // public final static short OBJECT_TYPE_COMBO_BOX = 20; public final static short OBJECT_TYPE_COMMENT = 25; // public final static short OBJECT_TYPE_MICROSOFT_OFFICE_DRAWING = 30; int shapeType = OBJECT_TYPE_LINE; HSSFSimpleShape( HSSFShape parent, HSSFAnchor anchor ) { super( parent, anchor ); } /** * Gets the shape type. * @return One of the OBJECT_TYPE_* constants. * * @see #OBJECT_TYPE_LINE * @see #OBJECT_TYPE_OVAL * @see #OBJECT_TYPE_RECTANGLE * @see #OBJECT_TYPE_PICTURE * @see #OBJECT_TYPE_COMMENT */ public int getShapeType() { return shapeType; } /** * Sets the shape types. * * @param shapeType One of the OBJECT_TYPE_* constants. * * @see #OBJECT_TYPE_LINE * @see #OBJECT_TYPE_OVAL * @see #OBJECT_TYPE_RECTANGLE * @see #OBJECT_TYPE_PICTURE * @see #OBJECT_TYPE_COMMENT */ public void setShapeType( int shapeType ){ this.shapeType = shapeType; } }
tobyclemson/msci-project
vendor/poi-3.6/src/java/org/apache/poi/hssf/usermodel/HSSFSimpleShape.java
Java
mit
3,641
// Generated by LiveScript 1.5.0 var onmessage, this$ = this; function addEventListener(event, cb){ return this.thread.on(event, cb); } function close(){ return this.thread.emit('close'); } function importScripts(){ var i$, len$, p, results$ = []; for (i$ = 0, len$ = (arguments).length; i$ < len$; ++i$) { p = (arguments)[i$]; results$.push(self.eval(native_fs_.readFileSync(p, 'utf8'))); } return results$; } onmessage = null; thread.on('message', function(args){ return typeof onmessage == 'function' ? onmessage(args) : void 8; });
romainmnr/chatboteseo
node_modules/webworker-threads/src/load.js
JavaScript
mit
558
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@zend.com so we can send you a copy immediately. * * @category Zend * @package Zend_Form * @subpackage Decorator * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ /** * @namespace */ namespace Zend\Form\Decorator\Captcha; use Zend\Form\Decorator\AbstractDecorator; /** * Word-based captcha decorator * * Adds hidden field for ID and text input field for captcha text * * @uses \Zend\Form\Decorator\AbstractDecorator * @category Zend * @package Zend_Form * @subpackage Element * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Word extends AbstractDecorator { /** * Render captcha * * @param string $content * @return string */ public function render($content) { $element = $this->getElement(); $view = $element->getView(); if (null === $view) { return $content; } $name = $element->getFullyQualifiedName(); $hiddenName = $name . '[id]'; $textName = $name . '[input]'; $label = $element->getDecorator("Label"); if($label) { $label->setOption("id", $element->getId()."-input"); } $placement = $this->getPlacement(); $separator = $this->getSeparator(); $hidden = $view->formHidden($hiddenName, $element->getValue(), $element->getAttribs()); $text = $view->formText($textName, '', $element->getAttribs()); switch ($placement) { case 'PREPEND': $content = $hidden . $separator . $text . $separator . $content; break; case 'APPEND': default: $content = $content . $separator . $hidden . $separator . $text; } return $content; } }
phphatesme/LiveTest
src/lib/Zend/Form/Decorator/Captcha/Word.php
PHP
mit
2,410
package com.laytonsmith.abstraction.entities; import com.laytonsmith.abstraction.MCEntity; import com.laytonsmith.abstraction.MCLivingEntity; public interface MCEvokerFangs extends MCEntity { MCLivingEntity getOwner(); void setOwner(MCLivingEntity owner); }
sk89q/CommandHelper
src/main/java/com/laytonsmith/abstraction/entities/MCEvokerFangs.java
Java
mit
262
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Bundle\FrameworkBundle\Command; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Exception\InvalidArgumentException; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Style\SymfonyStyle; use Symfony\Component\HttpKernel\KernelInterface; use Symfony\Component\Translation\Catalogue\MergeOperation; use Symfony\Component\Translation\DataCollectorTranslator; use Symfony\Component\Translation\Extractor\ExtractorInterface; use Symfony\Component\Translation\LoggingTranslator; use Symfony\Component\Translation\MessageCatalogue; use Symfony\Component\Translation\Reader\TranslationReaderInterface; use Symfony\Component\Translation\Translator; use Symfony\Component\Translation\TranslatorInterface as LegacyTranslatorInterface; use Symfony\Contracts\Translation\TranslatorInterface; /** * Helps finding unused or missing translation messages in a given locale * and comparing them with the fallback ones. * * @author Florian Voutzinos <florian@voutzinos.com> * * @final */ class TranslationDebugCommand extends Command { const MESSAGE_MISSING = 0; const MESSAGE_UNUSED = 1; const MESSAGE_EQUALS_FALLBACK = 2; protected static $defaultName = 'debug:translation'; private $translator; private $reader; private $extractor; private $defaultTransPath; private $defaultViewsPath; private $transPaths; private $viewsPaths; /** * @param TranslatorInterface $translator */ public function __construct($translator, TranslationReaderInterface $reader, ExtractorInterface $extractor, string $defaultTransPath = null, string $defaultViewsPath = null, array $transPaths = [], array $viewsPaths = []) { if (!$translator instanceof LegacyTranslatorInterface && !$translator instanceof TranslatorInterface) { throw new \TypeError(sprintf('Argument 1 passed to %s() must be an instance of %s, %s given.', __METHOD__, TranslatorInterface::class, \is_object($translator) ? \get_class($translator) : \gettype($translator))); } parent::__construct(); $this->translator = $translator; $this->reader = $reader; $this->extractor = $extractor; $this->defaultTransPath = $defaultTransPath; $this->defaultViewsPath = $defaultViewsPath; $this->transPaths = $transPaths; $this->viewsPaths = $viewsPaths; } /** * {@inheritdoc} */ protected function configure() { $this ->setDefinition([ new InputArgument('locale', InputArgument::REQUIRED, 'The locale'), new InputArgument('bundle', InputArgument::OPTIONAL, 'The bundle name or directory where to load the messages'), new InputOption('domain', null, InputOption::VALUE_OPTIONAL, 'The messages domain'), new InputOption('only-missing', null, InputOption::VALUE_NONE, 'Displays only missing messages'), new InputOption('only-unused', null, InputOption::VALUE_NONE, 'Displays only unused messages'), new InputOption('all', null, InputOption::VALUE_NONE, 'Load messages from all registered bundles'), ]) ->setDescription('Displays translation messages information') ->setHelp(<<<'EOF' The <info>%command.name%</info> command helps finding unused or missing translation messages and comparing them with the fallback ones by inspecting the templates and translation files of a given bundle or the default translations directory. You can display information about bundle translations in a specific locale: <info>php %command.full_name% en AcmeDemoBundle</info> You can also specify a translation domain for the search: <info>php %command.full_name% --domain=messages en AcmeDemoBundle</info> You can only display missing messages: <info>php %command.full_name% --only-missing en AcmeDemoBundle</info> You can only display unused messages: <info>php %command.full_name% --only-unused en AcmeDemoBundle</info> You can display information about application translations in a specific locale: <info>php %command.full_name% en</info> You can display information about translations in all registered bundles in a specific locale: <info>php %command.full_name% --all en</info> EOF ) ; } /** * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $io = new SymfonyStyle($input, $output); $locale = $input->getArgument('locale'); $domain = $input->getOption('domain'); /** @var KernelInterface $kernel */ $kernel = $this->getApplication()->getKernel(); $rootDir = $kernel->getContainer()->getParameter('kernel.root_dir'); // Define Root Paths $transPaths = $this->transPaths; if (is_dir($dir = $rootDir.'/Resources/translations')) { if ($dir !== $this->defaultTransPath) { $notice = sprintf('Storing translations in the "%s" directory is deprecated since Symfony 4.2, ', $dir); @trigger_error($notice.($this->defaultTransPath ? sprintf('use the "%s" directory instead.', $this->defaultTransPath) : 'configure and use "framework.translator.default_path" instead.'), E_USER_DEPRECATED); } $transPaths[] = $dir; } if ($this->defaultTransPath) { $transPaths[] = $this->defaultTransPath; } $viewsPaths = $this->viewsPaths; if (is_dir($dir = $rootDir.'/Resources/views')) { if ($dir !== $this->defaultViewsPath) { $notice = sprintf('Loading Twig templates from the "%s" directory is deprecated since Symfony 4.2, ', $dir); @trigger_error($notice.($this->defaultViewsPath ? sprintf('use the "%s" directory instead.', $this->defaultViewsPath) : 'configure and use "twig.default_path" instead.'), E_USER_DEPRECATED); } $viewsPaths[] = $dir; } if ($this->defaultViewsPath) { $viewsPaths[] = $this->defaultViewsPath; } // Override with provided Bundle info if (null !== $input->getArgument('bundle')) { try { $bundle = $kernel->getBundle($input->getArgument('bundle')); $transPaths = [$bundle->getPath().'/Resources/translations']; if ($this->defaultTransPath) { $transPaths[] = $this->defaultTransPath; } if (is_dir($dir = sprintf('%s/Resources/%s/translations', $rootDir, $bundle->getName()))) { $transPaths[] = $dir; $notice = sprintf('Storing translations files for "%s" in the "%s" directory is deprecated since Symfony 4.2, ', $dir, $bundle->getName()); @trigger_error($notice.($this->defaultTransPath ? sprintf('use the "%s" directory instead.', $this->defaultTransPath) : 'configure and use "framework.translator.default_path" instead.'), E_USER_DEPRECATED); } $viewsPaths = [$bundle->getPath().'/Resources/views']; if ($this->defaultViewsPath) { $viewsPaths[] = $this->defaultViewsPath; } if (is_dir($dir = sprintf('%s/Resources/%s/views', $rootDir, $bundle->getName()))) { $viewsPaths[] = $dir; $notice = sprintf('Loading Twig templates for "%s" from the "%s" directory is deprecated since Symfony 4.2, ', $bundle->getName(), $dir); @trigger_error($notice.($this->defaultViewsPath ? sprintf('use the "%s" directory instead.', $this->defaultViewsPath) : 'configure and use "twig.default_path" instead.'), E_USER_DEPRECATED); } } catch (\InvalidArgumentException $e) { // such a bundle does not exist, so treat the argument as path $path = $input->getArgument('bundle'); $transPaths = [$path.'/translations']; if (is_dir($dir = $path.'/Resources/translations')) { if ($dir !== $this->defaultTransPath) { @trigger_error(sprintf('Storing translations in the "%s" directory is deprecated since Symfony 4.2, use the "%s" directory instead.', $dir, $path.'/translations'), E_USER_DEPRECATED); } $transPaths[] = $dir; } $viewsPaths = [$path.'/templates']; if (is_dir($dir = $path.'/Resources/views')) { if ($dir !== $this->defaultViewsPath) { @trigger_error(sprintf('Loading Twig templates from the "%s" directory is deprecated since Symfony 4.2, use the "%s" directory instead.', $dir, $path.'/templates'), E_USER_DEPRECATED); } $viewsPaths[] = $dir; } if (!is_dir($transPaths[0]) && !isset($transPaths[1])) { throw new InvalidArgumentException(sprintf('"%s" is neither an enabled bundle nor a directory.', $transPaths[0])); } } } elseif ($input->getOption('all')) { foreach ($kernel->getBundles() as $bundle) { $transPaths[] = $bundle->getPath().'/Resources/translations'; if (is_dir($deprecatedPath = sprintf('%s/Resources/%s/translations', $rootDir, $bundle->getName()))) { $transPaths[] = $deprecatedPath; $notice = sprintf('Storing translations files for "%s" in the "%s" directory is deprecated since Symfony 4.2, ', $bundle->getName(), $deprecatedPath); @trigger_error($notice.($this->defaultTransPath ? sprintf('use the "%s" directory instead.', $this->defaultTransPath) : 'configure and use "framework.translator.default_path" instead.'), E_USER_DEPRECATED); } $viewsPaths[] = $bundle->getPath().'/Resources/views'; if (is_dir($deprecatedPath = sprintf('%s/Resources/%s/views', $rootDir, $bundle->getName()))) { $viewsPaths[] = $deprecatedPath; $notice = sprintf('Loading Twig templates for "%s" from the "%s" directory is deprecated since Symfony 4.2, ', $bundle->getName(), $deprecatedPath); @trigger_error($notice.($this->defaultViewsPath ? sprintf('use the "%s" directory instead.', $this->defaultViewsPath) : 'configure and use "twig.default_path" instead.'), E_USER_DEPRECATED); } } } // Extract used messages $extractedCatalogue = $this->extractMessages($locale, $viewsPaths); // Load defined messages $currentCatalogue = $this->loadCurrentMessages($locale, $transPaths); // Merge defined and extracted messages to get all message ids $mergeOperation = new MergeOperation($extractedCatalogue, $currentCatalogue); $allMessages = $mergeOperation->getResult()->all($domain); if (null !== $domain) { $allMessages = [$domain => $allMessages]; } // No defined or extracted messages if (empty($allMessages) || null !== $domain && empty($allMessages[$domain])) { $outputMessage = sprintf('No defined or extracted messages for locale "%s"', $locale); if (null !== $domain) { $outputMessage .= sprintf(' and domain "%s"', $domain); } $io->getErrorStyle()->warning($outputMessage); return; } // Load the fallback catalogues $fallbackCatalogues = $this->loadFallbackCatalogues($locale, $transPaths); // Display header line $headers = ['State', 'Domain', 'Id', sprintf('Message Preview (%s)', $locale)]; foreach ($fallbackCatalogues as $fallbackCatalogue) { $headers[] = sprintf('Fallback Message Preview (%s)', $fallbackCatalogue->getLocale()); } $rows = []; // Iterate all message ids and determine their state foreach ($allMessages as $domain => $messages) { foreach (array_keys($messages) as $messageId) { $value = $currentCatalogue->get($messageId, $domain); $states = []; if ($extractedCatalogue->defines($messageId, $domain)) { if (!$currentCatalogue->defines($messageId, $domain)) { $states[] = self::MESSAGE_MISSING; } } elseif ($currentCatalogue->defines($messageId, $domain)) { $states[] = self::MESSAGE_UNUSED; } if (!\in_array(self::MESSAGE_UNUSED, $states) && true === $input->getOption('only-unused') || !\in_array(self::MESSAGE_MISSING, $states) && true === $input->getOption('only-missing')) { continue; } foreach ($fallbackCatalogues as $fallbackCatalogue) { if ($fallbackCatalogue->defines($messageId, $domain) && $value === $fallbackCatalogue->get($messageId, $domain)) { $states[] = self::MESSAGE_EQUALS_FALLBACK; break; } } $row = [$this->formatStates($states), $domain, $this->formatId($messageId), $this->sanitizeString($value)]; foreach ($fallbackCatalogues as $fallbackCatalogue) { $row[] = $this->sanitizeString($fallbackCatalogue->get($messageId, $domain)); } $rows[] = $row; } } $io->table($headers, $rows); } private function formatState($state): string { if (self::MESSAGE_MISSING === $state) { return '<error> missing </error>'; } if (self::MESSAGE_UNUSED === $state) { return '<comment> unused </comment>'; } if (self::MESSAGE_EQUALS_FALLBACK === $state) { return '<info> fallback </info>'; } return $state; } private function formatStates(array $states): string { $result = []; foreach ($states as $state) { $result[] = $this->formatState($state); } return implode(' ', $result); } private function formatId(string $id): string { return sprintf('<fg=cyan;options=bold>%s</>', $id); } private function sanitizeString(string $string, int $length = 40): string { $string = trim(preg_replace('/\s+/', ' ', $string)); if (false !== $encoding = mb_detect_encoding($string, null, true)) { if (mb_strlen($string, $encoding) > $length) { return mb_substr($string, 0, $length - 3, $encoding).'...'; } } elseif (\strlen($string) > $length) { return substr($string, 0, $length - 3).'...'; } return $string; } private function extractMessages(string $locale, array $transPaths): MessageCatalogue { $extractedCatalogue = new MessageCatalogue($locale); foreach ($transPaths as $path) { if (is_dir($path) || is_file($path)) { $this->extractor->extract($path, $extractedCatalogue); } } return $extractedCatalogue; } private function loadCurrentMessages(string $locale, array $transPaths): MessageCatalogue { $currentCatalogue = new MessageCatalogue($locale); foreach ($transPaths as $path) { if (is_dir($path)) { $this->reader->read($path, $currentCatalogue); } } return $currentCatalogue; } /** * @return MessageCatalogue[] */ private function loadFallbackCatalogues(string $locale, array $transPaths): array { $fallbackCatalogues = []; if ($this->translator instanceof Translator || $this->translator instanceof DataCollectorTranslator || $this->translator instanceof LoggingTranslator) { foreach ($this->translator->getFallbackLocales() as $fallbackLocale) { if ($fallbackLocale === $locale) { continue; } $fallbackCatalogue = new MessageCatalogue($fallbackLocale); foreach ($transPaths as $path) { if (is_dir($path)) { $this->reader->read($path, $fallbackCatalogue); } } $fallbackCatalogues[] = $fallbackCatalogue; } } return $fallbackCatalogues; } }
curry684/symfony
src/Symfony/Bundle/FrameworkBundle/Command/TranslationDebugCommand.php
PHP
mit
17,092
module.exports = { "env": { "browser": true }, "plugins": [ "callback-function" ], "globals": { "_": true, "$": true, "ActErr": true, "async": true, "config": true, "logger": true, "moment": true, "respondWithError": true, "sendJSONResponse": true, "util": true, "admiral": true }, "extends": "airbnb-base/legacy", "rules": { // rules to override from airbnb/legacy "object-curly-spacing": ["error", "never"], "curly": ["error", "multi", "consistent"], "no-param-reassign": ["error", { "props": false }], "no-underscore-dangle": ["error", { "allow": ["_r", "_p"] }], "quote-props": ["error", "consistent-as-needed"], // rules from airbnb that we won't be using "consistent-return": 0, "default-case": 0, "func-names": 0, "no-plusplus": 0, "no-use-before-define": 0, "vars-on-top": 0, "no-loop-func": 0, "no-underscore-dangle": 0, "no-param-reassign": 0, "one-var-declaration-per-line": 0, "one-var": 0, "no-multi-assign": 0, "global-require": 0, // extra rules not present in airbnb "max-len": ["error", 80], } };
himanshu0503/admiral
.eslintrc.js
JavaScript
mit
1,174
// // Copyright (c) 2008-2011, Kenneth Bell // // 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 DiscUtils.Vmdk { using System; using System.IO; using System.IO.Compression; /// <summary> /// Represents and extent from a sparse disk from 'hosted' software (VMware Workstation, etc). /// </summary> /// <remarks>Hosted disks and server disks (ESX, etc) are subtly different formats.</remarks> internal sealed class HostedSparseExtentStream : CommonSparseExtentStream { private HostedSparseExtentHeader _hostedHeader; public HostedSparseExtentStream(Stream file, Ownership ownsFile, long diskOffset, SparseStream parentDiskStream, Ownership ownsParentDiskStream) { _fileStream = file; _ownsFileStream = ownsFile; _diskOffset = diskOffset; _parentDiskStream = parentDiskStream; _ownsParentDiskStream = ownsParentDiskStream; file.Position = 0; byte[] headerSector = Utilities.ReadFully(file, Sizes.Sector); _hostedHeader = HostedSparseExtentHeader.Read(headerSector, 0); if (_hostedHeader.GdOffset == -1) { // Fall back to secondary copy that (should) be at the end of the stream, just before the end-of-stream sector marker file.Position = file.Length - Sizes.OneKiB; headerSector = Utilities.ReadFully(file, Sizes.Sector); _hostedHeader = HostedSparseExtentHeader.Read(headerSector, 0); if (_hostedHeader.MagicNumber != HostedSparseExtentHeader.VmdkMagicNumber) { throw new IOException("Unable to locate valid VMDK header or footer"); } } _header = _hostedHeader; if (_hostedHeader.CompressAlgorithm != 0 && _hostedHeader.CompressAlgorithm != 1) { throw new NotSupportedException("Only uncompressed and DEFLATE compressed disks supported"); } _gtCoverage = _header.NumGTEsPerGT * _header.GrainSize * Sizes.Sector; LoadGlobalDirectory(); } public override bool CanWrite { get { // No write support for streamOptimized disks return _fileStream.CanWrite && (_hostedHeader.Flags & (HostedSparseExtentFlags.CompressedGrains | HostedSparseExtentFlags.MarkersInUse)) == 0; } } public override void Write(byte[] buffer, int offset, int count) { CheckDisposed(); if (!CanWrite) { throw new InvalidOperationException("Cannot write to this stream"); } if (_position + count > Length) { throw new IOException("Attempt to write beyond end of stream"); } int totalWritten = 0; while (totalWritten < count) { int grainTable = (int)(_position / _gtCoverage); int grainTableOffset = (int)(_position - (grainTable * _gtCoverage)); LoadGrainTable(grainTable); int grainSize = (int)(_header.GrainSize * Sizes.Sector); int grain = grainTableOffset / grainSize; int grainOffset = grainTableOffset - (grain * grainSize); if (GetGrainTableEntry(grain) == 0) { AllocateGrain(grainTable, grain); } int numToWrite = Math.Min(count - totalWritten, grainSize - grainOffset); _fileStream.Position = (((long)GetGrainTableEntry(grain)) * Sizes.Sector) + grainOffset; _fileStream.Write(buffer, offset + totalWritten, numToWrite); _position += numToWrite; totalWritten += numToWrite; } _atEof = _position == Length; } protected override int ReadGrain(byte[] buffer, int bufferOffset, long grainStart, int grainOffset, int numToRead) { if ((_hostedHeader.Flags & HostedSparseExtentFlags.CompressedGrains) != 0) { _fileStream.Position = grainStart; byte[] readBuffer = Utilities.ReadFully(_fileStream, CompressedGrainHeader.Size); CompressedGrainHeader hdr = new CompressedGrainHeader(); hdr.Read(readBuffer, 0); readBuffer = Utilities.ReadFully(_fileStream, hdr.DataSize); // This is really a zlib stream, so has header and footer. We ignore this right now, but we sanity // check against expected header values... ushort header = Utilities.ToUInt16BigEndian(readBuffer, 0); if ((header % 31) != 0) { throw new IOException("Invalid ZLib header found"); } if ((header & 0x0F00) != (8 << 8)) { throw new NotSupportedException("ZLib compression not using DEFLATE algorithm"); } if ((header & 0x0020) != 0) { throw new NotSupportedException("ZLib compression using preset dictionary"); } Stream readStream = new MemoryStream(readBuffer, 2, hdr.DataSize - 2, false); DeflateStream deflateStream = new DeflateStream(readStream, CompressionMode.Decompress); // Need to skip some bytes, but DefaultStream doesn't support seeking... Utilities.ReadFully(deflateStream, grainOffset); return deflateStream.Read(buffer, bufferOffset, numToRead); } else { return base.ReadGrain(buffer, bufferOffset, grainStart, grainOffset, numToRead); } } protected override StreamExtent MapGrain(long grainStart, int grainOffset, int numToRead) { if ((_hostedHeader.Flags & HostedSparseExtentFlags.CompressedGrains) != 0) { _fileStream.Position = grainStart; byte[] readBuffer = Utilities.ReadFully(_fileStream, CompressedGrainHeader.Size); CompressedGrainHeader hdr = new CompressedGrainHeader(); hdr.Read(readBuffer, 0); return new StreamExtent(grainStart + grainOffset, CompressedGrainHeader.Size + hdr.DataSize); } else { return base.MapGrain(grainStart, grainOffset, numToRead); } } protected override void LoadGlobalDirectory() { base.LoadGlobalDirectory(); if ((_hostedHeader.Flags & HostedSparseExtentFlags.RedundantGrainTable) != 0) { int numGTs = (int)Utilities.Ceil(_header.Capacity * Sizes.Sector, _gtCoverage); _redundantGlobalDirectory = new uint[numGTs]; _fileStream.Position = _hostedHeader.RgdOffset * Sizes.Sector; byte[] gdAsBytes = Utilities.ReadFully(_fileStream, numGTs * 4); for (int i = 0; i < _globalDirectory.Length; ++i) { _redundantGlobalDirectory[i] = Utilities.ToUInt32LittleEndian(gdAsBytes, i * 4); } } } private void AllocateGrain(int grainTable, int grain) { // Calculate start pos for new grain long grainStartPos = Utilities.RoundUp(_fileStream.Length, _header.GrainSize * Sizes.Sector); // Copy-on-write semantics, read the bytes from parent and write them out to this extent. _parentDiskStream.Position = _diskOffset + ((grain + (_header.NumGTEsPerGT * (long)grainTable)) * _header.GrainSize * Sizes.Sector); byte[] content = Utilities.ReadFully(_parentDiskStream, (int)_header.GrainSize * Sizes.Sector); _fileStream.Position = grainStartPos; _fileStream.Write(content, 0, content.Length); LoadGrainTable(grainTable); SetGrainTableEntry(grain, (uint)(grainStartPos / Sizes.Sector)); WriteGrainTable(); } private void WriteGrainTable() { if (_grainTable == null) { throw new InvalidOperationException("No grain table loaded"); } _fileStream.Position = _globalDirectory[_currentGrainTable] * (long)Sizes.Sector; _fileStream.Write(_grainTable, 0, _grainTable.Length); if (_redundantGlobalDirectory != null) { _fileStream.Position = _redundantGlobalDirectory[_currentGrainTable] * (long)Sizes.Sector; _fileStream.Write(_grainTable, 0, _grainTable.Length); } } } }
breezechen/DiscUtils
src/Vmdk/HostedSparseExtentStream.cs
C#
mit
10,139
<?php return [ 'Names' => [ 'Africa/Abidjan' => 'Waktu Greenwich (Abidjan)', 'Africa/Accra' => 'Waktu Greenwich (Accra)', 'Africa/Algiers' => 'Waktu Éropa Tengah (Algiers)', 'Africa/Bamako' => 'Waktu Greenwich (Bamako)', 'Africa/Banjul' => 'Waktu Greenwich (Banjul)', 'Africa/Bissau' => 'Waktu Greenwich (Bissau)', 'Africa/Cairo' => 'Waktu Éropa Timur (Cairo)', 'Africa/Casablanca' => 'Waktu Éropa Barat (Casablanca)', 'Africa/Ceuta' => 'Waktu Éropa Tengah (Ceuta)', 'Africa/Conakry' => 'Waktu Greenwich (Conakry)', 'Africa/Dakar' => 'Waktu Greenwich (Dakar)', 'Africa/El_Aaiun' => 'Waktu Éropa Barat (El Aaiun)', 'Africa/Freetown' => 'Waktu Greenwich (Freetown)', 'Africa/Lome' => 'Waktu Greenwich (Lome)', 'Africa/Monrovia' => 'Waktu Greenwich (Monrovia)', 'Africa/Nouakchott' => 'Waktu Greenwich (Nouakchott)', 'Africa/Ouagadougou' => 'Waktu Greenwich (Ouagadougou)', 'Africa/Sao_Tome' => 'Waktu Greenwich (Sao Tome)', 'Africa/Tripoli' => 'Waktu Éropa Timur (Tripoli)', 'Africa/Tunis' => 'Waktu Éropa Tengah (Tunis)', 'America/Adak' => 'Amérika Sarikat (Adak)', 'America/Anchorage' => 'Amérika Sarikat (Anchorage)', 'America/Anguilla' => 'Waktu Atlantik (Anguilla)', 'America/Antigua' => 'Waktu Atlantik (Antigua)', 'America/Araguaina' => 'Brasil (Araguaina)', 'America/Aruba' => 'Waktu Atlantik (Aruba)', 'America/Bahia' => 'Brasil (Bahia)', 'America/Bahia_Banderas' => 'Waktu Tengah (Bahia Banderas)', 'America/Barbados' => 'Waktu Atlantik (Barbados)', 'America/Belem' => 'Brasil (Belem)', 'America/Belize' => 'Waktu Tengah (Belize)', 'America/Blanc-Sablon' => 'Waktu Atlantik (Blanc-Sablon)', 'America/Boa_Vista' => 'Brasil (Boa Vista)', 'America/Bogota' => 'Waktu Kolombia (Bogota)', 'America/Boise' => 'Waktu Pagunungan (Boise)', 'America/Cambridge_Bay' => 'Waktu Pagunungan (Cambridge Bay)', 'America/Campo_Grande' => 'Brasil (Campo Grande)', 'America/Cancun' => 'Waktu Wétan (Cancun)', 'America/Cayman' => 'Waktu Wétan (Cayman)', 'America/Chicago' => 'Waktu Tengah (Chicago)', 'America/Coral_Harbour' => 'Waktu Wétan (Atikokan)', 'America/Costa_Rica' => 'Waktu Tengah (Costa Rica)', 'America/Creston' => 'Waktu Pagunungan (Creston)', 'America/Cuiaba' => 'Brasil (Cuiaba)', 'America/Curacao' => 'Waktu Atlantik (Curacao)', 'America/Danmarkshavn' => 'Waktu Greenwich (Danmarkshavn)', 'America/Dawson' => 'Waktu Pagunungan (Dawson)', 'America/Dawson_Creek' => 'Waktu Pagunungan (Dawson Creek)', 'America/Denver' => 'Waktu Pagunungan (Denver)', 'America/Detroit' => 'Waktu Wétan (Detroit)', 'America/Dominica' => 'Waktu Atlantik (Dominica)', 'America/Edmonton' => 'Waktu Pagunungan (Edmonton)', 'America/Eirunepe' => 'Brasil (Eirunepe)', 'America/El_Salvador' => 'Waktu Tengah (El Salvador)', 'America/Fort_Nelson' => 'Waktu Pagunungan (Fort Nelson)', 'America/Fortaleza' => 'Brasil (Fortaleza)', 'America/Glace_Bay' => 'Waktu Atlantik (Glace Bay)', 'America/Goose_Bay' => 'Waktu Atlantik (Goose Bay)', 'America/Grand_Turk' => 'Waktu Wétan (Grand Turk)', 'America/Grenada' => 'Waktu Atlantik (Grenada)', 'America/Guadeloupe' => 'Waktu Atlantik (Guadeloupe)', 'America/Guatemala' => 'Waktu Tengah (Guatemala)', 'America/Halifax' => 'Waktu Atlantik (Halifax)', 'America/Indiana/Knox' => 'Waktu Tengah (Knox, Indiana)', 'America/Indiana/Marengo' => 'Waktu Wétan (Marengo, Indiana)', 'America/Indiana/Petersburg' => 'Waktu Wétan (Petersburg, Indiana)', 'America/Indiana/Tell_City' => 'Waktu Tengah (Tell City, Indiana)', 'America/Indiana/Vevay' => 'Waktu Wétan (Vevay, Indiana)', 'America/Indiana/Vincennes' => 'Waktu Wétan (Vincennes, Indiana)', 'America/Indiana/Winamac' => 'Waktu Wétan (Winamac, Indiana)', 'America/Indianapolis' => 'Waktu Wétan (Indianapolis)', 'America/Inuvik' => 'Waktu Pagunungan (Inuvik)', 'America/Iqaluit' => 'Waktu Wétan (Iqaluit)', 'America/Jamaica' => 'Waktu Wétan (Jamaica)', 'America/Juneau' => 'Amérika Sarikat (Juneau)', 'America/Kentucky/Monticello' => 'Waktu Wétan (Monticello, Kentucky)', 'America/Kralendijk' => 'Waktu Atlantik (Kralendijk)', 'America/Los_Angeles' => 'Waktu Pasifik (Los Angeles)', 'America/Louisville' => 'Waktu Wétan (Louisville)', 'America/Lower_Princes' => 'Waktu Atlantik (Lower Prince’s Quarter)', 'America/Maceio' => 'Brasil (Maceio)', 'America/Managua' => 'Waktu Tengah (Managua)', 'America/Manaus' => 'Brasil (Manaus)', 'America/Marigot' => 'Waktu Atlantik (Marigot)', 'America/Martinique' => 'Waktu Atlantik (Martinique)', 'America/Matamoros' => 'Waktu Tengah (Matamoros)', 'America/Menominee' => 'Waktu Tengah (Menominee)', 'America/Merida' => 'Waktu Tengah (Merida)', 'America/Metlakatla' => 'Amérika Sarikat (Metlakatla)', 'America/Mexico_City' => 'Waktu Tengah (Mexico City)', 'America/Moncton' => 'Waktu Atlantik (Moncton)', 'America/Monterrey' => 'Waktu Tengah (Monterrey)', 'America/Montserrat' => 'Waktu Atlantik (Montserrat)', 'America/Nassau' => 'Waktu Wétan (Nassau)', 'America/New_York' => 'Waktu Wétan (New York)', 'America/Nipigon' => 'Waktu Wétan (Nipigon)', 'America/Nome' => 'Amérika Sarikat (Nome)', 'America/Noronha' => 'Brasil (Noronha)', 'America/North_Dakota/Beulah' => 'Waktu Tengah (Beulah, North Dakota)', 'America/North_Dakota/Center' => 'Waktu Tengah (Center, North Dakota)', 'America/North_Dakota/New_Salem' => 'Waktu Tengah (New Salem, North Dakota)', 'America/Ojinaga' => 'Waktu Pagunungan (Ojinaga)', 'America/Panama' => 'Waktu Wétan (Panama)', 'America/Pangnirtung' => 'Waktu Wétan (Pangnirtung)', 'America/Phoenix' => 'Waktu Pagunungan (Phoenix)', 'America/Port-au-Prince' => 'Waktu Wétan (Port-au-Prince)', 'America/Port_of_Spain' => 'Waktu Atlantik (Port of Spain)', 'America/Porto_Velho' => 'Brasil (Porto Velho)', 'America/Puerto_Rico' => 'Waktu Atlantik (Puerto Rico)', 'America/Rainy_River' => 'Waktu Tengah (Rainy River)', 'America/Rankin_Inlet' => 'Waktu Tengah (Rankin Inlet)', 'America/Recife' => 'Brasil (Recife)', 'America/Regina' => 'Waktu Tengah (Regina)', 'America/Resolute' => 'Waktu Tengah (Resolute)', 'America/Rio_Branco' => 'Brasil (Rio Branco)', 'America/Santarem' => 'Brasil (Santarem)', 'America/Santo_Domingo' => 'Waktu Atlantik (Santo Domingo)', 'America/Sao_Paulo' => 'Brasil (Sao Paulo)', 'America/Sitka' => 'Amérika Sarikat (Sitka)', 'America/St_Barthelemy' => 'Waktu Atlantik (St. Barthelemy)', 'America/St_Kitts' => 'Waktu Atlantik (St. Kitts)', 'America/St_Lucia' => 'Waktu Atlantik (St. Lucia)', 'America/St_Thomas' => 'Waktu Atlantik (St. Thomas)', 'America/St_Vincent' => 'Waktu Atlantik (St. Vincent)', 'America/Swift_Current' => 'Waktu Tengah (Swift Current)', 'America/Tegucigalpa' => 'Waktu Tengah (Tegucigalpa)', 'America/Thule' => 'Waktu Atlantik (Thule)', 'America/Thunder_Bay' => 'Waktu Wétan (Thunder Bay)', 'America/Tijuana' => 'Waktu Pasifik (Tijuana)', 'America/Toronto' => 'Waktu Wétan (Toronto)', 'America/Tortola' => 'Waktu Atlantik (Tortola)', 'America/Vancouver' => 'Waktu Pasifik (Vancouver)', 'America/Whitehorse' => 'Waktu Pagunungan (Whitehorse)', 'America/Winnipeg' => 'Waktu Tengah (Winnipeg)', 'America/Yakutat' => 'Amérika Sarikat (Yakutat)', 'America/Yellowknife' => 'Waktu Pagunungan (Yellowknife)', 'Antarctica/Troll' => 'Waktu Greenwich (Troll)', 'Arctic/Longyearbyen' => 'Waktu Éropa Tengah (Longyearbyen)', 'Asia/Amman' => 'Waktu Éropa Timur (Amman)', 'Asia/Anadyr' => 'Rusia (Anadyr)', 'Asia/Barnaul' => 'Rusia (Barnaul)', 'Asia/Beirut' => 'Waktu Éropa Timur (Beirut)', 'Asia/Calcutta' => 'India (Kolkata)', 'Asia/Chita' => 'Rusia (Chita)', 'Asia/Damascus' => 'Waktu Éropa Timur (Damascus)', 'Asia/Famagusta' => 'Waktu Éropa Timur (Famagusta)', 'Asia/Gaza' => 'Waktu Éropa Timur (Gaza)', 'Asia/Hebron' => 'Waktu Éropa Timur (Hebron)', 'Asia/Irkutsk' => 'Rusia (Irkutsk)', 'Asia/Kamchatka' => 'Rusia (Kamchatka)', 'Asia/Khandyga' => 'Rusia (Khandyga)', 'Asia/Krasnoyarsk' => 'Rusia (Krasnoyarsk)', 'Asia/Magadan' => 'Rusia (Magadan)', 'Asia/Nicosia' => 'Waktu Éropa Timur (Nicosia)', 'Asia/Novokuznetsk' => 'Rusia (Novokuznetsk)', 'Asia/Novosibirsk' => 'Rusia (Novosibirsk)', 'Asia/Omsk' => 'Rusia (Omsk)', 'Asia/Sakhalin' => 'Rusia (Sakhalin)', 'Asia/Shanghai' => 'Tiongkok (Shanghai)', 'Asia/Srednekolymsk' => 'Rusia (Srednekolymsk)', 'Asia/Tokyo' => 'Jepang (Tokyo)', 'Asia/Tomsk' => 'Rusia (Tomsk)', 'Asia/Urumqi' => 'Tiongkok (Urumqi)', 'Asia/Ust-Nera' => 'Rusia (Ust-Nera)', 'Asia/Vladivostok' => 'Rusia (Vladivostok)', 'Asia/Yakutsk' => 'Rusia (Yakutsk)', 'Asia/Yekaterinburg' => 'Rusia (Yekaterinburg)', 'Atlantic/Bermuda' => 'Waktu Atlantik (Bermuda)', 'Atlantic/Canary' => 'Waktu Éropa Barat (Canary)', 'Atlantic/Faeroe' => 'Waktu Éropa Barat (Faroe)', 'Atlantic/Madeira' => 'Waktu Éropa Barat (Madeira)', 'Atlantic/Reykjavik' => 'Waktu Greenwich (Reykjavik)', 'Atlantic/St_Helena' => 'Waktu Greenwich (St. Helena)', 'CST6CDT' => 'Waktu Tengah', 'EST5EDT' => 'Waktu Wétan', 'Etc/GMT' => 'Waktu Greenwich', 'Etc/UTC' => 'Waktu Universal Terkoordinasi', 'Europe/Amsterdam' => 'Waktu Éropa Tengah (Amsterdam)', 'Europe/Andorra' => 'Waktu Éropa Tengah (Andorra)', 'Europe/Astrakhan' => 'Rusia (Astrakhan)', 'Europe/Athens' => 'Waktu Éropa Timur (Athens)', 'Europe/Belgrade' => 'Waktu Éropa Tengah (Belgrade)', 'Europe/Berlin' => 'Waktu Éropa Tengah (Berlin)', 'Europe/Bratislava' => 'Waktu Éropa Tengah (Bratislava)', 'Europe/Brussels' => 'Waktu Éropa Tengah (Brussels)', 'Europe/Bucharest' => 'Waktu Éropa Timur (Bucharest)', 'Europe/Budapest' => 'Waktu Éropa Tengah (Budapest)', 'Europe/Busingen' => 'Waktu Éropa Tengah (Busingen)', 'Europe/Chisinau' => 'Waktu Éropa Timur (Chisinau)', 'Europe/Copenhagen' => 'Waktu Éropa Tengah (Copenhagen)', 'Europe/Dublin' => 'Waktu Greenwich (Dublin)', 'Europe/Gibraltar' => 'Waktu Éropa Tengah (Gibraltar)', 'Europe/Guernsey' => 'Waktu Greenwich (Guernsey)', 'Europe/Helsinki' => 'Waktu Éropa Timur (Helsinki)', 'Europe/Isle_of_Man' => 'Waktu Greenwich (Isle of Man)', 'Europe/Jersey' => 'Waktu Greenwich (Jersey)', 'Europe/Kaliningrad' => 'Waktu Éropa Timur (Kaliningrad)', 'Europe/Kiev' => 'Waktu Éropa Timur (Kiev)', 'Europe/Kirov' => 'Rusia (Kirov)', 'Europe/Lisbon' => 'Waktu Éropa Barat (Lisbon)', 'Europe/Ljubljana' => 'Waktu Éropa Tengah (Ljubljana)', 'Europe/London' => 'Waktu Greenwich (London)', 'Europe/Luxembourg' => 'Waktu Éropa Tengah (Luxembourg)', 'Europe/Madrid' => 'Waktu Éropa Tengah (Madrid)', 'Europe/Malta' => 'Waktu Éropa Tengah (Malta)', 'Europe/Mariehamn' => 'Waktu Éropa Timur (Mariehamn)', 'Europe/Monaco' => 'Waktu Éropa Tengah (Monaco)', 'Europe/Moscow' => 'Rusia (Moscow)', 'Europe/Oslo' => 'Waktu Éropa Tengah (Oslo)', 'Europe/Paris' => 'Waktu Éropa Tengah (Paris)', 'Europe/Podgorica' => 'Waktu Éropa Tengah (Podgorica)', 'Europe/Prague' => 'Waktu Éropa Tengah (Prague)', 'Europe/Riga' => 'Waktu Éropa Timur (Riga)', 'Europe/Rome' => 'Waktu Éropa Tengah (Rome)', 'Europe/Samara' => 'Rusia (Samara)', 'Europe/San_Marino' => 'Waktu Éropa Tengah (San Marino)', 'Europe/Sarajevo' => 'Waktu Éropa Tengah (Sarajevo)', 'Europe/Saratov' => 'Rusia (Saratov)', 'Europe/Skopje' => 'Waktu Éropa Tengah (Skopje)', 'Europe/Sofia' => 'Waktu Éropa Timur (Sofia)', 'Europe/Stockholm' => 'Waktu Éropa Tengah (Stockholm)', 'Europe/Tallinn' => 'Waktu Éropa Timur (Tallinn)', 'Europe/Tirane' => 'Waktu Éropa Tengah (Tirane)', 'Europe/Ulyanovsk' => 'Rusia (Ulyanovsk)', 'Europe/Uzhgorod' => 'Waktu Éropa Timur (Uzhgorod)', 'Europe/Vaduz' => 'Waktu Éropa Tengah (Vaduz)', 'Europe/Vatican' => 'Waktu Éropa Tengah (Vatican)', 'Europe/Vienna' => 'Waktu Éropa Tengah (Vienna)', 'Europe/Vilnius' => 'Waktu Éropa Timur (Vilnius)', 'Europe/Volgograd' => 'Rusia (Volgograd)', 'Europe/Warsaw' => 'Waktu Éropa Tengah (Warsaw)', 'Europe/Zagreb' => 'Waktu Éropa Tengah (Zagreb)', 'Europe/Zaporozhye' => 'Waktu Éropa Timur (Zaporozhye)', 'Europe/Zurich' => 'Waktu Éropa Tengah (Zurich)', 'MST7MDT' => 'Waktu Pagunungan', 'PST8PDT' => 'Waktu Pasifik', 'Pacific/Galapagos' => 'Waktu Galapagos', 'Pacific/Honolulu' => 'Amérika Sarikat (Honolulu)', ], 'Meta' => [ ], ];
Slamdunk/symfony
src/Symfony/Component/Intl/Resources/data/timezones/su.php
PHP
mit
13,893
// textarea‚̍‚‚³‚ðƒ‰ƒCƒu’²ß‚·‚é function adjustTextareaRows(obj, org, plus) { var brlen = null; if (obj.wrap) { if (obj.wrap == 'virtual' || obj.wrap == 'soft') { brlen = obj.cols; } } var aLen = countLines(obj.value, brlen); var aRows = aLen + plus; var move = 0; var scroll = 14; if (org) { if (Math.max(aRows, obj.rows) > org) { move = Math.abs((aRows - obj.rows) * scroll); if (move) { obj.rows = Math.max(org, aRows); window.scrollBy(0, move); } } /* if (aRows > org + plus) { if (obj.rows < aRows) { move = (aRows - obj.rows) * scroll; } else if (obj.rows > aRows) { move = (aRows - obj.rows) * -scroll; } if (move != 0) { if (move < 0) { window.scrollBy(0, move); } obj.rows = aRows; if (move > 0) { window.scrollBy(0, move); } } } */ } else if (obj.rows < aRows) { move = (aRows - obj.rows) * scroll; obj.rows = aRows; window.scrollBy(0, move); } } /** * \n ‚ð‰üs‚Æ‚µ‚čs”‚𐔂¦‚é * * @param integer brlen ‰üs‚·‚é•¶Žš”B–³Žw’è‚È‚ç•¶Žš”‚ʼnüs‚µ‚È‚¢ */ function countLines(str, brlen) { var lines = str.split("\n"); var count = lines.length; var aLen = 0; for (var i = 0; i < lines.length; i++) { aLen = jstrlen(lines[i]); if (brlen) { var adjust = 1.15; // ’PŒê’PˆÊ‚̐܂è•Ô‚µ‚ɑΉž‚µ‚Ä‚¢‚È‚¢‚̂ŃAƒoƒEƒg’²® if ((aLen * adjust) > brlen) { count = count + Math.floor((aLen * adjust) / brlen); } } } return count; } // •¶Žš—ñ‚ðƒoƒCƒg”‚Ő”‚¦‚é function jstrlen(str) { var len = 0; str = escape(str); for (var i = 0; i < str.length; i++, len++) { if (str.charAt(i) == "%") { if (str.charAt(++i) == "u") { i += 3; len++; } i++; } } return len; } // (‘Ώۂªdisable‚łȂ¯‚ê‚Î) ƒtƒH[ƒJƒX‚ð‡‚í‚¹‚é function setFocus(ID){ var obj; if (obj = document.getElementById(ID)) { if (obj.disabled != true) { obj.focus(); } } } // sageƒ`ƒFƒbƒN‚ɍ‡‚킹‚āAƒ[ƒ‹—“‚Ì“à—e‚ð‘‚«Š·‚¦‚é function mailSage(){ var mailran, cbsage; if (cbsage = document.getElementById('sage')) { if (mailran = document.getElementById('mail')) { if (cbsage.checked == true) { mailran.value = "sage"; } else { if (mailran.value == "sage") { mailran.value = ""; } } } } } // ƒ[ƒ‹—“‚Ì“à—e‚ɉž‚¶‚āAsageƒ`ƒFƒbƒN‚ðON OFF‚·‚é function checkSage(){ var mailran, cbsage; if (mailran = document.getElementById('mail')) { if (cbsage = document.getElementById('sage')) { if (mailran.value == "sage") { cbsage.checked = true; } else { cbsage.checked = false; } } } } /* // Ž©“®‚œǂݍž‚Þ‚±‚Ƃɂµ‚½‚̂ŁAŽg‚í‚È‚¢ // ‘O‰ñ‚̏‘‚«ž‚Ý“à—e‚𕜋A‚·‚é function loadLastPosted(from, mail, message){ if (fromran = document.getElementById('FROM')) { fromran.value = from; } if (mailran = document.getElementById('mail')) { mailran.value = mail; } if (messageran = document.getElementById('MESSAGE')) { messageran.value = message; } checkSage(); } */ // ‘‚«ž‚݃{ƒ^ƒ“‚Ì—LŒøE–³Œø‚ðØ‚è‘Ö‚¦‚é function switchBlockSubmit(onoff) { var kakiko_submit = document.getElementById('kakiko_submit'); if (kakiko_submit) { kakiko_submit.disabled = onoff; } var submit_beres = document.getElementById('submit_beres'); if (submit_beres) { submit_beres.disabled = onoff; } } // ’èŒ^•¶‚ð‘}“ü‚·‚é function inputConstant(obj) { var msg = document.getElementById('MESSAGE'); msg.value = msg.value + obj.options[obj.selectedIndex].value; msg.focus(); obj.options[0].selected = true; } // ‘‚«ž‚Ý“à—e‚ðŒŸØ‚·‚é function validateAll(doValidateMsg, doValidateSage) { var block_submit = document.getElementById('block_submit'); if (block_submit && block_submit.checked) { alert('‘‚«ž‚݃uƒƒbƒN’†'); return false; } if (doValidateMsg && !validateMsg()) { return false; } if (doValidateSage && !validateSage()) { return false; } return true; } // –{•¶‚ª‹ó‚łȂ¢‚©ŒŸØ‚·‚é function validateMsg() { if (document.getElementById('MESSAGE').value.length == 0) { alert('–{•¶‚ª‚ ‚è‚Ü‚¹‚ñB'); return false; } return true; } // sage‚Ä‚¢‚é‚©ŒŸØ‚·‚é function validateSage() { if (document.getElementById('mail').value.indexOf('sage') == -1) { if (window.confirm('sage‚Ă܂¹‚ñ‚æH')) { return true; } else { return false; } } return true; } // ˆø”‚Étrue‚ðŽw’肵‚½‚ç–¼–³‚µ‚ŏ‘ž‚·‚é‚©‚Ç‚¤‚©Šm”F‚·‚é function confirmNanashi(doconfirmNanashi) { // ˆø”‚ªtrue‚Å–¼‘O—“‚ª0•¶Žš(–¼–³‚µ)‚È‚ç‚Î if (doconfirmNanashi && document.getElementById('FROM').value.length == 0) { if(window.confirm('‚±‚̔‚͖¼–³‚µ‚É fusianasan ‚ªŠÜ‚Ü‚ê‚Ä‚¢‚Ü‚·B\n–¼–³‚µ‚ŏ‘‚«ž‚݂܂·‚©H')) { return true; } else { return false; } } return true; } //ˆø”‚Étrue‚ðŽw’肵‚½‚ç–¼–³‚µ‚ŏ‘žo—ˆ‚È‚¢ function blockNanashi(blockNanashi) { // ˆø”‚ªtrue‚Å–¼‘O—“‚ª0•¶Žš(–¼–³‚µ)‚È‚ç‚Î if (blockNanashi && document.getElementById('FROM').value.length == 0) { alert('‚±‚̔‚͖¼–³‚µ‚̏‘‚«ž‚Ý‚ª§ŒÀ‚³‚ê‚Ä‚¢‚é‚̂Ŗ¼–³‚µ‚ŏ‘‚«ž‚Þ‚±‚Æ‚ªo—ˆ‚Ü‚¹‚ñB'); return false; } return true; }
okyada/p2-php
rep2/js/post_form.js
JavaScript
mit
4,984
using System; using System.Diagnostics; using System.Globalization; namespace Octokit { /// <summary> /// Used to filter issue comments. /// </summary> [DebuggerDisplay("{DebuggerDisplay,nq}")] public class IssueCommentRequest : RequestParameters { /// <summary> /// Initializes a new instance of the <see cref="IssueCommentRequest"/> class. /// </summary> public IssueCommentRequest() { // Default arguments Sort = PullRequestReviewCommentSort.Created; Direction = SortDirection.Ascending; Since = null; } /// <summary> /// Can be either created or updated. Default: created. /// </summary> public PullRequestReviewCommentSort Sort { get; set; } /// <summary> /// Can be either asc or desc. Default: asc. /// </summary> public SortDirection Direction { get; set; } /// <summary> /// Only comments updated at or after this time are returned. This is a timestamp in ISO 8601 format: YYYY-MM-DDTHH:MM:SSZ. /// </summary> public DateTimeOffset? Since { get; set; } internal string DebuggerDisplay { get { return string.Format(CultureInfo.InvariantCulture, "Sort: {0}, Direction: {1}, Since: {2}", Sort, Direction, Since); } } } }
eriawan/octokit.net
Octokit/Models/Request/IssueCommentRequest.cs
C#
mit
1,391
/******************************************************************************* * Copyright (c) 2014 Salesforce.com, inc.. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Salesforce.com, inc. - initial API and implementation ******************************************************************************/ package com.salesforce.ide.ui.views.log; import static org.mockito.Mockito.mock; import java.io.File; import junit.framework.TestCase; /** * Class to unit test Logview * @author bvenkatesan * */ public class LogViewTest_unit extends TestCase { public void testCheckSpaceInLogEntryBeforeParentheses() throws Exception { String mockMessage = "Unable to get component for id"; File mockFile = mock(File.class); LogEntry mockEntry = mock(LogEntry.class); String TestMessage = new LogView(mockFile).new LogViewLabelProvider().getExceptionMessage(mockMessage, mockEntry); assertTrue(TestMessage.contains(" (Open")); } }
dipakmankumbare/idecore
com.salesforce.ide.ui.test/src/com/salesforce/ide/ui/views/log/LogViewTest_unit.java
Java
epl-1.0
1,175
/** * Copyright (c) 2010-2018 by the respective copyright holders. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.openhab.binding.satel.internal.command; import org.apache.commons.lang.StringUtils; import org.openhab.binding.satel.internal.protocol.SatelMessage; /** * Base class for all commands that return result code in the response. * * @author Krzysztof Goworek - Initial contribution * @since 1.9.0 */ public abstract class ControlCommand extends SatelCommandBase { /** * Creates new command class instance. * * @param commandCode * command code * @param payload */ public ControlCommand(byte commandCode, byte[] payload) { super(commandCode, payload); } @Override protected boolean isResponseValid(SatelMessage response) { return true; } protected static byte[] userCodeToBytes(String userCode) { if (StringUtils.isEmpty(userCode)) { throw new IllegalArgumentException("User code is empty"); } if (userCode.length() > 8) { throw new IllegalArgumentException("User code too long"); } byte[] bytes = new byte[8]; int digitsNbr = 2 * bytes.length; for (int i = 0; i < digitsNbr; ++i) { if (i < userCode.length()) { char digit = userCode.charAt(i); if (!Character.isDigit(digit)) { throw new IllegalArgumentException("User code must contain digits only"); } if (i % 2 == 0) { bytes[i / 2] = (byte) ((digit - '0') << 4); } else { bytes[i / 2] |= (byte) (digit - '0'); } } else if (i % 2 == 0) { bytes[i / 2] = (byte) 0xff; } else if (i == userCode.length()) { bytes[i / 2] |= 0x0f; } } return bytes; } }
johannrichard/openhab2-addons
addons/binding/org.openhab.binding.satel/src/main/java/org/openhab/binding/satel/internal/command/ControlCommand.java
Java
epl-1.0
2,159
/******************************************************************************* * Copyright (c) 2013, 2014 UT-Battelle, LLC. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Initial API and implementation and/or initial documentation - Jay Jay Billings, * Jordan H. Deyton, Dasha Gorin, Alexander J. McCaskey, Taylor Patterson, * Claire Saunders, Matthew Wang, Anna Wojtowicz *******************************************************************************/ package org.eclipse.ice.reactor.sfr.core.assembly; import org.eclipse.ice.reactor.sfr.base.ISFRComponentVisitor; import org.eclipse.ice.reactor.sfr.base.SFRComposite; import org.eclipse.ice.reactor.sfr.core.AssemblyType; /** * <p> * Class representing the assembly structure of a SFR. The SFR assembly is * housed in a hexagonal structure called the wrapper tube (or duct), and * contains a lattice of either pins or rods. * </p> * * @author Anna Wojtowicz */ public class SFRAssembly extends SFRComposite { /** * <p> * Size of a SFRAssembly. Size represents number of pins in a fuel or * control assembly, and rods in a reflector assembly. * </p> * */ private int size; /** * <p> * The type of SFR assembly represented, either fuel, control or reflector. * </p> * */ protected AssemblyType assemblyType; /** * <p> * Thickness of the assembly duct wall. * </p> * */ private double ductThickness; /** * <p> * Parameterized constructor with assemble size specified. Size represents * number of pins in a fuel or control assembly, and rods in a reflector * assembly. * </p> * * @param size * Size of the assembly. */ public SFRAssembly(int size) { // Set the size if positive, otherwise default to 1. this.size = (size > 0 ? size : 1); // Set the default name, description, and ID. setName("SFR Assembly 1"); setDescription("SFR Assembly 1's Description"); setId(1); // Default the assembly type to Fuel. assemblyType = AssemblyType.Fuel; // Initialize ductThickness. ductThickness = 0.0; return; } /** * <p> * Parameterized constructor with assembly name, type and size specified. * Size represents number of pins in a fuel or control assembly, and rods in * a reflector assembly. * </p> * * @param name * The name of the assembly. * @param type * The assembly type (fuel, control or reflector). * @param size * The size of the assembly. */ public SFRAssembly(String name, AssemblyType type, int size) { // Call the basic constructor first. this(size); // Set the name. setName(name); // Set the assembly type if possible. If null, the other constructor has // already set the type to the default (Fuel). if (type != null) { assemblyType = type; } return; } /** * <p> * Returns the assembly size. Size represents number of pins in a fuel or * control assembly, and rods in a reflector assembly. * </p> * * @return The size of the assembly. */ public int getSize() { return size; } /** * <p> * Returns the assembly type (fuel, control or reflector). * </p> * * @return The assembly type. */ public AssemblyType getAssemblyType() { return assemblyType; } /** * <p> * Sets the thickness of the assembly duct wall. * </p> * * @param thickness * The duct thickness. Must be non-negative. */ public void setDuctThickness(double thickness) { // Only set the duct thickness if it is 0 or larger. if (thickness >= 0.0) { ductThickness = thickness; } return; } /** * <p> * Returns the duct wall thickness of an assembly as a double. * </p> * * @return The duct thickness. */ public double getDuctThickness() { return ductThickness; } /** * <p> * Overrides the equals operation to check the attributes on this object * with another object of the same type. Returns true if the objects are * equal. False otherwise. * </p> * * @param otherObject * The object to be compared. * @return True if otherObject is equal. False otherwise. */ @Override public boolean equals(Object otherObject) { // By default, the objects are not equivalent. boolean equals = false; // Check the reference. if (this == otherObject) { equals = true; } // Check the information stored in the other object. else if (otherObject != null && otherObject instanceof SFRAssembly) { // We can now cast the other object. SFRAssembly assembly = (SFRAssembly) otherObject; // Compare the values between the two objects. equals = (super.equals(otherObject) && size == assembly.size && assemblyType == assembly.assemblyType && ductThickness == assembly.ductThickness); } return equals; } /** * <p> * Returns the hashCode of the object. * </p> * * @return <p> * The hash of the object. * </p> */ @Override public int hashCode() { // Hash based on super's hashCode. int hash = super.hashCode(); // Add local hashes. hash += 31 * size; hash += 31 * assemblyType.hashCode(); hash += 31 * ductThickness; return hash; } /** * <p> * Deep copies the contents of the object from another object. * </p> * * @param otherObject * <p> * The object to be copied from. * </p> */ public void copy(SFRAssembly otherObject) { // Check the parameters. if (otherObject == null) { return; } // Copy the super's values. super.copy(otherObject); // Copy the local values. size = otherObject.size; assemblyType = otherObject.assemblyType; ductThickness = otherObject.ductThickness; return; } /** * <p> * Deep copies and returns a newly instantiated object. * </p> * * @return <p> * The newly instantiated copied object. * </p> */ @Override public Object clone() { // Initialize a new object. SFRAssembly object = new SFRAssembly(size); // Copy the contents from this one. object.copy(this); // Return the newly instantiated object. return object; } /** * Overrides the default behavior (ignore) from SFRComponent and implements * the accept operation for this SFRComponent's type. */ @Override public void accept(ISFRComponentVisitor visitor) { if (visitor != null) { visitor.visit(this); } return; } }
gorindn/ice
src/org.eclipse.ice.reactor.sfr/src/org/eclipse/ice/reactor/sfr/core/assembly/SFRAssembly.java
Java
epl-1.0
6,609
<?php /** * Test Generated example demonstrating the GroupNesting.delete API. * * @return array * API result array */ function group_nesting_delete_example() { $params = [ 'id' => 1, ]; try{ $result = civicrm_api3('GroupNesting', 'delete', $params); } catch (CiviCRM_API3_Exception $e) { // Handle error here. $errorMessage = $e->getMessage(); $errorCode = $e->getErrorCode(); $errorData = $e->getExtraParams(); return [ 'is_error' => 1, 'error_message' => $errorMessage, 'error_code' => $errorCode, 'error_data' => $errorData, ]; } return $result; } /** * Function returns array of result expected from previous function. * * @return array * API result array */ function group_nesting_delete_expectedresult() { $expectedResult = [ 'is_error' => 0, 'version' => 3, 'count' => 1, 'values' => 1, ]; return $expectedResult; } /* * This example has been generated from the API test suite. * The test that created it is called "testDelete" * and can be found at: * https://github.com/civicrm/civicrm-core/blob/master/tests/phpunit/api/v3/GroupNestingTest.php * * You can see the outcome of the API tests at * https://test.civicrm.org/job/CiviCRM-Core-Matrix/ * * To Learn about the API read * https://docs.civicrm.org/dev/en/latest/api/ * * Browse the API on your own site with the API Explorer. It is in the main * CiviCRM menu, under: Support > Development > API Explorer. * * Read more about testing here * https://docs.civicrm.org/dev/en/latest/testing/ * * API Standards documentation: * https://docs.civicrm.org/dev/en/latest/framework/api-architecture/ */
kreynen/civicrm-starterkit-drops-7
profiles/civicrm_starterkit/modules/civicrm/api/v3/examples/GroupNesting/Delete.ex.php
PHP
gpl-2.0
1,670
/** * @author Moxiecode * @copyright Copyright © 2004-2008, Moxiecode Systems AB, All rights reserved. * * @author ralf57 * @author luciorota (lucio.rota@gmail.com) * @author dugris (dugris@frxoops.fr) */ tinyMCEPopup.requireLangPack(); var XoopsimagemanagerDialog = { preInit : function() { var url; if (url = tinyMCEPopup.getParam("external_image_list_url")) document.write('<script language="javascript" type="text/javascript" src="' + tinyMCEPopup.editor.documentBaseURI.toAbsolute(url) + '"></script>'); }, init : function(ed) { var f = document.forms[0], nl = f.elements, ed = tinyMCEPopup.editor, dom = ed.dom, n = ed.selection.getNode(); tinyMCEPopup.resizeToInnerSize(); this.fillClassList('class_list'); this.fillFileList('src_list', 'tinyMCEImageList'); this.fillFileList('over_list', 'tinyMCEImageList'); this.fillFileList('out_list', 'tinyMCEImageList'); if (n.nodeName == 'IMG') { nl.src.value = dom.getAttrib(n, 'src'); nl.width.value = dom.getAttrib(n, 'width'); nl.height.value = dom.getAttrib(n, 'height'); nl.alt.value = dom.getAttrib(n, 'alt'); nl.title.value = dom.getAttrib(n, 'title'); nl.vspace.value = this.getAttrib(n, 'vspace'); nl.hspace.value = this.getAttrib(n, 'hspace'); nl.border.value = this.getAttrib(n, 'border'); selectByValue(f, 'align', this.getAttrib(n, 'align')); selectByValue(f, 'class_list', dom.getAttrib(n, 'class')); nl.style.value = dom.getAttrib(n, 'style'); nl.id.value = dom.getAttrib(n, 'id'); nl.dir.value = dom.getAttrib(n, 'dir'); nl.lang.value = dom.getAttrib(n, 'lang'); nl.usemap.value = dom.getAttrib(n, 'usemap'); nl.longdesc.value = dom.getAttrib(n, 'longdesc'); nl.insert.value = ed.getLang('update'); if (/^\s*this.src\s*=\s*\'([^\']+)\';?\s*$/.test(dom.getAttrib(n, 'onmouseover'))) nl.onmouseoversrc.value = dom.getAttrib(n, 'onmouseover').replace(/^\s*this.src\s*=\s*\'([^\']+)\';?\s*$/, '$1'); if (/^\s*this.src\s*=\s*\'([^\']+)\';?\s*$/.test(dom.getAttrib(n, 'onmouseout'))) nl.onmouseoutsrc.value = dom.getAttrib(n, 'onmouseout').replace(/^\s*this.src\s*=\s*\'([^\']+)\';?\s*$/, '$1'); if (ed.settings.inline_styles) { // Move attribs to styles if (dom.getAttrib(n, 'align')) this.updateStyle('align'); if (dom.getAttrib(n, 'hspace')) this.updateStyle('hspace'); if (dom.getAttrib(n, 'border')) this.updateStyle('border'); if (dom.getAttrib(n, 'vspace')) this.updateStyle('vspace'); } } // Setup browse button document.getElementById('srcbrowsercontainer').innerHTML = getBrowserHTML('srcbrowser','src','image','theme_advanced_image'); if (isVisible('srcbrowser')) document.getElementById('src').style.width = '260px'; // Setup browse button document.getElementById('onmouseoversrccontainer').innerHTML = getBrowserHTML('overbrowser','onmouseoversrc','image','theme_advanced_image'); if (isVisible('overbrowser')) document.getElementById('onmouseoversrc').style.width = '260px'; // Setup browse button document.getElementById('onmouseoutsrccontainer').innerHTML = getBrowserHTML('outbrowser','onmouseoutsrc','image','theme_advanced_image'); if (isVisible('outbrowser')) document.getElementById('onmouseoutsrc').style.width = '260px'; // If option enabled default contrain proportions to checked if (ed.getParam("xoopsimagemanager_constrain_proportions", true)) f.constrain.checked = true; // Check swap image if valid data if (nl.onmouseoversrc.value || nl.onmouseoutsrc.value) this.setSwapImage(true); else this.setSwapImage(false); this.changeAppearance(); this.showPreviewImage(nl.src.value, 1); }, insert : function(file, title) { var ed = tinyMCEPopup.editor, t = this, f = document.forms[0]; if (f.src.value === '') { if (ed.selection.getNode().nodeName == 'IMG') { ed.dom.remove(ed.selection.getNode()); ed.execCommand('mceRepaint'); } tinyMCEPopup.close(); return; } if (tinyMCEPopup.getParam("accessibility_warnings", 1)) { if (!f.alt.value) { tinyMCEPopup.editor.windowManager.confirm(tinyMCEPopup.getLang('xoopsimagemanager_dlg.missing_alt'), function(s) { if (s) t.insertAndClose(); }); return; } } t.insertAndClose(); }, insertAndClose : function() { var ed = tinyMCEPopup.editor, f = document.forms[0], nl = f.elements, v, args = {}, el; tinyMCEPopup.restoreSelection(); // Fixes crash in Safari if (tinymce.isWebKit) ed.getWin().focus(); if (!ed.settings.inline_styles) { args = { vspace : nl.vspace.value, hspace : nl.hspace.value, border : nl.border.value, align : getSelectValue(f, 'align') }; } else { // Remove deprecated values args = { vspace : '', hspace : '', border : '', align : '' }; } tinymce.extend(args, { src : nl.src.value, width : nl.width.value, height : nl.height.value, alt : nl.alt.value, title : nl.title.value, 'class' : getSelectValue(f, 'class_list'), style : nl.style.value, id : nl.id.value, dir : nl.dir.value, lang : nl.lang.value, usemap : nl.usemap.value, longdesc : nl.longdesc.value }); args.onmouseover = args.onmouseout = ''; if (f.onmousemovecheck.checked) { if (nl.onmouseoversrc.value) args.onmouseover = "this.src='" + nl.onmouseoversrc.value + "';"; if (nl.onmouseoutsrc.value) args.onmouseout = "this.src='" + nl.onmouseoutsrc.value + "';"; } el = ed.selection.getNode(); if (el && el.nodeName == 'IMG') { ed.dom.setAttribs(el, args); } else { ed.execCommand('mceInsertContent', false, '<img id="__mce_tmp" src="javascript:;" />', {skip_undo : 1}); ed.dom.setAttribs('__mce_tmp', args); ed.dom.setAttrib('__mce_tmp', 'id', ''); ed.undoManager.add(); } tinyMCEPopup.close(); }, getAttrib : function(e, at) { var ed = tinyMCEPopup.editor, dom = ed.dom, v, v2; if (ed.settings.inline_styles) { switch (at) { case 'align': if (v = dom.getStyle(e, 'float')) return v; if (v = dom.getStyle(e, 'vertical-align')) return v; break; case 'hspace': v = dom.getStyle(e, 'margin-left') v2 = dom.getStyle(e, 'margin-right'); if (v && v == v2) return parseInt(v.replace(/[^0-9]/g, '')); break; case 'vspace': v = dom.getStyle(e, 'margin-top') v2 = dom.getStyle(e, 'margin-bottom'); if (v && v == v2) return parseInt(v.replace(/[^0-9]/g, '')); break; case 'border': v = 0; tinymce.each(['top', 'right', 'bottom', 'left'], function(sv) { sv = dom.getStyle(e, 'border-' + sv + '-width'); // False or not the same as prev if (!sv || (sv != v && v !== 0)) { v = 0; return false; } if (sv) v = sv; }); if (v) return parseInt(v.replace(/[^0-9]/g, '')); break; } } if (v = dom.getAttrib(e, at)) return v; return ''; }, setSwapImage : function(st) { var f = document.forms[0]; f.onmousemovecheck.checked = st; setBrowserDisabled('overbrowser', !st); setBrowserDisabled('outbrowser', !st); if (f.over_list) f.over_list.disabled = !st; if (f.out_list) f.out_list.disabled = !st; f.onmouseoversrc.disabled = !st; f.onmouseoutsrc.disabled = !st; }, fillClassList : function(id) { var dom = tinyMCEPopup.dom, lst = dom.get(id), v, cl; if (v = tinyMCEPopup.getParam('theme_advanced_styles')) { cl = []; tinymce.each(v.split(';'), function(v) { var p = v.split('='); cl.push({'title' : p[0], 'class' : p[1]}); }); } else cl = tinyMCEPopup.editor.dom.getClasses(); if (cl.length > 0) { lst.options[lst.options.length] = new Option(tinyMCEPopup.getLang('not_set'), ''); tinymce.each(cl, function(o) { lst.options[lst.options.length] = new Option(o.title || o['class'], o['class']); }); } else dom.remove(dom.getParent(id, 'tr')); }, fillFileList : function(id, l) { var dom = tinyMCEPopup.dom, lst = dom.get(id), v, cl; l = window[l]; if (l && l.length > 0) { lst.options[lst.options.length] = new Option('', ''); tinymce.each(l, function(o) { lst.options[lst.options.length] = new Option(o[0], o[1]); }); } else dom.remove(dom.getParent(id, 'tr')); }, resetImageData : function() { var f = document.forms[0]; f.elements.width.value = f.elements.height.value = ''; }, updateImageData : function(img, st) { var f = document.forms[0]; if (!st) { f.elements.width.value = img.width; f.elements.height.value = img.height; } this.preloadImg = img; }, changeAppearance : function() { var ed = tinyMCEPopup.editor, f = document.forms[0], img = document.getElementById('alignSampleImg'); if (img) { if (ed.getParam('inline_styles')) { ed.dom.setAttrib(img, 'style', f.style.value); } else { img.align = f.align.value; img.border = f.border.value; img.hspace = f.hspace.value; img.vspace = f.vspace.value; } } }, changeHeight : function() { var f = document.forms[0], tp, t = this; if (!f.constrain.checked || !t.preloadImg) { return; } if (f.width.value == "" || f.height.value == "") return; tp = (parseInt(f.width.value) / parseInt(t.preloadImg.width)) * t.preloadImg.height; f.height.value = tp.toFixed(0); }, changeWidth : function() { var f = document.forms[0], tp, t = this; if (!f.constrain.checked || !t.preloadImg) { return; } if (f.width.value == "" || f.height.value == "") return; tp = (parseInt(f.height.value) / parseInt(t.preloadImg.height)) * t.preloadImg.width; f.width.value = tp.toFixed(0); }, updateStyle : function(ty) { var dom = tinyMCEPopup.dom, st, v, f = document.forms[0], img = dom.create('img', {style : dom.get('style').value}); if (tinyMCEPopup.editor.settings.inline_styles) { // Handle align if (ty == 'align') { dom.setStyle(img, 'float', ''); dom.setStyle(img, 'vertical-align', ''); v = getSelectValue(f, 'align'); if (v) { if (v == 'left' || v == 'right') dom.setStyle(img, 'float', v); else img.style.verticalAlign = v; } } // Handle border if (ty == 'border') { dom.setStyle(img, 'border', ''); v = f.border.value; if (v || v == '0') { if (v == '0') img.style.border = ''; else img.style.border = v + 'px solid black'; } } // Handle hspace if (ty == 'hspace') { dom.setStyle(img, 'marginLeft', ''); dom.setStyle(img, 'marginRight', ''); v = f.hspace.value; if (v) { img.style.marginLeft = v + 'px'; img.style.marginRight = v + 'px'; } } // Handle vspace if (ty == 'vspace') { dom.setStyle(img, 'marginTop', ''); dom.setStyle(img, 'marginBottom', ''); v = f.vspace.value; if (v) { img.style.marginTop = v + 'px'; img.style.marginBottom = v + 'px'; } } // Merge dom.get('style').value = dom.serializeStyle(dom.parseStyle(img.style.cssText)); } }, changeMouseMove : function() { }, showPreviewImage : function(u, st) { if (!u) { tinyMCEPopup.dom.setHTML('prev', ''); return; } if (!st && tinyMCEPopup.getParam("xoopsimagemanager_update_dimensions_onchange", true)) this.resetImageData(); u = tinyMCEPopup.editor.documentBaseURI.toAbsolute(u); if (!st) tinyMCEPopup.dom.setHTML('prev', '<img id="previewImg" src="' + u + '" border="0" onload="XoopsimagemanagerDialog.updateImageData(this);" onerror="XoopsimagemanagerDialog.resetImageData();" />'); else tinyMCEPopup.dom.setHTML('prev', '<img id="previewImg" src="' + u + '" border="0" onload="XoopsimagemanagerDialog.updateImageData(this, 1);" />'); } }; XoopsimagemanagerDialog.preInit(); tinyMCEPopup.onInit.add(XoopsimagemanagerDialog.init, XoopsimagemanagerDialog); function XoopsImageBrowser( input ) { var url = "xoopsimagebrowser.php?target=src"; var type = "image"; var win = window.self; var cmsURL = window.location.href; // script URL var cmsURL = cmsURL.substring( 0, cmsURL.lastIndexOf("/") + 1 ); var searchString = window.location.search; // possible parameters if (searchString.length < 1) { // add "?" to the URL to include parameters (in other words: create a search string because there wasn't one before) searchString = "?"; } tinyMCE.activeEditor.windowManager.open({ file : cmsURL + url + searchString + "&type=" + type, title : 'Xoops Image Manager', width : 650, height : 440, resizable : "yes", scrollbars : "yes", inline : "yes", // This parameter only has an effect if you use the inlinepopups plugin! close_previous : "no" }, { window : win, input_src : input, input_title : "title", input_alt : "alt", input_align : "align" }); return false; }
mambax7/XoopsCore25
htdocs/class/xoopseditor/tinymce/tinymce/jscripts/tiny_mce/plugins/xoopsimagemanager/js/xoopsimagemanager.js
JavaScript
gpl-2.0
16,092
<?php /** * @file * Contains \Drupal\Core\Utility\UnroutedUrlAssembler. */ namespace Drupal\Core\Utility; use Drupal\Component\Utility\SafeMarkup; use Drupal\Component\Utility\UrlHelper; use Drupal\Core\Config\ConfigFactoryInterface; use Drupal\Core\GeneratedUrl; use Drupal\Core\PathProcessor\OutboundPathProcessorInterface; use Symfony\Component\HttpFoundation\RequestStack; /** * Provides a way to build external or non Drupal local domain URLs. * * It takes into account configured safe HTTP protocols. */ class UnroutedUrlAssembler implements UnroutedUrlAssemblerInterface { /** * A request stack object. * * @var \Symfony\Component\HttpFoundation\RequestStack */ protected $requestStack; /** * The outbound path processor. * * @var \Drupal\Core\PathProcessor\OutboundPathProcessorInterface */ protected $pathProcessor; /** * Constructs a new unroutedUrlAssembler object. * * @param \Symfony\Component\HttpFoundation\RequestStack $request_stack * A request stack object. * @param \Drupal\Core\Config\ConfigFactoryInterface $config * The config factory. * @param \Drupal\Core\PathProcessor\OutboundPathProcessorInterface $path_processor * The output path processor. */ public function __construct(RequestStack $request_stack, ConfigFactoryInterface $config, OutboundPathProcessorInterface $path_processor) { $allowed_protocols = $config->get('system.filter')->get('protocols') ?: ['http', 'https']; UrlHelper::setAllowedProtocols($allowed_protocols); $this->requestStack = $request_stack; $this->pathProcessor = $path_processor; } /** * {@inheritdoc} * * This is a helper function that calls buildExternalUrl() or buildLocalUrl() * based on a check of whether the path is a valid external URL. */ public function assemble($uri, array $options = [], $collect_cacheability_metadata = FALSE) { // Note that UrlHelper::isExternal will return FALSE if the $uri has a // disallowed protocol. This is later made safe since we always add at // least a leading slash. if (parse_url($uri, PHP_URL_SCHEME) === 'base') { return $this->buildLocalUrl($uri, $options, $collect_cacheability_metadata); } elseif (UrlHelper::isExternal($uri)) { // UrlHelper::isExternal() only returns true for safe protocols. return $this->buildExternalUrl($uri, $options, $collect_cacheability_metadata); } throw new \InvalidArgumentException(SafeMarkup::format('The URI "@uri" is invalid. You must use a valid URI scheme. Use base: for a path, e.g., to a Drupal file that needs the base path. Do not use this for internal paths controlled by Drupal.', ['@uri' => $uri])); } /** * {@inheritdoc} */ protected function buildExternalUrl($uri, array $options = [], $collect_cacheability_metadata = FALSE) { $this->addOptionDefaults($options); // Split off the fragment. if (strpos($uri, '#') !== FALSE) { list($uri, $old_fragment) = explode('#', $uri, 2); // If $options contains no fragment, take it over from the path. if (isset($old_fragment) && !$options['fragment']) { $options['fragment'] = '#' . $old_fragment; } } if (isset($options['https'])) { if ($options['https'] === TRUE) { $uri = str_replace('http://', 'https://', $uri); } elseif ($options['https'] === FALSE) { $uri = str_replace('https://', 'http://', $uri); } } // Append the query. if ($options['query']) { $uri .= (strpos($uri, '?') !== FALSE ? '&' : '?') . UrlHelper::buildQuery($options['query']); } // Reassemble. $url = $uri . $options['fragment']; return $collect_cacheability_metadata ? (new GeneratedUrl())->setGeneratedUrl($url) : $url; } /** * {@inheritdoc} */ protected function buildLocalUrl($uri, array $options = [], $collect_cacheability_metadata = FALSE) { $generated_url = $collect_cacheability_metadata ? new GeneratedUrl() : NULL; $this->addOptionDefaults($options); $request = $this->requestStack->getCurrentRequest(); // Remove the base: scheme. // @todo Consider using a class constant for this in // https://www.drupal.org/node/2417459 $uri = substr($uri, 5); // Strip leading slashes from internal paths to prevent them becoming // external URLs without protocol. /example.com should not be turned into // //example.com. $uri = ltrim($uri, '/'); // Allow (outbound) path processing, if needed. A valid use case is the path // alias overview form: // @see \Drupal\path\Controller\PathController::adminOverview(). if (!empty($options['path_processing'])) { // Do not pass the request, since this is a special case and we do not // want to include e.g. the request language in the processing. $uri = $this->pathProcessor->processOutbound($uri, $options, NULL, $generated_url); } // Add any subdirectory where Drupal is installed. $current_base_path = $request->getBasePath() . '/'; if ($options['absolute']) { $current_base_url = $request->getSchemeAndHttpHost() . $current_base_path; if (isset($options['https'])) { if (!empty($options['https'])) { $base = str_replace('http://', 'https://', $current_base_url); $options['absolute'] = TRUE; } else { $base = str_replace('https://', 'http://', $current_base_url); $options['absolute'] = TRUE; } } else { $base = $current_base_url; } if ($collect_cacheability_metadata) { $generated_url->addCacheContexts(['url.site']); } } else { $base = $current_base_path; } $prefix = empty($uri) ? rtrim($options['prefix'], '/') : $options['prefix']; $uri = str_replace('%2F', '/', rawurlencode($prefix . $uri)); $query = $options['query'] ? ('?' . UrlHelper::buildQuery($options['query'])) : ''; $url = $base . $options['script'] . $uri . $query . $options['fragment']; return $collect_cacheability_metadata ? $generated_url->setGeneratedUrl($url) : $url; } /** * Merges in default defaults * * @param array $options * The options to merge in the defaults. */ protected function addOptionDefaults(array &$options) { $request = $this->requestStack->getCurrentRequest(); $current_base_path = $request->getBasePath() . '/'; $current_script_path = ''; $base_path_with_script = $request->getBaseUrl(); // If the current request was made with the script name (eg, index.php) in // it, then extract it, making sure the leading / is gone, and a trailing / // is added, to allow simple string concatenation with other parts. This // mirrors code from UrlGenerator::generateFromPath(). if (!empty($base_path_with_script)) { $script_name = $request->getScriptName(); if (strpos($base_path_with_script, $script_name) !== FALSE) { $current_script_path = ltrim(substr($script_name, strlen($current_base_path)), '/') . '/'; } } // Merge in defaults. $options += [ 'fragment' => '', 'query' => [], 'absolute' => FALSE, 'prefix' => '', 'script' => $current_script_path, ]; if (isset($options['fragment']) && $options['fragment'] !== '') { $options['fragment'] = '#' . $options['fragment']; } } }
cpjobling/proman-d8
proman.swan.ac.uk/core/lib/Drupal/Core/Utility/UnroutedUrlAssembler.php
PHP
gpl-2.0
7,426
<?php /** * DmSetting filter form base class. * * @package retest * @subpackage filter * @author Your name here * @version SVN: $Id: sfDoctrineFormFilterGeneratedTemplate.php 24171 2009-11-19 16:37:50Z Kris.Wallsmith $ */ abstract class BaseDmSettingFormFilter extends BaseFormFilterDoctrine { public function setup() { if($this->needsWidget('id')){ $this->setWidget('id', new sfWidgetFormDmFilterInput()); $this->setValidator('id', new sfValidatorDoctrineChoice(array('required' => false, 'model' => 'DmSetting', 'column' => 'id'))); } if($this->needsWidget('name')){ $this->setWidget('name', new sfWidgetFormDmFilterInput()); $this->setValidator('name', new sfValidatorSchemaFilter('text', new sfValidatorString(array('required' => false)))); } if($this->needsWidget('type')){ $this->setWidget('type', new sfWidgetFormChoice(array('multiple' => true, 'choices' => array('' => '', 'text' => 'text', 'boolean' => 'boolean', 'select' => 'select', 'textarea' => 'textarea', 'number' => 'number', 'datetime' => 'datetime')))); $this->setValidator('type', new sfValidatorChoice(array('required' => false, 'multiple' => true , 'choices' => array('text' => 'text', 'boolean' => 'boolean', 'select' => 'select', 'textarea' => 'textarea', 'number' => 'number', 'datetime' => 'datetime')))); } if($this->needsWidget('params')){ $this->setWidget('params', new sfWidgetFormDmFilterInput()); $this->setValidator('params', new sfValidatorSchemaFilter('text', new sfValidatorString(array('required' => false)))); } if($this->needsWidget('group_name')){ $this->setWidget('group_name', new sfWidgetFormDmFilterInput()); $this->setValidator('group_name', new sfValidatorSchemaFilter('text', new sfValidatorString(array('required' => false)))); } if($this->needsWidget('credentials')){ $this->setWidget('credentials', new sfWidgetFormDmFilterInput()); $this->setValidator('credentials', new sfValidatorSchemaFilter('text', new sfValidatorString(array('required' => false)))); } $this->mergeI18nForm(); $this->widgetSchema->setNameFormat('dm_setting_filters[%s]'); $this->errorSchema = new sfValidatorErrorSchema($this->validatorSchema); $this->setupInheritance(); parent::setup(); } public function getModelName() { return 'DmSetting'; } public function getFields() { return array( 'id' => 'Number', 'name' => 'Text', 'type' => 'Enum', 'params' => 'Text', 'group_name' => 'Text', 'credentials' => 'Text', 'id' => 'Number', 'description' => 'Text', 'value' => 'Text', 'default_value' => 'Text', 'lang' => 'Text', ); } }
Teplitsa/bquest.ru
lib/vendor/diem/dmCorePlugin/test/project/lib/filter/doctrine/dmCorePlugin/base/BaseDmSettingFormFilter.class.php
PHP
gpl-2.0
2,784
/* * Copyright (C) 2013-2015 DeathCore <http://www.noffearrdeathproject.net/> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "Field.h" Field::Field() { data.value = NULL; data.type = MYSQL_TYPE_NULL; data.length = 0; data.raw = false; } Field::~Field() { CleanUp(); } void Field::SetByteValue(const void* newValue, const size_t newSize, enum_field_types newType, uint32 length) { if (data.value) CleanUp(); // This value stores raw bytes that have to be explicitly cast later if (newValue) { data.value = new char[newSize]; memcpy(data.value, newValue, newSize); data.length = length; } data.type = newType; data.raw = true; } void Field::SetStructuredValue(char* newValue, enum_field_types newType) { if (data.value) CleanUp(); // This value stores somewhat structured data that needs function style casting if (newValue) { size_t size = strlen(newValue); data.value = new char [size+1]; strcpy((char*)data.value, newValue); data.length = size; } data.type = newType; data.raw = false; }
ironhead123/DeathCore_3.3.5
src/server/shared/Database/Field.cpp
C++
gpl-2.0
1,759
<?php /** * @package JCE * @copyright Copyright (c)2016 Ryan Demmer * @license GNU General Public License version 2, or later */ defined('_JEXEC') or die; /** * Handle commercial extension update authorization * * @package Joomla.Plugin * @subpackage Installer.Jce * @since 2.6 */ class plgInstallerJce extends JPlugin { /** * Handle adding credentials to package download request * * @param string $url url from which package is going to be downloaded * @param array $headers headers to be sent along the download request (key => value format) * * @return boolean true if credentials have been added to request or not our business, false otherwise (credentials not set by user) * * @since 3.0 */ public function onInstallerBeforePackageDownload(&$url, &$headers) { $app = JFactory::getApplication(); $uri = JUri::getInstance($url); $host = $uri->getHost(); if ($host !== 'www.joomlacontenteditor.net') { return true; } // Get the subscription key JLoader::import('joomla.application.component.helper'); $component = JComponentHelper::getComponent('com_jce'); $key = $component->params->get('updates_key', ''); if (empty($key)) { $language = JFactory::getLanguage(); $language->load('plg_installer_jce', JPATH_ADMINISTRATOR); $app->enqueueMessage(JText::_('PLG_INSTALLER_JCE_KEY_WARNING'), 'notice'); } // Append the subscription key to the download URL $uri->setVar('key', $key); $url = $uri->toString(); return true; } }
khuongdang/dongtrungtruongsinh
plugins/installer/jce/jce.php
PHP
gpl-2.0
1,570
var express = require('express'); var leaderRouter = express.Router(); leaderRouter.route('/') .all(function(req, res, next) { res.writeHead(200, { 'Content-Type': 'text/plain' }); next(); }) .get(function(req, res, next){ res.end('Will send all the leaders to you!'); }) .post(function(req, res, next){ res.end('Will add the leader: ' + req.body.name + ' with details: ' + req.body.description); }) .delete(function(req, res, next){ res.end('Deleting all leaders'); }); leaderRouter.route('/:leaderId') .all(function(req, res, next) { res.writeHead(200, { 'Content-Type': 'text/plain' }); next(); }) .get(function(req, res, next){ res.end('Will send details of the leader: ' + req.params.leaderId +' to you!'); }) .put(function(req, res, next){ res.write('Updating the leader: ' + req.params.leaderId + '\n'); res.end('Will update the leader: ' + req.body.name + ' with details: ' + req.body.description); }) .delete(function(req, res, next){ res.end('Deleting the leader: ' + req.params.leaderId); }); module.exports = leaderRouter;
mikedanylov/full-stack-dev
NodeJS/week3/rest-server/routes/leaderRouter.js
JavaScript
gpl-2.0
1,220
# postgresql/pypostgresql.py # Copyright (C) 2005-2020 the SQLAlchemy authors and contributors # <see AUTHORS file> # # This module is part of SQLAlchemy and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php """ .. dialect:: postgresql+pypostgresql :name: py-postgresql :dbapi: pypostgresql :connectstring: postgresql+pypostgresql://user:password@host:port/dbname[?key=value&key=value...] :url: http://python.projects.pgfoundry.org/ .. note:: The pypostgresql dialect is **not tested as part of SQLAlchemy's continuous integration** and may have unresolved issues. The recommended PostgreSQL driver is psycopg2. """ # noqa from .base import PGDialect from .base import PGExecutionContext from ... import processors from ... import types as sqltypes from ... import util class PGNumeric(sqltypes.Numeric): def bind_processor(self, dialect): return processors.to_str def result_processor(self, dialect, coltype): if self.asdecimal: return None else: return processors.to_float class PGExecutionContext_pypostgresql(PGExecutionContext): pass class PGDialect_pypostgresql(PGDialect): driver = "pypostgresql" supports_unicode_statements = True supports_unicode_binds = True description_encoding = None default_paramstyle = "pyformat" # requires trunk version to support sane rowcounts # TODO: use dbapi version information to set this flag appropriately supports_sane_rowcount = True supports_sane_multi_rowcount = False execution_ctx_cls = PGExecutionContext_pypostgresql colspecs = util.update_copy( PGDialect.colspecs, { sqltypes.Numeric: PGNumeric, # prevents PGNumeric from being used sqltypes.Float: sqltypes.Float, }, ) @classmethod def dbapi(cls): from postgresql.driver import dbapi20 return dbapi20 _DBAPI_ERROR_NAMES = [ "Error", "InterfaceError", "DatabaseError", "DataError", "OperationalError", "IntegrityError", "InternalError", "ProgrammingError", "NotSupportedError", ] @util.memoized_property def dbapi_exception_translation_map(self): if self.dbapi is None: return {} return dict( (getattr(self.dbapi, name).__name__, name) for name in self._DBAPI_ERROR_NAMES ) def create_connect_args(self, url): opts = url.translate_connect_args(username="user") if "port" in opts: opts["port"] = int(opts["port"]) else: opts["port"] = 5432 opts.update(url.query) return ([], opts) def is_disconnect(self, e, connection, cursor): return "connection is closed" in str(e) dialect = PGDialect_pypostgresql
gltn/stdm
stdm/third_party/sqlalchemy/dialects/postgresql/pypostgresql.py
Python
gpl-2.0
2,915
<?php /** * Joomla! 1.5 component irbtools * * @version $Id: view.html.php 2010-10-13 07:12:40 svn $ * @author IRB Barcelona * @package Joomla * @subpackage irbtools * @license GNU/GPL * * IRB Barcelona Tools * * This component file was created using the Joomla Component Creator by Not Web Design * http://www.notwebdesign.com/joomla_component_creator/ * */ // no direct access defined('_JEXEC') or die('Restricted access'); // Import Joomla! libraries jimport( 'joomla.application.component.view'); class IrbtoolsViewDefault extends JView { function display($tpl = null) { parent::display($tpl); } } ?>
rbartolomeirb/joomlaatirb
tools/com_irbtools/build/administrator/components/com_irbtools/views/default/view.html.php
PHP
gpl-2.0
663
// $Id: Dynamic_Service_Dependency.cpp 96985 2013-04-11 15:50:32Z huangh $ #include "ace/ACE.h" #include "ace/DLL_Manager.h" #include "ace/Dynamic_Service_Dependency.h" #include "ace/Service_Config.h" #include "ace/Log_Category.h" ACE_BEGIN_VERSIONED_NAMESPACE_DECL ACE_Dynamic_Service_Dependency::ACE_Dynamic_Service_Dependency (const ACE_TCHAR *principal) { this->init (ACE_Service_Config::current (), principal); } ACE_Dynamic_Service_Dependency::ACE_Dynamic_Service_Dependency (const ACE_Service_Gestalt *cfg, const ACE_TCHAR *principal) { this->init (cfg, principal); } ACE_Dynamic_Service_Dependency::~ACE_Dynamic_Service_Dependency (void) { if (ACE::debug ()) ACELIB_DEBUG ((LM_DEBUG, ACE_TEXT ("(%P|%t) DSD, this=%@ - destroying\n"), this)); } void ACE_Dynamic_Service_Dependency::init (const ACE_Service_Gestalt *cfg, const ACE_TCHAR *principal) { const ACE_Service_Type* st = ACE_Dynamic_Service_Base::find_i (cfg, principal,false); if (ACE::debug ()) { ACELIB_DEBUG ((LM_DEBUG, ACE_TEXT ("(%P|%t) DSD, this=%@ - creating dependency on "), this)); st->dump (); } this->tracker_ = st->dll (); } ACE_END_VERSIONED_NAMESPACE_DECL
xIchigox/ArkCORE-NG
dep/acelite/ace/Dynamic_Service_Dependency.cpp
C++
gpl-2.0
1,326
<?php /** * @Project NUKEVIET 4.x * @Author VINADES.,JSC (contact@vinades.vn) * @Copyright (C) 2016 VINADES.,JSC. All rights reserved * @Language Français * @License CC BY-SA (http://creativecommons.org/licenses/by-sa/4.0/) * @Createdate Jul 31, 2015, 09:30:00 AM */ if (! defined('NV_ADMIN') or ! defined('NV_MAINFILE')) { die( 'Stop!!!' ); } $lang_translator['author'] = 'Nguyễn Phú Thành'; $lang_translator['createdate'] = '31/07/2015, 16:30'; $lang_translator['copyright'] = 'phuthanh.nguyen215@gmail.com'; $lang_translator['info'] = ''; $lang_translator['langtype'] = 'lang_block'; $lang_block['catid'] = 'Sujet'; $lang_block['numrow'] = 'Nombre d\'articles affichés'; $lang_block['type'] = 'Méthode d\'affichage'; $lang_block['showtooltip'] = 'Affichage de tooltip'; $lang_block['tooltip_position'] = 'Position'; $lang_block['tooltip_position_top'] = 'Au dessus'; $lang_block['tooltip_position_bottom'] = 'Au dessous'; $lang_block['tooltip_position_left'] = 'A gauche'; $lang_block['tooltip_position_right'] = 'A droite'; $lang_block['tooltip_length'] = 'Numero';
nhatnhatnet/nukecms
modules/news/language/block.global.block_news_cat_fr.php
PHP
gpl-2.0
1,084
/* java.lang.Number Copyright (C) 1998, 2001 Free Software Foundation, Inc. This file is part of GNU Classpath. GNU Classpath is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. GNU Classpath is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with GNU Classpath; see the file COPYING. If not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. Linking this library statically or dynamically with other modules is making a combined work based on this library. Thus, the terms and conditions of the GNU General Public License cover the whole combination. As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules, and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ package java.lang; import java.io.Serializable; /** ** Number is a generic superclass of all the numeric classes, namely ** <code>Byte</code>, <code>Short</code>, <code>Integer</code>, ** <code>Long</code>, <code>Float</code>, and <code>Double</code>. ** ** It provides ways to convert from any one value to any other. ** ** @author Paul Fisher ** @author John Keiser ** @author Warren Levy ** @since JDK1.0 **/ public abstract class Number implements Serializable { /** Return the value of this <code>Number</code> as a <code>byte</code>. ** @return the value of this <code>Number</code> as a <code>byte</code>. **/ public byte byteValue() { return (byte) intValue(); } /** Return the value of this <code>Number</code> as a <code>short</code>. ** @return the value of this <code>Number</code> as a <code>short</code>. **/ public short shortValue() { return (short) intValue(); } /** Return the value of this <code>Number</code> as an <code>int</code>. ** @return the value of this <code>Number</code> as an <code>int</code>. **/ public abstract int intValue(); /** Return the value of this <code>Number</code> as a <code>long</code>. ** @return the value of this <code>Number</code> as a <code>long</code>. **/ public abstract long longValue(); /** Return the value of this <code>Number</code> as a <code>float</code>. ** @return the value of this <code>Number</code> as a <code>float</code>. **/ public abstract float floatValue(); /** Return the value of this <code>Number</code> as a <code>float</code>. ** @return the value of this <code>Number</code> as a <code>float</code>. **/ public abstract double doubleValue(); private static final long serialVersionUID = -8742448824652078965L; }
aosm/gcc3
libjava/java/lang/Number.java
Java
gpl-2.0
3,524
<?php require(__DATAGEN_META_CONTROLS__ . '/AssetModelCustomFieldHelperMetaControlGen.class.php'); /** * This is a MetaControl customizable subclass, providing a QForm or QPanel access to event handlers * and QControls to perform the Create, Edit, and Delete functionality of the * AssetModelCustomFieldHelper class. This code-generated class extends from * the generated MetaControl class, which contains all the basic elements to help a QPanel or QForm * display an HTML form that can manipulate a single AssetModelCustomFieldHelper object. * * To take advantage of some (or all) of these control objects, you * must create a new QForm or QPanel which instantiates a AssetModelCustomFieldHelperMetaControl * class. * * This file is intended to be modified. Subsequent code regenerations will NOT modify * or overwrite this file. * * @package My Application * @subpackage MetaControls */ class AssetModelCustomFieldHelperMetaControl extends AssetModelCustomFieldHelperMetaControlGen { } ?>
mmuir-ca/tracmor
includes/data_meta_controls/AssetModelCustomFieldHelperMetaControl.class.php
PHP
gpl-2.0
1,030
<?php /* vim: set expandtab sw=4 ts=4 sts=4: */ /** * Various table operations * * @package PhpMyAdmin */ use PMA\libraries\Partition; use PMA\libraries\Table; use PMA\libraries\Response; /** * */ require_once 'libraries/common.inc.php'; /** * functions implementation for this script */ require_once 'libraries/check_user_privileges.lib.php'; require_once 'libraries/operations.lib.php'; $pma_table = new Table($GLOBALS['table'], $GLOBALS['db']); /** * Load JavaScript files */ $response = Response::getInstance(); $header = $response->getHeader(); $scripts = $header->getScripts(); $scripts->addFile('tbl_operations.js'); /** * Runs common work */ require 'libraries/tbl_common.inc.php'; $url_query .= '&amp;goto=tbl_operations.php&amp;back=tbl_operations.php'; $url_params['goto'] = $url_params['back'] = 'tbl_operations.php'; /** * Gets relation settings */ $cfgRelation = PMA_getRelationsParam(); // reselect current db (needed in some cases probably due to // the calling of relation.lib.php) $GLOBALS['dbi']->selectDb($GLOBALS['db']); /** * Gets tables information */ $pma_table = $GLOBALS['dbi']->getTable( $GLOBALS['db'], $GLOBALS['table'] ); $reread_info = $pma_table->getStatusInfo(null, false); $GLOBALS['showtable'] = $pma_table->getStatusInfo(null, (isset($reread_info) && $reread_info ? true : false)); if ($pma_table->isView()) { $tbl_is_view = true; $tbl_storage_engine = __('View'); $show_comment = null; } else { $tbl_is_view = false; $tbl_storage_engine = $pma_table->getStorageEngine(); $show_comment = $pma_table->getComment(); } $tbl_collation = $pma_table->getCollation(); $table_info_num_rows = $pma_table->getNumRows(); $row_format = $pma_table->getRowFormat(); $auto_increment = $pma_table->getAutoIncrement(); $create_options = $pma_table->getCreateOptions(); // set initial value of these variables, based on the current table engine if ($pma_table->isEngine('ARIA')) { // the value for transactional can be implicit // (no create option found, in this case it means 1) // or explicit (option found with a value of 0 or 1) // ($create_options['transactional'] may have been set by Table class, // from the $create_options) $create_options['transactional'] = (isset($create_options['transactional']) && $create_options['transactional'] == '0') ? '0' : '1'; $create_options['page_checksum'] = (isset($create_options['page_checksum'])) ? $create_options['page_checksum'] : ''; } $pma_table = $GLOBALS['dbi']->getTable( $GLOBALS['db'], $GLOBALS['table'] ); $reread_info = false; $table_alters = array(); /** * If the table has to be moved to some other database */ if (isset($_REQUEST['submit_move']) || isset($_REQUEST['submit_copy'])) { //$_message = ''; PMA_moveOrCopyTable($db, $table); // This was ended in an Ajax call exit; } /** * If the table has to be maintained */ if (isset($_REQUEST['table_maintenance'])) { include_once 'sql.php'; unset($result); } /** * Updates table comment, type and options if required */ if (isset($_REQUEST['submitoptions'])) { $_message = ''; $warning_messages = array(); if (isset($_REQUEST['new_name'])) { // Get original names before rename operation $oldTable = $pma_table->getName(); $oldDb = $pma_table->getDbName(); if ($pma_table->rename($_REQUEST['new_name'])) { if (isset($_REQUEST['adjust_privileges']) && ! empty($_REQUEST['adjust_privileges']) ) { PMA_AdjustPrivileges_renameOrMoveTable( $oldDb, $oldTable, $_REQUEST['db'], $_REQUEST['new_name'] ); } // Reselect the original DB $GLOBALS['db'] = $oldDb; $GLOBALS['dbi']->selectDb($oldDb); $_message .= $pma_table->getLastMessage(); $result = true; $GLOBALS['table'] = $pma_table->getName(); $reread_info = true; $reload = true; } else { $_message .= $pma_table->getLastError(); $result = false; } } if (! empty($_REQUEST['new_tbl_storage_engine']) && mb_strtoupper($_REQUEST['new_tbl_storage_engine']) !== $tbl_storage_engine ) { $new_tbl_storage_engine = mb_strtoupper($_REQUEST['new_tbl_storage_engine']); if ($pma_table->isEngine('ARIA')) { $create_options['transactional'] = (isset($create_options['transactional']) && $create_options['transactional'] == '0') ? '0' : '1'; $create_options['page_checksum'] = (isset($create_options['page_checksum'])) ? $create_options['page_checksum'] : ''; } } else { $new_tbl_storage_engine = ''; } $row_format = (isset($create_options['row_format'])) ? $create_options['row_format'] : $pma_table->getRowFormat(); $table_alters = PMA_getTableAltersArray( $pma_table, $create_options['pack_keys'], (empty($create_options['checksum']) ? '0' : '1'), ((isset($create_options['page_checksum'])) ? $create_options['page_checksum'] : ''), (empty($create_options['delay_key_write']) ? '0' : '1'), $row_format, $new_tbl_storage_engine, ((isset($create_options['transactional']) && $create_options['transactional'] == '0') ? '0' : '1'), $tbl_collation ); if (count($table_alters) > 0) { $sql_query = 'ALTER TABLE ' . PMA\libraries\Util::backquote($GLOBALS['table']); $sql_query .= "\r\n" . implode("\r\n", $table_alters); $sql_query .= ';'; $result .= $GLOBALS['dbi']->query($sql_query) ? true : false; $reread_info = true; unset($table_alters); $warning_messages = PMA_getWarningMessagesArray(); } if (isset($_REQUEST['tbl_collation']) && ! empty($_REQUEST['tbl_collation']) && isset($_REQUEST['change_all_collations']) && ! empty($_REQUEST['change_all_collations']) ) { PMA_changeAllColumnsCollation( $GLOBALS['db'], $GLOBALS['table'], $_REQUEST['tbl_collation'] ); } } /** * Reordering the table has been requested by the user */ if (isset($_REQUEST['submitorderby']) && ! empty($_REQUEST['order_field'])) { list($sql_query, $result) = PMA_getQueryAndResultForReorderingTable(); } // end if /** * A partition operation has been requested by the user */ if (isset($_REQUEST['submit_partition']) && ! empty($_REQUEST['partition_operation']) ) { list($sql_query, $result) = PMA_getQueryAndResultForPartition(); } // end if if ($reread_info) { // to avoid showing the old value (for example the AUTO_INCREMENT) after // a change, clear the cache $GLOBALS['dbi']->clearTableCache(); $GLOBALS['dbi']->selectDb($GLOBALS['db']); $GLOBALS['showtable'] = $pma_table->getStatusInfo(null, true); if ($pma_table->isView()) { $tbl_is_view = true; $tbl_storage_engine = __('View'); $show_comment = null; } else { $tbl_is_view = false; $tbl_storage_engine = $pma_table->getStorageEngine(); $show_comment = $pma_table->getComment(); } $tbl_collation = $pma_table->getCollation(); $table_info_num_rows = $pma_table->getNumRows(); $row_format = $pma_table->getRowFormat(); $auto_increment = $pma_table->getAutoIncrement(); $create_options = $pma_table->getCreateOptions(); } unset($reread_info); if (isset($result) && empty($message_to_show)) { if (empty($_message)) { if (empty($sql_query)) { $_message = PMA\libraries\Message::success(__('No change')); } else { $_message = $result ? PMA\libraries\Message::success() : PMA\libraries\Message::error(); } if ($response->isAjax()) { $response->setRequestStatus($_message->isSuccess()); $response->addJSON('message', $_message); if (!empty($sql_query)) { $response->addJSON( 'sql_query', PMA\libraries\Util::getMessage(null, $sql_query) ); } exit; } } else { $_message = $result ? PMA\libraries\Message::success($_message) : PMA\libraries\Message::error($_message); } if (! empty($warning_messages)) { $_message = new PMA\libraries\Message; $_message->addMessagesString($warning_messages); $_message->isError(true); if ($response->isAjax()) { $response->setRequestStatus(false); $response->addJSON('message', $_message); if (!empty($sql_query)) { $response->addJSON( 'sql_query', PMA\libraries\Util::getMessage(null, $sql_query) ); } exit; } unset($warning_messages); } if (empty($sql_query)) { $response->addHTML( $_message->getDisplay() ); } else { $response->addHTML( PMA\libraries\Util::getMessage($_message, $sql_query) ); } unset($_message); } $url_params['goto'] = $url_params['back'] = 'tbl_operations.php'; /** * Get columns names */ $columns = $GLOBALS['dbi']->getColumns($GLOBALS['db'], $GLOBALS['table']); /** * Displays the page */ $response->addHTML('<div id="boxContainer" data-box-width="300">'); /** * Order the table */ $hideOrderTable = false; // `ALTER TABLE ORDER BY` does not make sense for InnoDB tables that contain // a user-defined clustered index (PRIMARY KEY or NOT NULL UNIQUE index). // InnoDB always orders table rows according to such an index if one is present. if ($tbl_storage_engine == 'INNODB') { $indexes = PMA\libraries\Index::getFromTable($GLOBALS['table'], $GLOBALS['db']); foreach ($indexes as $name => $idx) { if ($name == 'PRIMARY') { $hideOrderTable = true; break; } elseif (! $idx->getNonUnique()) { $notNull = true; foreach ($idx->getColumns() as $column) { if ($column->getNull()) { $notNull = false; break; } } if ($notNull) { $hideOrderTable = true; break; } } } } if (! $hideOrderTable) { $response->addHTML(PMA_getHtmlForOrderTheTable($columns)); } /** * Move table */ $response->addHTML(PMA_getHtmlForMoveTable()); if (mb_strstr($show_comment, '; InnoDB free') === false) { if (mb_strstr($show_comment, 'InnoDB free') === false) { // only user entered comment $comment = $show_comment; } else { // here we have just InnoDB generated part $comment = ''; } } else { // remove InnoDB comment from end, just the minimal part (*? is non greedy) $comment = preg_replace('@; InnoDB free:.*?$@', '', $show_comment); } // PACK_KEYS: MyISAM or ISAM // DELAY_KEY_WRITE, CHECKSUM, : MyISAM only // AUTO_INCREMENT: MyISAM and InnoDB since 5.0.3, PBXT // Here should be version check for InnoDB, however it is supported // in >5.0.4, >4.1.12 and >4.0.11, so I decided not to // check for version $response->addHTML( PMA_getTableOptionDiv( $pma_table, $comment, $tbl_collation, $tbl_storage_engine, $create_options['pack_keys'], $auto_increment, (empty($create_options['delay_key_write']) ? '0' : '1'), ((isset($create_options['transactional']) && $create_options['transactional'] == '0') ? '0' : '1'), ((isset($create_options['page_checksum'])) ? $create_options['page_checksum'] : ''), (empty($create_options['checksum']) ? '0' : '1') ) ); /** * Copy table */ $response->addHTML(PMA_getHtmlForCopytable()); /** * Table maintenance */ $response->addHTML( PMA_getHtmlForTableMaintenance($pma_table, $url_params) ); if (! (isset($db_is_system_schema) && $db_is_system_schema)) { $truncate_table_url_params = array(); $drop_table_url_params = array(); if (! $tbl_is_view && ! (isset($db_is_system_schema) && $db_is_system_schema) ) { $this_sql_query = 'TRUNCATE TABLE ' . PMA\libraries\Util::backquote($GLOBALS['table']); $truncate_table_url_params = array_merge( $url_params, array( 'sql_query' => $this_sql_query, 'goto' => 'tbl_structure.php', 'reload' => '1', 'message_to_show' => sprintf( __('Table %s has been emptied.'), htmlspecialchars($table) ), ) ); } if (! (isset($db_is_system_schema) && $db_is_system_schema)) { $this_sql_query = 'DROP TABLE ' . PMA\libraries\Util::backquote($GLOBALS['table']); $drop_table_url_params = array_merge( $url_params, array( 'sql_query' => $this_sql_query, 'goto' => 'db_operations.php', 'reload' => '1', 'purge' => '1', 'message_to_show' => sprintf( ($tbl_is_view ? __('View %s has been dropped.') : __('Table %s has been dropped.') ), htmlspecialchars($table) ), // table name is needed to avoid running // PMA_relationsCleanupDatabase() on the whole db later 'table' => $GLOBALS['table'], ) ); } $response->addHTML( PMA_getHtmlForDeleteDataOrTable( $truncate_table_url_params, $drop_table_url_params ) ); } if (Partition::havePartitioning()) { $partition_names = Partition::getPartitionNames($db, $table); // show the Partition maintenance section only if we detect a partition if (! is_null($partition_names[0])) { $response->addHTML( PMA_getHtmlForPartitionMaintenance($partition_names, $url_params) ); } // end if } // end if unset($partition_names); // Referential integrity check // The Referential integrity check was intended for the non-InnoDB // tables for which the relations are defined in pmadb // so I assume that if the current table is InnoDB, I don't display // this choice (InnoDB maintains integrity by itself) if ($cfgRelation['relwork'] && ! $pma_table->isEngine("INNODB")) { $GLOBALS['dbi']->selectDb($GLOBALS['db']); $foreign = PMA_getForeigners($GLOBALS['db'], $GLOBALS['table'], '', 'internal'); if (! empty($foreign)) { $response->addHTML( PMA_getHtmlForReferentialIntegrityCheck($foreign, $url_params) ); } // end if ($foreign) } // end if (!empty($cfg['Server']['relation'])) $response->addHTML('</div>');
ragnerok/phpmyadmin
tbl_operations.php
PHP
gpl-2.0
15,012
//===--- Diagnostics.cpp - Helper class for error diagnostics -----*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "clang/ASTMatchers/Dynamic/Diagnostics.h" namespace clang { namespace ast_matchers { namespace dynamic { Diagnostics::ArgStream Diagnostics::pushContextFrame(ContextType Type, SourceRange Range) { ContextStack.emplace_back(); ContextFrame& data = ContextStack.back(); data.Type = Type; data.Range = Range; return ArgStream(&data.Args); } Diagnostics::Context::Context(ConstructMatcherEnum, Diagnostics *Error, StringRef MatcherName, const SourceRange &MatcherRange) : Error(Error) { Error->pushContextFrame(CT_MatcherConstruct, MatcherRange) << MatcherName; } Diagnostics::Context::Context(MatcherArgEnum, Diagnostics *Error, StringRef MatcherName, const SourceRange &MatcherRange, unsigned ArgNumber) : Error(Error) { Error->pushContextFrame(CT_MatcherArg, MatcherRange) << ArgNumber << MatcherName; } Diagnostics::Context::~Context() { Error->ContextStack.pop_back(); } Diagnostics::OverloadContext::OverloadContext(Diagnostics *Error) : Error(Error), BeginIndex(Error->Errors.size()) {} Diagnostics::OverloadContext::~OverloadContext() { // Merge all errors that happened while in this context. if (BeginIndex < Error->Errors.size()) { Diagnostics::ErrorContent &Dest = Error->Errors[BeginIndex]; for (size_t i = BeginIndex + 1, e = Error->Errors.size(); i < e; ++i) { Dest.Messages.push_back(Error->Errors[i].Messages[0]); } Error->Errors.resize(BeginIndex + 1); } } void Diagnostics::OverloadContext::revertErrors() { // Revert the errors. Error->Errors.resize(BeginIndex); } Diagnostics::ArgStream &Diagnostics::ArgStream::operator<<(const Twine &Arg) { Out->push_back(Arg.str()); return *this; } Diagnostics::ArgStream Diagnostics::addError(const SourceRange &Range, ErrorType Error) { Errors.emplace_back(); ErrorContent &Last = Errors.back(); Last.ContextStack = ContextStack; Last.Messages.emplace_back(); Last.Messages.back().Range = Range; Last.Messages.back().Type = Error; return ArgStream(&Last.Messages.back().Args); } static StringRef contextTypeToFormatString(Diagnostics::ContextType Type) { switch (Type) { case Diagnostics::CT_MatcherConstruct: return "Error building matcher $0."; case Diagnostics::CT_MatcherArg: return "Error parsing argument $0 for matcher $1."; } llvm_unreachable("Unknown ContextType value."); } static StringRef errorTypeToFormatString(Diagnostics::ErrorType Type) { switch (Type) { case Diagnostics::ET_RegistryMatcherNotFound: return "Matcher not found: $0"; case Diagnostics::ET_RegistryWrongArgCount: return "Incorrect argument count. (Expected = $0) != (Actual = $1)"; case Diagnostics::ET_RegistryWrongArgType: return "Incorrect type for arg $0. (Expected = $1) != (Actual = $2)"; case Diagnostics::ET_RegistryNotBindable: return "Matcher does not support binding."; case Diagnostics::ET_RegistryAmbiguousOverload: // TODO: Add type info about the overload error. return "Ambiguous matcher overload."; case Diagnostics::ET_RegistryValueNotFound: return "Value not found: $0"; case Diagnostics::ET_ParserStringError: return "Error parsing string token: <$0>"; case Diagnostics::ET_ParserNoOpenParen: return "Error parsing matcher. Found token <$0> while looking for '('."; case Diagnostics::ET_ParserNoCloseParen: return "Error parsing matcher. Found end-of-code while looking for ')'."; case Diagnostics::ET_ParserNoComma: return "Error parsing matcher. Found token <$0> while looking for ','."; case Diagnostics::ET_ParserNoCode: return "End of code found while looking for token."; case Diagnostics::ET_ParserNotAMatcher: return "Input value is not a matcher expression."; case Diagnostics::ET_ParserInvalidToken: return "Invalid token <$0> found when looking for a value."; case Diagnostics::ET_ParserMalformedBindExpr: return "Malformed bind() expression."; case Diagnostics::ET_ParserTrailingCode: return "Expected end of code."; case Diagnostics::ET_ParserUnsignedError: return "Error parsing unsigned token: <$0>"; case Diagnostics::ET_ParserOverloadedType: return "Input value has unresolved overloaded type: $0"; case Diagnostics::ET_None: return "<N/A>"; } llvm_unreachable("Unknown ErrorType value."); } static void formatErrorString(StringRef FormatString, ArrayRef<std::string> Args, llvm::raw_ostream &OS) { while (!FormatString.empty()) { std::pair<StringRef, StringRef> Pieces = FormatString.split("$"); OS << Pieces.first.str(); if (Pieces.second.empty()) break; const char Next = Pieces.second.front(); FormatString = Pieces.second.drop_front(); if (Next >= '0' && Next <= '9') { const unsigned Index = Next - '0'; if (Index < Args.size()) { OS << Args[Index]; } else { OS << "<Argument_Not_Provided>"; } } } } static void maybeAddLineAndColumn(const SourceRange &Range, llvm::raw_ostream &OS) { if (Range.Start.Line > 0 && Range.Start.Column > 0) { OS << Range.Start.Line << ":" << Range.Start.Column << ": "; } } static void printContextFrameToStream(const Diagnostics::ContextFrame &Frame, llvm::raw_ostream &OS) { maybeAddLineAndColumn(Frame.Range, OS); formatErrorString(contextTypeToFormatString(Frame.Type), Frame.Args, OS); } static void printMessageToStream(const Diagnostics::ErrorContent::Message &Message, const Twine Prefix, llvm::raw_ostream &OS) { maybeAddLineAndColumn(Message.Range, OS); OS << Prefix; formatErrorString(errorTypeToFormatString(Message.Type), Message.Args, OS); } static void printErrorContentToStream(const Diagnostics::ErrorContent &Content, llvm::raw_ostream &OS) { if (Content.Messages.size() == 1) { printMessageToStream(Content.Messages[0], "", OS); } else { for (size_t i = 0, e = Content.Messages.size(); i != e; ++i) { if (i != 0) OS << "\n"; printMessageToStream(Content.Messages[i], "Candidate " + Twine(i + 1) + ": ", OS); } } } void Diagnostics::printToStream(llvm::raw_ostream &OS) const { for (size_t i = 0, e = Errors.size(); i != e; ++i) { if (i != 0) OS << "\n"; printErrorContentToStream(Errors[i], OS); } } std::string Diagnostics::toString() const { std::string S; llvm::raw_string_ostream OS(S); printToStream(OS); return OS.str(); } void Diagnostics::printToStreamFull(llvm::raw_ostream &OS) const { for (size_t i = 0, e = Errors.size(); i != e; ++i) { if (i != 0) OS << "\n"; const ErrorContent &Error = Errors[i]; for (size_t i = 0, e = Error.ContextStack.size(); i != e; ++i) { printContextFrameToStream(Error.ContextStack[i], OS); OS << "\n"; } printErrorContentToStream(Error, OS); } } std::string Diagnostics::toStringFull() const { std::string S; llvm::raw_string_ostream OS(S); printToStreamFull(OS); return OS.str(); } } // namespace dynamic } // namespace ast_matchers } // namespace clang
rutgers-apl/Atomicity-Violation-Detector
tdebug-llvm/clang/lib/ASTMatchers/Dynamic/Diagnostics.cpp
C++
gpl-2.0
7,830
<?php /** *@file * Corp theme's implementation to display a single drupal page. */ global $base_url; $header_style = ''; //$header_bg_file = theme_get_setting('header_bg_file'); //if ($header_bg_file) { // $header_style .= 'filter:;background: url(' . $header_bg_file . ') repeat '; //} $header_bg_file = theme_get_setting('header_bg_file'); if ($header_bg_file) { $header_style .= 'filter:;background: url(' . $header_bg_file . ') repeat '; $header_style .= theme_get_setting('header_bg_alignment') . ';'; } ?> <div id="page" class="<?php print $classes; ?>"<?php print $attributes; ?>> <!-- ______________________ HEADER _______________________ --> <header id="header" style="<?php //echo $header_style; ?>> <?php if ($logo): ?> <a href="<?php print $front_page; ?>" title="<?php print t('Home'); ?>" rel="home" id="logo"> <img src="<?php print $logo; ?>" alt="<?php print t('Home'); ?>"/> </a> <?php endif; ?> <?php if ($site_name || $site_slogan): ?> <hgroup id="name-and-slogan"> <?php if ($site_name): ?> <?php if ($title): ?> <div id="site-name"> <a href="<?php print $front_page; ?>" title="<?php print t('Home'); ?>" rel="home"><?php print $site_name; ?></a> </div> <?php else: /* Use h1 when the content title is empty */ ?> <h1 id="site-name"> <a href="<?php print $front_page; ?>" title="<?php print t('Home'); ?>" rel="home"><?php print $site_name; ?></a> </h1> <?php endif; ?> <?php endif; ?> <?php if ($site_slogan): ?> <div id="site-slogan"><?php print $site_slogan; ?></div> <?php endif; ?> </hgroup> <?php endif; ?> <?php if ($page['header']): ?> <div id="header-region"> <?php print render($page['header']); ?> </div> <?php endif; ?> <!-- customize social links code --> <?php if (theme_get_setting('socialicon_display', 'corp')): ?> <?php $twitter_url = check_plain(theme_get_setting('twitter_url', 'corp')); $facebook_url = check_plain(theme_get_setting('facebook_url', 'corp')); $linkedin_url = check_plain(theme_get_setting('linkedin_url', 'corp')); $theme_path_social = base_path() . drupal_get_path('theme', 'corp'); ?> <div id="socialbar"> <ul class="social"> <?php if ($facebook_url): ?><li> <a href="<?php print $facebook_url; ?>" target="_blank"> <img src="<?php print $theme_path_social; ?>/images/facebook.png"> </a> </li> <?php endif; ?> <?php if ($twitter_url): ?><li> <a href="<?php print $twitter_url; ?>" target="_blank"> <img src="<?php print $theme_path_social; ?>/images/twitter.png"> </a> </li> <?php endif; ?> <?php if ($linkedin_url): ?><li> <a href="<?php print $linkedin_url; ?>" target="_blank"> <img src="<?php print $theme_path_social; ?>/images/in.png"> </a> </li> <?php endif; ?> <li> <a href="<?php print $front_page; ?>rss.xml"> <img src="<?php print $theme_path_social; ?>/images/rss.png"> </a> </li> </ul> </div> <?php endif; ?> <!-- customize social links code --> <div style="clear:both;"></div> </header> <!-- /header --> <?php if ($main_menu || $secondary_menu): ?> <nav id="navigation" class="menu <?php if (!empty($main_menu)) {print "with-primary";} if (!empty($secondary_menu)) {print " with-secondary";} ?>"> <?php print theme('links', array('links' => $main_menu, 'attributes' => array('id' => 'primary', 'class' => array('links', 'clearfix', 'main-menu')))); ?> <?php print theme('links', array('links' => $secondary_menu, 'attributes' => array('id' => 'secondary', 'class' => array('links', 'clearfix', 'sub-menu')))); ?> </nav> <!-- /navigation --> <?php endif; ?> <!--code to print the image in region--> <div id="banner_img" style="<?php echo $header_style; ?>"></div> <!-- ______________________ MAIN _______________________ --> <div id="main" class="clearfix"> <section id="content"> <?php if ($breadcrumb || $title|| $messages || $tabs || $action_links): ?> <div id="content-header"> <?php print $breadcrumb; ?> <?php if ($page['highlighted']): ?> <div id="highlighted"><?php print render($page['highlighted']) ?></div> <?php endif; ?> <?php print render($title_prefix); ?> <?php if ($title): ?> <h1 class="title"><?php print $title; ?></h1> <?php endif; ?> <?php print render($title_suffix); ?> <?php print $messages; ?> <?php print render($page['help']); ?> <?php if ($tabs): ?> <div class="tabs"><?php print render($tabs); ?></div> <?php endif; ?> <?php if ($action_links): ?> <ul class="action-links"><?php print render($action_links); ?></ul> <?php endif; ?> </div> <!-- /#content-header --> <?php endif; ?> <div id="content-area"> <?php print render($page['content']) ?> </div> <?php print $feed_icons; ?> </section> <!-- /content-inner /content --> <?php if ($page['sidebar_first']): ?> <aside id="sidebar-first" class="column sidebar first"> <?php print render($page['sidebar_first']); ?> </aside> <?php endif; ?> <!-- /sidebar-first --> <?php if ($page['sidebar_second']): ?> <aside id="sidebar-second" class="column sidebar second"> <?php print render($page['sidebar_second']); ?> </aside> <?php endif; ?> <!-- /sidebar-second --> </div> <!-- /main --> <!-- ______________________ PAGE BOTTOM _______________________ --> <div style="clear:both"></div> <?php if ($page['content_bottom']): ?> <div id="content-bottom"> <?php print render($page['content_bottom']); ?> </div> <!-- /footer --> <?php endif; ?> <!--Custom Bottom Columns--> <?php if ($page['bottom_column_first'] | $page['bottom_column_second'] | $page['bottom_column_third'] ) { ?> <div id="bottom-columns"> <?php print corp_build_columns( array( render($page['bottom_column_first']), render($page['bottom_column_second']), render($page['bottom_column_third']), )); ?> </div> <!--/bottom-columns --> <?php } ?> <!-- ______________________ FOOTER _______________________ --> <?php if ($page['footer']): ?> <footer id="footer"> <?php print render($page['footer']); ?> </footer> <!-- /footer --> <?php endif; ?> </div> <!-- /page -->
billmagee/bottomline
sites/all/themes/corp/templates/page.tpl.php
PHP
gpl-2.0
6,771
/** * \file Author.cpp * This file is part of LyX, the document processor. * Licence details can be found in the file COPYING. * * \author John Levon * * Full author contact details are available in file CREDITS. */ #include <config.h> #include "Author.h" #include "support/lassert.h" #include "support/lstrings.h" #include <algorithm> #include <istream> using namespace std; using namespace lyx::support; namespace lyx { static int computeHash(docstring const & name, docstring const & email) { string const full_author_string = to_utf8(name + email); // Bernstein's hash function unsigned int hash = 5381; for (unsigned int i = 0; i < full_author_string.length(); ++i) hash = ((hash << 5) + hash) + (unsigned int)(full_author_string[i]); return int(hash); } Author::Author(docstring const & name, docstring const & email) : name_(name), email_(email), used_(true) { buffer_id_ = computeHash(name_, email_); } bool operator==(Author const & l, Author const & r) { return l.name() == r.name() && l.email() == r.email(); } ostream & operator<<(ostream & os, Author const & a) { // FIXME UNICODE os << a.buffer_id_ << " \"" << to_utf8(a.name_) << "\" " << to_utf8(a.email_); return os; } istream & operator>>(istream & is, Author & a) { string s; is >> a.buffer_id_; getline(is, s); // FIXME UNICODE a.name_ = from_utf8(trim(token(s, '\"', 1))); a.email_ = from_utf8(trim(token(s, '\"', 2))); return is; } bool author_smaller(Author const & lhs, Author const & rhs) { return lhs.bufferId() < rhs.bufferId(); } AuthorList::AuthorList() : last_id_(0) {} int AuthorList::record(Author const & a) { // If we record an author which equals the current // author, we copy the buffer_id, so that it will // keep the same id in the file. if (!authors_.empty() && a == authors_[0]) authors_[0].setBufferId(a.bufferId()); Authors::const_iterator it(authors_.begin()); Authors::const_iterator itend(authors_.end()); for (int i = 0; it != itend; ++it, ++i) { if (*it == a) return i; } authors_.push_back(a); return last_id_++; } void AuthorList::record(int id, Author const & a) { LBUFERR(unsigned(id) < authors_.size()); authors_[id] = a; } void AuthorList::recordCurrentAuthor(Author const & a) { // current author has id 0 record(0, a); } Author const & AuthorList::get(int id) const { LASSERT(id < (int)authors_.size() , return authors_[0]); return authors_[id]; } AuthorList::Authors::const_iterator AuthorList::begin() const { return authors_.begin(); } AuthorList::Authors::const_iterator AuthorList::end() const { return authors_.end(); } void AuthorList::sort() { std::sort(authors_.begin(), authors_.end(), author_smaller); } ostream & operator<<(ostream & os, AuthorList const & a) { // Copy the authorlist, because we don't want to sort the original AuthorList sorted = a; sorted.sort(); AuthorList::Authors::const_iterator a_it = sorted.begin(); AuthorList::Authors::const_iterator a_end = sorted.end(); for (a_it = sorted.begin(); a_it != a_end; ++a_it) { if (a_it->used()) os << "\\author " << *a_it << "\n"; } return os; } } // namespace lyx
bpiwowar/lyx
src/Author.cpp
C++
gpl-2.0
3,160
//@tag dom,core //@define Ext-more //@require Ext.EventManager /** * @class Ext * * Ext is the global namespace for the whole Sencha Touch framework. Every class, function and configuration for the * whole framework exists under this single global variable. The Ext singleton itself contains a set of useful helper * functions (like {@link #apply}, {@link #min} and others), but most of the framework that you use day to day exists * in specialized classes (for example {@link Ext.Panel}, {@link Ext.Carousel} and others). * * If you are new to Sencha Touch we recommend starting with the [Getting Started Guide][getting_started] to * get a feel for how the framework operates. After that, use the more focused guides on subjects like panels, forms and data * to broaden your understanding. The MVC guides take you through the process of building full applications using the * framework, and detail how to deploy them to production. * * The functions listed below are mostly utility functions used internally by many of the classes shipped in the * framework, but also often useful in your own apps. * * A method that is crucial to beginning your application is {@link #setup Ext.setup}. Please refer to it's documentation, or the * [Getting Started Guide][getting_started] as a reference on beginning your application. * * Ext.setup({ * onReady: function() { * Ext.Viewport.add({ * xtype: 'component', * html: 'Hello world!' * }); * } * }); * * [getting_started]: #!/guide/getting_started */ Ext.setVersion('touch', '2.1.0'); Ext.apply(Ext, { /** * The version of the framework * @type String */ version: Ext.getVersion('touch'), /** * @private */ idSeed: 0, /** * Repaints the whole page. This fixes frequently encountered painting issues in mobile Safari. */ repaint: function() { var mask = Ext.getBody().createChild({ cls: Ext.baseCSSPrefix + 'mask ' + Ext.baseCSSPrefix + 'mask-transparent' }); setTimeout(function() { mask.destroy(); }, 0); }, /** * Generates unique ids. If the element already has an `id`, it is unchanged. * @param {Mixed} el (optional) The element to generate an id for. * @param {String} [prefix=ext-gen] (optional) The `id` prefix. * @return {String} The generated `id`. */ id: function(el, prefix) { if (el && el.id) { return el.id; } el = Ext.getDom(el) || {}; if (el === document || el === document.documentElement) { el.id = 'ext-application'; } else if (el === document.body) { el.id = 'ext-viewport'; } else if (el === window) { el.id = 'ext-window'; } el.id = el.id || ((prefix || 'ext-element-') + (++Ext.idSeed)); return el.id; }, /** * Returns the current document body as an {@link Ext.Element}. * @return {Ext.Element} The document body. */ getBody: function() { if (!Ext.documentBodyElement) { if (!document.body) { throw new Error("[Ext.getBody] document.body does not exist at this point"); } Ext.documentBodyElement = Ext.get(document.body); } return Ext.documentBodyElement; }, /** * Returns the current document head as an {@link Ext.Element}. * @return {Ext.Element} The document head. */ getHead: function() { if (!Ext.documentHeadElement) { Ext.documentHeadElement = Ext.get(document.head || document.getElementsByTagName('head')[0]); } return Ext.documentHeadElement; }, /** * Returns the current HTML document object as an {@link Ext.Element}. * @return {Ext.Element} The document. */ getDoc: function() { if (!Ext.documentElement) { Ext.documentElement = Ext.get(document); } return Ext.documentElement; }, /** * This is shorthand reference to {@link Ext.ComponentMgr#get}. * Looks up an existing {@link Ext.Component Component} by {@link Ext.Component#getId id} * @param {String} id The component {@link Ext.Component#getId id} * @return {Ext.Component} The Component, `undefined` if not found, or `null` if a * Class was found. */ getCmp: function(id) { return Ext.ComponentMgr.get(id); }, /** * Copies a set of named properties from the source object to the destination object. * * Example: * * ImageComponent = Ext.extend(Ext.Component, { * initComponent: function() { * this.autoEl = { tag: 'img' }; * MyComponent.superclass.initComponent.apply(this, arguments); * this.initialBox = Ext.copyTo({}, this.initialConfig, 'x,y,width,height'); * } * }); * * Important note: To borrow class prototype methods, use {@link Ext.Base#borrow} instead. * * @param {Object} dest The destination object. * @param {Object} source The source object. * @param {String/String[]} names Either an Array of property names, or a comma-delimited list * of property names to copy. * @param {Boolean} [usePrototypeKeys=false] (optional) Pass `true` to copy keys off of the prototype as well as the instance. * @return {Object} The modified object. */ copyTo : function(dest, source, names, usePrototypeKeys) { if (typeof names == 'string') { names = names.split(/[,;\s]/); } Ext.each (names, function(name) { if (usePrototypeKeys || source.hasOwnProperty(name)) { dest[name] = source[name]; } }, this); return dest; }, /** * Attempts to destroy any objects passed to it by removing all event listeners, removing them from the * DOM (if applicable) and calling their destroy functions (if available). This method is primarily * intended for arguments of type {@link Ext.Element} and {@link Ext.Component}. * Any number of elements and/or components can be passed into this function in a single * call as separate arguments. * @param {Mixed...} args An {@link Ext.Element}, {@link Ext.Component}, or an Array of either of these to destroy. */ destroy: function() { var args = arguments, ln = args.length, i, item; for (i = 0; i < ln; i++) { item = args[i]; if (item) { if (Ext.isArray(item)) { this.destroy.apply(this, item); } else if (Ext.isFunction(item.destroy)) { item.destroy(); } } } }, /** * Return the dom node for the passed String (id), dom node, or Ext.Element. * Here are some examples: * * // gets dom node based on id * var elDom = Ext.getDom('elId'); * * // gets dom node based on the dom node * var elDom1 = Ext.getDom(elDom); * * // If we don't know if we are working with an * // Ext.Element or a dom node use Ext.getDom * function(el){ * var dom = Ext.getDom(el); * // do something with the dom node * } * * __Note:__ the dom node to be found actually needs to exist (be rendered, etc) * when this method is called to be successful. * @param {Mixed} el * @return {HTMLElement} */ getDom: function(el) { if (!el || !document) { return null; } return el.dom ? el.dom : (typeof el == 'string' ? document.getElementById(el) : el); }, /** * Removes this element from the document, removes all DOM event listeners, and deletes the cache reference. * All DOM event listeners are removed from this element. * @param {HTMLElement} node The node to remove. */ removeNode: function(node) { if (node && node.parentNode && node.tagName != 'BODY') { Ext.get(node).clearListeners(); node.parentNode.removeChild(node); delete Ext.cache[node.id]; } }, /** * @private */ defaultSetupConfig: { eventPublishers: { dom: { xclass: 'Ext.event.publisher.Dom' }, touchGesture: { xclass: 'Ext.event.publisher.TouchGesture', recognizers: { drag: { xclass: 'Ext.event.recognizer.Drag' }, tap: { xclass: 'Ext.event.recognizer.Tap' }, doubleTap: { xclass: 'Ext.event.recognizer.DoubleTap' }, longPress: { xclass: 'Ext.event.recognizer.LongPress' }, swipe: { xclass: 'Ext.event.recognizer.HorizontalSwipe' }, pinch: { xclass: 'Ext.event.recognizer.Pinch' }, rotate: { xclass: 'Ext.event.recognizer.Rotate' } } }, componentDelegation: { xclass: 'Ext.event.publisher.ComponentDelegation' }, componentPaint: { xclass: 'Ext.event.publisher.ComponentPaint' }, // componentSize: { // xclass: 'Ext.event.publisher.ComponentSize' // }, elementPaint: { xclass: 'Ext.event.publisher.ElementPaint' }, elementSize: { xclass: 'Ext.event.publisher.ElementSize' } }, //<feature logger> logger: { enabled: true, xclass: 'Ext.log.Logger', minPriority: 'deprecate', writers: { console: { xclass: 'Ext.log.writer.Console', throwOnErrors: true, formatter: { xclass: 'Ext.log.formatter.Default' } } } }, //</feature> animator: { xclass: 'Ext.fx.Runner' }, viewport: { xclass: 'Ext.viewport.Viewport' } }, /** * @private */ isSetup: false, /** * This indicate the start timestamp of current cycle. * It is only reliable during dom-event-initiated cycles and * {@link Ext.draw.Animator} initiated cycles. */ frameStartTime: +new Date(), /** * @private */ setupListeners: [], /** * @private */ onSetup: function(fn, scope) { if (Ext.isSetup) { fn.call(scope); } else { Ext.setupListeners.push({ fn: fn, scope: scope }); } }, /** * Ext.setup() is the entry-point to initialize a Sencha Touch application. Note that if your application makes * use of MVC architecture, use {@link Ext#application} instead. * * This method accepts one single argument in object format. The most basic use of Ext.setup() is as follows: * * Ext.setup({ * onReady: function() { * // ... * } * }); * * This sets up the viewport, initializes the event system, instantiates a default animation runner, and a default * logger (during development). When all of that is ready, it invokes the callback function given to the `onReady` key. * * The default scope (`this`) of `onReady` is the main viewport. By default the viewport instance is stored in * {@link Ext.Viewport}. For example, this snippet adds a 'Hello World' button that is centered on the screen: * * Ext.setup({ * onReady: function() { * this.add({ * xtype: 'button', * centered: true, * text: 'Hello world!' * }); // Equivalent to Ext.Viewport.add(...) * } * }); * * @param {Object} config An object with the following config options: * * @param {Function} config.onReady * A function to be called when the application is ready. Your application logic should be here. * * @param {Object} config.viewport * A custom config object to be used when creating the global {@link Ext.Viewport} instance. Please refer to the * {@link Ext.Viewport} documentation for more information. * * Ext.setup({ * viewport: { * width: 500, * height: 500 * }, * onReady: function() { * // ... * } * }); * * @param {String/Object} config.icon * Specifies a set of URLs to the application icon for different device form factors. This icon is displayed * when the application is added to the device's Home Screen. * * Ext.setup({ * icon: { * 57: 'resources/icons/Icon.png', * 72: 'resources/icons/Icon~ipad.png', * 114: 'resources/icons/Icon@2x.png', * 144: 'resources/icons/Icon~ipad@2x.png' * }, * onReady: function() { * // ... * } * }); * * Each key represents the dimension of the icon as a square shape. For example: '57' is the key for a 57 x 57 * icon image. Here is the breakdown of each dimension and its device target: * * - 57: Non-retina iPhone, iPod touch, and all Android devices * - 72: Retina iPhone and iPod touch * - 114: Non-retina iPad (first and second generation) * - 144: Retina iPad (third generation) * * Note that the dimensions of the icon images must be exactly 57x57, 72x72, 114x114 and 144x144 respectively. * * It is highly recommended that you provide all these different sizes to accommodate a full range of * devices currently available. However if you only have one icon in one size, make it 57x57 in size and * specify it as a string value. This same icon will be used on all supported devices. * * Ext.setup({ * icon: 'resources/icons/Icon.png', * onReady: function() { * // ... * } * }); * * @param {Object} config.startupImage * Specifies a set of URLs to the application startup images for different device form factors. This image is * displayed when the application is being launched from the Home Screen icon. Note that this currently only applies * to iOS devices. * * Ext.setup({ * startupImage: { * '320x460': 'resources/startup/320x460.jpg', * '640x920': 'resources/startup/640x920.png', * '640x1096': 'resources/startup/640x1096.png', * '768x1004': 'resources/startup/768x1004.png', * '748x1024': 'resources/startup/748x1024.png', * '1536x2008': 'resources/startup/1536x2008.png', * '1496x2048': 'resources/startup/1496x2048.png' * }, * onReady: function() { * // ... * } * }); * * Each key represents the dimension of the image. For example: '320x460' is the key for a 320px x 460px image. * Here is the breakdown of each dimension and its device target: * * - 320x460: Non-retina iPhone, iPod touch, and all Android devices * - 640x920: Retina iPhone and iPod touch * - 640x1096: iPhone 5 and iPod touch (fifth generation) * - 768x1004: Non-retina iPad (first and second generation) in portrait orientation * - 748x1024: Non-retina iPad (first and second generation) in landscape orientation * - 1536x2008: Retina iPad (third generation) in portrait orientation * - 1496x2048: Retina iPad (third generation) in landscape orientation * * Please note that there's no automatic fallback mechanism for the startup images. In other words, if you don't specify * a valid image for a certain device, nothing will be displayed while the application is being launched on that device. * * @param {Boolean} isIconPrecomposed * True to not having a glossy effect added to the icon by the OS, which will preserve its exact look. This currently * only applies to iOS devices. * * @param {String} statusBarStyle * The style of status bar to be shown on applications added to the iOS home screen. Valid options are: * * * `default` * * `black` * * `black-translucent` * * @param {String[]} config.requires * An array of required classes for your application which will be automatically loaded before `onReady` is invoked. * Please refer to {@link Ext.Loader} and {@link Ext.Loader#require} for more information. * * Ext.setup({ * requires: ['Ext.Button', 'Ext.tab.Panel'], * onReady: function() { * // ... * } * }); * * @param {Object} config.eventPublishers * Sencha Touch, by default, includes various {@link Ext.event.recognizer.Recognizer} subclasses to recognize events fired * in your application. The list of default recognizers can be found in the documentation for * {@link Ext.event.recognizer.Recognizer}. * * To change the default recognizers, you can use the following syntax: * * Ext.setup({ * eventPublishers: { * touchGesture: { * recognizers: { * swipe: { * // this will include both vertical and horizontal swipe recognizers * xclass: 'Ext.event.recognizer.Swipe' * } * } * } * }, * onReady: function() { * // ... * } * }); * * You can also disable recognizers using this syntax: * * Ext.setup({ * eventPublishers: { * touchGesture: { * recognizers: { * swipe: null, * pinch: null, * rotate: null * } * } * }, * onReady: function() { * // ... * } * }); */ setup: function(config) { var defaultSetupConfig = Ext.defaultSetupConfig, emptyFn = Ext.emptyFn, onReady = config.onReady || emptyFn, onUpdated = config.onUpdated || emptyFn, scope = config.scope, requires = Ext.Array.from(config.requires), extOnReady = Ext.onReady, head = Ext.getHead(), callback, viewport, precomposed; Ext.setup = function() { throw new Error("Ext.setup has already been called before"); }; delete config.requires; delete config.onReady; delete config.onUpdated; delete config.scope; Ext.require(['Ext.event.Dispatcher']); callback = function() { var listeners = Ext.setupListeners, ln = listeners.length, i, listener; delete Ext.setupListeners; Ext.isSetup = true; for (i = 0; i < ln; i++) { listener = listeners[i]; listener.fn.call(listener.scope); } Ext.onReady = extOnReady; Ext.onReady(onReady, scope); }; Ext.onUpdated = onUpdated; Ext.onReady = function(fn, scope) { var origin = onReady; onReady = function() { origin(); Ext.onReady(fn, scope); }; }; config = Ext.merge({}, defaultSetupConfig, config); Ext.onDocumentReady(function() { Ext.factoryConfig(config, function(data) { Ext.event.Dispatcher.getInstance().setPublishers(data.eventPublishers); if (data.logger) { Ext.Logger = data.logger; } if (data.animator) { Ext.Animator = data.animator; } if (data.viewport) { Ext.Viewport = viewport = data.viewport; if (!scope) { scope = viewport; } Ext.require(requires, function() { Ext.Viewport.on('ready', callback, null, {single: true}); }); } else { Ext.require(requires, callback); } }); }); function addMeta(name, content) { var meta = document.createElement('meta'); meta.setAttribute('name', name); meta.setAttribute('content', content); head.append(meta); } function addIcon(href, sizes, precomposed) { var link = document.createElement('link'); link.setAttribute('rel', 'apple-touch-icon' + (precomposed ? '-precomposed' : '')); link.setAttribute('href', href); if (sizes) { link.setAttribute('sizes', sizes); } head.append(link); } function addStartupImage(href, media) { var link = document.createElement('link'); link.setAttribute('rel', 'apple-touch-startup-image'); link.setAttribute('href', href); if (media) { link.setAttribute('media', media); } head.append(link); } var icon = config.icon, isIconPrecomposed = Boolean(config.isIconPrecomposed), startupImage = config.startupImage || {}, statusBarStyle = config.statusBarStyle, devicePixelRatio = window.devicePixelRatio || 1; if (navigator.standalone) { addMeta('viewport', 'width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0'); } else { addMeta('viewport', 'initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0'); } addMeta('apple-mobile-web-app-capable', 'yes'); addMeta('apple-touch-fullscreen', 'yes'); // status bar style if (statusBarStyle) { addMeta('apple-mobile-web-app-status-bar-style', statusBarStyle); } if (Ext.isString(icon)) { icon = { 57: icon, 72: icon, 114: icon, 144: icon }; } else if (!icon) { icon = {}; } //<deprecated product=touch since=2.0.1> if ('phoneStartupScreen' in config) { //<debug warn> Ext.Logger.deprecate("[Ext.setup()] 'phoneStartupScreen' config is deprecated, please use 'startupImage' " + "config instead. Refer to the latest API docs for more details"); //</debug> config['320x460'] = config.phoneStartupScreen; } if ('tabletStartupScreen' in config) { //<debug warn> Ext.Logger.deprecate("[Ext.setup()] 'tabletStartupScreen' config is deprecated, please use 'startupImage' " + "config instead. Refer to the latest API docs for more details"); //</debug> config['768x1004'] = config.tabletStartupScreen; } if ('glossOnIcon' in config) { //<debug warn> Ext.Logger.deprecate("[Ext.setup()] 'glossOnIcon' config is deprecated, please use 'isIconPrecomposed' " + "config instead. Refer to the latest API docs for more details"); //</debug> isIconPrecomposed = Boolean(config.glossOnIcon); } //</deprecated> if (Ext.os.is.iPad) { if (devicePixelRatio >= 2) { // Retina iPad - Landscape if ('1496x2048' in startupImage) { addStartupImage(startupImage['1496x2048'], '(orientation: landscape)'); } // Retina iPad - Portrait if ('1536x2008' in startupImage) { addStartupImage(startupImage['1536x2008'], '(orientation: portrait)'); } // Retina iPad if ('144' in icon) { addIcon(icon['144'], '144x144', isIconPrecomposed); } } else { // Non-Retina iPad - Landscape if ('748x1024' in startupImage) { addStartupImage(startupImage['748x1024'], '(orientation: landscape)'); } // Non-Retina iPad - Portrait if ('768x1004' in startupImage) { addStartupImage(startupImage['768x1004'], '(orientation: portrait)'); } // Non-Retina iPad if ('72' in icon) { addIcon(icon['72'], '72x72', isIconPrecomposed); } } } else { // Retina iPhone, iPod touch with iOS version >= 4.3 if (devicePixelRatio >= 2 && Ext.os.version.gtEq('4.3')) { if (Ext.os.is.iPhone5) { addStartupImage(startupImage['640x1096']); } else { addStartupImage(startupImage['640x920']); } // Retina iPhone and iPod touch if ('114' in icon) { addIcon(icon['114'], '114x114', isIconPrecomposed); } } else { addStartupImage(startupImage['320x460']); // Non-Retina iPhone, iPod touch, and Android devices if ('57' in icon) { addIcon(icon['57'], null, isIconPrecomposed); } } } }, /** * @member Ext * @method application * * Loads Ext.app.Application class and starts it up with given configuration after the page is ready. * * Ext.application({ * launch: function() { * alert('Application launched!'); * } * }); * * See {@link Ext.app.Application} for details. * * @param {Object} config An object with the following config options: * * @param {Function} config.launch * A function to be called when the application is ready. Your application logic should be here. Please see {@link Ext.app.Application} * for details. * * @param {Object} config.viewport * An object to be used when creating the global {@link Ext.Viewport} instance. Please refer to the {@link Ext.Viewport} * documentation for more information. * * Ext.application({ * viewport: { * layout: 'vbox' * }, * launch: function() { * Ext.Viewport.add({ * flex: 1, * html: 'top (flex: 1)' * }); * * Ext.Viewport.add({ * flex: 4, * html: 'bottom (flex: 4)' * }); * } * }); * * @param {String/Object} config.icon * Specifies a set of URLs to the application icon for different device form factors. This icon is displayed * when the application is added to the device's Home Screen. * * Ext.application({ * icon: { * 57: 'resources/icons/Icon.png', * 72: 'resources/icons/Icon~ipad.png', * 114: 'resources/icons/Icon@2x.png', * 144: 'resources/icons/Icon~ipad@2x.png' * }, * launch: function() { * // ... * } * }); * * Each key represents the dimension of the icon as a square shape. For example: '57' is the key for a 57 x 57 * icon image. Here is the breakdown of each dimension and its device target: * * - 57: Non-retina iPhone, iPod touch, and all Android devices * - 72: Retina iPhone and iPod touch * - 114: Non-retina iPad (first and second generation) * - 144: Retina iPad (third generation) * * Note that the dimensions of the icon images must be exactly 57x57, 72x72, 114x114 and 144x144 respectively. * * It is highly recommended that you provide all these different sizes to accommodate a full range of * devices currently available. However if you only have one icon in one size, make it 57x57 in size and * specify it as a string value. This same icon will be used on all supported devices. * * Ext.setup({ * icon: 'resources/icons/Icon.png', * onReady: function() { * // ... * } * }); * * @param {Object} config.startupImage * Specifies a set of URLs to the application startup images for different device form factors. This image is * displayed when the application is being launched from the Home Screen icon. Note that this currently only applies * to iOS devices. * * Ext.application({ * startupImage: { * '320x460': 'resources/startup/320x460.jpg', * '640x920': 'resources/startup/640x920.png', * '640x1096': 'resources/startup/640x1096.png', * '768x1004': 'resources/startup/768x1004.png', * '748x1024': 'resources/startup/748x1024.png', * '1536x2008': 'resources/startup/1536x2008.png', * '1496x2048': 'resources/startup/1496x2048.png' * }, * launch: function() { * // ... * } * }); * * Each key represents the dimension of the image. For example: '320x460' is the key for a 320px x 460px image. * Here is the breakdown of each dimension and its device target: * * - 320x460: Non-retina iPhone, iPod touch, and all Android devices * - 640x920: Retina iPhone and iPod touch * - 640x1096: iPhone 5 and iPod touch (fifth generation) * - 768x1004: Non-retina iPad (first and second generation) in portrait orientation * - 748x1024: Non-retina iPad (first and second generation) in landscape orientation * - 1536x2008: Retina iPad (third generation) in portrait orientation * - 1496x2048: Retina iPad (third generation) in landscape orientation * * Please note that there's no automatic fallback mechanism for the startup images. In other words, if you don't specify * a valid image for a certain device, nothing will be displayed while the application is being launched on that device. * * @param {Boolean} config.isIconPrecomposed * True to not having a glossy effect added to the icon by the OS, which will preserve its exact look. This currently * only applies to iOS devices. * * @param {String} config.statusBarStyle * The style of status bar to be shown on applications added to the iOS home screen. Valid options are: * * * `default` * * `black` * * `black-translucent` * * @param {String[]} config.requires * An array of required classes for your application which will be automatically loaded if {@link Ext.Loader#enabled} is set * to `true`. Please refer to {@link Ext.Loader} and {@link Ext.Loader#require} for more information. * * Ext.application({ * requires: ['Ext.Button', 'Ext.tab.Panel'], * launch: function() { * // ... * } * }); * * @param {Object} config.eventPublishers * Sencha Touch, by default, includes various {@link Ext.event.recognizer.Recognizer} subclasses to recognize events fired * in your application. The list of default recognizers can be found in the documentation for {@link Ext.event.recognizer.Recognizer}. * * To change the default recognizers, you can use the following syntax: * * Ext.application({ * eventPublishers: { * touchGesture: { * recognizers: { * swipe: { * // this will include both vertical and horizontal swipe recognizers * xclass: 'Ext.event.recognizer.Swipe' * } * } * } * }, * launch: function() { * // ... * } * }); * * You can also disable recognizers using this syntax: * * Ext.application({ * eventPublishers: { * touchGesture: { * recognizers: { * swipe: null, * pinch: null, * rotate: null * } * } * }, * launch: function() { * // ... * } * }); */ application: function(config) { var appName = config.name, onReady, scope, requires; if (!config) { config = {}; } if (!Ext.Loader.config.paths[appName]) { Ext.Loader.setPath(appName, config.appFolder || 'app'); } requires = Ext.Array.from(config.requires); config.requires = ['Ext.app.Application']; onReady = config.onReady; scope = config.scope; config.onReady = function() { config.requires = requires; new Ext.app.Application(config); if (onReady) { onReady.call(scope); } }; Ext.setup(config); }, /** * @private * @param config * @param callback * @member Ext */ factoryConfig: function(config, callback) { var isSimpleObject = Ext.isSimpleObject(config); if (isSimpleObject && config.xclass) { var className = config.xclass; delete config.xclass; Ext.require(className, function() { Ext.factoryConfig(config, function(cfg) { callback(Ext.create(className, cfg)); }); }); return; } var isArray = Ext.isArray(config), keys = [], key, value, i, ln; if (isSimpleObject || isArray) { if (isSimpleObject) { for (key in config) { if (config.hasOwnProperty(key)) { value = config[key]; if (Ext.isSimpleObject(value) || Ext.isArray(value)) { keys.push(key); } } } } else { for (i = 0,ln = config.length; i < ln; i++) { value = config[i]; if (Ext.isSimpleObject(value) || Ext.isArray(value)) { keys.push(i); } } } i = 0; ln = keys.length; if (ln === 0) { callback(config); return; } function fn(value) { config[key] = value; i++; factory(); } function factory() { if (i >= ln) { callback(config); return; } key = keys[i]; value = config[key]; Ext.factoryConfig(value, fn); } factory(); return; } callback(config); }, /** * A global factory method to instantiate a class from a config object. For example, these two calls are equivalent: * * Ext.factory({ text: 'My Button' }, 'Ext.Button'); * Ext.create('Ext.Button', { text: 'My Button' }); * * If an existing instance is also specified, it will be updated with the supplied config object. This is useful * if you need to either create or update an object, depending on if an instance already exists. For example: * * var button; * button = Ext.factory({ text: 'New Button' }, 'Ext.Button', button); // Button created * button = Ext.factory({ text: 'Updated Button' }, 'Ext.Button', button); // Button updated * * @param {Object} config The config object to instantiate or update an instance with. * @param {String} classReference The class to instantiate from. * @param {Object} [instance] The instance to update. * @param [aliasNamespace] * @member Ext */ factory: function(config, classReference, instance, aliasNamespace) { var manager = Ext.ClassManager, newInstance; // If config is falsy or a valid instance, destroy the current instance // (if it exists) and replace with the new one if (!config || config.isInstance) { if (instance && instance !== config) { instance.destroy(); } return config; } if (aliasNamespace) { // If config is a string value, treat it as an alias if (typeof config == 'string') { return manager.instantiateByAlias(aliasNamespace + '.' + config); } // Same if 'type' is given in config else if (Ext.isObject(config) && 'type' in config) { return manager.instantiateByAlias(aliasNamespace + '.' + config.type, config); } } if (config === true) { return instance || manager.instantiate(classReference); } //<debug error> if (!Ext.isObject(config)) { Ext.Logger.error("Invalid config, must be a valid config object"); } //</debug> if ('xtype' in config) { newInstance = manager.instantiateByAlias('widget.' + config.xtype, config); } else if ('xclass' in config) { newInstance = manager.instantiate(config.xclass, config); } if (newInstance) { if (instance) { instance.destroy(); } return newInstance; } if (instance) { return instance.setConfig(config); } return manager.instantiate(classReference, config); }, /** * @private * @member Ext */ deprecateClassMember: function(cls, oldName, newName, message) { return this.deprecateProperty(cls.prototype, oldName, newName, message); }, /** * @private * @member Ext */ deprecateClassMembers: function(cls, members) { var prototype = cls.prototype, oldName, newName; for (oldName in members) { if (members.hasOwnProperty(oldName)) { newName = members[oldName]; this.deprecateProperty(prototype, oldName, newName); } } }, /** * @private * @member Ext */ deprecateProperty: function(object, oldName, newName, message) { if (!message) { message = "'" + oldName + "' is deprecated"; } if (newName) { message += ", please use '" + newName + "' instead"; } if (newName) { Ext.Object.defineProperty(object, oldName, { get: function() { //<debug warn> Ext.Logger.deprecate(message, 1); //</debug> return this[newName]; }, set: function(value) { //<debug warn> Ext.Logger.deprecate(message, 1); //</debug> this[newName] = value; }, configurable: true }); } }, /** * @private * @member Ext */ deprecatePropertyValue: function(object, name, value, message) { Ext.Object.defineProperty(object, name, { get: function() { //<debug warn> Ext.Logger.deprecate(message, 1); //</debug> return value; }, configurable: true }); }, /** * @private * @member Ext */ deprecateMethod: function(object, name, method, message) { object[name] = function() { //<debug warn> Ext.Logger.deprecate(message, 2); //</debug> if (method) { return method.apply(this, arguments); } }; }, /** * @private * @member Ext */ deprecateClassMethod: function(cls, name, method, message) { if (typeof name != 'string') { var from, to; for (from in name) { if (name.hasOwnProperty(from)) { to = name[from]; Ext.deprecateClassMethod(cls, from, to); } } return; } var isLateBinding = typeof method == 'string', member; if (!message) { message = "'" + name + "()' is deprecated, please use '" + (isLateBinding ? method : method.name) + "()' instead"; } if (isLateBinding) { member = function() { //<debug warn> Ext.Logger.deprecate(message, this); //</debug> return this[method].apply(this, arguments); }; } else { member = function() { //<debug warn> Ext.Logger.deprecate(message, this); //</debug> return method.apply(this, arguments); }; } if (name in cls.prototype) { Ext.Object.defineProperty(cls.prototype, name, { value: null, writable: true, configurable: true }); } cls.addMember(name, member); }, //<debug> /** * Useful snippet to show an exact, narrowed-down list of top-level Components that are not yet destroyed. * @private */ showLeaks: function() { var map = Ext.ComponentManager.all.map, leaks = [], parent; Ext.Object.each(map, function(id, component) { while ((parent = component.getParent()) && map.hasOwnProperty(parent.getId())) { component = parent; } if (leaks.indexOf(component) === -1) { leaks.push(component); } }); console.log(leaks); }, //</debug> /** * True when the document is fully initialized and ready for action * @type Boolean * @member Ext * @private */ isReady : false, /** * @private * @member Ext */ readyListeners: [], /** * @private * @member Ext */ triggerReady: function() { var listeners = Ext.readyListeners, i, ln, listener; if (!Ext.isReady) { Ext.isReady = true; for (i = 0,ln = listeners.length; i < ln; i++) { listener = listeners[i]; listener.fn.call(listener.scope); } delete Ext.readyListeners; } }, /** * @private * @member Ext */ onDocumentReady: function(fn, scope) { if (Ext.isReady) { fn.call(scope); } else { var triggerFn = Ext.triggerReady; Ext.readyListeners.push({ fn: fn, scope: scope }); if (Ext.browser.is.PhoneGap && !Ext.os.is.Desktop) { if (!Ext.readyListenerAttached) { Ext.readyListenerAttached = true; document.addEventListener('deviceready', triggerFn, false); } } else { if (document.readyState.match(/interactive|complete|loaded/) !== null) { triggerFn(); } else if (!Ext.readyListenerAttached) { Ext.readyListenerAttached = true; window.addEventListener('DOMContentLoaded', triggerFn, false); } } } }, /** * Calls function after specified delay, or right away when delay == 0. * @param {Function} callback The callback to execute. * @param {Object} scope (optional) The scope to execute in. * @param {Array} args (optional) The arguments to pass to the function. * @param {Number} delay (optional) Pass a number to delay the call by a number of milliseconds. * @member Ext */ callback: function(callback, scope, args, delay) { if (Ext.isFunction(callback)) { args = args || []; scope = scope || window; if (delay) { Ext.defer(callback, delay, scope, args); } else { callback.apply(scope, args); } } } }); //<debug> Ext.Object.defineProperty(Ext, 'Msg', { get: function() { Ext.Logger.error("Using Ext.Msg without requiring Ext.MessageBox"); return null; }, set: function(value) { Ext.Object.defineProperty(Ext, 'Msg', { value: value }); return value; }, configurable: true }); //</debug> //<deprecated product=touch since=2.0> Ext.deprecateMethod(Ext, 'getOrientation', function() { return Ext.Viewport.getOrientation(); }, "Ext.getOrientation() is deprecated, use Ext.Viewport.getOrientation() instead"); Ext.deprecateMethod(Ext, 'log', function(message) { return Ext.Logger.log(message); }, "Ext.log() is deprecated, please use Ext.Logger.log() instead"); /** * @member Ext.Function * @method createDelegate * @inheritdoc Ext.Function#bind * @deprecated 2.0.0 * Please use {@link Ext.Function#bind bind} instead */ Ext.deprecateMethod(Ext.Function, 'createDelegate', Ext.Function.bind, "Ext.createDelegate() is deprecated, please use Ext.Function.bind() instead"); /** * @member Ext * @method createInterceptor * @inheritdoc Ext.Function#createInterceptor * @deprecated 2.0.0 * Please use {@link Ext.Function#createInterceptor createInterceptor} instead */ Ext.deprecateMethod(Ext, 'createInterceptor', Ext.Function.createInterceptor, "Ext.createInterceptor() is deprecated, " + "please use Ext.Function.createInterceptor() instead"); /** * @member Ext * @property {Boolean} SSL_SECURE_URL * URL to a blank file used by Ext JS when in secure mode for iframe src and onReady * src to prevent the IE insecure content warning. * @removed 2.0.0 */ Ext.deprecateProperty(Ext, 'SSL_SECURE_URL', null, "Ext.SSL_SECURE_URL has been removed"); /** * @member Ext * @property {Boolean} enableGarbageCollector * `true` to automatically un-cache orphaned Ext.Elements periodically. * @removed 2.0.0 */ Ext.deprecateProperty(Ext, 'enableGarbageCollector', null, "Ext.enableGarbageCollector has been removed"); /** * @member Ext * @property {Boolean} enableListenerCollection * True to automatically purge event listeners during garbageCollection. * @removed 2.0.0 */ Ext.deprecateProperty(Ext, 'enableListenerCollection', null, "Ext.enableListenerCollection has been removed"); /** * @member Ext * @property {Boolean} isSecure * True if the page is running over SSL. * @removed 2.0.0 Please use {@link Ext.env.Browser#isSecure} instead */ Ext.deprecateProperty(Ext, 'isSecure', null, "Ext.enableListenerCollection has been removed, please use Ext.env.Browser.isSecure instead"); /** * @member Ext * @method dispatch * Dispatches a request to a controller action. * @removed 2.0.0 Please use {@link Ext.app.Application#dispatch} instead */ Ext.deprecateMethod(Ext, 'dispatch', null, "Ext.dispatch() is deprecated, please use Ext.app.Application.dispatch() instead"); /** * @member Ext * @method getOrientation * Returns the current orientation of the mobile device. * @removed 2.0.0 * Please use {@link Ext.Viewport#getOrientation getOrientation} instead */ Ext.deprecateMethod(Ext, 'getOrientation', null, "Ext.getOrientation() has been removed, " + "please use Ext.Viewport.getOrientation() instead"); /** * @member Ext * @method reg * Registers a new xtype. * @removed 2.0.0 */ Ext.deprecateMethod(Ext, 'reg', null, "Ext.reg() has been removed"); /** * @member Ext * @method preg * Registers a new ptype. * @removed 2.0.0 */ Ext.deprecateMethod(Ext, 'preg', null, "Ext.preg() has been removed"); /** * @member Ext * @method redirect * Dispatches a request to a controller action, adding to the History stack * and updating the page url as necessary. * @removed 2.0.0 */ Ext.deprecateMethod(Ext, 'redirect', null, "Ext.redirect() has been removed"); /** * @member Ext * @method regApplication * Creates a new Application class from the specified config object. * @removed 2.0.0 */ Ext.deprecateMethod(Ext, 'regApplication', null, "Ext.regApplication() has been removed"); /** * @member Ext * @method regController * Creates a new Controller class from the specified config object. * @removed 2.0.0 */ Ext.deprecateMethod(Ext, 'regController', null, "Ext.regController() has been removed"); /** * @member Ext * @method regLayout * Registers new layout type. * @removed 2.0.0 */ Ext.deprecateMethod(Ext, 'regLayout', null, "Ext.regLayout() has been removed"); //</deprecated>
hackathon-3d/team-gryffindor-repo
www/touch/src/core/Ext-more.js
JavaScript
gpl-2.0
50,756
/* * Copyright (C) 2005-2013 Team XBMC * http://xbmc.org * * This Program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. * * This Program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with XBMC; see the file COPYING. If not, see * <http://www.gnu.org/licenses/>. * */ #include "threads/SystemClock.h" #include "system.h" #include "GUIWindowFullScreen.h" #include "Application.h" #include "messaging/ApplicationMessenger.h" #ifdef HAS_VIDEO_PLAYBACK #include "cores/VideoRenderers/RenderManager.h" #endif #include "GUIInfoManager.h" #include "guilib/GUIProgressControl.h" #include "guilib/GUILabelControl.h" #include "video/dialogs/GUIDialogVideoOSD.h" #include "guilib/GUIWindowManager.h" #include "input/Key.h" #include "video/dialogs/GUIDialogFullScreenInfo.h" #include "settings/DisplaySettings.h" #include "settings/MediaSettings.h" #include "settings/Settings.h" #include "FileItem.h" #include "video/VideoReferenceClock.h" #include "utils/CPUInfo.h" #include "guilib/LocalizeStrings.h" #include "threads/SingleLock.h" #include "utils/StringUtils.h" #include "XBDateTime.h" #include "input/ButtonTranslator.h" #include "windowing/WindowingFactory.h" #include "cores/IPlayer.h" #include "guiinfo/GUIInfoLabels.h" #include <stdio.h> #include <algorithm> #if defined(TARGET_DARWIN) #include "linux/LinuxResourceCounter.h" #endif using namespace KODI::MESSAGING; #define BLUE_BAR 0 #define LABEL_ROW1 10 #define LABEL_ROW2 11 #define LABEL_ROW3 12 //Displays current position, visible after seek or when forced //Alt, use conditional visibility Player.DisplayAfterSeek #define LABEL_CURRENT_TIME 22 //Displays when video is rebuffering //Alt, use conditional visibility Player.IsCaching #define LABEL_BUFFERING 24 //Progressbar used for buffering status and after seeking #define CONTROL_PROGRESS 23 #if defined(TARGET_DARWIN) static CLinuxResourceCounter m_resourceCounter; #endif CGUIWindowFullScreen::CGUIWindowFullScreen(void) : CGUIWindow(WINDOW_FULLSCREEN_VIDEO, "VideoFullScreen.xml") { m_timeCodeStamp[0] = 0; m_timeCodePosition = 0; m_timeCodeShow = false; m_timeCodeTimeout = 0; m_bShowViewModeInfo = false; m_dwShowViewModeTimeout = 0; m_bShowCurrentTime = false; m_loadType = KEEP_IN_MEMORY; // audio // - language // - volume // - stream // video // - Create Bookmark (294) // - Cycle bookmarks (295) // - Clear bookmarks (296) // - jump to specific time // - slider // - av delay // subtitles // - delay // - language } CGUIWindowFullScreen::~CGUIWindowFullScreen(void) {} bool CGUIWindowFullScreen::OnAction(const CAction &action) { if (m_timeCodePosition > 0 && action.GetButtonCode()) { // check whether we have a mapping in our virtual videotimeseek "window" and have a select action CKey key(action.GetButtonCode()); CAction timeSeek = CButtonTranslator::GetInstance().GetAction(WINDOW_VIDEO_TIME_SEEK, key, false); if (timeSeek.GetID() == ACTION_SELECT_ITEM) { SeekToTimeCodeStamp(SEEK_ABSOLUTE); return true; } } switch (action.GetID()) { case ACTION_SHOW_OSD: ToggleOSD(); return true; case ACTION_TRIGGER_OSD: TriggerOSD(); return true; case ACTION_SHOW_GUI: { // switch back to the menu g_windowManager.PreviousWindow(); return true; } break; case ACTION_PLAYER_PLAY: case ACTION_PAUSE: if (m_timeCodePosition > 0) { SeekToTimeCodeStamp(SEEK_ABSOLUTE); return true; } break; case ACTION_SMALL_STEP_BACK: case ACTION_STEP_BACK: case ACTION_BIG_STEP_BACK: case ACTION_CHAPTER_OR_BIG_STEP_BACK: if (m_timeCodePosition > 0) { SeekToTimeCodeStamp(SEEK_RELATIVE, SEEK_BACKWARD); return true; } break; case ACTION_STEP_FORWARD: case ACTION_BIG_STEP_FORWARD: case ACTION_CHAPTER_OR_BIG_STEP_FORWARD: if (m_timeCodePosition > 0) { SeekToTimeCodeStamp(SEEK_RELATIVE, SEEK_FORWARD); return true; } break; case ACTION_SHOW_OSD_TIME: m_bShowCurrentTime = !m_bShowCurrentTime; if(!m_bShowCurrentTime) g_infoManager.SetDisplayAfterSeek(0); //Force display off g_infoManager.SetShowTime(m_bShowCurrentTime); return true; break; case ACTION_SHOW_INFO: { CGUIDialogFullScreenInfo* pDialog = (CGUIDialogFullScreenInfo*)g_windowManager.GetWindow(WINDOW_DIALOG_FULLSCREEN_INFO); if (pDialog) { CFileItem item(g_application.CurrentFileItem()); pDialog->Open(); return true; } break; } case REMOTE_0: case REMOTE_1: case REMOTE_2: case REMOTE_3: case REMOTE_4: case REMOTE_5: case REMOTE_6: case REMOTE_7: case REMOTE_8: case REMOTE_9: { if (!g_application.CurrentFileItem().IsLiveTV()) { ChangetheTimeCode(action.GetID()); return true; } } break; case ACTION_ASPECT_RATIO: { // toggle the aspect ratio mode (only if the info is onscreen) if (m_bShowViewModeInfo) { #ifdef HAS_VIDEO_PLAYBACK g_renderManager.SetViewMode(++CMediaSettings::Get().GetCurrentVideoSettings().m_ViewMode); #endif } m_bShowViewModeInfo = true; m_dwShowViewModeTimeout = XbmcThreads::SystemClockMillis(); } return true; break; case ACTION_SHOW_PLAYLIST: { CFileItem item(g_application.CurrentFileItem()); if (item.HasPVRChannelInfoTag()) g_windowManager.ActivateWindow(WINDOW_DIALOG_PVR_OSD_CHANNELS); else if (item.HasVideoInfoTag()) g_windowManager.ActivateWindow(WINDOW_VIDEO_PLAYLIST); else if (item.HasMusicInfoTag()) g_windowManager.ActivateWindow(WINDOW_MUSIC_PLAYLIST); } return true; break; default: break; } return CGUIWindow::OnAction(action); } void CGUIWindowFullScreen::ClearBackground() { if (g_renderManager.IsVideoLayer()) #ifdef HAS_IMXVPU g_graphicsContext.Clear((16 << 16)|(8 << 8)|16); #else g_graphicsContext.Clear(0); #endif } void CGUIWindowFullScreen::OnWindowLoaded() { CGUIWindow::OnWindowLoaded(); // override the clear colour - we must never clear fullscreen m_clearBackground = 0; CGUIProgressControl* pProgress = dynamic_cast<CGUIProgressControl*>(GetControl(CONTROL_PROGRESS)); if(pProgress) { if( pProgress->GetInfo() == 0 || !pProgress->HasVisibleCondition()) { pProgress->SetInfo(PLAYER_PROGRESS); pProgress->SetVisibleCondition("player.displayafterseek"); pProgress->SetVisible(true); } } CGUILabelControl* pLabel = dynamic_cast<CGUILabelControl*>(GetControl(LABEL_BUFFERING)); if(pLabel && !pLabel->HasVisibleCondition()) { pLabel->SetVisibleCondition("player.caching"); pLabel->SetVisible(true); } pLabel = dynamic_cast<CGUILabelControl*>(GetControl(LABEL_CURRENT_TIME)); if(pLabel && !pLabel->HasVisibleCondition()) { pLabel->SetVisibleCondition("player.displayafterseek"); pLabel->SetVisible(true); pLabel->SetLabel("$INFO(VIDEOPLAYER.TIME) / $INFO(VIDEOPLAYER.DURATION)"); } m_showCodec.Parse("player.showcodec", GetID()); } bool CGUIWindowFullScreen::OnMessage(CGUIMessage& message) { switch (message.GetMessage()) { case GUI_MSG_WINDOW_INIT: { // check whether we've come back here from a window during which time we've actually // stopped playing videos if (message.GetParam1() == WINDOW_INVALID && !g_application.m_pPlayer->IsPlayingVideo()) { // why are we here if nothing is playing??? g_windowManager.PreviousWindow(); return true; } g_infoManager.SetShowInfo(false); g_infoManager.SetShowCodec(false); m_bShowCurrentTime = false; g_infoManager.SetDisplayAfterSeek(0); // Make sure display after seek is off. // switch resolution g_graphicsContext.SetFullScreenVideo(true); #ifdef HAS_VIDEO_PLAYBACK // make sure renderer is uptospeed g_renderManager.Update(); #endif // now call the base class to load our windows CGUIWindow::OnMessage(message); m_bShowViewModeInfo = false; return true; } case GUI_MSG_WINDOW_DEINIT: { // close all active modal dialogs g_windowManager.CloseInternalModalDialogs(true); CGUIWindow::OnMessage(message); CSettings::Get().Save(); CSingleLock lock (g_graphicsContext); g_graphicsContext.SetFullScreenVideo(false); lock.Leave(); #ifdef HAS_VIDEO_PLAYBACK // make sure renderer is uptospeed g_renderManager.Update(); g_renderManager.FrameFinish(); #endif return true; } case GUI_MSG_SETFOCUS: case GUI_MSG_LOSTFOCUS: if (message.GetSenderId() != WINDOW_FULLSCREEN_VIDEO) return true; break; } return CGUIWindow::OnMessage(message); } EVENT_RESULT CGUIWindowFullScreen::OnMouseEvent(const CPoint &point, const CMouseEvent &event) { if (event.m_id == ACTION_MOUSE_RIGHT_CLICK) { // no control found to absorb this click - go back to GUI OnAction(CAction(ACTION_SHOW_GUI)); return EVENT_RESULT_HANDLED; } if (event.m_id == ACTION_MOUSE_WHEEL_UP) { return g_application.OnAction(CAction(ACTION_ANALOG_SEEK_FORWARD, 0.5f)) ? EVENT_RESULT_HANDLED : EVENT_RESULT_UNHANDLED; } if (event.m_id == ACTION_MOUSE_WHEEL_DOWN) { return g_application.OnAction(CAction(ACTION_ANALOG_SEEK_BACK, 0.5f)) ? EVENT_RESULT_HANDLED : EVENT_RESULT_UNHANDLED; } if (event.m_id >= ACTION_GESTURE_NOTIFY && event.m_id <= ACTION_GESTURE_END) // gestures return EVENT_RESULT_UNHANDLED; return EVENT_RESULT_UNHANDLED; } void CGUIWindowFullScreen::FrameMove() { if (g_application.m_pPlayer->GetPlaySpeed() != 1) g_infoManager.SetDisplayAfterSeek(); if (m_bShowCurrentTime) g_infoManager.SetDisplayAfterSeek(); if (!g_application.m_pPlayer->HasPlayer()) return; if( g_application.m_pPlayer->IsCaching() ) { g_infoManager.SetDisplayAfterSeek(0); //Make sure these stuff aren't visible now } //------------------------ m_showCodec.Update(); if (m_showCodec) { // show audio codec info std::string strAudio, strVideo, strGeneral; g_application.m_pPlayer->GetAudioInfo(strAudio); { CGUIMessage msg(GUI_MSG_LABEL_SET, GetID(), LABEL_ROW1); msg.SetLabel(strAudio); OnMessage(msg); } // show video codec info g_application.m_pPlayer->GetVideoInfo(strVideo); { CGUIMessage msg(GUI_MSG_LABEL_SET, GetID(), LABEL_ROW2); msg.SetLabel(strVideo); OnMessage(msg); } // show general info g_application.m_pPlayer->GetGeneralInfo(strGeneral); { std::string strGeneralFPS; #if defined(TARGET_DARWIN) // We show CPU usage for the entire process, as it's arguably more useful. double dCPU = m_resourceCounter.GetCPUUsage(); std::string strCores; strCores = StringUtils::Format("cpu:%.0f%%", dCPU); #else std::string strCores = g_cpuInfo.GetCoresUsageString(); #endif int missedvblanks; double refreshrate; double clockspeed; std::string strClock; if (g_VideoReferenceClock.GetClockInfo(missedvblanks, clockspeed, refreshrate)) strClock = StringUtils::Format("S( refresh:%.3f missed:%i speed:%+.3f%% %s )" , refreshrate , missedvblanks , clockspeed - 100.0 , g_renderManager.GetVSyncState().c_str()); strGeneralFPS = StringUtils::Format("%s\nW( %s )\n%s" , strGeneral.c_str() , strCores.c_str(), strClock.c_str() ); CGUIMessage msg(GUI_MSG_LABEL_SET, GetID(), LABEL_ROW3); msg.SetLabel(strGeneralFPS); OnMessage(msg); } } //---------------------- // ViewMode Information //---------------------- if (m_bShowViewModeInfo && XbmcThreads::SystemClockMillis() - m_dwShowViewModeTimeout > 2500) { m_bShowViewModeInfo = false; } if (m_bShowViewModeInfo) { RESOLUTION_INFO res = g_graphicsContext.GetResInfo(); { // get the "View Mode" string std::string strTitle = g_localizeStrings.Get(629); std::string strMode = g_localizeStrings.Get(630 + CMediaSettings::Get().GetCurrentVideoSettings().m_ViewMode); std::string strInfo = StringUtils::Format("%s : %s", strTitle.c_str(), strMode.c_str()); CGUIMessage msg(GUI_MSG_LABEL_SET, GetID(), LABEL_ROW1); msg.SetLabel(strInfo); OnMessage(msg); } // show sizing information SPlayerVideoStreamInfo info; g_application.m_pPlayer->GetVideoStreamInfo(info); { // Splitres scaling factor float xscale = (float)res.iScreenWidth / (float)res.iWidth; float yscale = (float)res.iScreenHeight / (float)res.iHeight; std::string strSizing = StringUtils::Format(g_localizeStrings.Get(245).c_str(), (int)info.SrcRect.Width(), (int)info.SrcRect.Height(), (int)(info.DestRect.Width() * xscale), (int)(info.DestRect.Height() * yscale), CDisplaySettings::Get().GetZoomAmount(), info.videoAspectRatio*CDisplaySettings::Get().GetPixelRatio(), CDisplaySettings::Get().GetPixelRatio(), CDisplaySettings::Get().GetVerticalShift()); CGUIMessage msg(GUI_MSG_LABEL_SET, GetID(), LABEL_ROW2); msg.SetLabel(strSizing); OnMessage(msg); } // show resolution information { std::string strStatus; if (g_Windowing.IsFullScreen()) strStatus = StringUtils::Format("%s %ix%i@%.2fHz - %s", g_localizeStrings.Get(13287).c_str(), res.iScreenWidth, res.iScreenHeight, res.fRefreshRate, g_localizeStrings.Get(244).c_str()); else strStatus = StringUtils::Format("%s %ix%i - %s", g_localizeStrings.Get(13287).c_str(), res.iScreenWidth, res.iScreenHeight, g_localizeStrings.Get(242).c_str()); CGUIMessage msg(GUI_MSG_LABEL_SET, GetID(), LABEL_ROW3); msg.SetLabel(strStatus); OnMessage(msg); } } if (m_timeCodeShow && m_timeCodePosition != 0) { if ( (XbmcThreads::SystemClockMillis() - m_timeCodeTimeout) >= 2500) { m_timeCodeShow = false; m_timeCodePosition = 0; } std::string strDispTime = "00:00:00"; CGUIMessage msg(GUI_MSG_LABEL_SET, GetID(), LABEL_ROW1); for (int pos = 7, i = m_timeCodePosition; pos >= 0 && i > 0; pos--) { if (strDispTime[pos] != ':') { i -= 1; strDispTime[pos] = (char)m_timeCodeStamp[i] + '0'; } } strDispTime += "/" + g_infoManager.GetDuration(TIME_FORMAT_HH_MM_SS) + " [" + g_infoManager.GetCurrentPlayTime(TIME_FORMAT_HH_MM_SS) + "]"; // duration [ time ] msg.SetLabel(strDispTime); OnMessage(msg); } if (m_showCodec || m_bShowViewModeInfo) { SET_CONTROL_VISIBLE(LABEL_ROW1); SET_CONTROL_VISIBLE(LABEL_ROW2); SET_CONTROL_VISIBLE(LABEL_ROW3); SET_CONTROL_VISIBLE(BLUE_BAR); } else if (m_timeCodeShow) { SET_CONTROL_VISIBLE(LABEL_ROW1); SET_CONTROL_HIDDEN(LABEL_ROW2); SET_CONTROL_HIDDEN(LABEL_ROW3); SET_CONTROL_VISIBLE(BLUE_BAR); } else { SET_CONTROL_HIDDEN(LABEL_ROW1); SET_CONTROL_HIDDEN(LABEL_ROW2); SET_CONTROL_HIDDEN(LABEL_ROW3); SET_CONTROL_HIDDEN(BLUE_BAR); } g_renderManager.FrameMove(); } void CGUIWindowFullScreen::Process(unsigned int currentTime, CDirtyRegionList &dirtyregion) { if (g_renderManager.IsGuiLayer()) MarkDirtyRegion(); CGUIWindow::Process(currentTime, dirtyregion); // TODO: This isn't quite optimal - ideally we'd only be dirtying up the actual video render rect // which is probably the job of the renderer as it can more easily track resizing etc. m_renderRegion.SetRect(0, 0, (float)g_graphicsContext.GetWidth(), (float)g_graphicsContext.GetHeight()); } void CGUIWindowFullScreen::Render() { g_graphicsContext.SetRenderingResolution(g_graphicsContext.GetVideoResolution(), false); g_renderManager.Render(true, 0, 255); g_graphicsContext.SetRenderingResolution(m_coordsRes, m_needsScaling); CGUIWindow::Render(); } void CGUIWindowFullScreen::RenderEx() { CGUIWindow::RenderEx(); g_graphicsContext.SetRenderingResolution(g_graphicsContext.GetVideoResolution(), false); #ifdef HAS_VIDEO_PLAYBACK g_renderManager.Render(false, 0, 255, false); g_renderManager.FrameFinish(); #endif } void CGUIWindowFullScreen::ChangetheTimeCode(int remote) { if (remote >= REMOTE_0 && remote <= REMOTE_9) { m_timeCodeShow = true; m_timeCodeTimeout = XbmcThreads::SystemClockMillis(); if (m_timeCodePosition < 6) m_timeCodeStamp[m_timeCodePosition++] = remote - REMOTE_0; else { // rotate around for (int i = 0; i < 5; i++) m_timeCodeStamp[i] = m_timeCodeStamp[i+1]; m_timeCodeStamp[5] = remote - REMOTE_0; } } } void CGUIWindowFullScreen::SeekToTimeCodeStamp(SEEK_TYPE type, SEEK_DIRECTION direction) { double total = GetTimeCodeStamp(); if (type == SEEK_RELATIVE) total = g_application.GetTime() + (((direction == SEEK_FORWARD) ? 1 : -1) * total); if (total < g_application.GetTotalTime()) g_application.SeekTime(total); m_timeCodePosition = 0; m_timeCodeShow = false; } double CGUIWindowFullScreen::GetTimeCodeStamp() { // Convert the timestamp into an integer int tot = 0; for (int i = 0; i < m_timeCodePosition; i++) tot = tot * 10 + m_timeCodeStamp[i]; // Interpret result as HHMMSS int s = tot % 100; tot /= 100; int m = tot % 100; tot /= 100; int h = tot % 100; return h * 3600 + m * 60 + s; } void CGUIWindowFullScreen::SeekChapter(int iChapter) { g_application.m_pPlayer->SeekChapter(iChapter); // Make sure gui items are visible. g_infoManager.SetDisplayAfterSeek(); } void CGUIWindowFullScreen::ToggleOSD() { CGUIDialogVideoOSD *pOSD = (CGUIDialogVideoOSD *)g_windowManager.GetWindow(WINDOW_DIALOG_VIDEO_OSD); if (pOSD) { if (pOSD->IsDialogRunning()) pOSD->Close(); else pOSD->Open(); } MarkDirtyRegion(); } void CGUIWindowFullScreen::TriggerOSD() { CGUIDialogVideoOSD *pOSD = (CGUIDialogVideoOSD *)g_windowManager.GetWindow(WINDOW_DIALOG_VIDEO_OSD); if (pOSD && !pOSD->IsDialogRunning()) { pOSD->SetAutoClose(3000); pOSD->Open(); } }
yuvalt/xbmc
xbmc/video/windows/GUIWindowFullScreen.cpp
C++
gpl-2.0
19,632
/* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * (c)Copyright 2006 Hewlett-Packard Development Company, LP. * */ #include "C_ProtocolControl.hpp" #include "Utils.hpp" #include "GeneratorTrace.hpp" #include "GeneratorError.h" #include "C_ProtocolBinary.hpp" #include "C_ProtocolExternal.hpp" #include "C_ProtocolBinaryBodyNotInterpreted.hpp" #include "C_ProtocolBinarySeparator.hpp" #include "C_ProtocolText.hpp" #include "C_ProtocolTlv.hpp" #define XML_PROTOCOL_SECTION (char*)"protocol" #define XML_PROTOCOL_NAME (char*)"name" #define XML_PROTOCOL_TYPE (char*)"type" C_ProtocolControl::C_ProtocolControl(C_TransportControl *P_transport_control) { GEN_DEBUG(1, "C_ProtocolControl::C_ProtocolControl() start"); NEW_VAR(m_name_map, T_ProtocolNameMap()); m_name_map->clear() ; m_protocol_table = NULL ; m_protocol_name_table = NULL ; m_protocol_table_size = 0 ; NEW_VAR(m_id_gen, C_IdGenerator()); m_transport_control = P_transport_control ; GEN_DEBUG(1, "C_ProtocolControl::C_ProtocolControl() end"); } C_ProtocolControl::~C_ProtocolControl() { int L_i ; GEN_DEBUG(1, "C_ProtocolControl::~C_ProtocolControl() start"); if (!m_name_map->empty()) { m_name_map->erase(m_name_map->begin(), m_name_map->end()); } DELETE_VAR(m_name_map); if (m_protocol_table_size != 0) { for (L_i = 0 ; L_i < m_protocol_table_size; L_i++) { DELETE_VAR(m_protocol_table[L_i]); } FREE_TABLE(m_protocol_table); FREE_TABLE(m_protocol_name_table); m_protocol_table_size = 0 ; } DELETE_VAR(m_id_gen) ; m_transport_control = NULL ; GEN_DEBUG(1, "C_ProtocolControl::~C_ProtocolControl() end"); } char* C_ProtocolControl::get_protocol_name(C_XmlData *P_data) { return (P_data->find_value(XML_PROTOCOL_NAME)) ; } char* C_ProtocolControl::get_protocol_type(C_XmlData *P_data) { return (P_data->find_value(XML_PROTOCOL_TYPE)) ; } bool C_ProtocolControl::fromXml (C_XmlData *P_data, T_pConfigValueList P_config_value_list, bool P_display_protocol_stats) { bool L_ret = true ; T_pXmlData_List L_subList ; T_XmlData_List::iterator L_subListIt ; C_XmlData *L_data ; char *L_protocol_name, *L_protocol_type ; int L_protocol_id ; T_ProtocolInstList L_protocol_inst_list ; T_pProtocolInstanceInfo L_protocol_info ; T_ProtocolInstList::iterator L_it ; GEN_DEBUG(1, "C_ProtocolControl::fromXml() start"); if (P_data != NULL) { if ((L_subList = P_data->get_sub_data()) != NULL) { for (L_subListIt = L_subList->begin() ; L_subListIt != L_subList->end() ; L_subListIt++) { L_data = *L_subListIt ; if (L_data != NULL) { if (strcmp(L_data->get_name(), XML_PROTOCOL_SECTION) == 0) { // protocol section definition found L_protocol_name = get_protocol_name (L_data) ; // check protocol type for creation L_protocol_type = get_protocol_type (L_data) ; // check name/type presence if (L_protocol_name == NULL) { GEN_ERROR(E_GEN_FATAL_ERROR, "name mandatory for section " << XML_PROTOCOL_SECTION); L_ret = false ; break ; } if (L_protocol_type == NULL) { GEN_ERROR(E_GEN_FATAL_ERROR, "type mandatory for section " << XML_PROTOCOL_SECTION); L_ret = false ; break ; } // check protocol name unicity if (m_name_map->find(T_ProtocolNameMap::key_type(L_protocol_name)) != m_name_map->end()) { GEN_ERROR(E_GEN_FATAL_ERROR, XML_PROTOCOL_SECTION << " with name [" << L_protocol_name << "] already defined"); L_ret = false ; break ; } // check protocol type or sub type if (strcmp(L_protocol_type, "binary") == 0) { // create protocol instance C_ProtocolBinary *L_protocol_instance = NULL ; T_ConstructorResult L_res ; NEW_VAR(L_protocol_instance, C_ProtocolBinary()); L_protocol_instance->construction_data(L_data, &L_protocol_name, &L_res) ; if (L_res != E_CONSTRUCTOR_OK) { GEN_ERROR(E_GEN_FATAL_ERROR, "Error found in protocol definition"); DELETE_VAR(L_protocol_instance); L_ret = false ; break ; } else { // store new instance if (P_display_protocol_stats == true) { C_ProtocolStats *L_protocol_stats ; NEW_VAR(L_protocol_stats,C_ProtocolStats(L_protocol_instance)); L_protocol_instance->set_stats(L_protocol_stats); } L_protocol_id = m_id_gen->new_id() ; ALLOC_VAR(L_protocol_info, T_pProtocolInstanceInfo, sizeof(T_ProtocolInstanceInfo)); L_protocol_info->m_instance = L_protocol_instance ; L_protocol_info->m_id = L_protocol_id ; L_protocol_info->m_name = L_protocol_name ; L_protocol_inst_list.push_back(L_protocol_info); m_name_map ->insert(T_ProtocolNameMap::value_type(L_protocol_name, L_protocol_id)) ; } } else if (strcmp(L_protocol_type, "binary-tlv") == 0) { // create protocol instance C_ProtocolTlv *L_protocol_instance = NULL ; T_ConstructorResult L_res ; NEW_VAR(L_protocol_instance, C_ProtocolTlv()); L_protocol_instance->construction_data(L_data, &L_protocol_name, &L_res) ; if (L_res != E_CONSTRUCTOR_OK) { GEN_ERROR(E_GEN_FATAL_ERROR, "Error found in protocol definition"); DELETE_VAR(L_protocol_instance); L_ret = false ; break ; } else { // store new instance if (P_display_protocol_stats == true) { C_ProtocolStats *L_protocol_stats ; NEW_VAR(L_protocol_stats,C_ProtocolStats(L_protocol_instance)); L_protocol_instance->set_stats(L_protocol_stats); } L_protocol_id = m_id_gen->new_id() ; ALLOC_VAR(L_protocol_info, T_pProtocolInstanceInfo, sizeof(T_ProtocolInstanceInfo)); L_protocol_info->m_instance = L_protocol_instance ; L_protocol_info->m_id = L_protocol_id ; L_protocol_info->m_name = L_protocol_name ; L_protocol_inst_list.push_back(L_protocol_info); m_name_map ->insert(T_ProtocolNameMap::value_type(L_protocol_name, L_protocol_id)) ; } } else if (strcmp(L_protocol_type, "binary-body-not-interpreted") == 0) { // create protocol instance C_ProtocolBinaryBodyNotInterpreted *L_protocol_instance = NULL ; T_ConstructorResult L_res ; NEW_VAR(L_protocol_instance, C_ProtocolBinaryBodyNotInterpreted()); L_protocol_instance->construction_data(L_data, &L_protocol_name, &L_res) ; if (L_res != E_CONSTRUCTOR_OK) { GEN_ERROR(E_GEN_FATAL_ERROR, "Error found in protocol definition"); DELETE_VAR(L_protocol_instance); L_ret = false ; break ; } else { // store new instance if (P_display_protocol_stats == true) { C_ProtocolStats *L_protocol_stats ; NEW_VAR(L_protocol_stats,C_ProtocolStats(L_protocol_instance)); L_protocol_instance->set_stats(L_protocol_stats); } L_protocol_id = m_id_gen->new_id() ; ALLOC_VAR(L_protocol_info, T_pProtocolInstanceInfo, sizeof(T_ProtocolInstanceInfo)); L_protocol_info->m_instance = L_protocol_instance ; L_protocol_info->m_id = L_protocol_id ; L_protocol_info->m_name = L_protocol_name ; L_protocol_inst_list.push_back(L_protocol_info); m_name_map ->insert(T_ProtocolNameMap::value_type(L_protocol_name, L_protocol_id)) ; } } else if (strcmp(L_protocol_type, "binary-separator") == 0) { // create protocol instance C_ProtocolBinarySeparator *L_protocol_instance = NULL ; T_ConstructorResult L_res ; NEW_VAR(L_protocol_instance, C_ProtocolBinarySeparator()); L_protocol_instance ->construction_data(L_data, &L_protocol_name, &L_res) ; if (L_res != E_CONSTRUCTOR_OK) { GEN_ERROR(E_GEN_FATAL_ERROR, "Error found in protocol definition"); DELETE_VAR(L_protocol_instance); L_ret = false ; break ; } else { // store new instance if (P_display_protocol_stats == true) { C_ProtocolStats *L_protocol_stats ; NEW_VAR(L_protocol_stats,C_ProtocolStats(L_protocol_instance)); L_protocol_instance->set_stats(L_protocol_stats); } L_protocol_id = m_id_gen->new_id() ; ALLOC_VAR(L_protocol_info, T_pProtocolInstanceInfo, sizeof(T_ProtocolInstanceInfo)); L_protocol_info->m_instance = L_protocol_instance ; L_protocol_info->m_id = L_protocol_id ; L_protocol_info->m_name = L_protocol_name ; L_protocol_inst_list.push_back(L_protocol_info); m_name_map ->insert(T_ProtocolNameMap::value_type(L_protocol_name, L_protocol_id)) ; } } else if (strcmp(L_protocol_type, "external-library") == 0) { C_ProtocolExternal *L_protocol_instance = NULL ; T_ConstructorResult L_res = E_CONSTRUCTOR_OK ; NEW_VAR(L_protocol_instance, C_ProtocolExternal(m_transport_control, L_data, &L_protocol_name, P_config_value_list, &L_res)); if (L_res != E_CONSTRUCTOR_OK) { GEN_ERROR(E_GEN_FATAL_ERROR, "Error found in protocol definition"); DELETE_VAR(L_protocol_instance); L_ret = false ; break ; } else { if (P_display_protocol_stats == true) { C_ProtocolStats *L_protocol_stats ; NEW_VAR(L_protocol_stats,C_ProtocolStats(L_protocol_instance)); L_protocol_instance->set_stats(L_protocol_stats); } // store new instance L_protocol_id = m_id_gen->new_id() ; ALLOC_VAR(L_protocol_info, T_pProtocolInstanceInfo, sizeof(T_ProtocolInstanceInfo)); L_protocol_info->m_instance = L_protocol_instance ; L_protocol_info->m_id = L_protocol_id ; L_protocol_info->m_name = L_protocol_name ; L_protocol_inst_list.push_back(L_protocol_info); m_name_map ->insert(T_ProtocolNameMap::value_type(L_protocol_name, L_protocol_id)) ; } } else if (strcmp(L_protocol_type, "text") == 0) { C_ProtocolText *L_protocol_instance = NULL ; T_ConstructorResult L_res = E_CONSTRUCTOR_OK ; NEW_VAR(L_protocol_instance, C_ProtocolText()); L_protocol_instance->analyze_data(L_data, &L_protocol_name, P_config_value_list, &L_res); if (L_res != E_CONSTRUCTOR_OK) { GEN_ERROR(E_GEN_FATAL_ERROR, "Error found in protocol definition"); DELETE_VAR(L_protocol_instance); L_ret = false ; break ; } else { if (P_display_protocol_stats == true) { C_ProtocolStats *L_protocol_stats ; NEW_VAR(L_protocol_stats,C_ProtocolStats(L_protocol_instance)); L_protocol_instance->set_stats(L_protocol_stats); } // store new instance L_protocol_id = m_id_gen->new_id() ; ALLOC_VAR(L_protocol_info, T_pProtocolInstanceInfo, sizeof(T_ProtocolInstanceInfo)); L_protocol_info->m_instance = L_protocol_instance ; L_protocol_info->m_id = L_protocol_id ; L_protocol_info->m_name = L_protocol_name ; L_protocol_inst_list.push_back(L_protocol_info); m_name_map ->insert(T_ProtocolNameMap::value_type(L_protocol_name, L_protocol_id)) ; } } else { GEN_ERROR(E_GEN_FATAL_ERROR, XML_PROTOCOL_SECTION << " [" << L_protocol_name << "] with type [" << L_protocol_type << "] unsupported"); L_ret = false ; } } } } if (L_ret != false) { if (!L_protocol_inst_list.empty()) { m_protocol_table_size = L_protocol_inst_list.size() ; ALLOC_TABLE(m_protocol_table, T_pC_ProtocolFrame*, sizeof(T_pC_ProtocolFrame), m_protocol_table_size) ; ALLOC_TABLE(m_protocol_name_table, char**, sizeof(char*), m_protocol_table_size) ; for (L_it = L_protocol_inst_list.begin(); L_it != L_protocol_inst_list.end() ; L_it++) { L_protocol_info = *L_it ; m_protocol_table[L_protocol_info->m_id] = L_protocol_info->m_instance ; m_protocol_name_table[L_protocol_info->m_id] = L_protocol_info->m_name ; } } else { GEN_ERROR(E_GEN_FATAL_ERROR, "No protocol definition found"); L_ret = false ; } } // if L_ret != false if (!L_protocol_inst_list.empty()) { for (L_it = L_protocol_inst_list.begin(); L_it != L_protocol_inst_list.end() ; L_it++) { FREE_VAR(*L_it); } L_protocol_inst_list.erase(L_protocol_inst_list.begin(), L_protocol_inst_list.end()); } } } GEN_DEBUG(1, "C_ProtocolControl::fromXml() end ret=" << L_ret); return (L_ret); } C_ProtocolFrame* C_ProtocolControl::get_protocol (char *P_name) { C_ProtocolFrame *L_ret = NULL ; int L_id ; L_id = get_protocol_id (P_name) ; if (L_id != ERROR_PROTOCOL_UNKNOWN) { L_ret = m_protocol_table[L_id] ; } return (L_ret) ; } C_ProtocolFrame* C_ProtocolControl::get_protocol (int P_id) { C_ProtocolFrame *L_ret = NULL ; if ((P_id < m_protocol_table_size) && (P_id >= 0)) { L_ret = m_protocol_table[P_id] ; } return (L_ret); } int C_ProtocolControl::get_protocol_id (char *P_name) { int L_ret = ERROR_PROTOCOL_UNKNOWN ; T_ProtocolNameMap::iterator L_it ; L_it = m_name_map->find(T_ProtocolNameMap::key_type(P_name)) ; if (L_it != m_name_map->end()) { L_ret = L_it->second ; } return (L_ret) ; } int C_ProtocolControl::get_nb_protocol () { return (m_protocol_table_size); } char* C_ProtocolControl::get_protocol_name (int P_id) { char *L_ret = NULL ; if ((P_id < m_protocol_table_size) && (P_id >= 0)) { L_ret = m_protocol_name_table[P_id] ; } return (L_ret); }
hamzasheikh/Seagull
seagull/trunk/src/generator-model/C_ProtocolControl.cpp
C++
gpl-2.0
14,839
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vhudson-jaxb-ri-2.2-147 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2012.07.04 at 04:19:28 PM CEST // package icaro.infraestructura.entidadesBasicas.descEntidadesOrganizacion.jaxb; import javax.xml.bind.JAXBElement; import javax.xml.bind.annotation.XmlElementDecl; import javax.xml.bind.annotation.XmlRegistry; import javax.xml.namespace.QName; /** * This object contains factory methods for each * Java content interface and Java element interface * generated in the icaro.aplicaciones.descripcionorganizaciones package. * <p>An ObjectFactory allows you to programatically * construct new instances of the Java representation * for XML content. The Java representation of XML * content can consist of schema derived interfaces * and classes representing the binding of schema * type definitions, element declarations and model * groups. Factory methods for each of these are * provided in this class. * */ @XmlRegistry public class ObjectFactory { private final static QName _DescOrganizacion_QNAME = new QName("urn:icaro:aplicaciones:descripcionOrganizaciones", "DescOrganizacion"); /** * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: icaro.aplicaciones.descripcionorganizaciones * */ public ObjectFactory() { } /** * Create an instance of {@link RecursosAplicacion } * */ public RecursosAplicacion createRecursosAplicacion() { return new RecursosAplicacion(); } /** * Create an instance of {@link InstanciaGestor } * */ public InstanciaGestor createInstanciaGestor() { return new InstanciaGestor(); } /** * Create an instance of {@link ListaPropiedades } * */ public ListaPropiedades createListaPropiedades() { return new ListaPropiedades(); } /** * Create an instance of {@link Nodo } * */ public Nodo createNodo() { return new Nodo(); } /** * Create an instance of {@link PropiedadesGlobales } * */ public PropiedadesGlobales createPropiedadesGlobales() { return new PropiedadesGlobales(); } /** * Create an instance of {@link DescripcionComponentes } * */ public DescripcionComponentes createDescripcionComponentes() { return new DescripcionComponentes(); } /** * Create an instance of {@link AgentesAplicacion } * */ public AgentesAplicacion createAgentesAplicacion() { return new AgentesAplicacion(); } /** * Create an instance of {@link ListaNodosEjecucion } * */ public ListaNodosEjecucion createListaNodosEjecucion() { return new ListaNodosEjecucion(); } /** * Create an instance of {@link DescComportamientoAgentesAplicacion } * */ public DescComportamientoAgentesAplicacion createDescComportamientoAgentesAplicacion() { return new DescComportamientoAgentesAplicacion(); } /** * Create an instance of {@link DescInstancias } * */ public DescInstancias createDescInstancias() { return new DescInstancias(); } /** * Create an instance of {@link DescRecursosAplicacion } * */ public DescRecursosAplicacion createDescRecursosAplicacion() { return new DescRecursosAplicacion(); } /** * Create an instance of {@link DescComportamientoGestores } * */ public DescComportamientoGestores createDescComportamientoGestores() { return new DescComportamientoGestores(); } /** * Create an instance of {@link Propiedad } * */ public Propiedad createPropiedad() { return new Propiedad(); } /** * Create an instance of {@link Gestores } * */ public Gestores createGestores() { return new Gestores(); } /** * Create an instance of {@link DescComportamientoAgentes } * */ public DescComportamientoAgentes createDescComportamientoAgentes() { return new DescComportamientoAgentes(); } /** * Create an instance of {@link ComponentesGestionados } * */ public ComponentesGestionados createComponentesGestionados() { return new ComponentesGestionados(); } /** * Create an instance of {@link DescRecursoAplicacion } * */ public DescRecursoAplicacion createDescRecursoAplicacion() { return new DescRecursoAplicacion(); } /** * Create an instance of {@link Instancia } * */ public Instancia createInstancia() { return new Instancia(); } /** * Create an instance of {@link DescComportamientoAgente } * */ public DescComportamientoAgente createDescComportamientoAgente() { return new DescComportamientoAgente(); } /** * Create an instance of {@link ComponenteGestionado } * */ public ComponenteGestionado createComponenteGestionado() { return new ComponenteGestionado(); } /** * Create an instance of {@link DescComportamientoAgenteReactivo } * */ public DescComportamientoAgenteReactivo createDescComportamientoAgenteReactivo() { return new DescComportamientoAgenteReactivo(); } /** * Create an instance of {@link DescOrganizacion } * */ public DescOrganizacion createDescOrganizacion() { return new DescOrganizacion(); } /** * Create an instance of {@link DescComportamientoAgenteCognitivo } * */ public DescComportamientoAgenteCognitivo createDescComportamientoAgenteCognitivo() { return new DescComportamientoAgenteCognitivo(); } /** * Create an instance of {@link JAXBElement }{@code <}{@link DescOrganizacion }{@code >}} * */ @XmlElementDecl(namespace = "urn:icaro:aplicaciones:descripcionOrganizaciones", name = "DescOrganizacion") public JAXBElement<DescOrganizacion> createDescOrganizacion(DescOrganizacion value) { return new JAXBElement<DescOrganizacion>(_DescOrganizacion_QNAME, DescOrganizacion.class, null, value); } }
palomagc/MovieChatter
src/icaro/infraestructura/entidadesBasicas/descEntidadesOrganizacion/jaxb/ObjectFactory.java
Java
gpl-2.0
6,481
<?php namespace Yoast\WP\SEO\Conditionals; /** * Conditional that is met when the current request is an XML-RPC request. */ class XMLRPC_Conditional implements Conditional { /** * Returns whether the current request is an XML-RPC request. * * @return bool `true` when the current request is an XML-RPC request, `false` if not. */ public function is_met() { return ( \defined( 'XMLRPC_REQUEST' ) && \XMLRPC_REQUEST ); } }
TheThumbsupguy/Ross-Upholstery-Inc
wp-content/plugins/wordpress-seo/src/conditionals/xmlrpc-conditional.php
PHP
gpl-2.0
440
// Targeted by JavaCPP version 0.8-SNAPSHOT package com.googlecode.javacpp; import com.googlecode.javacpp.*; import com.googlecode.javacpp.annotation.*; import java.nio.*; import static com.googlecode.javacpp.opencv_core.*; import static com.googlecode.javacpp.opencv_imgproc.*; public class opencv_highgui extends com.googlecode.javacpp.helper.opencv_highgui { static { Loader.load(); } // Parsed from /usr/local/include/opencv2/highgui/highgui_c.h /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // Intel License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000, Intel Corporation, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's 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. // // * The name of Intel Corporation may not 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 Intel Corporation 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. // //M*/ // #ifndef __OPENCV_HIGHGUI_H__ // #define __OPENCV_HIGHGUI_H__ // #include "opencv2/core/core_c.h" // #ifdef __cplusplus // #endif /* __cplusplus */ /****************************************************************************************\ * Basic GUI functions * \****************************************************************************************/ //YV //-----------New for Qt /* For font */ /** enum */ public static final int CV_FONT_LIGHT = 25,//QFont::Light, CV_FONT_NORMAL = 50,//QFont::Normal, CV_FONT_DEMIBOLD = 63,//QFont::DemiBold, CV_FONT_BOLD = 75,//QFont::Bold, CV_FONT_BLACK = 87; //QFont::Black /** enum */ public static final int CV_STYLE_NORMAL = 0,//QFont::StyleNormal, CV_STYLE_ITALIC = 1,//QFont::StyleItalic, CV_STYLE_OBLIQUE = 2; //QFont::StyleOblique /* ---------*/ //for color cvScalar(blue_component, green_component, red\_component[, alpha_component]) //and alpha= 0 <-> 0xFF (not transparent <-> transparent) public static native @ByVal @Platform("linux") CvFont cvFontQt(@Cast("const char*") BytePointer nameFont, int pointSize/*CV_DEFAULT(-1)*/, @ByVal CvScalar color/*CV_DEFAULT(cvScalarAll(0))*/, int weight/*CV_DEFAULT(CV_FONT_NORMAL)*/, int style/*CV_DEFAULT(CV_STYLE_NORMAL)*/, int spacing/*CV_DEFAULT(0)*/); public static native @ByVal @Platform("linux") CvFont cvFontQt(@Cast("const char*") BytePointer nameFont); public static native @ByVal @Platform("linux") CvFont cvFontQt(String nameFont, int pointSize/*CV_DEFAULT(-1)*/, @ByVal CvScalar color/*CV_DEFAULT(cvScalarAll(0))*/, int weight/*CV_DEFAULT(CV_FONT_NORMAL)*/, int style/*CV_DEFAULT(CV_STYLE_NORMAL)*/, int spacing/*CV_DEFAULT(0)*/); public static native @ByVal @Platform("linux") CvFont cvFontQt(String nameFont); public static native @Platform("linux") void cvAddText(@Const CvArr img, @Cast("const char*") BytePointer text, @ByVal CvPoint org, CvFont arg2); public static native @Platform("linux") void cvAddText(@Const CvArr img, String text, @ByVal @Cast("CvPoint*") IntBuffer org, CvFont arg2); public static native @Platform("linux") void cvAddText(@Const CvArr img, @Cast("const char*") BytePointer text, @ByVal @Cast("CvPoint*") int[] org, CvFont arg2); public static native @Platform("linux") void cvAddText(@Const CvArr img, String text, @ByVal CvPoint org, CvFont arg2); public static native @Platform("linux") void cvAddText(@Const CvArr img, @Cast("const char*") BytePointer text, @ByVal @Cast("CvPoint*") IntBuffer org, CvFont arg2); public static native @Platform("linux") void cvAddText(@Const CvArr img, String text, @ByVal @Cast("CvPoint*") int[] org, CvFont arg2); public static native @Platform("linux") void cvDisplayOverlay(@Cast("const char*") BytePointer name, @Cast("const char*") BytePointer text, int delayms/*CV_DEFAULT(0)*/); public static native @Platform("linux") void cvDisplayOverlay(@Cast("const char*") BytePointer name, @Cast("const char*") BytePointer text); public static native @Platform("linux") void cvDisplayOverlay(String name, String text, int delayms/*CV_DEFAULT(0)*/); public static native @Platform("linux") void cvDisplayOverlay(String name, String text); public static native @Platform("linux") void cvDisplayStatusBar(@Cast("const char*") BytePointer name, @Cast("const char*") BytePointer text, int delayms/*CV_DEFAULT(0)*/); public static native @Platform("linux") void cvDisplayStatusBar(@Cast("const char*") BytePointer name, @Cast("const char*") BytePointer text); public static native @Platform("linux") void cvDisplayStatusBar(String name, String text, int delayms/*CV_DEFAULT(0)*/); public static native @Platform("linux") void cvDisplayStatusBar(String name, String text); public static native @Platform("linux") void cvSaveWindowParameters(@Cast("const char*") BytePointer name); public static native @Platform("linux") void cvSaveWindowParameters(String name); public static native @Platform("linux") void cvLoadWindowParameters(@Cast("const char*") BytePointer name); public static native @Platform("linux") void cvLoadWindowParameters(String name); public static class Pt2Func_int_PointerPointer extends FunctionPointer { static { Loader.load(); } public Pt2Func_int_PointerPointer(Pointer p) { super(p); } protected Pt2Func_int_PointerPointer() { allocate(); } private native void allocate(); public native int call(int argc, @Cast("char**") PointerPointer argv); } public static native @Platform("linux") int cvStartLoop(Pt2Func_int_PointerPointer pt2Func, int argc, @Cast("char**") PointerPointer argv); public static class Pt2Func_int_BytePointer extends FunctionPointer { static { Loader.load(); } public Pt2Func_int_BytePointer(Pointer p) { super(p); } protected Pt2Func_int_BytePointer() { allocate(); } private native void allocate(); public native int call(int argc, @Cast("char**") @ByPtrPtr BytePointer argv); } public static native @Platform("linux") int cvStartLoop(Pt2Func_int_BytePointer pt2Func, int argc, @Cast("char**") @ByPtrPtr BytePointer argv); public static class Pt2Func_int_ByteBuffer extends FunctionPointer { static { Loader.load(); } public Pt2Func_int_ByteBuffer(Pointer p) { super(p); } protected Pt2Func_int_ByteBuffer() { allocate(); } private native void allocate(); public native int call(int argc, @Cast("char**") @ByPtrPtr ByteBuffer argv); } public static native @Platform("linux") int cvStartLoop(Pt2Func_int_ByteBuffer pt2Func, int argc, @Cast("char**") @ByPtrPtr ByteBuffer argv); public static class Pt2Func_int_byte__ extends FunctionPointer { static { Loader.load(); } public Pt2Func_int_byte__(Pointer p) { super(p); } protected Pt2Func_int_byte__() { allocate(); } private native void allocate(); public native int call(int argc, @Cast("char**") @ByPtrPtr byte[] argv); } public static native @Platform("linux") int cvStartLoop(Pt2Func_int_byte__ pt2Func, int argc, @Cast("char**") @ByPtrPtr byte[] argv); public static native @Platform("linux") void cvStopLoop( ); @Convention("CV_CDECL") public static class CvButtonCallback extends FunctionPointer { static { Loader.load(); } public CvButtonCallback(Pointer p) { super(p); } protected CvButtonCallback() { allocate(); } private native void allocate(); public native void call(int state, Pointer userdata); } /** enum */ public static final int CV_PUSH_BUTTON = 0, CV_CHECKBOX = 1, CV_RADIOBOX = 2; public static native @Platform("linux") int cvCreateButton( @Cast("const char*") BytePointer button_name/*CV_DEFAULT(NULL)*/,CvButtonCallback on_change/*CV_DEFAULT(NULL)*/, Pointer userdata/*CV_DEFAULT(NULL)*/, int button_type/*CV_DEFAULT(CV_PUSH_BUTTON)*/, int initial_button_state/*CV_DEFAULT(0)*/); public static native @Platform("linux") int cvCreateButton(); public static native @Platform("linux") int cvCreateButton( String button_name/*CV_DEFAULT(NULL)*/,CvButtonCallback on_change/*CV_DEFAULT(NULL)*/, Pointer userdata/*CV_DEFAULT(NULL)*/, int button_type/*CV_DEFAULT(CV_PUSH_BUTTON)*/, int initial_button_state/*CV_DEFAULT(0)*/); //---------------------- /* this function is used to set some external parameters in case of X Window */ public static native int cvInitSystem( int argc, @Cast("char**") PointerPointer argv ); public static native int cvInitSystem( int argc, @Cast("char**") @ByPtrPtr BytePointer argv ); public static native int cvInitSystem( int argc, @Cast("char**") @ByPtrPtr ByteBuffer argv ); public static native int cvInitSystem( int argc, @Cast("char**") @ByPtrPtr byte[] argv ); public static native int cvStartWindowThread( ); // --------- YV --------- /** enum */ public static final int //These 3 flags are used by cvSet/GetWindowProperty CV_WND_PROP_FULLSCREEN = 0, //to change/get window's fullscreen property CV_WND_PROP_AUTOSIZE = 1, //to change/get window's autosize property CV_WND_PROP_ASPECTRATIO= 2, //to change/get window's aspectratio property CV_WND_PROP_OPENGL = 3, //to change/get window's opengl support //These 2 flags are used by cvNamedWindow and cvSet/GetWindowProperty CV_WINDOW_NORMAL = 0x00000000, //the user can resize the window (no constraint) / also use to switch a fullscreen window to a normal size CV_WINDOW_AUTOSIZE = 0x00000001, //the user cannot resize the window, the size is constrainted by the image displayed CV_WINDOW_OPENGL = 0x00001000, //window with opengl support //Those flags are only for Qt CV_GUI_EXPANDED = 0x00000000, //status bar and tool bar CV_GUI_NORMAL = 0x00000010, //old fashious way //These 3 flags are used by cvNamedWindow and cvSet/GetWindowProperty CV_WINDOW_FULLSCREEN = 1,//change the window to fullscreen CV_WINDOW_FREERATIO = 0x00000100,//the image expends as much as it can (no ratio constraint) CV_WINDOW_KEEPRATIO = 0x00000000;//the ration image is respected. /* create window */ public static native int cvNamedWindow( @Cast("const char*") BytePointer name, int flags/*CV_DEFAULT(CV_WINDOW_AUTOSIZE)*/ ); public static native int cvNamedWindow( @Cast("const char*") BytePointer name ); public static native int cvNamedWindow( String name, int flags/*CV_DEFAULT(CV_WINDOW_AUTOSIZE)*/ ); public static native int cvNamedWindow( String name ); /* Set and Get Property of the window */ public static native void cvSetWindowProperty(@Cast("const char*") BytePointer name, int prop_id, double prop_value); public static native void cvSetWindowProperty(String name, int prop_id, double prop_value); public static native double cvGetWindowProperty(@Cast("const char*") BytePointer name, int prop_id); public static native double cvGetWindowProperty(String name, int prop_id); /* display image within window (highgui windows remember their content) */ public static native void cvShowImage( @Cast("const char*") BytePointer name, @Const CvArr image ); public static native void cvShowImage( String name, @Const CvArr image ); /* resize/move window */ public static native void cvResizeWindow( @Cast("const char*") BytePointer name, int width, int height ); public static native void cvResizeWindow( String name, int width, int height ); public static native void cvMoveWindow( @Cast("const char*") BytePointer name, int x, int y ); public static native void cvMoveWindow( String name, int x, int y ); /* destroy window and all the trackers associated with it */ public static native void cvDestroyWindow( @Cast("const char*") BytePointer name ); public static native void cvDestroyWindow( String name ); public static native void cvDestroyAllWindows(); /* get native window handle (HWND in case of Win32 and Widget in case of X Window) */ public static native Pointer cvGetWindowHandle( @Cast("const char*") BytePointer name ); public static native Pointer cvGetWindowHandle( String name ); /* get name of highgui window given its native handle */ public static native @Cast("const char*") BytePointer cvGetWindowName( Pointer window_handle ); @Convention("CV_CDECL") public static class CvTrackbarCallback extends FunctionPointer { static { Loader.load(); } public CvTrackbarCallback(Pointer p) { super(p); } protected CvTrackbarCallback() { allocate(); } private native void allocate(); public native void call(int pos); } /* create trackbar and display it on top of given window, set callback */ public static native int cvCreateTrackbar( @Cast("const char*") BytePointer trackbar_name, @Cast("const char*") BytePointer window_name, IntPointer value, int count, CvTrackbarCallback on_change/*CV_DEFAULT(NULL)*/); public static native int cvCreateTrackbar( @Cast("const char*") BytePointer trackbar_name, @Cast("const char*") BytePointer window_name, IntPointer value, int count); public static native int cvCreateTrackbar( String trackbar_name, String window_name, IntBuffer value, int count, CvTrackbarCallback on_change/*CV_DEFAULT(NULL)*/); public static native int cvCreateTrackbar( String trackbar_name, String window_name, IntBuffer value, int count); public static native int cvCreateTrackbar( @Cast("const char*") BytePointer trackbar_name, @Cast("const char*") BytePointer window_name, int[] value, int count, CvTrackbarCallback on_change/*CV_DEFAULT(NULL)*/); public static native int cvCreateTrackbar( @Cast("const char*") BytePointer trackbar_name, @Cast("const char*") BytePointer window_name, int[] value, int count); public static native int cvCreateTrackbar( String trackbar_name, String window_name, IntPointer value, int count, CvTrackbarCallback on_change/*CV_DEFAULT(NULL)*/); public static native int cvCreateTrackbar( String trackbar_name, String window_name, IntPointer value, int count); public static native int cvCreateTrackbar( @Cast("const char*") BytePointer trackbar_name, @Cast("const char*") BytePointer window_name, IntBuffer value, int count, CvTrackbarCallback on_change/*CV_DEFAULT(NULL)*/); public static native int cvCreateTrackbar( @Cast("const char*") BytePointer trackbar_name, @Cast("const char*") BytePointer window_name, IntBuffer value, int count); public static native int cvCreateTrackbar( String trackbar_name, String window_name, int[] value, int count, CvTrackbarCallback on_change/*CV_DEFAULT(NULL)*/); public static native int cvCreateTrackbar( String trackbar_name, String window_name, int[] value, int count); @Convention("CV_CDECL") public static class CvTrackbarCallback2 extends FunctionPointer { static { Loader.load(); } public CvTrackbarCallback2(Pointer p) { super(p); } protected CvTrackbarCallback2() { allocate(); } private native void allocate(); public native void call(int pos, Pointer userdata); } public static native int cvCreateTrackbar2( @Cast("const char*") BytePointer trackbar_name, @Cast("const char*") BytePointer window_name, IntPointer value, int count, CvTrackbarCallback2 on_change, Pointer userdata/*CV_DEFAULT(0)*/); public static native int cvCreateTrackbar2( @Cast("const char*") BytePointer trackbar_name, @Cast("const char*") BytePointer window_name, IntPointer value, int count, CvTrackbarCallback2 on_change); public static native int cvCreateTrackbar2( String trackbar_name, String window_name, IntBuffer value, int count, CvTrackbarCallback2 on_change, Pointer userdata/*CV_DEFAULT(0)*/); public static native int cvCreateTrackbar2( String trackbar_name, String window_name, IntBuffer value, int count, CvTrackbarCallback2 on_change); public static native int cvCreateTrackbar2( @Cast("const char*") BytePointer trackbar_name, @Cast("const char*") BytePointer window_name, int[] value, int count, CvTrackbarCallback2 on_change, Pointer userdata/*CV_DEFAULT(0)*/); public static native int cvCreateTrackbar2( @Cast("const char*") BytePointer trackbar_name, @Cast("const char*") BytePointer window_name, int[] value, int count, CvTrackbarCallback2 on_change); public static native int cvCreateTrackbar2( String trackbar_name, String window_name, IntPointer value, int count, CvTrackbarCallback2 on_change, Pointer userdata/*CV_DEFAULT(0)*/); public static native int cvCreateTrackbar2( String trackbar_name, String window_name, IntPointer value, int count, CvTrackbarCallback2 on_change); public static native int cvCreateTrackbar2( @Cast("const char*") BytePointer trackbar_name, @Cast("const char*") BytePointer window_name, IntBuffer value, int count, CvTrackbarCallback2 on_change, Pointer userdata/*CV_DEFAULT(0)*/); public static native int cvCreateTrackbar2( @Cast("const char*") BytePointer trackbar_name, @Cast("const char*") BytePointer window_name, IntBuffer value, int count, CvTrackbarCallback2 on_change); public static native int cvCreateTrackbar2( String trackbar_name, String window_name, int[] value, int count, CvTrackbarCallback2 on_change, Pointer userdata/*CV_DEFAULT(0)*/); public static native int cvCreateTrackbar2( String trackbar_name, String window_name, int[] value, int count, CvTrackbarCallback2 on_change); /* retrieve or set trackbar position */ public static native int cvGetTrackbarPos( @Cast("const char*") BytePointer trackbar_name, @Cast("const char*") BytePointer window_name ); public static native int cvGetTrackbarPos( String trackbar_name, String window_name ); public static native void cvSetTrackbarPos( @Cast("const char*") BytePointer trackbar_name, @Cast("const char*") BytePointer window_name, int pos ); public static native void cvSetTrackbarPos( String trackbar_name, String window_name, int pos ); /** enum */ public static final int CV_EVENT_MOUSEMOVE = 0, CV_EVENT_LBUTTONDOWN = 1, CV_EVENT_RBUTTONDOWN = 2, CV_EVENT_MBUTTONDOWN = 3, CV_EVENT_LBUTTONUP = 4, CV_EVENT_RBUTTONUP = 5, CV_EVENT_MBUTTONUP = 6, CV_EVENT_LBUTTONDBLCLK = 7, CV_EVENT_RBUTTONDBLCLK = 8, CV_EVENT_MBUTTONDBLCLK = 9; /** enum */ public static final int CV_EVENT_FLAG_LBUTTON = 1, CV_EVENT_FLAG_RBUTTON = 2, CV_EVENT_FLAG_MBUTTON = 4, CV_EVENT_FLAG_CTRLKEY = 8, CV_EVENT_FLAG_SHIFTKEY = 16, CV_EVENT_FLAG_ALTKEY = 32; @Convention("CV_CDECL") public static class CvMouseCallback extends FunctionPointer { static { Loader.load(); } public CvMouseCallback(Pointer p) { super(p); } protected CvMouseCallback() { allocate(); } private native void allocate(); public native void call(int event, int x, int y, int flags, Pointer param); } /* assign callback for mouse events */ public static native void cvSetMouseCallback( @Cast("const char*") BytePointer window_name, CvMouseCallback on_mouse, Pointer param/*CV_DEFAULT(NULL)*/); public static native void cvSetMouseCallback( @Cast("const char*") BytePointer window_name, CvMouseCallback on_mouse); public static native void cvSetMouseCallback( String window_name, CvMouseCallback on_mouse, Pointer param/*CV_DEFAULT(NULL)*/); public static native void cvSetMouseCallback( String window_name, CvMouseCallback on_mouse); /** enum */ public static final int /* 8bit, color or not */ CV_LOAD_IMAGE_UNCHANGED = -1, /* 8bit, gray */ CV_LOAD_IMAGE_GRAYSCALE = 0, /* ?, color */ CV_LOAD_IMAGE_COLOR = 1, /* any depth, ? */ CV_LOAD_IMAGE_ANYDEPTH = 2, /* ?, any color */ CV_LOAD_IMAGE_ANYCOLOR = 4; /* load image from file iscolor can be a combination of above flags where CV_LOAD_IMAGE_UNCHANGED overrides the other flags using CV_LOAD_IMAGE_ANYCOLOR alone is equivalent to CV_LOAD_IMAGE_UNCHANGED unless CV_LOAD_IMAGE_ANYDEPTH is specified images are converted to 8bit */ public static native IplImage cvLoadImage( @Cast("const char*") BytePointer filename, int iscolor/*CV_DEFAULT(CV_LOAD_IMAGE_COLOR)*/); public static native IplImage cvLoadImage( @Cast("const char*") BytePointer filename); public static native IplImage cvLoadImage( String filename, int iscolor/*CV_DEFAULT(CV_LOAD_IMAGE_COLOR)*/); public static native IplImage cvLoadImage( String filename); public static native CvMat cvLoadImageM( @Cast("const char*") BytePointer filename, int iscolor/*CV_DEFAULT(CV_LOAD_IMAGE_COLOR)*/); public static native CvMat cvLoadImageM( @Cast("const char*") BytePointer filename); public static native CvMat cvLoadImageM( String filename, int iscolor/*CV_DEFAULT(CV_LOAD_IMAGE_COLOR)*/); public static native CvMat cvLoadImageM( String filename); /** enum */ public static final int CV_IMWRITE_JPEG_QUALITY = 1, CV_IMWRITE_PNG_COMPRESSION = 16, CV_IMWRITE_PNG_STRATEGY = 17, CV_IMWRITE_PNG_BILEVEL = 18, CV_IMWRITE_PNG_STRATEGY_DEFAULT = 0, CV_IMWRITE_PNG_STRATEGY_FILTERED = 1, CV_IMWRITE_PNG_STRATEGY_HUFFMAN_ONLY = 2, CV_IMWRITE_PNG_STRATEGY_RLE = 3, CV_IMWRITE_PNG_STRATEGY_FIXED = 4, CV_IMWRITE_PXM_BINARY = 32; /* save image to file */ public static native int cvSaveImage( @Cast("const char*") BytePointer filename, @Const CvArr image, @Const IntPointer params/*CV_DEFAULT(0)*/ ); public static native int cvSaveImage( @Cast("const char*") BytePointer filename, @Const CvArr image ); public static native int cvSaveImage( String filename, @Const CvArr image, @Const IntBuffer params/*CV_DEFAULT(0)*/ ); public static native int cvSaveImage( String filename, @Const CvArr image ); public static native int cvSaveImage( @Cast("const char*") BytePointer filename, @Const CvArr image, @Const int[] params/*CV_DEFAULT(0)*/ ); public static native int cvSaveImage( String filename, @Const CvArr image, @Const IntPointer params/*CV_DEFAULT(0)*/ ); public static native int cvSaveImage( @Cast("const char*") BytePointer filename, @Const CvArr image, @Const IntBuffer params/*CV_DEFAULT(0)*/ ); public static native int cvSaveImage( String filename, @Const CvArr image, @Const int[] params/*CV_DEFAULT(0)*/ ); /* decode image stored in the buffer */ public static native IplImage cvDecodeImage( @Const CvMat buf, int iscolor/*CV_DEFAULT(CV_LOAD_IMAGE_COLOR)*/); public static native IplImage cvDecodeImage( @Const CvMat buf); public static native CvMat cvDecodeImageM( @Const CvMat buf, int iscolor/*CV_DEFAULT(CV_LOAD_IMAGE_COLOR)*/); public static native CvMat cvDecodeImageM( @Const CvMat buf); /* encode image and store the result as a byte vector (single-row 8uC1 matrix) */ public static native CvMat cvEncodeImage( @Cast("const char*") BytePointer ext, @Const CvArr image, @Const IntPointer params/*CV_DEFAULT(0)*/ ); public static native CvMat cvEncodeImage( @Cast("const char*") BytePointer ext, @Const CvArr image ); public static native CvMat cvEncodeImage( String ext, @Const CvArr image, @Const IntBuffer params/*CV_DEFAULT(0)*/ ); public static native CvMat cvEncodeImage( String ext, @Const CvArr image ); public static native CvMat cvEncodeImage( @Cast("const char*") BytePointer ext, @Const CvArr image, @Const int[] params/*CV_DEFAULT(0)*/ ); public static native CvMat cvEncodeImage( String ext, @Const CvArr image, @Const IntPointer params/*CV_DEFAULT(0)*/ ); public static native CvMat cvEncodeImage( @Cast("const char*") BytePointer ext, @Const CvArr image, @Const IntBuffer params/*CV_DEFAULT(0)*/ ); public static native CvMat cvEncodeImage( String ext, @Const CvArr image, @Const int[] params/*CV_DEFAULT(0)*/ ); /** enum */ public static final int CV_CVTIMG_FLIP = 1, CV_CVTIMG_SWAP_RB = 2; /* utility function: convert one image to another with optional vertical flip */ public static native void cvConvertImage( @Const CvArr src, CvArr dst, int flags/*CV_DEFAULT(0)*/); public static native void cvConvertImage( @Const CvArr src, CvArr dst); /* wait for key event infinitely (delay<=0) or for "delay" milliseconds */ public static native int cvWaitKey(int delay/*CV_DEFAULT(0)*/); public static native int cvWaitKey(); // OpenGL support @Convention("CV_CDECL") public static class CvOpenGlDrawCallback extends FunctionPointer { static { Loader.load(); } public CvOpenGlDrawCallback(Pointer p) { super(p); } protected CvOpenGlDrawCallback() { allocate(); } private native void allocate(); public native void call(Pointer userdata); } public static native void cvSetOpenGlDrawCallback(@Cast("const char*") BytePointer window_name, CvOpenGlDrawCallback callback, Pointer userdata/*CV_DEFAULT(NULL)*/); public static native void cvSetOpenGlDrawCallback(@Cast("const char*") BytePointer window_name, CvOpenGlDrawCallback callback); public static native void cvSetOpenGlDrawCallback(String window_name, CvOpenGlDrawCallback callback, Pointer userdata/*CV_DEFAULT(NULL)*/); public static native void cvSetOpenGlDrawCallback(String window_name, CvOpenGlDrawCallback callback); public static native void cvSetOpenGlContext(@Cast("const char*") BytePointer window_name); public static native void cvSetOpenGlContext(String window_name); public static native void cvUpdateWindow(@Cast("const char*") BytePointer window_name); public static native void cvUpdateWindow(String window_name); /****************************************************************************************\ * Working with Video Files and Cameras * \****************************************************************************************/ /* "black box" capture structure */ @Opaque public static class CvCapture extends Pointer { public CvCapture() { } public CvCapture(Pointer p) { super(p); } } /* start capturing frames from video file */ public static native CvCapture cvCreateFileCapture( @Cast("const char*") BytePointer filename ); public static native CvCapture cvCreateFileCapture( String filename ); /** enum */ public static final int CV_CAP_ANY = 0, // autodetect CV_CAP_MIL = 100, // MIL proprietary drivers CV_CAP_VFW = 200, // platform native CV_CAP_V4L = 200, CV_CAP_V4L2 = 200, CV_CAP_FIREWARE = 300, // IEEE 1394 drivers CV_CAP_FIREWIRE = 300, CV_CAP_IEEE1394 = 300, CV_CAP_DC1394 = 300, CV_CAP_CMU1394 = 300, CV_CAP_STEREO = 400, // TYZX proprietary drivers CV_CAP_TYZX = 400, CV_TYZX_LEFT = 400, CV_TYZX_RIGHT = 401, CV_TYZX_COLOR = 402, CV_TYZX_Z = 403, CV_CAP_QT = 500, // QuickTime CV_CAP_UNICAP = 600, // Unicap drivers CV_CAP_DSHOW = 700, // DirectShow (via videoInput) CV_CAP_MSMF = 1400, // Microsoft Media Foundation (via videoInput) CV_CAP_PVAPI = 800, // PvAPI, Prosilica GigE SDK CV_CAP_OPENNI = 900, // OpenNI (for Kinect) CV_CAP_OPENNI_ASUS = 910, // OpenNI (for Asus Xtion) CV_CAP_ANDROID = 1000, // Android CV_CAP_ANDROID_BACK = CV_CAP_ANDROID+99, // Android back camera CV_CAP_ANDROID_FRONT = CV_CAP_ANDROID+98, // Android front camera CV_CAP_XIAPI = 1100, // XIMEA Camera API CV_CAP_AVFOUNDATION = 1200, // AVFoundation framework for iOS (OS X Lion will have the same API) CV_CAP_GIGANETIX = 1300, // Smartek Giganetix GigEVisionSDK CV_CAP_INTELPERC = 1500; // Intel Perceptual Computing SDK /* start capturing frames from camera: index = camera_index + domain_offset (CV_CAP_*) */ public static native CvCapture cvCreateCameraCapture( int index ); /* grab a frame, return 1 on success, 0 on fail. this function is thought to be fast */ public static native int cvGrabFrame( CvCapture capture ); /* get the frame grabbed with cvGrabFrame(..) This function may apply some frame processing like frame decompression, flipping etc. !!!DO NOT RELEASE or MODIFY the retrieved frame!!! */ public static native IplImage cvRetrieveFrame( CvCapture capture, int streamIdx/*CV_DEFAULT(0)*/ ); public static native IplImage cvRetrieveFrame( CvCapture capture ); /* Just a combination of cvGrabFrame and cvRetrieveFrame !!!DO NOT RELEASE or MODIFY the retrieved frame!!! */ public static native IplImage cvQueryFrame( CvCapture capture ); /* stop capturing/reading and free resources */ public static native void cvReleaseCapture( @Cast("CvCapture**") PointerPointer capture ); public static native void cvReleaseCapture( @ByPtrPtr CvCapture capture ); /** enum */ public static final int // modes of the controlling registers (can be: auto, manual, auto single push, absolute Latter allowed with any other mode) // every feature can have only one mode turned on at a time CV_CAP_PROP_DC1394_OFF = -4, //turn the feature off (not controlled manually nor automatically) CV_CAP_PROP_DC1394_MODE_MANUAL = -3, //set automatically when a value of the feature is set by the user CV_CAP_PROP_DC1394_MODE_AUTO = -2, CV_CAP_PROP_DC1394_MODE_ONE_PUSH_AUTO = -1, CV_CAP_PROP_POS_MSEC = 0, CV_CAP_PROP_POS_FRAMES = 1, CV_CAP_PROP_POS_AVI_RATIO = 2, CV_CAP_PROP_FRAME_WIDTH = 3, CV_CAP_PROP_FRAME_HEIGHT = 4, CV_CAP_PROP_FPS = 5, CV_CAP_PROP_FOURCC = 6, CV_CAP_PROP_FRAME_COUNT = 7, CV_CAP_PROP_FORMAT = 8, CV_CAP_PROP_MODE = 9, CV_CAP_PROP_BRIGHTNESS = 10, CV_CAP_PROP_CONTRAST = 11, CV_CAP_PROP_SATURATION = 12, CV_CAP_PROP_HUE = 13, CV_CAP_PROP_GAIN = 14, CV_CAP_PROP_EXPOSURE = 15, CV_CAP_PROP_CONVERT_RGB = 16, CV_CAP_PROP_WHITE_BALANCE_BLUE_U = 17, CV_CAP_PROP_RECTIFICATION = 18, CV_CAP_PROP_MONOCROME = 19, CV_CAP_PROP_SHARPNESS = 20, CV_CAP_PROP_AUTO_EXPOSURE = 21, // exposure control done by camera, // user can adjust refernce level // using this feature CV_CAP_PROP_GAMMA = 22, CV_CAP_PROP_TEMPERATURE = 23, CV_CAP_PROP_TRIGGER = 24, CV_CAP_PROP_TRIGGER_DELAY = 25, CV_CAP_PROP_WHITE_BALANCE_RED_V = 26, CV_CAP_PROP_ZOOM = 27, CV_CAP_PROP_FOCUS = 28, CV_CAP_PROP_GUID = 29, CV_CAP_PROP_ISO_SPEED = 30, CV_CAP_PROP_MAX_DC1394 = 31, CV_CAP_PROP_BACKLIGHT = 32, CV_CAP_PROP_PAN = 33, CV_CAP_PROP_TILT = 34, CV_CAP_PROP_ROLL = 35, CV_CAP_PROP_IRIS = 36, CV_CAP_PROP_SETTINGS = 37, CV_CAP_PROP_AUTOGRAB = 1024, // property for highgui class CvCapture_Android only CV_CAP_PROP_SUPPORTED_PREVIEW_SIZES_STRING= 1025, // readonly, tricky property, returns cpnst char* indeed CV_CAP_PROP_PREVIEW_FORMAT= 1026, // readonly, tricky property, returns cpnst char* indeed // OpenNI map generators CV_CAP_OPENNI_DEPTH_GENERATOR = 1 << 31, CV_CAP_OPENNI_IMAGE_GENERATOR = 1 << 30, CV_CAP_OPENNI_GENERATORS_MASK = CV_CAP_OPENNI_DEPTH_GENERATOR + CV_CAP_OPENNI_IMAGE_GENERATOR, // Properties of cameras available through OpenNI interfaces CV_CAP_PROP_OPENNI_OUTPUT_MODE = 100, CV_CAP_PROP_OPENNI_FRAME_MAX_DEPTH = 101, // in mm CV_CAP_PROP_OPENNI_BASELINE = 102, // in mm CV_CAP_PROP_OPENNI_FOCAL_LENGTH = 103, // in pixels CV_CAP_PROP_OPENNI_REGISTRATION = 104, // flag CV_CAP_PROP_OPENNI_REGISTRATION_ON = CV_CAP_PROP_OPENNI_REGISTRATION, // flag that synchronizes the remapping depth map to image map // by changing depth generator's view point (if the flag is "on") or // sets this view point to its normal one (if the flag is "off"). CV_CAP_PROP_OPENNI_APPROX_FRAME_SYNC = 105, CV_CAP_PROP_OPENNI_MAX_BUFFER_SIZE = 106, CV_CAP_PROP_OPENNI_CIRCLE_BUFFER = 107, CV_CAP_PROP_OPENNI_MAX_TIME_DURATION = 108, CV_CAP_PROP_OPENNI_GENERATOR_PRESENT = 109, CV_CAP_OPENNI_IMAGE_GENERATOR_PRESENT = CV_CAP_OPENNI_IMAGE_GENERATOR + CV_CAP_PROP_OPENNI_GENERATOR_PRESENT, CV_CAP_OPENNI_IMAGE_GENERATOR_OUTPUT_MODE = CV_CAP_OPENNI_IMAGE_GENERATOR + CV_CAP_PROP_OPENNI_OUTPUT_MODE, CV_CAP_OPENNI_DEPTH_GENERATOR_BASELINE = CV_CAP_OPENNI_DEPTH_GENERATOR + CV_CAP_PROP_OPENNI_BASELINE, CV_CAP_OPENNI_DEPTH_GENERATOR_FOCAL_LENGTH = CV_CAP_OPENNI_DEPTH_GENERATOR + CV_CAP_PROP_OPENNI_FOCAL_LENGTH, CV_CAP_OPENNI_DEPTH_GENERATOR_REGISTRATION = CV_CAP_OPENNI_DEPTH_GENERATOR + CV_CAP_PROP_OPENNI_REGISTRATION, CV_CAP_OPENNI_DEPTH_GENERATOR_REGISTRATION_ON = CV_CAP_OPENNI_DEPTH_GENERATOR_REGISTRATION, // Properties of cameras available through GStreamer interface CV_CAP_GSTREAMER_QUEUE_LENGTH = 200, // default is 1 CV_CAP_PROP_PVAPI_MULTICASTIP = 300, // ip for anable multicast master mode. 0 for disable multicast // Properties of cameras available through XIMEA SDK interface CV_CAP_PROP_XI_DOWNSAMPLING = 400, // Change image resolution by binning or skipping. CV_CAP_PROP_XI_DATA_FORMAT = 401, // Output data format. CV_CAP_PROP_XI_OFFSET_X = 402, // Horizontal offset from the origin to the area of interest (in pixels). CV_CAP_PROP_XI_OFFSET_Y = 403, // Vertical offset from the origin to the area of interest (in pixels). CV_CAP_PROP_XI_TRG_SOURCE = 404, // Defines source of trigger. CV_CAP_PROP_XI_TRG_SOFTWARE = 405, // Generates an internal trigger. PRM_TRG_SOURCE must be set to TRG_SOFTWARE. CV_CAP_PROP_XI_GPI_SELECTOR = 406, // Selects general purpose input CV_CAP_PROP_XI_GPI_MODE = 407, // Set general purpose input mode CV_CAP_PROP_XI_GPI_LEVEL = 408, // Get general purpose level CV_CAP_PROP_XI_GPO_SELECTOR = 409, // Selects general purpose output CV_CAP_PROP_XI_GPO_MODE = 410, // Set general purpose output mode CV_CAP_PROP_XI_LED_SELECTOR = 411, // Selects camera signalling LED CV_CAP_PROP_XI_LED_MODE = 412, // Define camera signalling LED functionality CV_CAP_PROP_XI_MANUAL_WB = 413, // Calculates White Balance(must be called during acquisition) CV_CAP_PROP_XI_AUTO_WB = 414, // Automatic white balance CV_CAP_PROP_XI_AEAG = 415, // Automatic exposure/gain CV_CAP_PROP_XI_EXP_PRIORITY = 416, // Exposure priority (0.5 - exposure 50%, gain 50%). CV_CAP_PROP_XI_AE_MAX_LIMIT = 417, // Maximum limit of exposure in AEAG procedure CV_CAP_PROP_XI_AG_MAX_LIMIT = 418, // Maximum limit of gain in AEAG procedure CV_CAP_PROP_XI_AEAG_LEVEL = 419, // Average intensity of output signal AEAG should achieve(in %) CV_CAP_PROP_XI_TIMEOUT = 420, // Image capture timeout in milliseconds // Properties for Android cameras CV_CAP_PROP_ANDROID_FLASH_MODE = 8001, CV_CAP_PROP_ANDROID_FOCUS_MODE = 8002, CV_CAP_PROP_ANDROID_WHITE_BALANCE = 8003, CV_CAP_PROP_ANDROID_ANTIBANDING = 8004, CV_CAP_PROP_ANDROID_FOCAL_LENGTH = 8005, CV_CAP_PROP_ANDROID_FOCUS_DISTANCE_NEAR = 8006, CV_CAP_PROP_ANDROID_FOCUS_DISTANCE_OPTIMAL = 8007, CV_CAP_PROP_ANDROID_FOCUS_DISTANCE_FAR = 8008, // Properties of cameras available through AVFOUNDATION interface CV_CAP_PROP_IOS_DEVICE_FOCUS = 9001, CV_CAP_PROP_IOS_DEVICE_EXPOSURE = 9002, CV_CAP_PROP_IOS_DEVICE_FLASH = 9003, CV_CAP_PROP_IOS_DEVICE_WHITEBALANCE = 9004, CV_CAP_PROP_IOS_DEVICE_TORCH = 9005, // Properties of cameras available through Smartek Giganetix Ethernet Vision interface /* --- Vladimir Litvinenko (litvinenko.vladimir@gmail.com) --- */ CV_CAP_PROP_GIGA_FRAME_OFFSET_X = 10001, CV_CAP_PROP_GIGA_FRAME_OFFSET_Y = 10002, CV_CAP_PROP_GIGA_FRAME_WIDTH_MAX = 10003, CV_CAP_PROP_GIGA_FRAME_HEIGH_MAX = 10004, CV_CAP_PROP_GIGA_FRAME_SENS_WIDTH = 10005, CV_CAP_PROP_GIGA_FRAME_SENS_HEIGH = 10006, CV_CAP_PROP_INTELPERC_PROFILE_COUNT = 11001, CV_CAP_PROP_INTELPERC_PROFILE_IDX = 11002, CV_CAP_PROP_INTELPERC_DEPTH_LOW_CONFIDENCE_VALUE = 11003, CV_CAP_PROP_INTELPERC_DEPTH_SATURATION_VALUE = 11004, CV_CAP_PROP_INTELPERC_DEPTH_CONFIDENCE_THRESHOLD = 11005, CV_CAP_PROP_INTELPERC_DEPTH_FOCAL_LENGTH_HORZ = 11006, CV_CAP_PROP_INTELPERC_DEPTH_FOCAL_LENGTH_VERT = 11007, // Intel PerC streams CV_CAP_INTELPERC_DEPTH_GENERATOR = 1 << 29, CV_CAP_INTELPERC_IMAGE_GENERATOR = 1 << 28, CV_CAP_INTELPERC_GENERATORS_MASK = CV_CAP_INTELPERC_DEPTH_GENERATOR + CV_CAP_INTELPERC_IMAGE_GENERATOR; /** enum */ public static final int // Data given from depth generator. CV_CAP_OPENNI_DEPTH_MAP = 0, // Depth values in mm (CV_16UC1) CV_CAP_OPENNI_POINT_CLOUD_MAP = 1, // XYZ in meters (CV_32FC3) CV_CAP_OPENNI_DISPARITY_MAP = 2, // Disparity in pixels (CV_8UC1) CV_CAP_OPENNI_DISPARITY_MAP_32F = 3, // Disparity in pixels (CV_32FC1) CV_CAP_OPENNI_VALID_DEPTH_MASK = 4, // CV_8UC1 // Data given from RGB image generator. CV_CAP_OPENNI_BGR_IMAGE = 5, CV_CAP_OPENNI_GRAY_IMAGE = 6; // Supported output modes of OpenNI image generator /** enum */ public static final int CV_CAP_OPENNI_VGA_30HZ = 0, CV_CAP_OPENNI_SXGA_15HZ = 1, CV_CAP_OPENNI_SXGA_30HZ = 2, CV_CAP_OPENNI_QVGA_30HZ = 3, CV_CAP_OPENNI_QVGA_60HZ = 4; //supported by Android camera output formats /** enum */ public static final int CV_CAP_ANDROID_COLOR_FRAME_BGR = 0, //BGR CV_CAP_ANDROID_COLOR_FRAME = CV_CAP_ANDROID_COLOR_FRAME_BGR, CV_CAP_ANDROID_GREY_FRAME = 1, //Y CV_CAP_ANDROID_COLOR_FRAME_RGB = 2, CV_CAP_ANDROID_COLOR_FRAME_BGRA = 3, CV_CAP_ANDROID_COLOR_FRAME_RGBA = 4; // supported Android camera flash modes /** enum */ public static final int CV_CAP_ANDROID_FLASH_MODE_AUTO = 0, CV_CAP_ANDROID_FLASH_MODE_OFF = 1, CV_CAP_ANDROID_FLASH_MODE_ON = 2, CV_CAP_ANDROID_FLASH_MODE_RED_EYE = 3, CV_CAP_ANDROID_FLASH_MODE_TORCH = 4; // supported Android camera focus modes /** enum */ public static final int CV_CAP_ANDROID_FOCUS_MODE_AUTO = 0, CV_CAP_ANDROID_FOCUS_MODE_CONTINUOUS_VIDEO = 1, CV_CAP_ANDROID_FOCUS_MODE_EDOF = 2, CV_CAP_ANDROID_FOCUS_MODE_FIXED = 3, CV_CAP_ANDROID_FOCUS_MODE_INFINITY = 4, CV_CAP_ANDROID_FOCUS_MODE_MACRO = 5; // supported Android camera white balance modes /** enum */ public static final int CV_CAP_ANDROID_WHITE_BALANCE_AUTO = 0, CV_CAP_ANDROID_WHITE_BALANCE_CLOUDY_DAYLIGHT = 1, CV_CAP_ANDROID_WHITE_BALANCE_DAYLIGHT = 2, CV_CAP_ANDROID_WHITE_BALANCE_FLUORESCENT = 3, CV_CAP_ANDROID_WHITE_BALANCE_INCANDESCENT = 4, CV_CAP_ANDROID_WHITE_BALANCE_SHADE = 5, CV_CAP_ANDROID_WHITE_BALANCE_TWILIGHT = 6, CV_CAP_ANDROID_WHITE_BALANCE_WARM_FLUORESCENT = 7; // supported Android camera antibanding modes /** enum */ public static final int CV_CAP_ANDROID_ANTIBANDING_50HZ = 0, CV_CAP_ANDROID_ANTIBANDING_60HZ = 1, CV_CAP_ANDROID_ANTIBANDING_AUTO = 2, CV_CAP_ANDROID_ANTIBANDING_OFF = 3; /** enum */ public static final int CV_CAP_INTELPERC_DEPTH_MAP = 0, // Each pixel is a 16-bit integer. The value indicates the distance from an object to the camera's XY plane or the Cartesian depth. CV_CAP_INTELPERC_UVDEPTH_MAP = 1, // Each pixel contains two 32-bit floating point values in the range of 0-1, representing the mapping of depth coordinates to the color coordinates. CV_CAP_INTELPERC_IR_MAP = 2, // Each pixel is a 16-bit integer. The value indicates the intensity of the reflected laser beam. CV_CAP_INTELPERC_IMAGE = 3; /* retrieve or set capture properties */ public static native double cvGetCaptureProperty( CvCapture capture, int property_id ); public static native int cvSetCaptureProperty( CvCapture capture, int property_id, double value ); // Return the type of the capturer (eg, CV_CAP_V4W, CV_CAP_UNICAP), which is unknown if created with CV_CAP_ANY public static native int cvGetCaptureDomain( CvCapture capture); /* "black box" video file writer structure */ @Opaque public static class CvVideoWriter extends Pointer { public CvVideoWriter() { } public CvVideoWriter(Pointer p) { super(p); } } // #define CV_FOURCC_MACRO(c1, c2, c3, c4) (((c1) & 255) + (((c2) & 255) << 8) + (((c3) & 255) << 16) + (((c4) & 255) << 24)) public static native int CV_FOURCC(@Cast("char") byte c1, @Cast("char") byte c2, @Cast("char") byte c3, @Cast("char") byte c4); public static final int CV_FOURCC_PROMPT = -1; /* Open Codec Selection Dialog (Windows only) */ public static native @MemberGetter int CV_FOURCC_DEFAULT(); public static final int CV_FOURCC_DEFAULT = CV_FOURCC_DEFAULT(); /* Use default codec for specified filename (Linux only) */ /* initialize video file writer */ public static native CvVideoWriter cvCreateVideoWriter( @Cast("const char*") BytePointer filename, int fourcc, double fps, @ByVal CvSize frame_size, int is_color/*CV_DEFAULT(1)*/); public static native CvVideoWriter cvCreateVideoWriter( @Cast("const char*") BytePointer filename, int fourcc, double fps, @ByVal CvSize frame_size); public static native CvVideoWriter cvCreateVideoWriter( String filename, int fourcc, double fps, @ByVal CvSize frame_size, int is_color/*CV_DEFAULT(1)*/); public static native CvVideoWriter cvCreateVideoWriter( String filename, int fourcc, double fps, @ByVal CvSize frame_size); //CVAPI(CvVideoWriter*) cvCreateImageSequenceWriter( const char* filename, // int is_color CV_DEFAULT(1)); /* write frame to video file */ public static native int cvWriteFrame( CvVideoWriter writer, @Const IplImage image ); /* close video file writer */ public static native void cvReleaseVideoWriter( @Cast("CvVideoWriter**") PointerPointer writer ); public static native void cvReleaseVideoWriter( @ByPtrPtr CvVideoWriter writer ); /****************************************************************************************\ * Obsolete functions/synonyms * \****************************************************************************************/ public static native CvCapture cvCaptureFromFile(@Cast("const char*") BytePointer arg1); public static native CvCapture cvCaptureFromFile(String arg1); public static native CvCapture cvCaptureFromCAM(int arg1); public static native CvCapture cvCaptureFromAVI(@Cast("const char*") BytePointer arg1); public static native CvCapture cvCaptureFromAVI(String arg1); public static native CvVideoWriter cvCreateAVIWriter(@Cast("const char*") BytePointer arg1, int arg2, double arg3, @ByVal CvSize arg4, int arg5); public static native CvVideoWriter cvCreateAVIWriter(String arg1, int arg2, double arg3, @ByVal CvSize arg4, int arg5); public static native int cvWriteToAVI(CvVideoWriter arg1, IplImage arg2); public static native void cvAddSearchPath(@Cast("const char*") BytePointer path); public static native void cvAddSearchPath(String path); public static native int cvvInitSystem(int arg1, @Cast("char**") PointerPointer arg2); public static native int cvvInitSystem(int arg1, @Cast("char**") @ByPtrPtr BytePointer arg2); public static native int cvvInitSystem(int arg1, @Cast("char**") @ByPtrPtr ByteBuffer arg2); public static native int cvvInitSystem(int arg1, @Cast("char**") @ByPtrPtr byte[] arg2); public static native void cvvNamedWindow(@Cast("const char*") BytePointer arg1, int arg2); public static native void cvvNamedWindow(String arg1, int arg2); public static native void cvvShowImage(@Cast("const char*") BytePointer arg1, CvArr arg2); public static native void cvvShowImage(String arg1, CvArr arg2); public static native void cvvResizeWindow(@Cast("const char*") BytePointer arg1, int arg2, int arg3); public static native void cvvResizeWindow(String arg1, int arg2, int arg3); public static native void cvvDestroyWindow(@Cast("const char*") BytePointer arg1); public static native void cvvDestroyWindow(String arg1); public static native int cvvCreateTrackbar(@Cast("const char*") BytePointer arg1, @Cast("const char*") BytePointer arg2, IntPointer arg3, int arg4, CvTrackbarCallback arg5); public static native int cvvCreateTrackbar(String arg1, String arg2, IntBuffer arg3, int arg4, CvTrackbarCallback arg5); public static native int cvvCreateTrackbar(@Cast("const char*") BytePointer arg1, @Cast("const char*") BytePointer arg2, int[] arg3, int arg4, CvTrackbarCallback arg5); public static native int cvvCreateTrackbar(String arg1, String arg2, IntPointer arg3, int arg4, CvTrackbarCallback arg5); public static native int cvvCreateTrackbar(@Cast("const char*") BytePointer arg1, @Cast("const char*") BytePointer arg2, IntBuffer arg3, int arg4, CvTrackbarCallback arg5); public static native int cvvCreateTrackbar(String arg1, String arg2, int[] arg3, int arg4, CvTrackbarCallback arg5); public static native IplImage cvvLoadImage(@Cast("const char*") BytePointer name); public static native IplImage cvvLoadImage(String name); public static native int cvvSaveImage(@Cast("const char*") BytePointer arg1, CvArr arg2, IntPointer arg3); public static native int cvvSaveImage(String arg1, CvArr arg2, IntBuffer arg3); public static native int cvvSaveImage(@Cast("const char*") BytePointer arg1, CvArr arg2, int[] arg3); public static native int cvvSaveImage(String arg1, CvArr arg2, IntPointer arg3); public static native int cvvSaveImage(@Cast("const char*") BytePointer arg1, CvArr arg2, IntBuffer arg3); public static native int cvvSaveImage(String arg1, CvArr arg2, int[] arg3); public static native void cvvAddSearchPath(@Cast("const char*") BytePointer arg1); public static native void cvvAddSearchPath(String arg1); public static native int cvvWaitKey(@Cast("const char*") BytePointer name); public static native int cvvWaitKey(String name); public static native int cvvWaitKeyEx(@Cast("const char*") BytePointer name, int delay); public static native int cvvWaitKeyEx(String name, int delay); public static native void cvvConvertImage(CvArr arg1, CvArr arg2, int arg3); public static final int HG_AUTOSIZE = CV_WINDOW_AUTOSIZE; // #define set_preprocess_func cvSetPreprocessFuncWin32 // #define set_postprocess_func cvSetPostprocessFuncWin32 // #if defined WIN32 || defined _WIN32 // #endif // #ifdef __cplusplus // #endif // #endif // Parsed from /usr/local/include/opencv2/highgui/highgui.hpp /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's 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. // // * The name of the copyright holders may not 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 Intel Corporation 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. // //M*/ // #ifndef __OPENCV_HIGHGUI_HPP__ // #define __OPENCV_HIGHGUI_HPP__ // #include "opencv2/core/core.hpp" // #include "opencv2/highgui/highgui_c.h" // #ifdef __cplusplus /** enum cv:: */ public static final int // Flags for namedWindow WINDOW_NORMAL = CV_WINDOW_NORMAL, // the user can resize the window (no constraint) / also use to switch a fullscreen window to a normal size WINDOW_AUTOSIZE = CV_WINDOW_AUTOSIZE, // the user cannot resize the window, the size is constrainted by the image displayed WINDOW_OPENGL = CV_WINDOW_OPENGL, // window with opengl support // Flags for set / getWindowProperty WND_PROP_FULLSCREEN = CV_WND_PROP_FULLSCREEN, // fullscreen property WND_PROP_AUTOSIZE = CV_WND_PROP_AUTOSIZE, // autosize property WND_PROP_ASPECT_RATIO = CV_WND_PROP_ASPECTRATIO, // window's aspect ration WND_PROP_OPENGL = CV_WND_PROP_OPENGL; // opengl support @Namespace("cv") public static native void namedWindow(@StdString BytePointer winname, int flags/*=WINDOW_AUTOSIZE*/); @Namespace("cv") public static native void namedWindow(@StdString BytePointer winname); @Namespace("cv") public static native void namedWindow(@StdString String winname, int flags/*=WINDOW_AUTOSIZE*/); @Namespace("cv") public static native void namedWindow(@StdString String winname); @Namespace("cv") public static native void destroyWindow(@StdString BytePointer winname); @Namespace("cv") public static native void destroyWindow(@StdString String winname); @Namespace("cv") public static native void destroyAllWindows(); @Namespace("cv") public static native int startWindowThread(); @Namespace("cv") public static native int waitKey(int delay/*=0*/); @Namespace("cv") public static native int waitKey(); @Namespace("cv") public static native void imshow(@StdString BytePointer winname, @ByVal Mat mat); @Namespace("cv") public static native void imshow(@StdString String winname, @ByVal Mat mat); @Namespace("cv") public static native void resizeWindow(@StdString BytePointer winname, int width, int height); @Namespace("cv") public static native void resizeWindow(@StdString String winname, int width, int height); @Namespace("cv") public static native void moveWindow(@StdString BytePointer winname, int x, int y); @Namespace("cv") public static native void moveWindow(@StdString String winname, int x, int y); @Namespace("cv") public static native void setWindowProperty(@StdString BytePointer winname, int prop_id, double prop_value); @Namespace("cv") public static native void setWindowProperty(@StdString String winname, int prop_id, double prop_value);//YV @Namespace("cv") public static native double getWindowProperty(@StdString BytePointer winname, int prop_id); @Namespace("cv") public static native double getWindowProperty(@StdString String winname, int prop_id);//YV /** enum cv:: */ public static final int EVENT_MOUSEMOVE = 0, EVENT_LBUTTONDOWN = 1, EVENT_RBUTTONDOWN = 2, EVENT_MBUTTONDOWN = 3, EVENT_LBUTTONUP = 4, EVENT_RBUTTONUP = 5, EVENT_MBUTTONUP = 6, EVENT_LBUTTONDBLCLK = 7, EVENT_RBUTTONDBLCLK = 8, EVENT_MBUTTONDBLCLK = 9; /** enum cv:: */ public static final int EVENT_FLAG_LBUTTON = 1, EVENT_FLAG_RBUTTON = 2, EVENT_FLAG_MBUTTON = 4, EVENT_FLAG_CTRLKEY = 8, EVENT_FLAG_SHIFTKEY = 16, EVENT_FLAG_ALTKEY = 32; public static class MouseCallback extends FunctionPointer { static { Loader.load(); } public MouseCallback(Pointer p) { super(p); } protected MouseCallback() { allocate(); } private native void allocate(); public native void call(int event, int x, int y, int flags, Pointer userdata); } /** assigns callback for mouse events */ @Namespace("cv") public static native void setMouseCallback(@StdString BytePointer winname, MouseCallback onMouse, Pointer userdata/*=0*/); @Namespace("cv") public static native void setMouseCallback(@StdString BytePointer winname, MouseCallback onMouse); @Namespace("cv") public static native void setMouseCallback(@StdString String winname, MouseCallback onMouse, Pointer userdata/*=0*/); @Namespace("cv") public static native void setMouseCallback(@StdString String winname, MouseCallback onMouse); @Convention("CV_CDECL") public static class TrackbarCallback extends FunctionPointer { static { Loader.load(); } public TrackbarCallback(Pointer p) { super(p); } protected TrackbarCallback() { allocate(); } private native void allocate(); public native void call(int pos, Pointer userdata); } @Namespace("cv") public static native int createTrackbar(@StdString BytePointer trackbarname, @StdString BytePointer winname, IntPointer value, int count, TrackbarCallback onChange/*=0*/, Pointer userdata/*=0*/); @Namespace("cv") public static native int createTrackbar(@StdString BytePointer trackbarname, @StdString BytePointer winname, IntPointer value, int count); @Namespace("cv") public static native int createTrackbar(@StdString String trackbarname, @StdString String winname, IntBuffer value, int count, TrackbarCallback onChange/*=0*/, Pointer userdata/*=0*/); @Namespace("cv") public static native int createTrackbar(@StdString String trackbarname, @StdString String winname, IntBuffer value, int count); @Namespace("cv") public static native int createTrackbar(@StdString BytePointer trackbarname, @StdString BytePointer winname, int[] value, int count, TrackbarCallback onChange/*=0*/, Pointer userdata/*=0*/); @Namespace("cv") public static native int createTrackbar(@StdString BytePointer trackbarname, @StdString BytePointer winname, int[] value, int count); @Namespace("cv") public static native int createTrackbar(@StdString String trackbarname, @StdString String winname, IntPointer value, int count, TrackbarCallback onChange/*=0*/, Pointer userdata/*=0*/); @Namespace("cv") public static native int createTrackbar(@StdString String trackbarname, @StdString String winname, IntPointer value, int count); @Namespace("cv") public static native int createTrackbar(@StdString BytePointer trackbarname, @StdString BytePointer winname, IntBuffer value, int count, TrackbarCallback onChange/*=0*/, Pointer userdata/*=0*/); @Namespace("cv") public static native int createTrackbar(@StdString BytePointer trackbarname, @StdString BytePointer winname, IntBuffer value, int count); @Namespace("cv") public static native int createTrackbar(@StdString String trackbarname, @StdString String winname, int[] value, int count, TrackbarCallback onChange/*=0*/, Pointer userdata/*=0*/); @Namespace("cv") public static native int createTrackbar(@StdString String trackbarname, @StdString String winname, int[] value, int count); @Namespace("cv") public static native int getTrackbarPos(@StdString BytePointer trackbarname, @StdString BytePointer winname); @Namespace("cv") public static native int getTrackbarPos(@StdString String trackbarname, @StdString String winname); @Namespace("cv") public static native void setTrackbarPos(@StdString BytePointer trackbarname, @StdString BytePointer winname, int pos); @Namespace("cv") public static native void setTrackbarPos(@StdString String trackbarname, @StdString String winname, int pos); // OpenGL support public static class OpenGlDrawCallback extends FunctionPointer { static { Loader.load(); } public OpenGlDrawCallback(Pointer p) { super(p); } protected OpenGlDrawCallback() { allocate(); } private native void allocate(); public native void call(Pointer userdata); } @Namespace("cv") public static native void setOpenGlDrawCallback(@StdString BytePointer winname, OpenGlDrawCallback onOpenGlDraw, Pointer userdata/*=0*/); @Namespace("cv") public static native void setOpenGlDrawCallback(@StdString BytePointer winname, OpenGlDrawCallback onOpenGlDraw); @Namespace("cv") public static native void setOpenGlDrawCallback(@StdString String winname, OpenGlDrawCallback onOpenGlDraw, Pointer userdata/*=0*/); @Namespace("cv") public static native void setOpenGlDrawCallback(@StdString String winname, OpenGlDrawCallback onOpenGlDraw); @Namespace("cv") public static native void setOpenGlContext(@StdString BytePointer winname); @Namespace("cv") public static native void setOpenGlContext(@StdString String winname); @Namespace("cv") public static native void updateWindow(@StdString BytePointer winname); @Namespace("cv") public static native void updateWindow(@StdString String winname); // < Deperecated @Namespace("cv") public static native void pointCloudShow(@StdString BytePointer winname, @Const @ByRef GlCamera camera, @Const @ByRef GlArrays arr); @Namespace("cv") public static native void pointCloudShow(@StdString String winname, @Const @ByRef GlCamera camera, @Const @ByRef GlArrays arr); @Namespace("cv") public static native void pointCloudShow(@StdString BytePointer winname, @Const @ByRef GlCamera camera, @ByVal Mat points, @ByVal Mat colors/*=noArray()*/); @Namespace("cv") public static native void pointCloudShow(@StdString BytePointer winname, @Const @ByRef GlCamera camera, @ByVal Mat points); @Namespace("cv") public static native void pointCloudShow(@StdString String winname, @Const @ByRef GlCamera camera, @ByVal Mat points, @ByVal Mat colors/*=noArray()*/); @Namespace("cv") public static native void pointCloudShow(@StdString String winname, @Const @ByRef GlCamera camera, @ByVal Mat points); // > //Only for Qt @Namespace("cv") public static native @ByVal CvFont fontQt(@StdString BytePointer nameFont, int pointSize/*=-1*/, @ByVal Scalar color/*=Scalar::all(0)*/, int weight/*=CV_FONT_NORMAL*/, int style/*=CV_STYLE_NORMAL*/, int spacing/*=0*/); @Namespace("cv") public static native @ByVal CvFont fontQt(@StdString BytePointer nameFont); @Namespace("cv") public static native @ByVal CvFont fontQt(@StdString String nameFont, int pointSize/*=-1*/, @ByVal Scalar color/*=Scalar::all(0)*/, int weight/*=CV_FONT_NORMAL*/, int style/*=CV_STYLE_NORMAL*/, int spacing/*=0*/); @Namespace("cv") public static native @ByVal CvFont fontQt(@StdString String nameFont); @Namespace("cv") public static native void addText( @Const @ByRef Mat img, @StdString BytePointer text, @ByVal Point org, @ByVal CvFont font); @Namespace("cv") public static native void addText( @Const @ByRef Mat img, @StdString String text, @ByVal Point org, @ByVal CvFont font); @Namespace("cv") public static native void displayOverlay(@StdString BytePointer winname, @StdString BytePointer text, int delayms/*CV_DEFAULT(0)*/); @Namespace("cv") public static native void displayOverlay(@StdString BytePointer winname, @StdString BytePointer text); @Namespace("cv") public static native void displayOverlay(@StdString String winname, @StdString String text, int delayms/*CV_DEFAULT(0)*/); @Namespace("cv") public static native void displayOverlay(@StdString String winname, @StdString String text); @Namespace("cv") public static native void displayStatusBar(@StdString BytePointer winname, @StdString BytePointer text, int delayms/*CV_DEFAULT(0)*/); @Namespace("cv") public static native void displayStatusBar(@StdString BytePointer winname, @StdString BytePointer text); @Namespace("cv") public static native void displayStatusBar(@StdString String winname, @StdString String text, int delayms/*CV_DEFAULT(0)*/); @Namespace("cv") public static native void displayStatusBar(@StdString String winname, @StdString String text); @Namespace("cv") public static native void saveWindowParameters(@StdString BytePointer windowName); @Namespace("cv") public static native void saveWindowParameters(@StdString String windowName); @Namespace("cv") public static native void loadWindowParameters(@StdString BytePointer windowName); @Namespace("cv") public static native void loadWindowParameters(@StdString String windowName); @Namespace("cv") public static native int startLoop(Pt2Func_int_PointerPointer pt2Func, int argc, @Cast("char**") PointerPointer argv); @Namespace("cv") public static native int startLoop(Pt2Func_int_BytePointer pt2Func, int argc, @Cast("char**") @ByPtrPtr BytePointer argv); @Namespace("cv") public static native int startLoop(Pt2Func_int_ByteBuffer pt2Func, int argc, @Cast("char**") @ByPtrPtr ByteBuffer argv); @Namespace("cv") public static native int startLoop(Pt2Func_int_byte__ pt2Func, int argc, @Cast("char**") @ByPtrPtr byte[] argv); @Namespace("cv") public static native void stopLoop(); @Convention("CV_CDECL") public static class ButtonCallback extends FunctionPointer { static { Loader.load(); } public ButtonCallback(Pointer p) { super(p); } protected ButtonCallback() { allocate(); } private native void allocate(); public native void call(int state, Pointer userdata); } @Namespace("cv") public static native int createButton( @StdString BytePointer bar_name, ButtonCallback on_change, Pointer userdata/*=NULL*/, int type/*=CV_PUSH_BUTTON*/, @Cast("bool") boolean initial_button_state/*=0*/); @Namespace("cv") public static native int createButton( @StdString BytePointer bar_name, ButtonCallback on_change); @Namespace("cv") public static native int createButton( @StdString String bar_name, ButtonCallback on_change, Pointer userdata/*=NULL*/, int type/*=CV_PUSH_BUTTON*/, @Cast("bool") boolean initial_button_state/*=0*/); @Namespace("cv") public static native int createButton( @StdString String bar_name, ButtonCallback on_change); //------------------------- /** enum cv:: */ public static final int // 8bit, color or not IMREAD_UNCHANGED = -1, // 8bit, gray IMREAD_GRAYSCALE = 0, // ?, color IMREAD_COLOR = 1, // any depth, ? IMREAD_ANYDEPTH = 2, // ?, any color IMREAD_ANYCOLOR = 4; /** enum cv:: */ public static final int IMWRITE_JPEG_QUALITY = 1, IMWRITE_PNG_COMPRESSION = 16, IMWRITE_PNG_STRATEGY = 17, IMWRITE_PNG_BILEVEL = 18, IMWRITE_PNG_STRATEGY_DEFAULT = 0, IMWRITE_PNG_STRATEGY_FILTERED = 1, IMWRITE_PNG_STRATEGY_HUFFMAN_ONLY = 2, IMWRITE_PNG_STRATEGY_RLE = 3, IMWRITE_PNG_STRATEGY_FIXED = 4, IMWRITE_PXM_BINARY = 32; @Namespace("cv") public static native @ByVal Mat imread( @StdString BytePointer filename, int flags/*=1*/ ); @Namespace("cv") public static native @ByVal Mat imread( @StdString BytePointer filename ); @Namespace("cv") public static native @ByVal Mat imread( @StdString String filename, int flags/*=1*/ ); @Namespace("cv") public static native @ByVal Mat imread( @StdString String filename ); @Namespace("cv") public static native @Cast("bool") boolean imwrite( @StdString BytePointer filename, @ByVal Mat img, @StdVector IntPointer params/*=vector<int>()*/); @Namespace("cv") public static native @Cast("bool") boolean imwrite( @StdString BytePointer filename, @ByVal Mat img); @Namespace("cv") public static native @Cast("bool") boolean imwrite( @StdString String filename, @ByVal Mat img, @StdVector IntBuffer params/*=vector<int>()*/); @Namespace("cv") public static native @Cast("bool") boolean imwrite( @StdString String filename, @ByVal Mat img); @Namespace("cv") public static native @Cast("bool") boolean imwrite( @StdString BytePointer filename, @ByVal Mat img, @StdVector int[] params/*=vector<int>()*/); @Namespace("cv") public static native @Cast("bool") boolean imwrite( @StdString String filename, @ByVal Mat img, @StdVector IntPointer params/*=vector<int>()*/); @Namespace("cv") public static native @Cast("bool") boolean imwrite( @StdString BytePointer filename, @ByVal Mat img, @StdVector IntBuffer params/*=vector<int>()*/); @Namespace("cv") public static native @Cast("bool") boolean imwrite( @StdString String filename, @ByVal Mat img, @StdVector int[] params/*=vector<int>()*/); @Namespace("cv") public static native @ByVal Mat imdecode( @ByVal Mat buf, int flags ); @Namespace("cv") public static native @ByVal Mat imdecode( @ByVal Mat buf, int flags, Mat dst ); @Namespace("cv") public static native @Cast("bool") boolean imencode( @StdString BytePointer ext, @ByVal Mat img, @Cast("uchar*") @StdVector BytePointer buf, @StdVector IntPointer params/*=vector<int>()*/); @Namespace("cv") public static native @Cast("bool") boolean imencode( @StdString BytePointer ext, @ByVal Mat img, @Cast("uchar*") @StdVector BytePointer buf); @Namespace("cv") public static native @Cast("bool") boolean imencode( @StdString String ext, @ByVal Mat img, @Cast("uchar*") @StdVector ByteBuffer buf, @StdVector IntBuffer params/*=vector<int>()*/); @Namespace("cv") public static native @Cast("bool") boolean imencode( @StdString String ext, @ByVal Mat img, @Cast("uchar*") @StdVector ByteBuffer buf); @Namespace("cv") public static native @Cast("bool") boolean imencode( @StdString BytePointer ext, @ByVal Mat img, @Cast("uchar*") @StdVector byte[] buf, @StdVector int[] params/*=vector<int>()*/); @Namespace("cv") public static native @Cast("bool") boolean imencode( @StdString BytePointer ext, @ByVal Mat img, @Cast("uchar*") @StdVector byte[] buf); @Namespace("cv") public static native @Cast("bool") boolean imencode( @StdString String ext, @ByVal Mat img, @Cast("uchar*") @StdVector BytePointer buf, @StdVector IntPointer params/*=vector<int>()*/); @Namespace("cv") public static native @Cast("bool") boolean imencode( @StdString String ext, @ByVal Mat img, @Cast("uchar*") @StdVector BytePointer buf); @Namespace("cv") public static native @Cast("bool") boolean imencode( @StdString BytePointer ext, @ByVal Mat img, @Cast("uchar*") @StdVector ByteBuffer buf, @StdVector IntBuffer params/*=vector<int>()*/); @Namespace("cv") public static native @Cast("bool") boolean imencode( @StdString BytePointer ext, @ByVal Mat img, @Cast("uchar*") @StdVector ByteBuffer buf); @Namespace("cv") public static native @Cast("bool") boolean imencode( @StdString String ext, @ByVal Mat img, @Cast("uchar*") @StdVector byte[] buf, @StdVector int[] params/*=vector<int>()*/); @Namespace("cv") public static native @Cast("bool") boolean imencode( @StdString String ext, @ByVal Mat img, @Cast("uchar*") @StdVector byte[] buf); // #ifndef CV_NO_VIDEO_CAPTURE_CPP_API @Namespace("cv") @NoOffset public static class VideoCapture extends Pointer { static { Loader.load(); } public VideoCapture(Pointer p) { super(p); } public VideoCapture() { allocate(); } private native void allocate(); public VideoCapture(@StdString BytePointer filename) { allocate(filename); } private native void allocate(@StdString BytePointer filename); public VideoCapture(@StdString String filename) { allocate(filename); } private native void allocate(@StdString String filename); public VideoCapture(int device) { allocate(device); } private native void allocate(int device); public native @Cast("bool") boolean open(@StdString BytePointer filename); public native @Cast("bool") boolean open(@StdString String filename); public native @Cast("bool") boolean open(int device); public native @Cast("bool") boolean isOpened(); public native void release(); public native @Cast("bool") boolean grab(); public native @Cast("bool") boolean retrieve(@ByRef Mat image, int channel/*=0*/); public native @Cast("bool") boolean retrieve(@ByRef Mat image); public native @ByRef @Name("operator>>") VideoCapture shiftRight(@ByRef Mat image); public native @Cast("bool") boolean read(@ByRef Mat image); public native @Cast("bool") boolean set(int propId, double value); public native double get(int propId); } @Namespace("cv") @NoOffset public static class VideoWriter extends Pointer { static { Loader.load(); } public VideoWriter(Pointer p) { super(p); } public VideoWriter(int size) { allocateArray(size); } private native void allocateArray(int size); @Override public VideoWriter position(int position) { return (VideoWriter)super.position(position); } public VideoWriter() { allocate(); } private native void allocate(); public VideoWriter(@StdString BytePointer filename, int fourcc, double fps, @ByVal Size frameSize, @Cast("bool") boolean isColor/*=true*/) { allocate(filename, fourcc, fps, frameSize, isColor); } private native void allocate(@StdString BytePointer filename, int fourcc, double fps, @ByVal Size frameSize, @Cast("bool") boolean isColor/*=true*/); public VideoWriter(@StdString BytePointer filename, int fourcc, double fps, @ByVal Size frameSize) { allocate(filename, fourcc, fps, frameSize); } private native void allocate(@StdString BytePointer filename, int fourcc, double fps, @ByVal Size frameSize); public VideoWriter(@StdString String filename, int fourcc, double fps, @ByVal Size frameSize, @Cast("bool") boolean isColor/*=true*/) { allocate(filename, fourcc, fps, frameSize, isColor); } private native void allocate(@StdString String filename, int fourcc, double fps, @ByVal Size frameSize, @Cast("bool") boolean isColor/*=true*/); public VideoWriter(@StdString String filename, int fourcc, double fps, @ByVal Size frameSize) { allocate(filename, fourcc, fps, frameSize); } private native void allocate(@StdString String filename, int fourcc, double fps, @ByVal Size frameSize); public native @Cast("bool") boolean open(@StdString BytePointer filename, int fourcc, double fps, @ByVal Size frameSize, @Cast("bool") boolean isColor/*=true*/); public native @Cast("bool") boolean open(@StdString BytePointer filename, int fourcc, double fps, @ByVal Size frameSize); public native @Cast("bool") boolean open(@StdString String filename, int fourcc, double fps, @ByVal Size frameSize, @Cast("bool") boolean isColor/*=true*/); public native @Cast("bool") boolean open(@StdString String filename, int fourcc, double fps, @ByVal Size frameSize); public native @Cast("bool") boolean isOpened(); public native void release(); public native @ByRef @Name("operator<<") VideoWriter shiftLeft(@Const @ByRef Mat image); public native void write(@Const @ByRef Mat image); } // #endif // #endif // #endif }
duongtung4691/javacpp.presets
opencv/src/main/java/com/googlecode/javacpp/opencv_highgui.java
Java
gpl-2.0
75,386
<?php namespace Drupal\admin_toolbar_tools\Controller; use Drupal\Core\Cache\CacheBackendInterface; use Drupal\Core\Controller\ControllerBase; use Drupal\Core\CronInterface; use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\HttpFoundation\RedirectResponse; use Drupal\Core\Menu\ContextualLinkManager; use Drupal\Core\Menu\LocalActionManager; use Drupal\Core\Menu\LocalTaskManager; use Drupal\Core\Menu\MenuLinkManager; /** * Class ToolbarController * @package Drupal\admin_toolbar_tools\Controller */ class ToolbarController extends ControllerBase { /** * The cron service. * * @var $cron \Drupal\Core\CronInterface */ protected $cron; protected $menuLinkManager; protected $contextualLinkManager; protected $localTaskLinkManager; protected $localActionLinkManager; protected $cacheRender; /** * Constructs a CronController object. * * @param \Drupal\Core\CronInterface $cron * The cron service. */ public function __construct(CronInterface $cron, MenuLinkManager $menuLinkManager, ContextualLinkManager $contextualLinkManager, LocalTaskManager $localTaskLinkManager, LocalActionManager $localActionLinkManager, CacheBackendInterface $cacheRender) { $this->cron = $cron; $this->menuLinkManager = $menuLinkManager; $this->contextualLinkManager = $contextualLinkManager; $this->localTaskLinkManager = $localTaskLinkManager; $this->localActionLinkManager = $localActionLinkManager; $this->cacheRender = $cacheRender; } /** * {@inheritdoc} */ public static function create(ContainerInterface $container) { return new static( $container->get('cron'), $container->get('plugin.manager.menu.link'), $container->get('plugin.manager.menu.contextual_link'), $container->get('plugin.manager.menu.local_task'), $container->get('plugin.manager.menu.local_action'), $container->get('cache.render') ); } // Reload the previous page. public function reload_page() { $request = \Drupal::request(); if($request->server->get('HTTP_REFERER')) { return $request->server->get('HTTP_REFERER'); } else{ return '/'; } } // Flushes all caches. public function flushAll() { drupal_flush_all_caches(); drupal_set_message($this->t('All caches cleared.')); return new RedirectResponse($this->reload_page()); } // Flushes css and javascript caches. public function flush_js_css() { \Drupal::state() ->set('system.css_js_query_string', base_convert(REQUEST_TIME, 10, 36)); drupal_set_message($this->t('CSS and JavaScript cache cleared.')); return new RedirectResponse($this->reload_page()); } // Flushes plugins caches. public function flush_plugins() { \Drupal::service('plugin.cache_clearer')->clearCachedDefinitions(); drupal_set_message($this->t('Plugins cache cleared.')); return new RedirectResponse($this->reload_page()); } // Resets all static caches. public function flush_static() { drupal_static_reset(); drupal_set_message($this->t('Static cache cleared.')); return new RedirectResponse($this->reload_page()); } // Clears all cached menu data. public function flush_menu() { menu_cache_clear_all(); $this->menuLinkManager->rebuild(); $this->contextualLinkManager->clearCachedDefinitions(); $this->localTaskLinkManager->clearCachedDefinitions(); $this->localActionLinkManager->clearCachedDefinitions(); drupal_set_message($this->t('Routing and links cache cleared.')); return new RedirectResponse($this->reload_page()); } // Links to drupal.org home page. public function drupal_org() { $response = new RedirectResponse("https://www.drupal.org"); $response->send(); return $response; } // Displays the administration link Development. public function development() { return new RedirectResponse('/admin/structure/menu/'); } // Access to Drupal 8 changes (list changes of the different versions of drupal core). public function list_changes() { $response = new RedirectResponse("https://www.drupal.org/list-changes"); $response->send(); return $response; } // Adds a link to the Drupal 8 documentation. public function documentation() { $response = new RedirectResponse("https://api.drupal.org/api/drupal/8"); $response->send(); return $response; } public function runCron() { $this->cron->run(); drupal_set_message($this->t('CRON ran successfully.')); return new RedirectResponse($this->reload_page()); } public function cacheRender() { $this->cacheRender->invalidateAll(); drupal_set_message($this->t('Render cache cleared.')); return new RedirectResponse($this->reload_page()); } }
hook42/towel
modules/contrib/admin_toolbar/admin_toolbar_tools/src/Controller/ToolbarController.php
PHP
gpl-2.0
4,942
/** * This file is part of OXID eShop Community Edition. * * OXID eShop Community Edition is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OXID eShop Community Edition is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OXID eShop Community Edition. If not, see <http://www.gnu.org/licenses/>. * * @link http://www.oxid-esales.com * @package out * @copyright (C) OXID eSales AG 2003-2013 * @version OXID eShop CE * @version SVN: $Id: oxpromocategory.js 35529 2011-05-23 07:31:20Z vilma $ */ ( function( $ ) { oxCenterElementOnHover = { _create: function(){ var self = this; var el = self.element; el.hover(function(){ var targetObj = $(".viewAllHover", el); var targetObjWidth = targetObj.outerWidth() / 2; var parentObjWidth = el.width() / 2; targetObj.css("left", parentObjWidth - targetObjWidth + "px"); targetObj.show(); }, function(){ $(".viewAllHover", el).hide(); }); } } $.widget( "ui.oxCenterElementOnHover", oxCenterElementOnHover ); } )( jQuery );
apnfq/oxid_test
out/azure/src/js/widgets/oxcenterelementonhover.js
JavaScript
gpl-3.0
1,679
<?php /** * PHPExcel * * Copyright (c) 2006 - 2013 PHPExcel * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * @category PHPExcel * @package PHPExcel_Shared * @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel) * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL * @version 1.7.9, 2013-06-02 */ /** * PHPExcel_Shared_Date * * @category PHPExcel * @package PHPExcel_Shared * @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel) */ class PHPExcel_Shared_Date { /** constants */ const CALENDAR_WINDOWS_1900 = 1900; // Base date of 1st Jan 1900 = 1.0 const CALENDAR_MAC_1904 = 1904; // Base date of 2nd Jan 1904 = 1.0 /* * Names of the months of the year, indexed by shortname * Planned usage for locale settings * * @public * @var string[] */ public static $_monthNames = array( 'Jan' => 'January', 'Feb' => 'February', 'Mar' => 'March', 'Apr' => 'April', 'May' => 'May', 'Jun' => 'June', 'Jul' => 'July', 'Aug' => 'August', 'Sep' => 'September', 'Oct' => 'October', 'Nov' => 'November', 'Dec' => 'December', ); /* * Names of the months of the year, indexed by shortname * Planned usage for locale settings * * @public * @var string[] */ public static $_numberSuffixes = array( 'st', 'nd', 'rd', 'th', ); /* * Base calendar year to use for calculations * * @private * @var int */ protected static $_excelBaseDate = self::CALENDAR_WINDOWS_1900; /** * Set the Excel calendar (Windows 1900 or Mac 1904) * * @param integer $baseDate Excel base date (1900 or 1904) * @return boolean Success or failure */ public static function setExcelCalendar($baseDate) { if (($baseDate == self::CALENDAR_WINDOWS_1900) || ($baseDate == self::CALENDAR_MAC_1904)) { self::$_excelBaseDate = $baseDate; return TRUE; } return FALSE; } // function setExcelCalendar() /** * Return the Excel calendar (Windows 1900 or Mac 1904) * * @return integer Excel base date (1900 or 1904) */ public static function getExcelCalendar() { return self::$_excelBaseDate; } // function getExcelCalendar() /** * Convert a date from Excel to PHP * * @param long $dateValue Excel date/time value * @param boolean $adjustToTimezone Flag indicating whether $dateValue should be treated as * a UST timestamp, or adjusted to UST * @param StringHelper $timezone The timezone for finding the adjustment from UST * @return long PHP serialized date/time */ public static function ExcelToPHP($dateValue = 0, $adjustToTimezone = FALSE, $timezone = NULL) { if (self::$_excelBaseDate == self::CALENDAR_WINDOWS_1900) { $my_excelBaseDate = 25569; // Adjust for the spurious 29-Feb-1900 (Day 60) if ($dateValue < 60) { --$my_excelBaseDate; } } else { $my_excelBaseDate = 24107; } // Perform conversion if ($dateValue >= 1) { $utcDays = $dateValue - $my_excelBaseDate; $returnValue = round($utcDays * 86400); if (($returnValue <= PHP_INT_MAX) && ($returnValue >= -PHP_INT_MAX)) { $returnValue = (integer) $returnValue; } } else { $hours = round($dateValue * 24); $mins = round($dateValue * 1440) - round($hours * 60); $secs = round($dateValue * 86400) - round($hours * 3600) - round($mins * 60); $returnValue = (integer) gmmktime($hours, $mins, $secs); } $timezoneAdjustment = ($adjustToTimezone) ? PHPExcel_Shared_TimeZone::getTimezoneAdjustment($timezone, $returnValue) : 0; // Return return $returnValue + $timezoneAdjustment; } // function ExcelToPHP() /** * Convert a date from Excel to a PHP Date/Time object * * @param integer $dateValue Excel date/time value * @return integer PHP date/time object */ public static function ExcelToPHPObject($dateValue = 0) { $dateTime = self::ExcelToPHP($dateValue); $days = floor($dateTime / 86400); $time = round((($dateTime / 86400) - $days) * 86400); $hours = round($time / 3600); $minutes = round($time / 60) - ($hours * 60); $seconds = round($time) - ($hours * 3600) - ($minutes * 60); $dateObj = date_create('1-Jan-1970+'.$days.' days'); $dateObj->setTime($hours,$minutes,$seconds); return $dateObj; } // function ExcelToPHPObject() /** * Convert a date from PHP to Excel * * @param mixed $dateValue PHP serialized date/time or date object * @param boolean $adjustToTimezone Flag indicating whether $dateValue should be treated as * a UST timestamp, or adjusted to UST * @param StringHelper $timezone The timezone for finding the adjustment from UST * @return mixed Excel date/time value * or boolean FALSE on failure */ public static function PHPToExcel($dateValue = 0, $adjustToTimezone = FALSE, $timezone = NULL) { $saveTimeZone = date_default_timezone_get(); date_default_timezone_set('UTC'); $retValue = FALSE; if ((is_object($dateValue)) && ($dateValue instanceof DateTime)) { $retValue = self::FormattedPHPToExcel( $dateValue->format('Y'), $dateValue->format('m'), $dateValue->format('d'), $dateValue->format('H'), $dateValue->format('i'), $dateValue->format('s') ); } elseif (is_numeric($dateValue)) { $retValue = self::FormattedPHPToExcel( date('Y',$dateValue), date('m',$dateValue), date('d',$dateValue), date('H',$dateValue), date('i',$dateValue), date('s',$dateValue) ); } date_default_timezone_set($saveTimeZone); return $retValue; } // function PHPToExcel() /** * FormattedPHPToExcel * * @param long $year * @param long $month * @param long $day * @param long $hours * @param long $minutes * @param long $seconds * @return long Excel date/time value */ public static function FormattedPHPToExcel($year, $month, $day, $hours=0, $minutes=0, $seconds=0) { if (self::$_excelBaseDate == self::CALENDAR_WINDOWS_1900) { // // Fudge factor for the erroneous fact that the year 1900 is treated as a Leap Year in MS Excel // This affects every date following 28th February 1900 // $excel1900isLeapYear = TRUE; if (($year == 1900) && ($month <= 2)) { $excel1900isLeapYear = FALSE; } $my_excelBaseDate = 2415020; } else { $my_excelBaseDate = 2416481; $excel1900isLeapYear = FALSE; } // Julian base date Adjustment if ($month > 2) { $month -= 3; } else { $month += 9; --$year; } // Calculate the Julian Date, then subtract the Excel base date (JD 2415020 = 31-Dec-1899 Giving Excel Date of 0) $century = substr($year,0,2); $decade = substr($year,2,2); $excelDate = floor((146097 * $century) / 4) + floor((1461 * $decade) / 4) + floor((153 * $month + 2) / 5) + $day + 1721119 - $my_excelBaseDate + $excel1900isLeapYear; $excelTime = (($hours * 3600) + ($minutes * 60) + $seconds) / 86400; return (float) $excelDate + $excelTime; } // function FormattedPHPToExcel() /** * Is a given cell a date/time? * * @param PHPExcel_Cell $pCell * @return boolean */ public static function isDateTime(PHPExcel_Cell $pCell) { return self::isDateTimeFormat( $pCell->getWorksheet()->getStyle( $pCell->getCoordinate() )->getNumberFormat() ); } // function isDateTime() /** * Is a given number format a date/time? * * @param PHPExcel_Style_NumberFormat $pFormat * @return boolean */ public static function isDateTimeFormat(PHPExcel_Style_NumberFormat $pFormat) { return self::isDateTimeFormatCode($pFormat->getFormatCode()); } // function isDateTimeFormat() private static $possibleDateFormatCharacters = 'eymdHs'; /** * Is a given number format code a date/time? * * @param string $pFormatCode * @return boolean */ public static function isDateTimeFormatCode($pFormatCode = '') { // Switch on formatcode switch ($pFormatCode) { // General contains an epoch letter 'e', so we trap for it explicitly here case PHPExcel_Style_NumberFormat::FORMAT_GENERAL: return FALSE; // Explicitly defined date formats case PHPExcel_Style_NumberFormat::FORMAT_DATE_YYYYMMDD: case PHPExcel_Style_NumberFormat::FORMAT_DATE_YYYYMMDD2: case PHPExcel_Style_NumberFormat::FORMAT_DATE_DDMMYYYY: case PHPExcel_Style_NumberFormat::FORMAT_DATE_DMYSLASH: case PHPExcel_Style_NumberFormat::FORMAT_DATE_DMYMINUS: case PHPExcel_Style_NumberFormat::FORMAT_DATE_DMMINUS: case PHPExcel_Style_NumberFormat::FORMAT_DATE_MYMINUS: case PHPExcel_Style_NumberFormat::FORMAT_DATE_DATETIME: case PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME1: case PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME2: case PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME3: case PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME4: case PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME5: case PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME6: case PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME7: case PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME8: case PHPExcel_Style_NumberFormat::FORMAT_DATE_YYYYMMDDSLASH: case PHPExcel_Style_NumberFormat::FORMAT_DATE_XLSX14: case PHPExcel_Style_NumberFormat::FORMAT_DATE_XLSX15: case PHPExcel_Style_NumberFormat::FORMAT_DATE_XLSX16: case PHPExcel_Style_NumberFormat::FORMAT_DATE_XLSX17: case PHPExcel_Style_NumberFormat::FORMAT_DATE_XLSX22: return TRUE; } // Typically number, currency or accounting (or occasionally fraction) formats if ((substr($pFormatCode,0,1) == '_') || (substr($pFormatCode,0,2) == '0 ')) { return FALSE; } // Try checking for any of the date formatting characters that don't appear within square braces if (preg_match('/(^|\])[^\[]*['.self::$possibleDateFormatCharacters.']/i',$pFormatCode)) { // We might also have a format mask containing quoted strings... // we don't want to test for any of our characters within the quoted blocks if (strpos($pFormatCode,'"') !== FALSE) { $segMatcher = FALSE; foreach(explode('"',$pFormatCode) as $subVal) { // Only test in alternate array entries (the non-quoted blocks) if (($segMatcher = !$segMatcher) && (preg_match('/(^|\])[^\[]*['.self::$possibleDateFormatCharacters.']/i',$subVal))) { return TRUE; } } return FALSE; } return TRUE; } // No date... return FALSE; } // function isDateTimeFormatCode() /** * Convert a date/time string to Excel time * * @param string $dateValue Examples: '2009-12-31', '2009-12-31 15:59', '2009-12-31 15:59:10' * @return float|FALSE Excel date/time serial value */ public static function stringToExcel($dateValue = '') { if (strlen($dateValue) < 2) return FALSE; if (!preg_match('/^(\d{1,4}[ \.\/\-][A-Z]{3,9}([ \.\/\-]\d{1,4})?|[A-Z]{3,9}[ \.\/\-]\d{1,4}([ \.\/\-]\d{1,4})?|\d{1,4}[ \.\/\-]\d{1,4}([ \.\/\-]\d{1,4})?)( \d{1,2}:\d{1,2}(:\d{1,2})?)?$/iu', $dateValue)) return FALSE; $dateValueNew = PHPExcel_Calculation_DateTime::DATEVALUE($dateValue); if ($dateValueNew === PHPExcel_Calculation_Functions::VALUE()) { return FALSE; } else { if (strpos($dateValue, ':') !== FALSE) { $timeValue = PHPExcel_Calculation_DateTime::TIMEVALUE($dateValue); if ($timeValue === PHPExcel_Calculation_Functions::VALUE()) { return FALSE; } $dateValueNew += $timeValue; } return $dateValueNew; } } public static function monthStringToNumber($month) { $monthIndex = 1; foreach(self::$_monthNames as $shortMonthName => $longMonthName) { if (($month === $longMonthName) || ($month === $shortMonthName)) { return $monthIndex; } ++$monthIndex; } return $month; } public static function dayStringToNumber($day) { $strippedDayValue = (str_replace(self::$_numberSuffixes,'',$day)); if (is_numeric($strippedDayValue)) { return $strippedDayValue; } return $day; } }
deependhulla/powermail-debian9
files/rootdir/usr/local/src/groupoffice-6.2/groupoffice-6.2-setup-www/go/vendor/PHPExcel/PHPExcel/Shared/Date.php
PHP
gpl-3.0
12,755
// Generated by CoffeeScript 1.5.0 var auth, changeDashboard, createGraph, dashboard, dataPoll, default_graphite_url, default_period, description, generateDataURL, generateEventsURL, generateGraphiteTargets, getTargetColor, graphScaffold, graphite_url, graphs, init, metrics, period, refresh, refreshSummary, refreshTimer, scheme, toggleCss, _avg, _formatBase1024KMGTP, _last, _max, _min, _sum; graphite_url = graphite_url || 'demo'; default_graphite_url = graphite_url; default_period = 1440; if (scheme === void 0) { scheme = 'classic9'; } period = default_period; dashboard = dashboards[0]; metrics = dashboard['metrics']; description = dashboard['description']; refresh = dashboard['refresh']; refreshTimer = null; auth = auth != null ? auth : false; graphs = []; dataPoll = function() { var graph, _i, _len, _results; _results = []; for (_i = 0, _len = graphs.length; _i < _len; _i++) { graph = graphs[_i]; _results.push(graph.refreshGraph(period)); } return _results; }; _sum = function(series) { return _.reduce(series, (function(memo, val) { return memo + val; }), 0); }; _avg = function(series) { return _sum(series) / series.length; }; _max = function(series) { return _.reduce(series, (function(memo, val) { if (memo === null) { return val; } if (val > memo) { return val; } return memo; }), null); }; _min = function(series) { return _.reduce(series, (function(memo, val) { if (memo === null) { return val; } if (val < memo) { return val; } return memo; }), null); }; _last = function(series) { return _.reduce(series, (function(memo, val) { if (val !== null) { return val; } return memo; }), null); }; _formatBase1024KMGTP = function(y, formatter) { var abs_y; if (formatter == null) { formatter = d3.format(".2r"); } abs_y = Math.abs(y); if (abs_y >= 1125899906842624) { return formatter(y / 1125899906842624) + "P"; } else if (abs_y >= 1099511627776) { return formatter(y / 1099511627776) + "T"; } else if (abs_y >= 1073741824) { return formatter(y / 1073741824) + "G"; } else if (abs_y >= 1048576) { return formatter(y / 1048576) + "M"; } else if (abs_y >= 1024) { return formatter(y / 1024) + "K"; } else if (abs_y < 1 && y > 0) { return formatter(y); } else if (abs_y === 0) { return 0; } else { return formatter(y); } }; refreshSummary = function(graph) { var summary_func, y_data, _ref; if (!((_ref = graph.args) != null ? _ref.summary : void 0)) { return; } if (graph.args.summary === "sum") { summary_func = _sum; } if (graph.args.summary === "avg") { summary_func = _avg; } if (graph.args.summary === "min") { summary_func = _min; } if (graph.args.summary === "max") { summary_func = _max; } if (graph.args.summary === "last") { summary_func = _last; } if (typeof graph.args.summary === "function") { summary_func = graph.args.summary; } if (!summary_func) { console.log("unknown summary function " + graph.args.summary); } y_data = _.map(_.flatten(_.pluck(graph.graph.series, 'data')), function(d) { return d.y; }); return $("" + graph.args.anchor + " .graph-summary").html(graph.args.summary_formatter(summary_func(y_data))); }; graphScaffold = function() { var colspan, context, converter, graph_template, i, metric, offset, _i, _len; graph_template = "{{#dashboard_description}}\n <div class=\"well\">{{{dashboard_description}}}</div>\n{{/dashboard_description}}\n{{#metrics}}\n {{#start_row}}\n <div class=\"row-fluid\">\n {{/start_row}}\n <div class=\"{{span}}\" id=\"graph-{{graph_id}}\">\n <h2>{{metric_alias}} <span class=\"pull-right graph-summary\"><span></h2>\n <div class=\"chart\"></div>\n <div class=\"timeline\"></div>\n <p>{{metric_description}}</p>\n <div class=\"legend\"></div>\n </div>\n {{#end_row}}\n </div>\n {{/end_row}}\n{{/metrics}}"; $('#graphs').empty(); context = { metrics: [] }; converter = new Markdown.Converter(); if (description) { context['dashboard_description'] = converter.makeHtml(description); } offset = 0; for (i = _i = 0, _len = metrics.length; _i < _len; i = ++_i) { metric = metrics[i]; colspan = metric.colspan != null ? metric.colspan : 1; context['metrics'].push({ start_row: offset % 3 === 0, end_row: offset % 3 === 2, graph_id: i, span: 'span' + (4 * colspan), metric_alias: metric.alias, metric_description: metric.description }); offset += colspan; } return $('#graphs').append(Mustache.render(graph_template, context)); }; init = function() { var dash, i, metric, refreshInterval, _i, _j, _len, _len1; $('.dropdown-menu').empty(); for (_i = 0, _len = dashboards.length; _i < _len; _i++) { dash = dashboards[_i]; $('.dropdown-menu').append("<li><a href=\"#\">" + dash.name + "</a></li>"); } graphScaffold(); graphs = []; for (i = _j = 0, _len1 = metrics.length; _j < _len1; i = ++_j) { metric = metrics[i]; graphs.push(createGraph("#graph-" + i, metric)); } $('.page-header h1').empty().append(dashboard.name); refreshInterval = refresh || 10000; if (refreshTimer) { clearInterval(refreshTimer); } return refreshTimer = setInterval(dataPoll, refreshInterval); }; getTargetColor = function(targets, target) { var t, _i, _len; if (typeof targets !== 'object') { return; } for (_i = 0, _len = targets.length; _i < _len; _i++) { t = targets[_i]; if (!t.color) { continue; } if (t.target === target || t.alias === target) { return t.color; } } }; generateGraphiteTargets = function(targets) { var graphite_targets, target, _i, _len; if (typeof targets === "string") { return "&target=" + targets; } if (typeof targets === "function") { return "&target=" + (targets()); } graphite_targets = ""; for (_i = 0, _len = targets.length; _i < _len; _i++) { target = targets[_i]; if (typeof target === "string") { graphite_targets += "&target=" + target; } if (typeof target === "function") { graphite_targets += "&target=" + (target()); } if (typeof target === "object") { graphite_targets += "&target=" + ((target != null ? target.target : void 0) || ''); } } return graphite_targets; }; generateDataURL = function(targets, annotator_target, max_data_points) { var data_targets; annotator_target = annotator_target ? "&target=" + annotator_target : ""; data_targets = generateGraphiteTargets(targets); return "" + graphite_url + "/render?from=-" + period + "minutes&" + data_targets + annotator_target + "&maxDataPoints=" + max_data_points + "&format=json&jsonp=?"; }; generateEventsURL = function(event_tags) { var jsonp, tags; tags = event_tags === '*' ? '' : "&tags=" + event_tags; jsonp = window.json_fallback ? '' : "&jsonp=?"; return "" + graphite_url + "/events/get_data?from=-" + period + "minutes" + tags + jsonp; }; createGraph = function(anchor, metric) { var graph, graph_provider, _ref, _ref1; if (graphite_url === 'demo') { graph_provider = Rickshaw.Graph.Demo; } else { graph_provider = Rickshaw.Graph.JSONP.Graphite; } return graph = new graph_provider({ anchor: anchor, targets: metric.target || metric.targets, summary: metric.summary, summary_formatter: metric.summary_formatter || _formatBase1024KMGTP, scheme: metric.scheme || dashboard.scheme || scheme || 'classic9', annotator_target: ((_ref = metric.annotator) != null ? _ref.target : void 0) || metric.annotator, annotator_description: ((_ref1 = metric.annotator) != null ? _ref1.description : void 0) || 'deployment', events: metric.events, element: $("" + anchor + " .chart")[0], width: $("" + anchor + " .chart").width(), height: metric.height || 300, min: metric.min || 0, max: metric.max, null_as: metric.null_as === void 0 ? null : metric.null_as, renderer: metric.renderer || 'area', interpolation: metric.interpolation || 'step-before', unstack: metric.unstack, stroke: metric.stroke === false ? false : true, strokeWidth: metric.stroke_width, dataURL: generateDataURL(metric.target || metric.targets), onRefresh: function(transport) { return refreshSummary(transport); }, onComplete: function(transport) { var detail, hover_formatter, shelving, xAxis, yAxis; graph = transport.graph; xAxis = new Rickshaw.Graph.Axis.Time({ graph: graph }); xAxis.render(); yAxis = new Rickshaw.Graph.Axis.Y({ graph: graph, tickFormat: function(y) { return _formatBase1024KMGTP(y); }, ticksTreatment: 'glow' }); yAxis.render(); hover_formatter = metric.hover_formatter || _formatBase1024KMGTP; detail = new Rickshaw.Graph.HoverDetail({ graph: graph, yFormatter: function(y) { return hover_formatter(y); } }); $("" + anchor + " .legend").empty(); this.legend = new Rickshaw.Graph.Legend({ graph: graph, element: $("" + anchor + " .legend")[0] }); shelving = new Rickshaw.Graph.Behavior.Series.Toggle({ graph: graph, legend: this.legend }); if (metric.annotator || metric.events) { this.annotator = new GiraffeAnnotate({ graph: graph, element: $("" + anchor + " .timeline")[0] }); } return refreshSummary(this); } }); }; Rickshaw.Graph.JSONP.Graphite = Rickshaw.Class.create(Rickshaw.Graph.JSONP, { request: function() { return this.refreshGraph(period); }, refreshGraph: function(period) { var deferred, _this = this; deferred = this.getAjaxData(period); return deferred.done(function(result) { var annotations, el, i, result_data, series, _i, _len; if (result.length <= 0) { return; } result_data = _.filter(result, function(el) { var _ref; return el.target !== ((_ref = _this.args.annotator_target) != null ? _ref.replace(/["']/g, '') : void 0); }); result_data = _this.preProcess(result_data); if (!_this.graph) { _this.success(_this.parseGraphiteData(result_data, _this.args.null_as)); } series = _this.parseGraphiteData(result_data, _this.args.null_as); if (_this.args.annotator_target) { annotations = _this.parseGraphiteData(_.filter(result, function(el) { return el.target === _this.args.annotator_target.replace(/["']/g, ''); }), _this.args.null_as); } for (i = _i = 0, _len = series.length; _i < _len; i = ++_i) { el = series[i]; _this.graph.series[i].data = el.data; _this.addTotals(i); } _this.graph.renderer.unstack = _this.args.unstack; _this.graph.render(); if (_this.args.events) { deferred = _this.getEvents(period); deferred.done(function(result) { return _this.addEventAnnotations(result); }); } _this.addAnnotations(annotations, _this.args.annotator_description); return _this.args.onRefresh(_this); }); }, addTotals: function(i) { var avg, label, max, min, series_data, sum; label = $(this.legend.lines[i].element).find('span.label').text(); $(this.legend.lines[i].element).find('span.totals').remove(); series_data = _.map(this.legend.lines[i].series.data, function(d) { return d.y; }); sum = _formatBase1024KMGTP(_sum(series_data)); max = _formatBase1024KMGTP(_max(series_data)); min = _formatBase1024KMGTP(_min(series_data)); avg = _formatBase1024KMGTP(_avg(series_data)); return $(this.legend.lines[i].element).append("<span class='totals pull-right'> &Sigma;: " + sum + " <i class='icon-caret-down'></i>: " + min + " <i class='icon-caret-up'></i>: " + max + " <i class='icon-sort'></i>: " + avg + "</span>"); }, preProcess: function(result) { var item, _i, _len; for (_i = 0, _len = result.length; _i < _len; _i++) { item = result[_i]; if (item.datapoints.length === 1) { item.datapoints[0][1] = 0; if (this.args.unstack) { item.datapoints.push([0, 1]); } else { item.datapoints.push([item.datapoints[0][0], 1]); } } } return result; }, parseGraphiteData: function(d, null_as) { var palette, rev_xy, targets; if (null_as == null) { null_as = null; } rev_xy = function(datapoints) { return _.map(datapoints, function(point) { return { 'x': point[1], 'y': point[0] !== null ? point[0] : null_as }; }); }; palette = new Rickshaw.Color.Palette({ scheme: this.args.scheme }); targets = this.args.target || this.args.targets; d = _.map(d, function(el) { var color, _ref; if ((_ref = typeof targets) === "string" || _ref === "function") { color = palette.color(); } else { color = getTargetColor(targets, el.target) || palette.color(); } return { "color": color, "name": el.target, "data": rev_xy(el.datapoints) }; }); Rickshaw.Series.zeroFill(d); return d; }, addEventAnnotations: function(events_json) { var active_annotation, event, _i, _len, _ref, _ref1; if (!events_json) { return; } this.annotator || (this.annotator = new GiraffeAnnotate({ graph: this.graph, element: $("" + this.args.anchor + " .timeline")[0] })); this.annotator.data = {}; $(this.annotator.elements.timeline).empty(); active_annotation = $(this.annotator.elements.timeline).parent().find('.annotation_line.active').size() > 0; if ((_ref = $(this.annotator.elements.timeline).parent()) != null) { _ref.find('.annotation_line').remove(); } for (_i = 0, _len = events_json.length; _i < _len; _i++) { event = events_json[_i]; this.annotator.add(event.when, "" + event.what + " " + (event.data || '')); } this.annotator.update(); if (active_annotation) { return (_ref1 = $(this.annotator.elements.timeline).parent()) != null ? _ref1.find('.annotation_line').addClass('active') : void 0; } }, addAnnotations: function(annotations, description) { var annotation_timestamps, _ref; if (!annotations) { return; } annotation_timestamps = _((_ref = annotations[0]) != null ? _ref.data : void 0).filter(function(el) { return el.y !== 0 && el.y !== null; }); return this.addEventAnnotations(_.map(annotation_timestamps, function(a) { return { when: a.x, what: description }; })); }, getEvents: function(period) { var deferred, _this = this; this.period = period; return deferred = $.ajax({ dataType: 'json', url: generateEventsURL(this.args.events), error: function(xhr, textStatus, errorThrown) { if (textStatus === 'parsererror' && /was not called/.test(errorThrown.message)) { window.json_fallback = true; return _this.refreshGraph(period); } else { return console.log("error loading eventsURL: " + generateEventsURL(_this.args.events)); } } }); }, getAjaxData: function(period) { var deferred; this.period = period; return deferred = $.ajax({ dataType: 'json', url: generateDataURL(this.args.targets, this.args.annotator_target, this.args.width), error: this.error.bind(this) }); } }); Rickshaw.Graph.Demo = Rickshaw.Class.create(Rickshaw.Graph.JSONP.Graphite, { success: function(data) { var i, palette, _i; palette = new Rickshaw.Color.Palette({ scheme: this.args.scheme }); this.seriesData = [[], [], [], [], [], [], [], [], []]; this.random = new Rickshaw.Fixtures.RandomData(period / 60 + 10); for (i = _i = 0; _i <= 60; i = ++_i) { this.random.addData(this.seriesData); } this.graph = new Rickshaw.Graph({ element: this.args.element, width: this.args.width, height: this.args.height, min: this.args.min, max: this.args.max, renderer: this.args.renderer, interpolation: this.args.interpolation, stroke: this.args.stroke, strokeWidth: this.args.strokeWidth, series: [ { color: palette.color(), data: this.seriesData[0], name: 'Moscow' }, { color: palette.color(), data: this.seriesData[1], name: 'Shanghai' }, { color: palette.color(), data: this.seriesData[2], name: 'Amsterdam' }, { color: palette.color(), data: this.seriesData[3], name: 'Paris' }, { color: palette.color(), data: this.seriesData[4], name: 'Tokyo' }, { color: palette.color(), data: this.seriesData[5], name: 'London' }, { color: palette.color(), data: this.seriesData[6], name: 'New York' } ] }); this.graph.renderer.unstack = this.args.unstack; this.graph.render(); return this.onComplete(this); }, refreshGraph: function(period) { var i, _i, _ref, _results; if (!this.graph) { return this.success(); } else { this.random.addData(this.seriesData); this.random.addData(this.seriesData); _.each(this.seriesData, function(d) { return d.shift(); }); this.args.onRefresh(this); this.graph.render(); _results = []; for (i = _i = 0, _ref = this.graph.series.length; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) { _results.push(this.addTotals(i)); } return _results; } } }); /* # Events and interaction */ $('.dropdown-menu').on('click', 'a', function() { changeDashboard($(this).text()); $('.dropdown').removeClass('open'); return false; }); changeDashboard = function(dash_name) { dashboard = _.where(dashboards, { name: dash_name })[0] || dashboards[0]; graphite_url = dashboard['graphite_url'] || default_graphite_url; description = dashboard['description']; metrics = dashboard['metrics']; refresh = dashboard['refresh']; period || (period = default_period); init(); return $.bbq.pushState({ dashboard: dashboard.name }); }; $('.timepanel').on('click', 'a.range', function() { var dash, timeFrame, _ref; if (graphite_url === 'demo') { changeDashboard(dashboard.name); } period = $(this).attr('data-timeframe') || default_period; dataPoll(); timeFrame = $(this).attr('href').replace(/^#/, ''); dash = (_ref = $.bbq.getState()) != null ? _ref.dashboard : void 0; $.bbq.pushState({ timeFrame: timeFrame, dashboard: dash || dashboard.name }); $(this).parent('.btn-group').find('a').removeClass('active'); $(this).addClass('active'); return false; }); toggleCss = function(css_selector) { if ($.rule(css_selector).text().match('display: ?none')) { return $.rule(css_selector, 'style').remove(); } else { return $.rule("" + css_selector + " {display:none;}").appendTo('style'); } }; $('#legend-toggle').on('click', function() { $(this).toggleClass('active'); $('.legend').toggle(); return false; }); $('#axis-toggle').on('click', function() { $(this).toggleClass('active'); toggleCss('.y_grid'); toggleCss('.y_ticks'); toggleCss('.x_tick'); return false; }); $('#x-label-toggle').on('click', function() { toggleCss('.rickshaw_graph .detail .x_label'); $(this).toggleClass('active'); return false; }); $('#x-item-toggle').on('click', function() { toggleCss('.rickshaw_graph .detail .item.active'); $(this).toggleClass('active'); return false; }); $(window).bind('hashchange', function(e) { var dash, timeFrame, _ref, _ref1; timeFrame = ((_ref = e.getState()) != null ? _ref.timeFrame : void 0) || $(".timepanel a.range[data-timeframe='" + default_period + "']")[0].text || "1d"; dash = (_ref1 = e.getState()) != null ? _ref1.dashboard : void 0; if (dash !== dashboard.name) { changeDashboard(dash); } return $('.timepanel a.range[href="#' + timeFrame + '"]').click(); }); $(function() { $(window).trigger('hashchange'); return init(); });
Stub-O-Matic-BA/stubo-app
stubo/static/giraffe/js/giraffe.js
JavaScript
gpl-3.0
20,491
/*==LICENSE==* CyanWorlds.com Engine - MMOG client, server and tools Copyright (C) 2011 Cyan Worlds, Inc. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Additional permissions under GNU GPL version 3 section 7 If you modify this Program, or any covered work, by linking or combining it with any of RAD Game Tools Bink SDK, Autodesk 3ds Max SDK, NVIDIA PhysX SDK, Microsoft DirectX SDK, OpenSSL library, Independent JPEG Group JPEG library, Microsoft Windows Media SDK, or Apple QuickTime SDK (or a modified version of those libraries), containing parts covered by the terms of the Bink SDK EULA, 3ds Max EULA, PhysX SDK EULA, DirectX SDK EULA, OpenSSL and SSLeay licenses, IJG JPEG Library README, Windows Media SDK EULA, or QuickTime SDK EULA, the licensors of this Program grant you additional permission to convey the resulting work. Corresponding Source for a non-source form of such a combination shall include the source code for the parts of OpenSSL and IJG JPEG Library used as well as that of the covered work. You can contact Cyan Worlds, Inc. by email legal@cyan.com or by snail mail at: Cyan Worlds, Inc. 14617 N Newport Hwy Mead, WA 99021 *==LICENSE==*/ #include "plServerReplyMsg.h" #include "hsStream.h" #include "hsBitVector.h" void plServerReplyMsg::Read(hsStream* stream, hsResMgr* mgr) { plMessage::IMsgRead(stream, mgr); stream->ReadLE(&fType); } void plServerReplyMsg::Write(hsStream* stream, hsResMgr* mgr) { plMessage::IMsgWrite(stream, mgr); stream->WriteLE(fType); } enum ServerReplyFlags { kServerReplyType, }; void plServerReplyMsg::ReadVersion(hsStream* s, hsResMgr* mgr) { plMessage::IMsgReadVersion(s, mgr); hsBitVector contentFlags; contentFlags.Read(s); if (contentFlags.IsBitSet(kServerReplyType)) s->ReadLE(&fType); } void plServerReplyMsg::WriteVersion(hsStream* s, hsResMgr* mgr) { plMessage::IMsgWriteVersion(s, mgr); hsBitVector contentFlags; contentFlags.SetBit(kServerReplyType); contentFlags.Write(s); // kServerReplyType s->WriteLE(fType); }
cwalther/Plasma-nobink-test
Sources/Plasma/NucleusLib/pnMessage/plServerReplyMsg.cpp
C++
gpl-3.0
2,654
package org.whispersystems.signalservice.api.storage; import org.whispersystems.libsignal.util.guava.Preconditions; import org.whispersystems.signalservice.internal.storage.protos.ManifestRecord; import java.util.Arrays; import java.util.Objects; public class StorageId { private final int type; private final byte[] raw; public static StorageId forContact(byte[] raw) { return new StorageId(ManifestRecord.Identifier.Type.CONTACT_VALUE, Preconditions.checkNotNull(raw)); } public static StorageId forGroupV1(byte[] raw) { return new StorageId(ManifestRecord.Identifier.Type.GROUPV1_VALUE, Preconditions.checkNotNull(raw)); } public static StorageId forGroupV2(byte[] raw) { return new StorageId(ManifestRecord.Identifier.Type.GROUPV2_VALUE, Preconditions.checkNotNull(raw)); } public static StorageId forAccount(byte[] raw) { return new StorageId(ManifestRecord.Identifier.Type.ACCOUNT_VALUE, Preconditions.checkNotNull(raw)); } public static StorageId forType(byte[] raw, int type) { return new StorageId(type, raw); } public boolean isUnknown() { return !isKnownType(type); } private StorageId(int type, byte[] raw) { this.type = type; this.raw = raw; } public int getType() { return type; } public byte[] getRaw() { return raw; } public StorageId withNewBytes(byte[] key) { return new StorageId(type, key); } public static boolean isKnownType(int val) { for (ManifestRecord.Identifier.Type type : ManifestRecord.Identifier.Type.values()) { if (type != ManifestRecord.Identifier.Type.UNRECOGNIZED && type.getNumber() == val) { return true; } } return false; } public static int largestKnownType() { int max = 0; for (ManifestRecord.Identifier.Type type : ManifestRecord.Identifier.Type.values()) { if (type != ManifestRecord.Identifier.Type.UNRECOGNIZED) { max = Math.max(type.getNumber(), max); } } return max; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; StorageId storageId = (StorageId) o; return type == storageId.type && Arrays.equals(raw, storageId.raw); } @Override public int hashCode() { int result = Objects.hash(type); result = 31 * result + Arrays.hashCode(raw); return result; } }
Turasa/libsignal-service-java
service/src/main/java/org/whispersystems/signalservice/api/storage/StorageId.java
Java
gpl-3.0
2,421
// -*- Mode: Go; indent-tabs-mode: t -*- /* * Copyright (C) 2020 Canonical Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 3 as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package kernel import ( "fmt" "path/filepath" "strings" "github.com/snapcore/snapd/osutil" ) func validateAssetsContent(kernelRoot string, info *Info) error { // bare structure content is checked to exist during layout // make sure that filesystem content source paths exist as well for name, as := range info.Assets { for _, assetContent := range as.Content { c := assetContent // a single trailing / is allowed and indicates a directory isDir := strings.HasSuffix(c, "/") if isDir { c = strings.TrimSuffix(c, "/") } if filepath.Clean(c) != c || strings.Contains(c, "..") || c == "/" { return fmt.Errorf("asset %q: invalid content %q", name, assetContent) } realSource := filepath.Join(kernelRoot, c) if !osutil.FileExists(realSource) { return fmt.Errorf("asset %q: content %q source path does not exist", name, assetContent) } if isDir { // expecting a directory if !osutil.IsDirectory(realSource + "/") { return fmt.Errorf("asset %q: content %q is not a directory", name, assetContent) } } } } return nil } // Validate checks whether the given directory contains valid kernel snap // metadata and a matching content. func Validate(kernelRoot string) error { info, err := ReadInfo(kernelRoot) if err != nil { return fmt.Errorf("invalid kernel metadata: %v", err) } if err := validateAssetsContent(kernelRoot, info); err != nil { return err } return nil }
mvo5/snappy
kernel/validate.go
GO
gpl-3.0
2,124
<?php /* * @copyright 2015 Mautic Contributors. All rights reserved * @author Mautic * * @link http://mautic.org * * @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html */ $isPrototype = ($form->vars['name'] == '__name__'); $filterType = $form['field']->vars['value']; $inGroup = $form->vars['data']['glue'] === 'and'; $object = (isset($form->vars['data']['object'])) ? $form->vars['data']['object'] : 'lead'; $class = (isset($form->vars['data']['object']) && $form->vars['data']['object'] == 'company') ? 'fa-building' : 'fa-user'; ?> <div class="panel<?php echo ($inGroup && $first === false) ? ' in-group' : ''; ?>"> <div class="panel-heading <?php if (!$isPrototype && $form->vars['name'] === '0') { echo ' hide'; } ?>"> <div class="panel-glue col-sm-2 pl-0 "> <?php echo $view['form']->widget($form['glue']); ?> </div> </div> <div class="panel-body"> <div class="col-xs-6 col-sm-3 field-name"> <i class="object-icon fa <?php echo $class; ?>" aria-hidden="true"></i> <span><?php echo ($isPrototype) ? '__label__' : $fields[$object][$filterType]['label']; ?></span> </div> <div class="col-xs-6 col-sm-3 padding-none"> <?php echo $view['form']->widget($form['operator']); ?> </div> <?php $hasErrors = count($form['filter']->vars['errors']) || count($form['display']->vars['errors']); ?> <div class="col-xs-10 col-sm-5 padding-none<?php if ($hasErrors) { echo ' has-error'; } ?>"> <?php echo $view['form']->widget($form['filter']); ?> <?php echo $view['form']->errors($form['filter']); ?> <?php echo $view['form']->widget($form['display']); ?> <?php echo $view['form']->errors($form['display']); ?> </div> <div class="col-xs-2 col-sm-1"> <a href="javascript: void(0);" class="remove-selected btn btn-default text-danger pull-right"><i class="fa fa-trash-o"></i></a> </div> <?php echo $view['form']->widget($form['field']); ?> <?php echo $view['form']->widget($form['type']); ?> <?php echo $view['form']->widget($form['object']); ?> </div> </div>
PatchRanger/mautic
app/bundles/LeadBundle/Views/FormTheme/Filter/_leadlist_filters_entry_widget.html.php
PHP
gpl-3.0
2,233
package org.limewire.collection; import java.util.Iterator; /** * A convenience class to aid in developing iterators that cannot be modified. */ public abstract class UnmodifiableIterator<E> implements Iterator<E> { /** Throws UnsupportedOperationException */ public final void remove() { throw new UnsupportedOperationException(); } }
alejandroarturom/frostwire-desktop
src/org/limewire/collection/UnmodifiableIterator.java
Java
gpl-3.0
355
//===-- XCoreISelDAGToDAG.cpp - A dag to dag inst selector for XCore ------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines an instruction selector for the XCore target. // //===----------------------------------------------------------------------===// #include "XCore.h" #include "XCoreTargetMachine.h" #include "llvm/CodeGen/MachineFrameInfo.h" #include "llvm/CodeGen/MachineFunction.h" #include "llvm/CodeGen/MachineInstrBuilder.h" #include "llvm/CodeGen/MachineRegisterInfo.h" #include "llvm/CodeGen/SelectionDAG.h" #include "llvm/CodeGen/SelectionDAGISel.h" #include "llvm/IR/CallingConv.h" #include "llvm/IR/Constants.h" #include "llvm/IR/DerivedTypes.h" #include "llvm/IR/Function.h" #include "llvm/IR/Intrinsics.h" #include "llvm/IR/LLVMContext.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/Debug.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Target/TargetLowering.h" using namespace llvm; /// XCoreDAGToDAGISel - XCore specific code to select XCore machine /// instructions for SelectionDAG operations. /// namespace { class XCoreDAGToDAGISel : public SelectionDAGISel { public: XCoreDAGToDAGISel(XCoreTargetMachine &TM, CodeGenOpt::Level OptLevel) : SelectionDAGISel(TM, OptLevel) {} SDNode *Select(SDNode *N) override; SDNode *SelectBRIND(SDNode *N); /// getI32Imm - Return a target constant with the specified value, of type /// i32. inline SDValue getI32Imm(unsigned Imm, SDLoc dl) { return CurDAG->getTargetConstant(Imm, dl, MVT::i32); } inline bool immMskBitp(SDNode *inN) const { ConstantSDNode *N = cast<ConstantSDNode>(inN); uint32_t value = (uint32_t)N->getZExtValue(); if (!isMask_32(value)) { return false; } int msksize = 32 - countLeadingZeros(value); return (msksize >= 1 && msksize <= 8) || msksize == 16 || msksize == 24 || msksize == 32; } // Complex Pattern Selectors. bool SelectADDRspii(SDValue Addr, SDValue &Base, SDValue &Offset); bool SelectInlineAsmMemoryOperand(const SDValue &Op, unsigned ConstraintID, std::vector<SDValue> &OutOps) override; const char *getPassName() const override { return "XCore DAG->DAG Pattern Instruction Selection"; } // Include the pieces autogenerated from the target description. #include "XCoreGenDAGISel.inc" }; } // end anonymous namespace /// createXCoreISelDag - This pass converts a legalized DAG into a /// XCore-specific DAG, ready for instruction scheduling. /// FunctionPass *llvm::createXCoreISelDag(XCoreTargetMachine &TM, CodeGenOpt::Level OptLevel) { return new XCoreDAGToDAGISel(TM, OptLevel); } bool XCoreDAGToDAGISel::SelectADDRspii(SDValue Addr, SDValue &Base, SDValue &Offset) { FrameIndexSDNode *FIN = nullptr; if ((FIN = dyn_cast<FrameIndexSDNode>(Addr))) { Base = CurDAG->getTargetFrameIndex(FIN->getIndex(), MVT::i32); Offset = CurDAG->getTargetConstant(0, SDLoc(Addr), MVT::i32); return true; } if (Addr.getOpcode() == ISD::ADD) { ConstantSDNode *CN = nullptr; if ((FIN = dyn_cast<FrameIndexSDNode>(Addr.getOperand(0))) && (CN = dyn_cast<ConstantSDNode>(Addr.getOperand(1))) && (CN->getSExtValue() % 4 == 0 && CN->getSExtValue() >= 0)) { // Constant positive word offset from frame index Base = CurDAG->getTargetFrameIndex(FIN->getIndex(), MVT::i32); Offset = CurDAG->getTargetConstant(CN->getSExtValue(), SDLoc(Addr), MVT::i32); return true; } } return false; } bool XCoreDAGToDAGISel:: SelectInlineAsmMemoryOperand(const SDValue &Op, unsigned ConstraintID, std::vector<SDValue> &OutOps) { SDValue Reg; switch (ConstraintID) { default: return true; case InlineAsm::Constraint_m: // Memory. switch (Op.getOpcode()) { default: return true; case XCoreISD::CPRelativeWrapper: Reg = CurDAG->getRegister(XCore::CP, MVT::i32); break; case XCoreISD::DPRelativeWrapper: Reg = CurDAG->getRegister(XCore::DP, MVT::i32); break; } } OutOps.push_back(Reg); OutOps.push_back(Op.getOperand(0)); return false; } SDNode *XCoreDAGToDAGISel::Select(SDNode *N) { SDLoc dl(N); switch (N->getOpcode()) { default: break; case ISD::Constant: { uint64_t Val = cast<ConstantSDNode>(N)->getZExtValue(); if (immMskBitp(N)) { // Transformation function: get the size of a mask // Look for the first non-zero bit SDValue MskSize = getI32Imm(32 - countLeadingZeros((uint32_t)Val), dl); return CurDAG->getMachineNode(XCore::MKMSK_rus, dl, MVT::i32, MskSize); } else if (!isUInt<16>(Val)) { SDValue CPIdx = CurDAG->getTargetConstantPool( ConstantInt::get(Type::getInt32Ty(*CurDAG->getContext()), Val), getTargetLowering()->getPointerTy(CurDAG->getDataLayout())); SDNode *node = CurDAG->getMachineNode(XCore::LDWCP_lru6, dl, MVT::i32, MVT::Other, CPIdx, CurDAG->getEntryNode()); MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1); MemOp[0] = MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF), MachineMemOperand::MOLoad, 4, 4); cast<MachineSDNode>(node)->setMemRefs(MemOp, MemOp + 1); return node; } break; } case XCoreISD::LADD: { SDValue Ops[] = { N->getOperand(0), N->getOperand(1), N->getOperand(2) }; return CurDAG->getMachineNode(XCore::LADD_l5r, dl, MVT::i32, MVT::i32, Ops); } case XCoreISD::LSUB: { SDValue Ops[] = { N->getOperand(0), N->getOperand(1), N->getOperand(2) }; return CurDAG->getMachineNode(XCore::LSUB_l5r, dl, MVT::i32, MVT::i32, Ops); } case XCoreISD::MACCU: { SDValue Ops[] = { N->getOperand(0), N->getOperand(1), N->getOperand(2), N->getOperand(3) }; return CurDAG->getMachineNode(XCore::MACCU_l4r, dl, MVT::i32, MVT::i32, Ops); } case XCoreISD::MACCS: { SDValue Ops[] = { N->getOperand(0), N->getOperand(1), N->getOperand(2), N->getOperand(3) }; return CurDAG->getMachineNode(XCore::MACCS_l4r, dl, MVT::i32, MVT::i32, Ops); } case XCoreISD::LMUL: { SDValue Ops[] = { N->getOperand(0), N->getOperand(1), N->getOperand(2), N->getOperand(3) }; return CurDAG->getMachineNode(XCore::LMUL_l6r, dl, MVT::i32, MVT::i32, Ops); } case XCoreISD::CRC8: { SDValue Ops[] = { N->getOperand(0), N->getOperand(1), N->getOperand(2) }; return CurDAG->getMachineNode(XCore::CRC8_l4r, dl, MVT::i32, MVT::i32, Ops); } case ISD::BRIND: if (SDNode *ResNode = SelectBRIND(N)) return ResNode; break; // Other cases are autogenerated. } return SelectCode(N); } /// Given a chain return a new chain where any appearance of Old is replaced /// by New. There must be at most one instruction between Old and Chain and /// this instruction must be a TokenFactor. Returns an empty SDValue if /// these conditions don't hold. static SDValue replaceInChain(SelectionDAG *CurDAG, SDValue Chain, SDValue Old, SDValue New) { if (Chain == Old) return New; if (Chain->getOpcode() != ISD::TokenFactor) return SDValue(); SmallVector<SDValue, 8> Ops; bool found = false; for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i) { if (Chain->getOperand(i) == Old) { Ops.push_back(New); found = true; } else { Ops.push_back(Chain->getOperand(i)); } } if (!found) return SDValue(); return CurDAG->getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, Ops); } SDNode *XCoreDAGToDAGISel::SelectBRIND(SDNode *N) { SDLoc dl(N); // (brind (int_xcore_checkevent (addr))) SDValue Chain = N->getOperand(0); SDValue Addr = N->getOperand(1); if (Addr->getOpcode() != ISD::INTRINSIC_W_CHAIN) return nullptr; unsigned IntNo = cast<ConstantSDNode>(Addr->getOperand(1))->getZExtValue(); if (IntNo != Intrinsic::xcore_checkevent) return nullptr; SDValue nextAddr = Addr->getOperand(2); SDValue CheckEventChainOut(Addr.getNode(), 1); if (!CheckEventChainOut.use_empty()) { // If the chain out of the checkevent intrinsic is an operand of the // indirect branch or used in a TokenFactor which is the operand of the // indirect branch then build a new chain which uses the chain coming into // the checkevent intrinsic instead. SDValue CheckEventChainIn = Addr->getOperand(0); SDValue NewChain = replaceInChain(CurDAG, Chain, CheckEventChainOut, CheckEventChainIn); if (!NewChain.getNode()) return nullptr; Chain = NewChain; } // Enable events on the thread using setsr 1 and then disable them immediately // after with clrsr 1. If any resources owned by the thread are ready an event // will be taken. If no resource is ready we branch to the address which was // the operand to the checkevent intrinsic. SDValue constOne = getI32Imm(1, dl); SDValue Glue = SDValue(CurDAG->getMachineNode(XCore::SETSR_branch_u6, dl, MVT::Glue, constOne, Chain), 0); Glue = SDValue(CurDAG->getMachineNode(XCore::CLRSR_branch_u6, dl, MVT::Glue, constOne, Glue), 0); if (nextAddr->getOpcode() == XCoreISD::PCRelativeWrapper && nextAddr->getOperand(0)->getOpcode() == ISD::TargetBlockAddress) { return CurDAG->SelectNodeTo(N, XCore::BRFU_lu6, MVT::Other, nextAddr->getOperand(0), Glue); } return CurDAG->SelectNodeTo(N, XCore::BAU_1r, MVT::Other, nextAddr, Glue); }
vinutah/apps
tools/llvm/llvm_39/opt/lib/Target/XCore/XCoreISelDAGToDAG.cpp
C++
gpl-3.0
10,390
/* Copyright (C) 2010,2011,2012,2013,2014 The ESPResSo project Copyright (C) 2002,2003,2004,2005,2006,2007,2008,2009,2010 Max-Planck-Institute for Polymer Research, Theory Group, This file is part of ESPResSo. ESPResSo is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. ESPResSo is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** \file lb-boundaries.cpp * * Boundary conditions for Lattice Boltzmann fluid dynamics. * Header file for \ref lb-boundaries.hpp. * */ #include "utils.hpp" #include "constraint.hpp" #include "lb-boundaries.hpp" #include "lbgpu.hpp" #include "lb.hpp" #include "electrokinetics.hpp" #include "electrokinetics_pdb_parse.hpp" #include "interaction_data.hpp" #include "communication.hpp" #if defined (LB_BOUNDARIES) || defined (LB_BOUNDARIES_GPU) int n_lb_boundaries = 0; LB_Boundary *lb_boundaries = NULL; void lbboundary_mindist_position(double pos[3], double* mindist, double distvec[3], int* no) { double vec[3] = {1e100, 1e100, 1e100}; double dist=1e100; *mindist = 1e100; int n; Particle* p1=0; for(n=0;n<n_lb_boundaries;n++) { switch(lb_boundaries[n].type) { case LB_BOUNDARY_WAL: calculate_wall_dist(p1, pos, (Particle*) NULL, &lb_boundaries[n].c.wal, &dist, vec); break; case LB_BOUNDARY_SPH: calculate_sphere_dist(p1, pos, (Particle*) NULL, &lb_boundaries[n].c.sph, &dist, vec); break; case LB_BOUNDARY_CYL: calculate_cylinder_dist(p1, pos, (Particle*) NULL, &lb_boundaries[n].c.cyl, &dist, vec); break; case LB_BOUNDARY_RHOMBOID: calculate_rhomboid_dist(p1, pos, (Particle*) NULL, &lb_boundaries[n].c.rhomboid, &dist, vec); break; case LB_BOUNDARY_POR: calculate_pore_dist(p1, pos, (Particle*) NULL, &lb_boundaries[n].c.pore, &dist, vec); break; case LB_BOUNDARY_STOMATOCYTE: calculate_stomatocyte_dist(p1, pos, (Particle*) NULL, &lb_boundaries[n].c.stomatocyte, &dist, vec); break; case LB_BOUNDARY_HOLLOW_CONE: calculate_hollow_cone_dist(p1, pos, (Particle*) NULL, &lb_boundaries[n].c.hollow_cone, &dist, vec); break; case CONSTRAINT_SPHEROCYLINDER: calculate_spherocylinder_dist(p1, pos, (Particle*) NULL, &lb_boundaries[n].c.spherocyl, &dist, vec); break; case LB_BOUNDARY_VOXEL: // needed for fluid calculation ??? calculate_voxel_dist(p1, pos, (Particle*) NULL, &lb_boundaries[n].c.voxel, &dist, vec); break; } if (dist<*mindist || n == 0) { *no=n; *mindist=dist; distvec[0] = vec[0]; distvec[1] = vec[1]; distvec[2] = vec[2]; } } } /** Initialize boundary conditions for all constraints in the system. */ void lb_init_boundaries() { int n, x, y, z; //char *errtxt; double pos[3], dist, dist_tmp=0.0, dist_vec[3]; if (lattice_switch & LATTICE_LB_GPU) { #if defined (LB_GPU) && defined (LB_BOUNDARIES_GPU) int number_of_boundnodes = 0; int *host_boundary_node_list= (int*)Utils::malloc(sizeof(int)); int *host_boundary_index_list= (int*)Utils::malloc(sizeof(int)); size_t size_of_index; int boundary_number = -1; // the number the boundary will actually belong to. #ifdef EK_BOUNDARIES ekfloat *host_wallcharge_species_density = NULL; float node_wallcharge = 0.0f; int wallcharge_species = -1, charged_boundaries = 0; int node_charged = 0; for(n = 0; n < int(n_lb_boundaries); n++) lb_boundaries[n].net_charge = 0.0; if (ek_initialized) { host_wallcharge_species_density = (ekfloat*) Utils::malloc(ek_parameters.number_of_nodes * sizeof(ekfloat)); for(n = 0; n < int(n_lb_boundaries); n++) { if(lb_boundaries[n].charge_density != 0.0) { charged_boundaries = 1; break; } } if (pdb_charge_lattice) { charged_boundaries = 1; } for(n = 0; n < int(ek_parameters.number_of_species); n++) if(ek_parameters.valency[n] != 0.0) { wallcharge_species = n; break; } if(wallcharge_species == -1 && charged_boundaries) { ostringstream msg; msg <<"no charged species available to create wall charge\n"; runtimeError(msg); } } #endif for(z=0; z<int(lbpar_gpu.dim_z); z++) { for(y=0; y<int(lbpar_gpu.dim_y); y++) { for (x=0; x<int(lbpar_gpu.dim_x); x++) { pos[0] = (x+0.5)*lbpar_gpu.agrid; pos[1] = (y+0.5)*lbpar_gpu.agrid; pos[2] = (z+0.5)*lbpar_gpu.agrid; dist = 1e99; #ifdef EK_BOUNDARIES if (ek_initialized) { host_wallcharge_species_density[ek_parameters.dim_y*ek_parameters.dim_x*z + ek_parameters.dim_x*y + x] = 0.0f; node_charged = 0; node_wallcharge = 0.0f; } #endif for (n=0; n < n_lb_boundaries; n++) { switch (lb_boundaries[n].type) { case LB_BOUNDARY_WAL: calculate_wall_dist((Particle*) NULL, pos, (Particle*) NULL, &lb_boundaries[n].c.wal, &dist_tmp, dist_vec); break; case LB_BOUNDARY_SPH: calculate_sphere_dist((Particle*) NULL, pos, (Particle*) NULL, &lb_boundaries[n].c.sph, &dist_tmp, dist_vec); break; case LB_BOUNDARY_CYL: calculate_cylinder_dist((Particle*) NULL, pos, (Particle*) NULL, &lb_boundaries[n].c.cyl, &dist_tmp, dist_vec); break; case LB_BOUNDARY_RHOMBOID: calculate_rhomboid_dist((Particle*) NULL, pos, (Particle*) NULL, &lb_boundaries[n].c.rhomboid, &dist_tmp, dist_vec); break; case LB_BOUNDARY_POR: calculate_pore_dist((Particle*) NULL, pos, (Particle*) NULL, &lb_boundaries[n].c.pore, &dist_tmp, dist_vec); break; case LB_BOUNDARY_STOMATOCYTE: calculate_stomatocyte_dist((Particle*) NULL, pos, (Particle*) NULL, &lb_boundaries[n].c.stomatocyte, &dist_tmp, dist_vec); break; case LB_BOUNDARY_HOLLOW_CONE: calculate_hollow_cone_dist((Particle*) NULL, pos, (Particle*) NULL, &lb_boundaries[n].c.hollow_cone, &dist_tmp, dist_vec); break; case LB_BOUNDARY_SPHEROCYLINDER: calculate_spherocylinder_dist((Particle*) NULL, pos, (Particle*) NULL, &lb_boundaries[n].c.spherocyl, &dist_tmp, dist_vec); break; case LB_BOUNDARY_VOXEL: // voxel data do not need dist //calculate_voxel_dist((Particle*) NULL, pos, (Particle*) NULL, &lb_boundaries[n].c.voxel, &dist_tmp, dist_vec); dist_tmp=1e99; break; default: ostringstream msg; msg <<"lbboundary type "<< lb_boundaries[n].type << " not implemented in lb_init_boundaries()\n"; runtimeError(msg); } if (dist > dist_tmp || n == 0) { dist = dist_tmp; boundary_number = n; } #ifdef EK_BOUNDARIES if (ek_initialized) { if(dist_tmp <= 0 && lb_boundaries[n].charge_density != 0.0f) { node_charged = 1; node_wallcharge += lb_boundaries[n].charge_density * ek_parameters.agrid*ek_parameters.agrid*ek_parameters.agrid; lb_boundaries[n].net_charge += lb_boundaries[n].charge_density * ek_parameters.agrid*ek_parameters.agrid*ek_parameters.agrid; } } #endif } #ifdef EK_BOUNDARIES if(pdb_boundary_lattice && pdb_boundary_lattice[ek_parameters.dim_y*ek_parameters.dim_x*z + ek_parameters.dim_x*y + x]) { dist = -1; boundary_number = n_lb_boundaries; // Makes sure that boundary_number is not used by a constraint } #endif if (dist <= 0 && boundary_number >= 0 && (n_lb_boundaries > 0 || pdb_boundary_lattice)) { size_of_index = (number_of_boundnodes+1)*sizeof(int); host_boundary_node_list = (int *) Utils::realloc(host_boundary_node_list, size_of_index); host_boundary_index_list = (int *) Utils::realloc(host_boundary_index_list, size_of_index); host_boundary_node_list[number_of_boundnodes] = x + lbpar_gpu.dim_x*y + lbpar_gpu.dim_x*lbpar_gpu.dim_y*z; host_boundary_index_list[number_of_boundnodes] = boundary_number + 1; number_of_boundnodes++; //printf("boundindex %i: \n", number_of_boundnodes); } #ifdef EK_BOUNDARIES if (ek_initialized) { ek_parameters.number_of_boundary_nodes = number_of_boundnodes; if(wallcharge_species != -1) { if(pdb_charge_lattice && pdb_charge_lattice[ek_parameters.dim_y*ek_parameters.dim_x*z + ek_parameters.dim_x*y + x] != 0.0f) { node_charged = 1; node_wallcharge += pdb_charge_lattice[ek_parameters.dim_y*ek_parameters.dim_x*z + ek_parameters.dim_x*y + x]; } if(node_charged) host_wallcharge_species_density[ek_parameters.dim_y*ek_parameters.dim_x*z + ek_parameters.dim_x*y + x] = node_wallcharge / ek_parameters.valency[wallcharge_species]; else if(dist <= 0) host_wallcharge_species_density[ek_parameters.dim_y*ek_parameters.dim_x*z + ek_parameters.dim_x*y + x] = 0.0f; else host_wallcharge_species_density[ek_parameters.dim_y*ek_parameters.dim_x*z + ek_parameters.dim_x*y + x] = ek_parameters.density[wallcharge_species] * ek_parameters.agrid*ek_parameters.agrid*ek_parameters.agrid; } } #endif } } } /**call of cuda fkt*/ float* boundary_velocity = (float *) Utils::malloc(3*(n_lb_boundaries+1)*sizeof(float)); for (n=0; n<n_lb_boundaries; n++) { boundary_velocity[3*n+0]=lb_boundaries[n].velocity[0]; boundary_velocity[3*n+1]=lb_boundaries[n].velocity[1]; boundary_velocity[3*n+2]=lb_boundaries[n].velocity[2]; } boundary_velocity[3*n_lb_boundaries+0] = 0.0f; boundary_velocity[3*n_lb_boundaries+1] = 0.0f; boundary_velocity[3*n_lb_boundaries+2] = 0.0f; if (n_lb_boundaries || pdb_boundary_lattice) lb_init_boundaries_GPU(n_lb_boundaries, number_of_boundnodes, host_boundary_node_list, host_boundary_index_list, boundary_velocity); free(boundary_velocity); free(host_boundary_node_list); free(host_boundary_index_list); #ifdef EK_BOUNDARIES if (ek_initialized) { ek_init_species_density_wallcharge(host_wallcharge_species_density, wallcharge_species); free(host_wallcharge_species_density); } #endif #endif /* defined (LB_GPU) && defined (LB_BOUNDARIES_GPU) */ } else { #if defined (LB) && defined (LB_BOUNDARIES) int node_domain_position[3], offset[3]; int the_boundary=-1; map_node_array(this_node, node_domain_position); offset[0] = node_domain_position[0]*lblattice.grid[0]; offset[1] = node_domain_position[1]*lblattice.grid[1]; offset[2] = node_domain_position[2]*lblattice.grid[2]; for (n=0;n<lblattice.halo_grid_volume;n++) { lbfields[n].boundary = 0; } if (lblattice.halo_grid_volume==0) return; for (z=0; z<lblattice.grid[2]+2; z++) { for (y=0; y<lblattice.grid[1]+2; y++) { for (x=0; x<lblattice.grid[0]+2; x++) { pos[0] = (offset[0]+(x-0.5))*lblattice.agrid[0]; pos[1] = (offset[1]+(y-0.5))*lblattice.agrid[1]; pos[2] = (offset[2]+(z-0.5))*lblattice.agrid[2]; dist = 1e99; for (n=0;n<n_lb_boundaries;n++) { switch (lb_boundaries[n].type) { case LB_BOUNDARY_WAL: calculate_wall_dist((Particle*) NULL, pos, (Particle*) NULL, &lb_boundaries[n].c.wal, &dist_tmp, dist_vec); break; case LB_BOUNDARY_SPH: calculate_sphere_dist((Particle*) NULL, pos, (Particle*) NULL, &lb_boundaries[n].c.sph, &dist_tmp, dist_vec); break; case LB_BOUNDARY_CYL: calculate_cylinder_dist((Particle*) NULL, pos, (Particle*) NULL, &lb_boundaries[n].c.cyl, &dist_tmp, dist_vec); break; case LB_BOUNDARY_RHOMBOID: calculate_rhomboid_dist((Particle*) NULL, pos, (Particle*) NULL, &lb_boundaries[n].c.rhomboid, &dist_tmp, dist_vec); break; case LB_BOUNDARY_POR: calculate_pore_dist((Particle*) NULL, pos, (Particle*) NULL, &lb_boundaries[n].c.pore, &dist_tmp, dist_vec); break; case LB_BOUNDARY_STOMATOCYTE: calculate_stomatocyte_dist((Particle*) NULL, pos, (Particle*) NULL, &lb_boundaries[n].c.stomatocyte, &dist_tmp, dist_vec); break; case LB_BOUNDARY_HOLLOW_CONE: calculate_hollow_cone_dist((Particle*) NULL, pos, (Particle*) NULL, &lb_boundaries[n].c.hollow_cone, &dist_tmp, dist_vec); break; case LB_BOUNDARY_VOXEL: // voxel data do not need dist dist_tmp=1e99; //calculate_voxel_dist((Particle*) NULL, pos, (Particle*) NULL, &lb_boundaries[n].c.voxel, &dist_tmp, dist_vec); break; default: ostringstream msg; msg <<"lbboundary type " << lb_boundaries[n].type << " not implemented in lb_init_boundaries()\n"; runtimeError(msg); } if (dist_tmp<dist || n == 0) { dist = dist_tmp; the_boundary = n; } } if (dist <= 0 && the_boundary >= 0 && n_lb_boundaries > 0) { lbfields[get_linear_index(x,y,z,lblattice.halo_grid)].boundary = the_boundary+1; //printf("boundindex %i: \n", get_linear_index(x,y,z,lblattice.halo_grid)); } else { lbfields[get_linear_index(x,y,z,lblattice.halo_grid)].boundary = 0; } } } } //printf("init voxels\n\n"); // SET VOXEL BOUNDARIES DIRECTLY int xxx,yyy,zzz=0; char line[80]; for (n=0;n<n_lb_boundaries;n++) { switch (lb_boundaries[n].type) { case LB_BOUNDARY_VOXEL: //lbfields[get_linear_index(lb_boundaries[n].c.voxel.pos[0],lb_boundaries[n].c.voxel.pos[1],lb_boundaries[n].c.voxel.pos[2],lblattice.halo_grid)].boundary = n+1; FILE *fp; //fp=fopen("/home/mgusenbauer/Daten/Copy/DUK/GentlePump/Optimierer/NSvsLBM/geometry_files/bottleneck_fine_voxel_data_d20_converted_noMirror.csv", "r"); //fp=fopen("/home/mgusenbauer/Daten/Copy/DUK/GentlePump/Optimierer/NSvsLBM/geometry_files/bottleneck_fine_voxel_data_d80_converted_noMirror.csv", "r"); //fp=fopen("/home/mgusenbauer/Daten/Copy/DUK/GentlePump/Optimierer/NSvsLBM/geometry_files/bottleneck_fine_voxel_data_d80_converted.csv", "r"); fp=fopen(lb_boundaries[n].c.voxel.filename, "r"); while(fgets(line, 80, fp) != NULL) { /* get a line, up to 80 chars from fp, done if NULL */ sscanf (line, "%d %d %d", &xxx,&yyy,&zzz); //printf("%d %d %d\n", xxx,yyy,zzz); //lbfields[get_linear_index(xxx,yyy+30,zzz,lblattice.halo_grid)].boundary = n+1; lbfields[get_linear_index(xxx,yyy,zzz,lblattice.halo_grid)].boundary = n+1; } fclose(fp); break; default: break; } } // CHECK FOR BOUNDARY NEIGHBOURS AND SET FLUID NORMAL VECTOR //int neighbours = {0,0,0,0,0,0}; //int x=0,y=0,z=0; //double nn[]={0.0,0.0,0.0,0.0,0.0,0.0}; //for (n=0;n<n_lb_boundaries;n++) { //switch (lb_boundaries[n].type) { //case LB_BOUNDARY_VOXEL: //x=lb_boundaries[n].c.voxel.pos[0]; //y=lb_boundaries[n].c.voxel.pos[1]; //z=lb_boundaries[n].c.voxel.pos[2]; //if(((x-1) >= 0) && (lbfields[get_linear_index(x-1,y,z,lblattice.halo_grid)].boundary == 0)) nn[0] = -1.0;//neighbours[0] = -1; //if(((x+1) <= lblattice.grid[0]) && (lbfields[get_linear_index(x+1,y,z,lblattice.halo_grid)].boundary == 0)) nn[1] = 1.0;//neighbours[1] = 1; ////printf("%.0lf %.0lf ",nn[0],nn[1]); //lb_boundaries[n].c.voxel.n[0] = nn[0]+nn[1]; ////nn=0.0; //if(((y-1) >= 0) && (lbfields[get_linear_index(x,y-1,z,lblattice.halo_grid)].boundary == 0)) nn[2] = -1.0;//neighbours[2] = -1; //if(((y+1) <= lblattice.grid[1]) && (lbfields[get_linear_index(x,y+1,z,lblattice.halo_grid)].boundary == 0)) nn[3] = 1.0;//neighbours[3] = 1; ////printf("%.0lf %.0lf ",nn[2],nn[3]); //lb_boundaries[n].c.voxel.n[1] = nn[2]+nn[3]; ////nn=0.0; //if(((z-1) >= 0) && (lbfields[get_linear_index(x,y,z-1,lblattice.halo_grid)].boundary == 0)) nn[4] = -1.0;//neighbours[4] = -1; //if(((z+1) <= lblattice.grid[2]) && (lbfields[get_linear_index(x,y,z+1,lblattice.halo_grid)].boundary == 0)) nn[5] = 1.0;//neighbours[5]= 1; ////printf("%.0lf %.0lf ",nn[4],nn[5]); //lb_boundaries[n].c.voxel.n[2] = nn[4]+nn[5]; //nn[0]=0.0,nn[1]=0.0,nn[2]=0.0,nn[3]=0.0,nn[4]=0.0,nn[5]=0.0; ////printf("t %d pos: %.0lf %.0lf %.0lf, fluid normal %.0lf %.0lf %.0lf\n",n, x,y,z,lb_boundaries[n].c.voxel.normal[0],lb_boundaries[n].c.voxel.normal[1],lb_boundaries[n].c.voxel.normal[2]); ////printf("boundaries: %d %d %d %d %d %d\n",lbfields[get_linear_index(x-1,y,z,lblattice.halo_grid)].boundary,lbfields[get_linear_index(x+1,y,z,lblattice.halo_grid)].boundary,lbfields[get_linear_index(x,y-1,z,lblattice.halo_grid)].boundary,lbfields[get_linear_index(x,y+1,z,lblattice.halo_grid)].boundary,lbfields[get_linear_index(x,y,z-1,lblattice.halo_grid)].boundary,lbfields[get_linear_index(x,y,z+1,lblattice.halo_grid)].boundary); //break; //default: //break; //} //} //// DO THE SAME FOR THE CONSTRAINTS: CONSTRAINTS MUST BE SET AND THE SAME AS LB_BOUNDARY !!! //for(n=0;n<n_constraints;n++) { //switch(constraints[n].type) { //case CONSTRAINT_VOXEL: //x=constraints[n].c.voxel.pos[0]; //y=constraints[n].c.voxel.pos[1]; //z=constraints[n].c.voxel.pos[2]; //if(((x-1) >= 0) && (lbfields[get_linear_index(x-1,y,z,lblattice.halo_grid)].boundary == 0)) nn[0] = -1.0;//neighbours[0] = -1; //if(((x+1) <= lblattice.grid[0]) && (lbfields[get_linear_index(x+1,y,z,lblattice.halo_grid)].boundary == 0)) nn[1] = 1.0;//neighbours[1] = 1; ////printf("%.0lf %.0lf ",nn[0],nn[1]); //constraints[n].c.voxel.n[0] = nn[0]+nn[1]; ////nn=0.0; //if(((y-1) >= 0) && (lbfields[get_linear_index(x,y-1,z,lblattice.halo_grid)].boundary == 0)) nn[2] = -1.0;//neighbours[2] = -1; //if(((y+1) <= lblattice.grid[1]) && (lbfields[get_linear_index(x,y+1,z,lblattice.halo_grid)].boundary == 0)) nn[3] = 1.0;//neighbours[3] = 1; ////printf("%.0lf %.0lf ",nn[2],nn[3]); //constraints[n].c.voxel.n[1] = nn[2]+nn[3]; ////nn=0.0; //if(((z-1) >= 0) && (lbfields[get_linear_index(x,y,z-1,lblattice.halo_grid)].boundary == 0)) nn[4] = -1.0;//neighbours[4] = -1; //if(((z+1) <= lblattice.grid[2]) && (lbfields[get_linear_index(x,y,z+1,lblattice.halo_grid)].boundary == 0)) nn[5] = 1.0;//neighbours[5]= 1; ////printf("%.0lf %.0lf ",nn[4],nn[5]); //constraints[n].c.voxel.n[2] = nn[4]+nn[5]; //nn[0]=0.0,nn[1]=0.0,nn[2]=0.0,nn[3]=0.0,nn[4]=0.0,nn[5]=0.0; //break; //default: //break; //} //} //#ifdef VOXEL_BOUNDARIES /* for (z=0; z<lblattice.grid[2]+2; z++) { for (y=0; y<lblattice.grid[1]+2; y++) { for (x=0; x<lblattice.grid[0]+2; x++) { lbfields[get_linear_index(x,y,z,lblattice.halo_grid)].boundary = 1; } } } static const char filename[] = "/home/mgusenbauer/Daten/Copy/DUK/GentlePump/Optimierer/voxels/stl/data_final.csv"; FILE *file = fopen ( filename, "r" ); int coords[3]; printf("start new\n"); if ( file != NULL ){ char line [ 128 ]; // or other suitable maximum line size while ( fgets ( line, sizeof line, file ) != NULL ) {// read a line //fputs ( line, stdout ); // write the line //coords = line.Split(' ').Select(n => Convert.ToInt32(n)).ToArray(); //printf("readline: %s\n",line); int i; sscanf(line, "%d %d %d", &coords[0],&coords[1],&coords[2]); //printf("%d %d %d\n", coords[0],coords[1],coords[2]); lbfields[get_linear_index(coords[0]+5,coords[1]+5,coords[2]+5,lblattice.halo_grid)].boundary = 0; } fclose ( file ); } printf("end new\n"); */ #endif } } int lbboundary_get_force(int no, double* f) { #if defined (LB_BOUNDARIES) || defined (LB_BOUNDARIES_GPU) double* forces = (double *) Utils::malloc(3*n_lb_boundaries*sizeof(double)); if (lattice_switch & LATTICE_LB_GPU) { #if defined (LB_BOUNDARIES_GPU) && defined (LB_GPU) lb_gpu_get_boundary_forces(forces); f[0]=-forces[3*no+0]; f[1]=-forces[3*no+1]; f[2]=-forces[3*no+2]; #else return ES_ERROR; #endif } else { #if defined (LB_BOUNDARIES) && defined (LB) mpi_gather_stats(8, forces, NULL, NULL, NULL); f[0]=forces[3*no+0]*lbpar.agrid/lbpar.tau/lbpar.tau; f[1]=forces[3*no+1]*lbpar.agrid/lbpar.tau/lbpar.tau; f[2]=forces[3*no+2]*lbpar.agrid/lbpar.tau/lbpar.tau; #else return ES_ERROR; #endif } free(forces); #endif return 0; } #endif /* LB_BOUNDARIES or LB_BOUNDARIES_GPU */ #ifdef LB_BOUNDARIES void lb_bounce_back() { #ifdef D3Q19 #ifndef PULL int k,i,l; int yperiod = lblattice.halo_grid[0]; int zperiod = lblattice.halo_grid[0]*lblattice.halo_grid[1]; int next[19]; int x,y,z; double population_shift; double modes[19]; next[0] = 0; // ( 0, 0, 0) = next[1] = 1; // ( 1, 0, 0) + next[2] = - 1; // (-1, 0, 0) next[3] = yperiod; // ( 0, 1, 0) + next[4] = - yperiod; // ( 0,-1, 0) next[5] = zperiod; // ( 0, 0, 1) + next[6] = - zperiod; // ( 0, 0,-1) next[7] = (1+yperiod); // ( 1, 1, 0) + next[8] = - (1+yperiod); // (-1,-1, 0) next[9] = (1-yperiod); // ( 1,-1, 0) next[10] = - (1-yperiod); // (-1, 1, 0) + next[11] = (1+zperiod); // ( 1, 0, 1) + next[12] = - (1+zperiod); // (-1, 0,-1) next[13] = (1-zperiod); // ( 1, 0,-1) next[14] = - (1-zperiod); // (-1, 0, 1) + next[15] = (yperiod+zperiod); // ( 0, 1, 1) + next[16] = - (yperiod+zperiod); // ( 0,-1,-1) next[17] = (yperiod-zperiod); // ( 0, 1,-1) next[18] = - (yperiod-zperiod); // ( 0,-1, 1) + int reverse[] = { 0, 2, 1, 4, 3, 6, 5, 8, 7, 10, 9, 12, 11, 14, 13, 16, 15, 18, 17 }; /* bottom-up sweep */ // for (k=lblattice.halo_offset;k<lblattice.halo_grid_volume;k++) { for (z=0; z<lblattice.grid[2]+2; z++) { for (y=0; y<lblattice.grid[1]+2; y++) { for (x=0; x<lblattice.grid[0]+2; x++) { k= get_linear_index(x,y,z,lblattice.halo_grid); if (lbfields[k].boundary) { lb_calc_modes(k, modes); for (i=0; i<19; i++) { population_shift=0; for (l=0; l<3; l++) { population_shift-=lbpar.agrid*lbpar.agrid*lbpar.agrid*lbpar.agrid*lbpar.agrid*lbpar.rho[0]*2*lbmodel.c[i][l]*lbmodel.w[i]*lb_boundaries[lbfields[k].boundary-1].velocity[l]/lbmodel.c_sound_sq; } if ( x-lbmodel.c[i][0] > 0 && x -lbmodel.c[i][0] < lblattice.grid[0]+1 && y-lbmodel.c[i][1] > 0 && y -lbmodel.c[i][1] < lblattice.grid[1]+1 && z-lbmodel.c[i][2] > 0 && z -lbmodel.c[i][2] < lblattice.grid[2]+1) { if ( !lbfields[k-next[i]].boundary ) { for (l=0; l<3; l++) { lb_boundaries[lbfields[k].boundary-1].force[l]+=(2*lbfluid[1][i][k]+population_shift)*lbmodel.c[i][l]; } lbfluid[1][reverse[i]][k-next[i]] = lbfluid[1][i][k]+ population_shift; } else { lbfluid[1][reverse[i]][k-next[i]] = lbfluid[1][i][k] = 0.0; } } } } } } } #else #error Bounce back boundary conditions are only implemented for PUSH scheme! #endif #else #error Bounce back boundary conditions are only implemented for D3Q19! #endif } #endif
Smiljanic/Esspresso-Code
src/core/lb-boundaries.cpp
C++
gpl-3.0
25,248
/* -*- c++ -*- */ /* * Copyright 2006 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include <atsc_rs_decoder.h> #include <gr_io_signature.h> #include <atsc_consts.h> atsc_rs_decoder_sptr atsc_make_rs_decoder() { return atsc_rs_decoder_sptr(new atsc_rs_decoder()); } atsc_rs_decoder::atsc_rs_decoder() : gr_sync_block("atsc_rs_decoder", gr_make_io_signature(1, 1, sizeof(atsc_mpeg_packet_rs_encoded)), gr_make_io_signature(1, 1, sizeof(atsc_mpeg_packet_no_sync))) { reset(); } int atsc_rs_decoder::work (int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const atsc_mpeg_packet_rs_encoded *in = (const atsc_mpeg_packet_rs_encoded *) input_items[0]; atsc_mpeg_packet_no_sync *out = (atsc_mpeg_packet_no_sync *) output_items[0]; for (int i = 0; i < noutput_items; i++){ assert(in[i].pli.regular_seg_p()); out[i].pli = in[i].pli; // copy pipeline info... int nerrors_corrrected = d_rs_decoder.decode(out[i], in[i]); out[i].pli.set_transport_error(nerrors_corrrected == -1); } return noutput_items; }
GREO/GNU-Radio
gr-atsc/src/lib/atsc_rs_decoder.cc
C++
gpl-3.0
1,900
/* * Copyright (C) 2010-2015 JPEXS, All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3.0 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. */ package com.jpexs.decompiler.flash.exporters; import com.jpexs.decompiler.flash.AbortRetryIgnoreHandler; import com.jpexs.decompiler.flash.EventListener; import com.jpexs.decompiler.flash.RetryTask; import com.jpexs.decompiler.flash.SWF; import com.jpexs.decompiler.flash.exporters.commonshape.ExportRectangle; import com.jpexs.decompiler.flash.exporters.commonshape.SVGExporter; import com.jpexs.decompiler.flash.exporters.modes.MorphShapeExportMode; import com.jpexs.decompiler.flash.exporters.morphshape.CanvasMorphShapeExporter; import com.jpexs.decompiler.flash.exporters.settings.MorphShapeExportSettings; import com.jpexs.decompiler.flash.tags.DefineMorphShapeTag; import com.jpexs.decompiler.flash.tags.Tag; import com.jpexs.decompiler.flash.tags.base.CharacterTag; import com.jpexs.decompiler.flash.tags.base.MorphShapeTag; import com.jpexs.decompiler.flash.types.CXFORMWITHALPHA; import com.jpexs.helpers.Helper; import com.jpexs.helpers.Path; import com.jpexs.helpers.utf8.Utf8Helper; import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; /** * * @author JPEXS */ public class MorphShapeExporter { //TODO: implement morphshape export. How to handle 65536 frames? public List<File> exportMorphShapes(AbortRetryIgnoreHandler handler, final String outdir, List<Tag> tags, final MorphShapeExportSettings settings, EventListener evl) throws IOException, InterruptedException { List<File> ret = new ArrayList<>(); if (tags.isEmpty()) { return ret; } File foutdir = new File(outdir); Path.createDirectorySafe(foutdir); int count = 0; for (Tag t : tags) { if (t instanceof MorphShapeTag) { count++; } } if (count == 0) { return ret; } int currentIndex = 1; for (final Tag t : tags) { if (t instanceof MorphShapeTag) { if (evl != null) { evl.handleExportingEvent("morphshape", currentIndex, count, t.getName()); } int characterID = 0; if (t instanceof CharacterTag) { characterID = ((CharacterTag) t).getCharacterId(); } String ext = settings.mode == MorphShapeExportMode.CANVAS ? "html" : "svg"; final File file = new File(outdir + File.separator + characterID + "." + ext); new RetryTask(() -> { MorphShapeTag mst = (MorphShapeTag) t; switch (settings.mode) { case SVG: try (OutputStream fos = new BufferedOutputStream(new FileOutputStream(file))) { ExportRectangle rect = new ExportRectangle(mst.getRect()); rect.xMax *= settings.zoom; rect.yMax *= settings.zoom; rect.xMin *= settings.zoom; rect.yMin *= settings.zoom; SVGExporter exporter = new SVGExporter(rect); mst.toSVG(exporter, -2, new CXFORMWITHALPHA(), 0, settings.zoom); fos.write(Utf8Helper.getBytes(exporter.getSVG())); } break; case CANVAS: try (OutputStream fos = new BufferedOutputStream(new FileOutputStream(file))) { int deltaX = -Math.min(mst.getStartBounds().Xmin, mst.getEndBounds().Xmin); int deltaY = -Math.min(mst.getStartBounds().Ymin, mst.getEndBounds().Ymin); CanvasMorphShapeExporter cse = new CanvasMorphShapeExporter(((Tag) mst).getSwf(), mst.getShapeAtRatio(0), mst.getShapeAtRatio(DefineMorphShapeTag.MAX_RATIO), new CXFORMWITHALPHA(), SWF.unitDivisor, deltaX, deltaY); cse.export(); Set<Integer> needed = new HashSet<>(); CharacterTag ct = ((CharacterTag) mst); needed.add(ct.getCharacterId()); ct.getNeededCharactersDeep(needed); ByteArrayOutputStream baos = new ByteArrayOutputStream(); SWF.writeLibrary(ct.getSwf(), needed, baos); fos.write(Utf8Helper.getBytes(cse.getHtml(new String(baos.toByteArray(), Utf8Helper.charset), SWF.getTypePrefix(mst) + mst.getCharacterId(), mst.getRect()))); } break; } }, handler).run(); ret.add(file); if (evl != null) { evl.handleExportedEvent("morphshape", currentIndex, count, t.getName()); } currentIndex++; } } if (settings.mode == MorphShapeExportMode.CANVAS) { File fcanvas = new File(foutdir + File.separator + "canvas.js"); Helper.saveStream(SWF.class.getClassLoader().getResourceAsStream("com/jpexs/helpers/resource/canvas.js"), fcanvas); ret.add(fcanvas); } return ret; } }
Jackkal/jpexs-decompiler
libsrc/ffdec_lib/src/com/jpexs/decompiler/flash/exporters/MorphShapeExporter.java
Java
gpl-3.0
6,261
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. /** * Short answer * * @package mod * @subpackage lesson * @copyright 2009 Sam Hemelryk * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later **/ defined('MOODLE_INTERNAL') || die(); /** Short answer question type */ define("LESSON_PAGE_SHORTANSWER", "1"); class lesson_page_type_shortanswer extends lesson_page { protected $type = lesson_page::TYPE_QUESTION; protected $typeidstring = 'shortanswer'; protected $typeid = LESSON_PAGE_SHORTANSWER; protected $string = null; public function get_typeid() { return $this->typeid; } public function get_typestring() { if ($this->string===null) { $this->string = get_string($this->typeidstring, 'lesson'); } return $this->string; } public function get_idstring() { return $this->typeidstring; } public function display($renderer, $attempt) { global $USER, $CFG, $PAGE; $mform = new lesson_display_answer_form_shortanswer($CFG->wwwroot.'/mod/lesson/continue.php', array('contents'=>$this->get_contents())); $data = new stdClass; $data->id = $PAGE->cm->id; $data->pageid = $this->properties->id; if (isset($USER->modattempts[$this->lesson->id])) { $data->answer = s($attempt->useranswer); } $mform->set_data($data); return $mform->display(); } public function check_answer() { global $CFG; $result = parent::check_answer(); $mform = new lesson_display_answer_form_shortanswer($CFG->wwwroot.'/mod/lesson/continue.php', array('contents'=>$this->get_contents())); $data = $mform->get_data(); require_sesskey(); $studentanswer = trim($data->answer); if ($studentanswer === '') { $result->noanswer = true; return $result; } $studentanswer = s($studentanswer); $i=0; $answers = $this->get_answers(); foreach ($answers as $answer) { $i++; $expectedanswer = $answer->answer; // for easier handling of $answer->answer $ismatch = false; $markit = false; $useregexp = ($this->qoption); if ($useregexp) { //we are using 'normal analysis', which ignores case $ignorecase = ''; if (substr($expectedanswer,0,-2) == '/i') { $expectedanswer = substr($expectedanswer,0,-2); $ignorecase = 'i'; } } else { $expectedanswer = str_replace('*', '#####', $expectedanswer); $expectedanswer = preg_quote($expectedanswer, '/'); $expectedanswer = str_replace('#####', '.*', $expectedanswer); } // see if user typed in any of the correct answers if ((!$this->lesson->custom && $this->lesson->jumpto_is_correct($this->properties->id, $answer->jumpto)) or ($this->lesson->custom && $answer->score > 0) ) { if (!$useregexp) { // we are using 'normal analysis', which ignores case if (preg_match('/^'.$expectedanswer.'$/i',$studentanswer)) { $ismatch = true; } } else { if (preg_match('/^'.$expectedanswer.'$/'.$ignorecase,$studentanswer)) { $ismatch = true; } } if ($ismatch == true) { $result->correctanswer = true; } } else { if (!$useregexp) { //we are using 'normal analysis' // see if user typed in any of the wrong answers; don't worry about case if (preg_match('/^'.$expectedanswer.'$/i',$studentanswer)) { $ismatch = true; } } else { // we are using regular expressions analysis $startcode = substr($expectedanswer,0,2); switch ($startcode){ //1- check for absence of required string in $studentanswer (coded by initial '--') case "--": $expectedanswer = substr($expectedanswer,2); if (!preg_match('/^'.$expectedanswer.'$/'.$ignorecase,$studentanswer)) { $ismatch = true; } break; //2- check for code for marking wrong strings (coded by initial '++') case "++": $expectedanswer=substr($expectedanswer,2); $markit = true; //check for one or several matches if (preg_match_all('/'.$expectedanswer.'/'.$ignorecase,$studentanswer, $matches)) { $ismatch = true; $nb = count($matches[0]); $original = array(); $marked = array(); $fontStart = '<span class="incorrect matches">'; $fontEnd = '</span>'; for ($i = 0; $i < $nb; $i++) { array_push($original,$matches[0][$i]); array_push($marked,$fontStart.$matches[0][$i].$fontEnd); } $studentanswer = str_replace($original, $marked, $studentanswer); } break; //3- check for wrong answers belonging neither to -- nor to ++ categories default: if (preg_match('/^'.$expectedanswer.'$/'.$ignorecase,$studentanswer, $matches)) { $ismatch = true; } break; } $result->correctanswer = false; } } if ($ismatch) { $result->newpageid = $answer->jumpto; if (trim(strip_tags($answer->response))) { $result->response = $answer->response; } $result->answerid = $answer->id; break; // quit answer analysis immediately after a match has been found } } $result->studentanswer = $result->userresponse = $studentanswer; return $result; } public function option_description_string() { if ($this->properties->qoption) { return " - ".get_string("casesensitive", "lesson"); } return parent::option_description_string(); } public function display_answers(html_table $table) { $answers = $this->get_answers(); $options = new stdClass; $options->noclean = true; $options->para = false; $i = 1; foreach ($answers as $answer) { $cells = array(); if ($this->lesson->custom && $answer->score > 0) { // if the score is > 0, then it is correct $cells[] = '<span class="labelcorrect">'.get_string("answer", "lesson")." $i</span>: \n"; } else if ($this->lesson->custom) { $cells[] = '<span class="label">'.get_string("answer", "lesson")." $i</span>: \n"; } else if ($this->lesson->jumpto_is_correct($this->properties->id, $answer->jumpto)) { // underline correct answers $cells[] = '<span class="correct">'.get_string("answer", "lesson")." $i</span>: \n"; } else { $cells[] = '<span class="labelcorrect">'.get_string("answer", "lesson")." $i</span>: \n"; } $cells[] = format_text($answer->answer, $answer->answerformat, $options); $table->data[] = new html_table_row($cells); $cells = array(); $cells[] = "<span class=\"label\">".get_string("response", "lesson")." $i</span>"; $cells[] = format_text($answer->response, $answer->responseformat, $options); $table->data[] = new html_table_row($cells); $cells = array(); $cells[] = "<span class=\"label\">".get_string("score", "lesson").'</span>'; $cells[] = $answer->score; $table->data[] = new html_table_row($cells); $cells = array(); $cells[] = "<span class=\"label\">".get_string("jump", "lesson").'</span>'; $cells[] = $this->get_jump_name($answer->jumpto); $table->data[] = new html_table_row($cells); if ($i === 1){ $table->data[count($table->data)-1]->cells[0]->style = 'width:20%;'; } $i++; } return $table; } public function stats(array &$pagestats, $tries) { if(count($tries) > $this->lesson->maxattempts) { // if there are more tries than the max that is allowed, grab the last "legal" attempt $temp = $tries[$this->lesson->maxattempts - 1]; } else { // else, user attempted the question less than the max, so grab the last one $temp = end($tries); } if (isset($pagestats[$temp->pageid][$temp->useranswer])) { $pagestats[$temp->pageid][$temp->useranswer]++; } else { $pagestats[$temp->pageid][$temp->useranswer] = 1; } if (isset($pagestats[$temp->pageid]["total"])) { $pagestats[$temp->pageid]["total"]++; } else { $pagestats[$temp->pageid]["total"] = 1; } return true; } public function report_answers($answerpage, $answerdata, $useranswer, $pagestats, &$i, &$n) { $answers = $this->get_answers(); $formattextdefoptions = new stdClass; $formattextdefoptions->para = false; //I'll use it widely in this page foreach ($answers as $answer) { if ($useranswer == null && $i == 0) { // I have the $i == 0 because it is easier to blast through it all at once. if (isset($pagestats[$this->properties->id])) { $stats = $pagestats[$this->properties->id]; $total = $stats["total"]; unset($stats["total"]); foreach ($stats as $valentered => $ntimes) { $data = '<input type="text" size="50" disabled="disabled" readonly="readonly" value="'.s($valentered).'" />'; $percent = $ntimes / $total * 100; $percent = round($percent, 2); $percent .= "% ".get_string("enteredthis", "lesson"); $answerdata->answers[] = array($data, $percent); } } else { $answerdata->answers[] = array(get_string("nooneansweredthisquestion", "lesson"), " "); } $i++; } else if ($useranswer != null && ($answer->id == $useranswer->answerid || ($answer == end($answers) && empty($answerdata)))) { // get in here when what the user entered is not one of the answers $data = '<input type="text" size="50" disabled="disabled" readonly="readonly" value="'.s($useranswer->useranswer).'">'; if (isset($pagestats[$this->properties->id][$useranswer->useranswer])) { $percent = $pagestats[$this->properties->id][$useranswer->useranswer] / $pagestats[$this->properties->id]["total"] * 100; $percent = round($percent, 2); $percent .= "% ".get_string("enteredthis", "lesson"); } else { $percent = get_string("nooneenteredthis", "lesson"); } $answerdata->answers[] = array($data, $percent); if ($answer->id == $useranswer->answerid) { if ($answer->response == NULL) { if ($useranswer->correct) { $answerdata->response = get_string("thatsthecorrectanswer", "lesson"); } else { $answerdata->response = get_string("thatsthewronganswer", "lesson"); } } else { $answerdata->response = $answer->response; } if ($this->lesson->custom) { $answerdata->score = get_string("pointsearned", "lesson").": ".$answer->score; } elseif ($useranswer->correct) { $answerdata->score = get_string("receivedcredit", "lesson"); } else { $answerdata->score = get_string("didnotreceivecredit", "lesson"); } } else { $answerdata->response = get_string("thatsthewronganswer", "lesson"); if ($this->lesson->custom) { $answerdata->score = get_string("pointsearned", "lesson").": 0"; } else { $answerdata->score = get_string("didnotreceivecredit", "lesson"); } } } $answerpage->answerdata = $answerdata; } return $answerpage; } } class lesson_add_page_form_shortanswer extends lesson_add_page_form_base { public $qtype = 'shortanswer'; public $qtypestring = 'shortanswer'; public function custom_definition() { $this->_form->addElement('checkbox', 'qoption', get_string('options', 'lesson'), get_string('casesensitive', 'lesson')); //oh my, this is a regex option! $this->_form->setDefault('qoption', 0); $this->_form->addHelpButton('qoption', 'casesensitive', 'lesson'); for ($i = 0; $i < $this->_customdata['lesson']->maxanswers; $i++) { $this->_form->addElement('header', 'answertitle'.$i, get_string('answer').' '.($i+1)); $this->add_answer($i); $this->add_response($i); $this->add_jumpto($i, NULL, ($i == 0 ? LESSON_NEXTPAGE : LESSON_THISPAGE)); $this->add_score($i, null, ($i===0)?1:0); } } } class lesson_display_answer_form_shortanswer extends moodleform { public function definition() { global $OUTPUT; $mform = $this->_form; $contents = $this->_customdata['contents']; $mform->addElement('header', 'pageheader', $OUTPUT->box($contents, 'contents')); $options = new stdClass; $options->para = false; $options->noclean = true; $mform->addElement('hidden', 'id'); $mform->setType('id', PARAM_INT); $mform->addElement('hidden', 'pageid'); $mform->setType('pageid', PARAM_INT); $mform->addElement('text', 'answer', get_string('youranswer', 'lesson'), array('size'=>'50', 'maxlength'=>'200')); $mform->setType('answer', PARAM_TEXT); $this->add_action_buttons(null, get_string("pleaseenteryouranswerinthebox", "lesson")); } }
vuchannguyen/web
mod/lesson/pagetypes/shortanswer.php
PHP
gpl-3.0
15,979
#include <AP_HAL/AP_HAL.h> #include "AC_PrecLand.h" #include "AC_PrecLand_Backend.h" #include "AC_PrecLand_Companion.h" #include "AC_PrecLand_IRLock.h" #include "AC_PrecLand_SITL_Gazebo.h" #include "AC_PrecLand_SITL.h" extern const AP_HAL::HAL& hal; const AP_Param::GroupInfo AC_PrecLand::var_info[] = { // @Param: ENABLED // @DisplayName: Precision Land enabled/disabled and behaviour // @Description: Precision Land enabled/disabled and behaviour // @Values: 0:Disabled, 1:Enabled Always Land, 2:Enabled Strict // @User: Advanced AP_GROUPINFO_FLAGS("ENABLED", 0, AC_PrecLand, _enabled, 0, AP_PARAM_FLAG_ENABLE), // @Param: TYPE // @DisplayName: Precision Land Type // @Description: Precision Land Type // @Values: 0:None, 1:CompanionComputer, 2:IRLock, 3:SITL_Gazebo, 4:SITL // @User: Advanced AP_GROUPINFO("TYPE", 1, AC_PrecLand, _type, 0), // @Param: YAW_ALIGN // @DisplayName: Sensor yaw alignment // @Description: Yaw angle from body x-axis to sensor x-axis. // @Range: 0 360 // @Increment: 1 // @User: Advanced // @Units: Centi-degrees AP_GROUPINFO("YAW_ALIGN", 2, AC_PrecLand, _yaw_align, 0), // @Param: LAND_OFS_X // @DisplayName: Land offset forward // @Description: Desired landing position of the camera forward of the target in vehicle body frame // @Range: -20 20 // @Increment: 1 // @User: Advanced // @Units: Centimeters AP_GROUPINFO("LAND_OFS_X", 3, AC_PrecLand, _land_ofs_cm_x, 0), // @Param: LAND_OFS_Y // @DisplayName: Land offset right // @Description: desired landing position of the camera right of the target in vehicle body frame // @Range: -20 20 // @Increment: 1 // @User: Advanced // @Units: Centimeters AP_GROUPINFO("LAND_OFS_Y", 4, AC_PrecLand, _land_ofs_cm_y, 0), // 5 RESERVED for EKF_TYPE // 6 RESERVED for ACC_NSE AP_GROUPEND }; // Default constructor. // Note that the Vector/Matrix constructors already implicitly zero // their values. // AC_PrecLand::AC_PrecLand(const AP_AHRS& ahrs, const AP_InertialNav& inav) : _ahrs(ahrs), _inav(inav), _last_update_ms(0), _last_backend_los_meas_ms(0), _backend(nullptr) { // set parameters to defaults AP_Param::setup_object_defaults(this, var_info); // other initialisation _backend_state.healthy = false; } // init - perform any required initialisation of backends void AC_PrecLand::init() { // exit immediately if init has already been run if (_backend != nullptr) { return; } // default health to false _backend = nullptr; _backend_state.healthy = false; // instantiate backend based on type parameter switch ((enum PrecLandType)(_type.get())) { // no type defined case PRECLAND_TYPE_NONE: default: return; // companion computer case PRECLAND_TYPE_COMPANION: _backend = new AC_PrecLand_Companion(*this, _backend_state); break; // IR Lock #if CONFIG_HAL_BOARD == HAL_BOARD_PX4 || CONFIG_HAL_BOARD == HAL_BOARD_VRBRAIN case PRECLAND_TYPE_IRLOCK: _backend = new AC_PrecLand_IRLock(*this, _backend_state); break; #endif #if CONFIG_HAL_BOARD == HAL_BOARD_SITL case PRECLAND_TYPE_SITL_GAZEBO: _backend = new AC_PrecLand_SITL_Gazebo(*this, _backend_state); break; case PRECLAND_TYPE_SITL: _backend = new AC_PrecLand_SITL(*this, _backend_state); break; #endif } // init backend if (_backend != nullptr) { _backend->init(); } } // update - give chance to driver to get updates from sensor void AC_PrecLand::update(float rangefinder_alt_cm, bool rangefinder_alt_valid) { _attitude_history.push_back(_ahrs.get_rotation_body_to_ned()); // run backend update if (_backend != nullptr && _enabled) { // read from sensor _backend->update(); Vector3f vehicleVelocityNED = _inav.get_velocity()*0.01f; vehicleVelocityNED.z = -vehicleVelocityNED.z; if (target_acquired()) { // EKF prediction step float dt; Vector3f targetDelVel; _ahrs.getCorrectedDeltaVelocityNED(targetDelVel, dt); targetDelVel = -targetDelVel; _ekf_x.predict(dt, targetDelVel.x, 0.5f*dt); _ekf_y.predict(dt, targetDelVel.y, 0.5f*dt); } if (_backend->have_los_meas() && _backend->los_meas_time_ms() != _last_backend_los_meas_ms) { // we have a new, unique los measurement _last_backend_los_meas_ms = _backend->los_meas_time_ms(); Vector3f target_vec_unit_body; _backend->get_los_body(target_vec_unit_body); // Apply sensor yaw alignment rotation float sin_yaw_align = sinf(radians(_yaw_align*0.01f)); float cos_yaw_align = cosf(radians(_yaw_align*0.01f)); Matrix3f Rz = Matrix3f( cos_yaw_align, -sin_yaw_align, 0, sin_yaw_align, cos_yaw_align, 0, 0, 0, 1 ); Vector3f target_vec_unit_ned = _attitude_history.front() * Rz * target_vec_unit_body; bool target_vec_valid = target_vec_unit_ned.z > 0.0f; bool alt_valid = (rangefinder_alt_valid && rangefinder_alt_cm > 0.0f) || (_backend->distance_to_target() > 0.0f); if (target_vec_valid && alt_valid) { float alt; if (_backend->distance_to_target() > 0.0f) { alt = _backend->distance_to_target(); } else { alt = MAX(rangefinder_alt_cm*0.01f, 0.0f); } float dist = alt/target_vec_unit_ned.z; Vector3f targetPosRelMeasNED = Vector3f(target_vec_unit_ned.x*dist, target_vec_unit_ned.y*dist, alt); float xy_pos_var = sq(targetPosRelMeasNED.z*(0.01f + 0.01f*_ahrs.get_gyro().length()) + 0.02f); if (!target_acquired()) { // reset filter state if (_inav.get_filter_status().flags.horiz_pos_rel) { _ekf_x.init(targetPosRelMeasNED.x, xy_pos_var, -vehicleVelocityNED.x, sq(2.0f)); _ekf_y.init(targetPosRelMeasNED.y, xy_pos_var, -vehicleVelocityNED.y, sq(2.0f)); } else { _ekf_x.init(targetPosRelMeasNED.x, xy_pos_var, 0.0f, sq(10.0f)); _ekf_y.init(targetPosRelMeasNED.y, xy_pos_var, 0.0f, sq(10.0f)); } _last_update_ms = AP_HAL::millis(); } else { float NIS_x = _ekf_x.getPosNIS(targetPosRelMeasNED.x, xy_pos_var); float NIS_y = _ekf_y.getPosNIS(targetPosRelMeasNED.y, xy_pos_var); if (MAX(NIS_x, NIS_y) < 3.0f || _outlier_reject_count >= 3) { _outlier_reject_count = 0; _ekf_x.fusePos(targetPosRelMeasNED.x, xy_pos_var); _ekf_y.fusePos(targetPosRelMeasNED.y, xy_pos_var); _last_update_ms = AP_HAL::millis(); } else { _outlier_reject_count++; } } } } } } bool AC_PrecLand::target_acquired() const { return (AP_HAL::millis()-_last_update_ms) < 2000; } bool AC_PrecLand::get_target_position_cm(Vector2f& ret) const { if (!target_acquired()) { return false; } Vector3f land_ofs_ned_cm = _ahrs.get_rotation_body_to_ned() * Vector3f(_land_ofs_cm_x,_land_ofs_cm_y,0); ret.x = _ekf_x.getPos()*100.0f + _inav.get_position().x + land_ofs_ned_cm.x; ret.y = _ekf_y.getPos()*100.0f + _inav.get_position().y + land_ofs_ned_cm.y; return true; } bool AC_PrecLand::get_target_position_relative_cm(Vector2f& ret) const { if (!target_acquired()) { return false; } Vector3f land_ofs_ned_cm = _ahrs.get_rotation_body_to_ned() * Vector3f(_land_ofs_cm_x,_land_ofs_cm_y,0); ret.x = _ekf_x.getPos()*100.0f + land_ofs_ned_cm.x; ret.y = _ekf_y.getPos()*100.0f + land_ofs_ned_cm.y; return true; } bool AC_PrecLand::get_target_velocity_relative_cms(Vector2f& ret) const { if (!target_acquired()) { return false; } ret.x = _ekf_x.getVel()*100.0f; ret.y = _ekf_y.getVel()*100.0f; return true; } // handle_msg - Process a LANDING_TARGET mavlink message void AC_PrecLand::handle_msg(mavlink_message_t* msg) { // run backend update if (_backend != nullptr) { _backend->handle_msg(msg); } }
farmer-martin/ardupilot
libraries/AC_PrecLand/AC_PrecLand.cpp
C++
gpl-3.0
8,721
--TEST-- IntlTimeZone::createEnumeration(): variant with country --SKIPIF-- <?php if (!extension_loaded('intl')) die('skip intl extension not enabled'); --FILE-- <?php ini_set("intl.error_level", E_WARNING); $tz = IntlTimeZone::createEnumeration('NL'); var_dump(get_class($tz)); $count = count(iterator_to_array($tz)); var_dump($count >= 1); $tz->rewind(); var_dump(in_array('Europe/Amsterdam', iterator_to_array($tz))); ?> ==DONE== --EXPECT-- string(12) "IntlIterator" bool(true) bool(true) ==DONE==
tukusejssirs/eSpievatko
spievatko/espievatko/prtbl/srv/php-5.5.11/ext/intl/tests/timezone_createEnumeration_variation2.phpt
PHP
gpl-3.0
504
function rewriteTaskTitles(blockid) { forEach( getElementsByTagAndClassName('a', 'task-title', 'tasktable_' + blockid), function(element) { disconnectAll(element); connect(element, 'onclick', function(e) { e.stop(); var description = getFirstElementByTagAndClassName('div', 'task-desc', element.parentNode); toggleElementClass('hidden', description); }); } ); } function TaskPager(blockid) { var self = this; paginatorProxy.addObserver(self); connect(self, 'pagechanged', partial(rewriteTaskTitles, blockid)); } var taskPagers = []; function initNewPlansBlock(blockid) { if ($('plans_page_container_' + blockid)) { new Paginator('block' + blockid + '_pagination', 'tasktable_' + blockid, 'artefact/plans/viewtasks.json.php', null); taskPagers.push(new TaskPager(blockid)); } rewriteTaskTitles(blockid); }
eireford/mahara
htdocs/artefact/plans/blocktype/plans/js/plansblock.js
JavaScript
gpl-3.0
963
/******************************************************************************* * Copyright (c) 2000, 2004 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.compiler.lookup; import org.eclipse.jdt.core.compiler.CharOperation; import org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration; import org.eclipse.jdt.internal.compiler.ast.Clinit; import org.eclipse.jdt.internal.compiler.ast.FieldDeclaration; import org.eclipse.jdt.internal.compiler.ast.TypeDeclaration; import org.eclipse.jdt.internal.compiler.ast.TypeParameter; import org.eclipse.jdt.internal.compiler.ast.TypeReference; import org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants; import org.eclipse.jdt.internal.compiler.problem.AbortCompilation; import org.eclipse.jdt.internal.compiler.problem.ProblemReporter; import org.eclipse.jdt.internal.compiler.util.HashtableOfObject; public class ClassScope extends Scope { public TypeDeclaration referenceContext; private TypeReference superTypeReference; private final static char[] IncompleteHierarchy = new char[] {'h', 'a', 's', ' ', 'i', 'n', 'c', 'o', 'n', 's', 'i', 's', 't', 'e', 'n', 't', ' ', 'h', 'i', 'e', 'r', 'a', 'r', 'c', 'h', 'y'}; public ClassScope(Scope parent, TypeDeclaration context) { super(CLASS_SCOPE, parent); this.referenceContext = context; } void buildAnonymousTypeBinding(SourceTypeBinding enclosingType, ReferenceBinding supertype) { LocalTypeBinding anonymousType = buildLocalType(enclosingType, enclosingType.fPackage); SourceTypeBinding sourceType = referenceContext.binding; if (supertype.isInterface()) { sourceType.superclass = getJavaLangObject(); sourceType.superInterfaces = new ReferenceBinding[] { supertype }; } else { sourceType.superclass = supertype; sourceType.superInterfaces = TypeConstants.NoSuperInterfaces; } connectMemberTypes(); buildFieldsAndMethods(); anonymousType.faultInTypesForFieldsAndMethods(); sourceType.verifyMethods(environment().methodVerifier()); } private void buildFields() { boolean hierarchyIsInconsistent = referenceContext.binding.isHierarchyInconsistent(); if (referenceContext.fields == null) { if (hierarchyIsInconsistent) { // 72468 referenceContext.binding.fields = new FieldBinding[1]; referenceContext.binding.fields[0] = new FieldBinding(IncompleteHierarchy, VoidBinding, AccPrivate, referenceContext.binding, null); } else { referenceContext.binding.fields = NoFields; } return; } // count the number of fields vs. initializers FieldDeclaration[] fields = referenceContext.fields; int size = fields.length; int count = 0; for (int i = 0; i < size; i++) if (fields[i].isField()) count++; if (hierarchyIsInconsistent) count++; // iterate the field declarations to create the bindings, lose all duplicates FieldBinding[] fieldBindings = new FieldBinding[count]; HashtableOfObject knownFieldNames = new HashtableOfObject(count); boolean duplicate = false; count = 0; for (int i = 0; i < size; i++) { FieldDeclaration field = fields[i]; if (!field.isField()) { if (referenceContext.binding.isInterface()) problemReporter().interfaceCannotHaveInitializers(referenceContext.binding, field); } else { FieldBinding fieldBinding = new FieldBinding(field, null, field.modifiers | AccUnresolved, referenceContext.binding); // field's type will be resolved when needed for top level types checkAndSetModifiersForField(fieldBinding, field); if (knownFieldNames.containsKey(field.name)) { duplicate = true; FieldBinding previousBinding = (FieldBinding) knownFieldNames.get(field.name); if (previousBinding != null) { for (int f = 0; f < i; f++) { FieldDeclaration previousField = fields[f]; if (previousField.binding == previousBinding) { problemReporter().duplicateFieldInType(referenceContext.binding, previousField); previousField.binding = null; break; } } } knownFieldNames.put(field.name, null); // ensure that the duplicate field is found & removed problemReporter().duplicateFieldInType(referenceContext.binding, field); field.binding = null; } else { knownFieldNames.put(field.name, fieldBinding); // remember that we have seen a field with this name if (fieldBinding != null) fieldBindings[count++] = fieldBinding; } } } // remove duplicate fields if (duplicate) { FieldBinding[] newFieldBindings = new FieldBinding[knownFieldNames.size() - 1]; // we know we'll be removing at least 1 duplicate name size = count; count = 0; for (int i = 0; i < size; i++) { FieldBinding fieldBinding = fieldBindings[i]; if (knownFieldNames.get(fieldBinding.name) != null) newFieldBindings[count++] = fieldBinding; } fieldBindings = newFieldBindings; } if (hierarchyIsInconsistent) fieldBindings[count++] = new FieldBinding(IncompleteHierarchy, VoidBinding, AccPrivate, referenceContext.binding, null); if (count != fieldBindings.length) System.arraycopy(fieldBindings, 0, fieldBindings = new FieldBinding[count], 0, count); for (int i = 0; i < count; i++) fieldBindings[i].id = i; referenceContext.binding.fields = fieldBindings; } void buildFieldsAndMethods() { buildFields(); buildMethods(); SourceTypeBinding sourceType = referenceContext.binding; if (sourceType.isMemberType() && !sourceType.isLocalType()) ((MemberTypeBinding) sourceType).checkSyntheticArgsAndFields(); ReferenceBinding[] memberTypes = sourceType.memberTypes; for (int i = 0, length = memberTypes.length; i < length; i++) ((SourceTypeBinding) memberTypes[i]).scope.buildFieldsAndMethods(); } private LocalTypeBinding buildLocalType( SourceTypeBinding enclosingType, PackageBinding packageBinding) { referenceContext.scope = this; referenceContext.staticInitializerScope = new MethodScope(this, referenceContext, true); referenceContext.initializerScope = new MethodScope(this, referenceContext, false); // build the binding or the local type LocalTypeBinding localType = new LocalTypeBinding(this, enclosingType, this.switchCase()); referenceContext.binding = localType; checkAndSetModifiers(); buildTypeVariables(); // Look at member types ReferenceBinding[] memberTypeBindings = NoMemberTypes; if (referenceContext.memberTypes != null) { int size = referenceContext.memberTypes.length; memberTypeBindings = new ReferenceBinding[size]; int count = 0; nextMember : for (int i = 0; i < size; i++) { TypeDeclaration memberContext = referenceContext.memberTypes[i]; if (memberContext.isInterface()) { problemReporter().nestedClassCannotDeclareInterface(memberContext); continue nextMember; } ReferenceBinding type = localType; // check that the member does not conflict with an enclosing type do { if (CharOperation.equals(type.sourceName, memberContext.name)) { problemReporter().hidingEnclosingType(memberContext); continue nextMember; } type = type.enclosingType(); } while (type != null); // check the member type does not conflict with another sibling member type for (int j = 0; j < i; j++) { if (CharOperation.equals(referenceContext.memberTypes[j].name, memberContext.name)) { problemReporter().duplicateNestedType(memberContext); continue nextMember; } } ClassScope memberScope = new ClassScope(this, referenceContext.memberTypes[i]); LocalTypeBinding memberBinding = memberScope.buildLocalType(localType, packageBinding); memberBinding.setAsMemberType(); memberTypeBindings[count++] = memberBinding; } if (count != size) System.arraycopy(memberTypeBindings, 0, memberTypeBindings = new ReferenceBinding[count], 0, count); } localType.memberTypes = memberTypeBindings; return localType; } void buildLocalTypeBinding(SourceTypeBinding enclosingType) { LocalTypeBinding localType = buildLocalType(enclosingType, enclosingType.fPackage); connectTypeHierarchy(); buildFieldsAndMethods(); localType.faultInTypesForFieldsAndMethods(); referenceContext.binding.verifyMethods(environment().methodVerifier()); } private void buildMemberTypes() { SourceTypeBinding sourceType = referenceContext.binding; ReferenceBinding[] memberTypeBindings = NoMemberTypes; if (referenceContext.memberTypes != null) { int length = referenceContext.memberTypes.length; memberTypeBindings = new ReferenceBinding[length]; int count = 0; nextMember : for (int i = 0; i < length; i++) { TypeDeclaration memberContext = referenceContext.memberTypes[i]; if (memberContext.isInterface() && sourceType.isNestedType() && sourceType.isClass() && !sourceType.isStatic()) { problemReporter().nestedClassCannotDeclareInterface(memberContext); continue nextMember; } ReferenceBinding type = sourceType; // check that the member does not conflict with an enclosing type do { if (CharOperation.equals(type.sourceName, memberContext.name)) { problemReporter().hidingEnclosingType(memberContext); continue nextMember; } type = type.enclosingType(); } while (type != null); // check that the member type does not conflict with another sibling member type for (int j = 0; j < i; j++) { if (CharOperation.equals(referenceContext.memberTypes[j].name, memberContext.name)) { problemReporter().duplicateNestedType(memberContext); continue nextMember; } } ClassScope memberScope = new ClassScope(this, memberContext); memberTypeBindings[count++] = memberScope.buildType(sourceType, sourceType.fPackage); } if (count != length) System.arraycopy(memberTypeBindings, 0, memberTypeBindings = new ReferenceBinding[count], 0, count); } sourceType.memberTypes = memberTypeBindings; } private void buildMethods() { if (referenceContext.methods == null) { referenceContext.binding.methods = NoMethods; return; } // iterate the method declarations to create the bindings AbstractMethodDeclaration[] methods = referenceContext.methods; int size = methods.length; int clinitIndex = -1; for (int i = 0; i < size; i++) { if (methods[i] instanceof Clinit) { clinitIndex = i; break; } } MethodBinding[] methodBindings = new MethodBinding[clinitIndex == -1 ? size : size - 1]; int count = 0; for (int i = 0; i < size; i++) { if (i != clinitIndex) { MethodScope scope = new MethodScope(this, methods[i], false); MethodBinding methodBinding = scope.createMethod(methods[i]); if (methodBinding != null) // is null if binding could not be created methodBindings[count++] = methodBinding; } } if (count != methodBindings.length) System.arraycopy(methodBindings, 0, methodBindings = new MethodBinding[count], 0, count); referenceContext.binding.methods = methodBindings; referenceContext.binding.modifiers |= AccUnresolved; // until methods() is sent } SourceTypeBinding buildType(SourceTypeBinding enclosingType, PackageBinding packageBinding) { // provide the typeDeclaration with needed scopes referenceContext.scope = this; referenceContext.staticInitializerScope = new MethodScope(this, referenceContext, true); referenceContext.initializerScope = new MethodScope(this, referenceContext, false); if (enclosingType == null) { char[][] className = CharOperation.arrayConcat(packageBinding.compoundName, referenceContext.name); referenceContext.binding = new SourceTypeBinding(className, packageBinding, this); } else { char[][] className = CharOperation.deepCopy(enclosingType.compoundName); className[className.length - 1] = CharOperation.concat(className[className.length - 1], referenceContext.name, '$'); referenceContext.binding = new MemberTypeBinding(className, this, enclosingType); } SourceTypeBinding sourceType = referenceContext.binding; sourceType.fPackage.addType(sourceType); checkAndSetModifiers(); buildTypeVariables(); buildMemberTypes(); return sourceType; } private void buildTypeVariables() { SourceTypeBinding sourceType = referenceContext.binding; TypeParameter[] typeParameters = referenceContext.typeParameters; // do not construct type variables if source < 1.5 if (typeParameters == null || environment().options.sourceLevel < ClassFileConstants.JDK1_5) { sourceType.typeVariables = NoTypeVariables; return; } sourceType.typeVariables = NoTypeVariables; // safety if (sourceType.id == T_Object) { // handle the case of redefining java.lang.Object up front problemReporter().objectCannotBeGeneric(referenceContext); return; } sourceType.typeVariables = createTypeVariables(typeParameters, sourceType); sourceType.modifiers |= AccGenericSignature; } private void checkAndSetModifiers() { SourceTypeBinding sourceType = referenceContext.binding; int modifiers = sourceType.modifiers; if ((modifiers & AccAlternateModifierProblem) != 0) problemReporter().duplicateModifierForType(sourceType); ReferenceBinding enclosingType = sourceType.enclosingType(); boolean isMemberType = sourceType.isMemberType(); if (isMemberType) { // checks for member types before local types to catch local members if (enclosingType.isStrictfp()) modifiers |= AccStrictfp; if (enclosingType.isViewedAsDeprecated() && !sourceType.isDeprecated()) modifiers |= AccDeprecatedImplicitly; if (enclosingType.isInterface()) modifiers |= AccPublic; } else if (sourceType.isLocalType()) { if (sourceType.isAnonymousType()) modifiers |= AccFinal; Scope scope = this; do { switch (scope.kind) { case METHOD_SCOPE : MethodScope methodScope = (MethodScope) scope; if (methodScope.isInsideInitializer()) { SourceTypeBinding type = ((TypeDeclaration) methodScope.referenceContext).binding; // inside field declaration ? check field modifier to see if deprecated if (methodScope.initializedField != null) { // currently inside this field initialization if (methodScope.initializedField.isViewedAsDeprecated() && !sourceType.isDeprecated()){ modifiers |= AccDeprecatedImplicitly; } } else { if (type.isStrictfp()) modifiers |= AccStrictfp; if (type.isViewedAsDeprecated() && !sourceType.isDeprecated()) modifiers |= AccDeprecatedImplicitly; } } else { MethodBinding method = ((AbstractMethodDeclaration) methodScope.referenceContext).binding; if (method != null){ if (method.isStrictfp()) modifiers |= AccStrictfp; if (method.isViewedAsDeprecated() && !sourceType.isDeprecated()) modifiers |= AccDeprecatedImplicitly; } } break; case CLASS_SCOPE : // local member if (enclosingType.isStrictfp()) modifiers |= AccStrictfp; if (enclosingType.isViewedAsDeprecated() && !sourceType.isDeprecated()) modifiers |= AccDeprecatedImplicitly; break; } scope = scope.parent; } while (scope != null); } // after this point, tests on the 16 bits reserved. int realModifiers = modifiers & AccJustFlag; if ((realModifiers & AccInterface) != 0) { // detect abnormal cases for interfaces if (isMemberType) { int unexpectedModifiers = ~(AccPublic | AccPrivate | AccProtected | AccStatic | AccAbstract | AccInterface | AccStrictfp); if ((realModifiers & unexpectedModifiers) != 0) problemReporter().illegalModifierForMemberInterface(sourceType); /* } else if (sourceType.isLocalType()) { //interfaces cannot be defined inside a method int unexpectedModifiers = ~(AccAbstract | AccInterface | AccStrictfp); if ((realModifiers & unexpectedModifiers) != 0) problemReporter().illegalModifierForLocalInterface(sourceType); */ } else { int unexpectedModifiers = ~(AccPublic | AccAbstract | AccInterface | AccStrictfp); if ((realModifiers & unexpectedModifiers) != 0) problemReporter().illegalModifierForInterface(sourceType); } modifiers |= AccAbstract; } else { // detect abnormal cases for types if (isMemberType) { // includes member types defined inside local types int unexpectedModifiers = ~(AccPublic | AccPrivate | AccProtected | AccStatic | AccAbstract | AccFinal | AccStrictfp); if ((realModifiers & unexpectedModifiers) != 0) problemReporter().illegalModifierForMemberClass(sourceType); } else if (sourceType.isLocalType()) { int unexpectedModifiers = ~(AccAbstract | AccFinal | AccStrictfp); if ((realModifiers & unexpectedModifiers) != 0) problemReporter().illegalModifierForLocalClass(sourceType); } else { int unexpectedModifiers = ~(AccPublic | AccAbstract | AccFinal | AccStrictfp); if ((realModifiers & unexpectedModifiers) != 0) problemReporter().illegalModifierForClass(sourceType); } // check that Final and Abstract are not set together if ((realModifiers & (AccFinal | AccAbstract)) == (AccFinal | AccAbstract)) problemReporter().illegalModifierCombinationFinalAbstractForClass(sourceType); } if (isMemberType) { // test visibility modifiers inconsistency, isolate the accessors bits if (enclosingType.isInterface()) { if ((realModifiers & (AccProtected | AccPrivate)) != 0) { problemReporter().illegalVisibilityModifierForInterfaceMemberType(sourceType); // need to keep the less restrictive if ((realModifiers & AccProtected) != 0) modifiers ^= AccProtected; if ((realModifiers & AccPrivate) != 0) modifiers ^= AccPrivate; } } else { int accessorBits = realModifiers & (AccPublic | AccProtected | AccPrivate); if ((accessorBits & (accessorBits - 1)) > 1) { problemReporter().illegalVisibilityModifierCombinationForMemberType(sourceType); // need to keep the less restrictive if ((accessorBits & AccPublic) != 0) { if ((accessorBits & AccProtected) != 0) modifiers ^= AccProtected; if ((accessorBits & AccPrivate) != 0) modifiers ^= AccPrivate; } if ((accessorBits & AccProtected) != 0) if ((accessorBits & AccPrivate) != 0) modifiers ^= AccPrivate; } } // static modifier test if ((realModifiers & AccStatic) == 0) { if (enclosingType.isInterface()) modifiers |= AccStatic; } else { if (!enclosingType.isStatic()) // error the enclosing type of a static field must be static or a top-level type problemReporter().illegalStaticModifierForMemberType(sourceType); } } sourceType.modifiers = modifiers; } /* This method checks the modifiers of a field. * * 9.3 & 8.3 * Need to integrate the check for the final modifiers for nested types * * Note : A scope is accessible by : fieldBinding.declaringClass.scope */ private void checkAndSetModifiersForField(FieldBinding fieldBinding, FieldDeclaration fieldDecl) { int modifiers = fieldBinding.modifiers; if ((modifiers & AccAlternateModifierProblem) != 0) problemReporter().duplicateModifierForField(fieldBinding.declaringClass, fieldDecl); if (fieldBinding.declaringClass.isInterface()) { int expectedValue = AccPublic | AccStatic | AccFinal; // set the modifiers modifiers |= expectedValue; // and then check that they are the only ones if ((modifiers & AccJustFlag) != expectedValue) problemReporter().illegalModifierForInterfaceField(fieldBinding.declaringClass, fieldDecl); fieldBinding.modifiers = modifiers; return; } // after this point, tests on the 16 bits reserved. int realModifiers = modifiers & AccJustFlag; int unexpectedModifiers = ~(AccPublic | AccPrivate | AccProtected | AccFinal | AccStatic | AccTransient | AccVolatile); if ((realModifiers & unexpectedModifiers) != 0) problemReporter().illegalModifierForField(fieldBinding.declaringClass, fieldDecl); int accessorBits = realModifiers & (AccPublic | AccProtected | AccPrivate); if ((accessorBits & (accessorBits - 1)) > 1) { problemReporter().illegalVisibilityModifierCombinationForField( fieldBinding.declaringClass, fieldDecl); // need to keep the less restrictive if ((accessorBits & AccPublic) != 0) { if ((accessorBits & AccProtected) != 0) modifiers ^= AccProtected; if ((accessorBits & AccPrivate) != 0) modifiers ^= AccPrivate; } if ((accessorBits & AccProtected) != 0) if ((accessorBits & AccPrivate) != 0) modifiers ^= AccPrivate; } if ((realModifiers & (AccFinal | AccVolatile)) == (AccFinal | AccVolatile)) problemReporter().illegalModifierCombinationFinalVolatileForField( fieldBinding.declaringClass, fieldDecl); if (fieldDecl.initialization == null && (modifiers & AccFinal) != 0) { modifiers |= AccBlankFinal; } fieldBinding.modifiers = modifiers; } private void checkForInheritedMemberTypes(SourceTypeBinding sourceType) { // search up the hierarchy of the sourceType to see if any superType defines a member type // when no member types are defined, tag the sourceType & each superType with the HasNoMemberTypes bit // assumes super types have already been checked & tagged ReferenceBinding currentType = sourceType; ReferenceBinding[][] interfacesToVisit = null; int lastPosition = -1; do { if (currentType.hasMemberTypes()) // avoid resolving member types eagerly return; ReferenceBinding[] itsInterfaces = currentType.superInterfaces(); if (itsInterfaces != NoSuperInterfaces) { if (interfacesToVisit == null) interfacesToVisit = new ReferenceBinding[5][]; if (++lastPosition == interfacesToVisit.length) System.arraycopy(interfacesToVisit, 0, interfacesToVisit = new ReferenceBinding[lastPosition * 2][], 0, lastPosition); interfacesToVisit[lastPosition] = itsInterfaces; } } while ((currentType = currentType.superclass()) != null && (currentType.tagBits & HasNoMemberTypes) == 0); if (interfacesToVisit != null) { // contains the interfaces between the sourceType and any superclass, which was tagged as having no member types boolean needToTag = false; for (int i = 0; i <= lastPosition; i++) { ReferenceBinding[] interfaces = interfacesToVisit[i]; for (int j = 0, length = interfaces.length; j < length; j++) { ReferenceBinding anInterface = interfaces[j]; if ((anInterface.tagBits & HasNoMemberTypes) == 0) { // skip interface if it already knows it has no member types if (anInterface.hasMemberTypes()) // avoid resolving member types eagerly return; needToTag = true; ReferenceBinding[] itsInterfaces = anInterface.superInterfaces(); if (itsInterfaces != NoSuperInterfaces) { if (++lastPosition == interfacesToVisit.length) System.arraycopy(interfacesToVisit, 0, interfacesToVisit = new ReferenceBinding[lastPosition * 2][], 0, lastPosition); interfacesToVisit[lastPosition] = itsInterfaces; } } } } if (needToTag) { for (int i = 0; i <= lastPosition; i++) { ReferenceBinding[] interfaces = interfacesToVisit[i]; for (int j = 0, length = interfaces.length; j < length; j++) interfaces[j].tagBits |= HasNoMemberTypes; } } } // tag the sourceType and all of its superclasses, unless they have already been tagged currentType = sourceType; do { currentType.tagBits |= HasNoMemberTypes; } while ((currentType = currentType.superclass()) != null && (currentType.tagBits & HasNoMemberTypes) == 0); } // Perform deferred bound checks for parameterized type references (only done after hierarchy is connected) private void checkParameterizedTypeBounds() { TypeReference superclass = referenceContext.superclass; if (superclass != null) { superclass.checkBounds(this); } TypeReference[] superinterfaces = referenceContext.superInterfaces; if (superinterfaces != null) { for (int i = 0, length = superinterfaces.length; i < length; i++) { superinterfaces[i].checkBounds(this); } } TypeParameter[] typeParameters = referenceContext.typeParameters; if (typeParameters != null) { for (int i = 0, paramLength = typeParameters.length; i < paramLength; i++) { TypeParameter typeParameter = typeParameters[i]; TypeReference typeRef = typeParameter.type; if (typeRef != null) { typeRef.checkBounds(this); TypeReference[] boundRefs = typeParameter.bounds; if (boundRefs != null) for (int j = 0, k = boundRefs.length; j < k; j++) boundRefs[j].checkBounds(this); } } } } private void connectMemberTypes() { SourceTypeBinding sourceType = referenceContext.binding; if (sourceType.memberTypes != NoMemberTypes) for (int i = 0, size = sourceType.memberTypes.length; i < size; i++) ((SourceTypeBinding) sourceType.memberTypes[i]).scope.connectTypeHierarchy(); } /* Our current belief based on available JCK tests is: inherited member types are visible as a potential superclass. inherited interfaces are not visible when defining a superinterface. Error recovery story: ensure the superclass is set to java.lang.Object if a problem is detected resolving the superclass. Answer false if an error was reported against the sourceType. */ private boolean connectSuperclass() { SourceTypeBinding sourceType = referenceContext.binding; if (sourceType.id == T_Object) { // handle the case of redefining java.lang.Object up front sourceType.superclass = null; sourceType.superInterfaces = NoSuperInterfaces; if (referenceContext.superclass != null || referenceContext.superInterfaces != null) problemReporter().objectCannotHaveSuperTypes(sourceType); return true; // do not propagate Object's hierarchy problems down to every subtype } if (referenceContext.superclass == null) { sourceType.superclass = getJavaLangObject(); return !detectCycle(sourceType, sourceType.superclass, null); } TypeReference superclassRef = referenceContext.superclass; ReferenceBinding superclass = findSupertype(superclassRef); if (superclass != null) { // is null if a cycle was detected cycle or a problem if (superclass.isInterface()) { problemReporter().superclassMustBeAClass(sourceType, superclassRef, superclass); } else if (superclass.isFinal()) { problemReporter().classExtendFinalClass(sourceType, superclassRef, superclass); } else if ((superclass.tagBits & TagBits.HasWildcard) != 0) { problemReporter().superTypeCannotUseWildcard(sourceType, superclassRef, superclass); } else { // only want to reach here when no errors are reported sourceType.superclass = superclass; return true; } } sourceType.tagBits |= HierarchyHasProblems; sourceType.superclass = getJavaLangObject(); if ((sourceType.superclass.tagBits & BeginHierarchyCheck) == 0) detectCycle(sourceType, sourceType.superclass, null); return false; // reported some error against the source type } /* Our current belief based on available JCK 1.3 tests is: inherited member types are visible as a potential superclass. inherited interfaces are visible when defining a superinterface. Error recovery story: ensure the superinterfaces contain only valid visible interfaces. Answer false if an error was reported against the sourceType. */ private boolean connectSuperInterfaces() { SourceTypeBinding sourceType = referenceContext.binding; sourceType.superInterfaces = NoSuperInterfaces; if (referenceContext.superInterfaces == null) return true; if (sourceType.id == T_Object) // already handled the case of redefining java.lang.Object return true; boolean noProblems = true; int length = referenceContext.superInterfaces.length; ReferenceBinding[] interfaceBindings = new ReferenceBinding[length]; int count = 0; nextInterface : for (int i = 0; i < length; i++) { TypeReference superInterfaceRef = referenceContext.superInterfaces[i]; ReferenceBinding superInterface = findSupertype(superInterfaceRef); if (superInterface == null) { // detected cycle sourceType.tagBits |= HierarchyHasProblems; noProblems = false; continue nextInterface; } superInterfaceRef.resolvedType = superInterface; // hold onto the problem type // Check for a duplicate interface once the name is resolved, otherwise we may be confused (ie : a.b.I and c.d.I) for (int k = 0; k < count; k++) { if (interfaceBindings[k] == superInterface) { // should this be treated as a warning? problemReporter().duplicateSuperinterface(sourceType, referenceContext, superInterface); continue nextInterface; } } if (superInterface.isClass()) { problemReporter().superinterfaceMustBeAnInterface(sourceType, superInterfaceRef, superInterface); sourceType.tagBits |= HierarchyHasProblems; noProblems = false; continue nextInterface; } if ((superInterface.tagBits & TagBits.HasWildcard) != 0) { problemReporter().superTypeCannotUseWildcard(sourceType, superInterfaceRef, superInterface); sourceType.tagBits |= HierarchyHasProblems; noProblems = false; continue nextInterface; } ReferenceBinding invalid = findAmbiguousInterface(superInterface, sourceType); if (invalid != null) { ReferenceBinding generic = null; if (superInterface.isParameterizedType()) generic = ((ParameterizedTypeBinding) superInterface).type; else if (invalid.isParameterizedType()) generic = ((ParameterizedTypeBinding) invalid).type; problemReporter().superinterfacesCollide(generic, referenceContext, superInterface, invalid); sourceType.tagBits |= HierarchyHasProblems; noProblems = false; continue nextInterface; } // only want to reach here when no errors are reported interfaceBindings[count++] = superInterface; } // hold onto all correctly resolved superinterfaces if (count > 0) { if (count != length) System.arraycopy(interfaceBindings, 0, interfaceBindings = new ReferenceBinding[count], 0, count); sourceType.superInterfaces = interfaceBindings; } return noProblems; } void connectTypeHierarchy() { SourceTypeBinding sourceType = referenceContext.binding; if ((sourceType.tagBits & BeginHierarchyCheck) == 0) { sourceType.tagBits |= BeginHierarchyCheck; boolean noProblems = connectTypeVariables(referenceContext.typeParameters); noProblems &= connectSuperclass(); noProblems &= connectSuperInterfaces(); sourceType.tagBits |= EndHierarchyCheck; if (noProblems && sourceType.isHierarchyInconsistent()) problemReporter().hierarchyHasProblems(sourceType); } // Perform deferred bound checks for parameterized type references (only done after hierarchy is connected) checkParameterizedTypeBounds(); connectMemberTypes(); try { checkForInheritedMemberTypes(sourceType); } catch (AbortCompilation e) { e.updateContext(referenceContext, referenceCompilationUnit().compilationResult); throw e; } } private void connectTypeHierarchyWithoutMembers() { // must ensure the imports are resolved if (parent instanceof CompilationUnitScope) { if (((CompilationUnitScope) parent).imports == null) ((CompilationUnitScope) parent).checkAndSetImports(); } else if (parent instanceof ClassScope) { // ensure that the enclosing type has already been checked ((ClassScope) parent).connectTypeHierarchyWithoutMembers(); } // double check that the hierarchy search has not already begun... SourceTypeBinding sourceType = referenceContext.binding; if ((sourceType.tagBits & BeginHierarchyCheck) != 0) return; sourceType.tagBits |= BeginHierarchyCheck; boolean noProblems = connectTypeVariables(referenceContext.typeParameters); noProblems &= connectSuperclass(); noProblems &= connectSuperInterfaces(); sourceType.tagBits |= EndHierarchyCheck; if (noProblems && sourceType.isHierarchyInconsistent()) problemReporter().hierarchyHasProblems(sourceType); } public boolean detectCycle(TypeBinding superType, TypeReference reference, TypeBinding[] argTypes) { if (!(superType instanceof ReferenceBinding)) return false; if (argTypes != null) { for (int i = 0, l = argTypes.length; i < l; i++) { TypeBinding argType = argTypes[i].leafComponentType(); if ((argType.tagBits & BeginHierarchyCheck) == 0 && argType instanceof SourceTypeBinding) // ensure if this is a source argument type that it has already been checked ((SourceTypeBinding) argType).scope.connectTypeHierarchyWithoutMembers(); } } if (reference == this.superTypeReference) { // see findSuperType() if (superType.isTypeVariable()) return false; // error case caught in resolveSuperType() // abstract class X<K,V> implements java.util.Map<K,V> // static abstract class M<K,V> implements Entry<K,V> if (superType.isParameterizedType()) superType = ((ParameterizedTypeBinding) superType).type; compilationUnitScope().recordSuperTypeReference(superType); // to record supertypes return detectCycle(referenceContext.binding, (ReferenceBinding) superType, reference); } if ((superType.tagBits & BeginHierarchyCheck) == 0 && superType instanceof SourceTypeBinding) // ensure if this is a source superclass that it has already been checked ((SourceTypeBinding) superType).scope.connectTypeHierarchyWithoutMembers(); return false; } // Answer whether a cycle was found between the sourceType & the superType private boolean detectCycle(SourceTypeBinding sourceType, ReferenceBinding superType, TypeReference reference) { if (superType.isRawType()) superType = ((RawTypeBinding) superType).type; // by this point the superType must be a binary or source type if (sourceType == superType) { problemReporter().hierarchyCircularity(sourceType, superType, reference); sourceType.tagBits |= HierarchyHasProblems; return true; } if (superType.isMemberType()) { ReferenceBinding current = superType.enclosingType(); do { if (current.isHierarchyBeingConnected()) { problemReporter().hierarchyCircularity(sourceType, current, reference); sourceType.tagBits |= HierarchyHasProblems; current.tagBits |= HierarchyHasProblems; return true; } } while ((current = current.enclosingType()) != null); } if (superType.isBinaryBinding()) { // force its superclass & superinterfaces to be found... 2 possibilities exist - the source type is included in the hierarchy of: // - a binary type... this case MUST be caught & reported here // - another source type... this case is reported against the other source type boolean hasCycle = false; if (superType.superclass() != null) { if (sourceType == superType.superclass()) { problemReporter().hierarchyCircularity(sourceType, superType, reference); sourceType.tagBits |= HierarchyHasProblems; superType.tagBits |= HierarchyHasProblems; return true; } ReferenceBinding parentType = superType.superclass(); if (parentType.isParameterizedType()) parentType = ((ParameterizedTypeBinding) parentType).type; hasCycle |= detectCycle(sourceType, parentType, reference); if ((parentType.tagBits & HierarchyHasProblems) != 0) { sourceType.tagBits |= HierarchyHasProblems; parentType.tagBits |= HierarchyHasProblems; // propagate down the hierarchy } } ReferenceBinding[] itsInterfaces = superType.superInterfaces(); if (itsInterfaces != NoSuperInterfaces) { for (int i = 0, length = itsInterfaces.length; i < length; i++) { ReferenceBinding anInterface = itsInterfaces[i]; if (sourceType == anInterface) { problemReporter().hierarchyCircularity(sourceType, superType, reference); sourceType.tagBits |= HierarchyHasProblems; superType.tagBits |= HierarchyHasProblems; return true; } if (anInterface.isParameterizedType()) anInterface = ((ParameterizedTypeBinding) anInterface).type; hasCycle |= detectCycle(sourceType, anInterface, reference); if ((anInterface.tagBits & HierarchyHasProblems) != 0) { sourceType.tagBits |= HierarchyHasProblems; superType.tagBits |= HierarchyHasProblems; } } } return hasCycle; } if (superType.isHierarchyBeingConnected()) { if (((SourceTypeBinding) superType).scope.superTypeReference != null) { // if null then its connecting its type variables problemReporter().hierarchyCircularity(sourceType, superType, reference); sourceType.tagBits |= HierarchyHasProblems; superType.tagBits |= HierarchyHasProblems; return true; } } if ((superType.tagBits & BeginHierarchyCheck) == 0) // ensure if this is a source superclass that it has already been checked ((SourceTypeBinding) superType).scope.connectTypeHierarchyWithoutMembers(); if ((superType.tagBits & HierarchyHasProblems) != 0) sourceType.tagBits |= HierarchyHasProblems; return false; } private ReferenceBinding findAmbiguousInterface(ReferenceBinding newInterface, ReferenceBinding currentType) { TypeBinding newErasure = newInterface.erasure(); if (newInterface == newErasure) return null; ReferenceBinding[][] interfacesToVisit = new ReferenceBinding[5][]; int lastPosition = -1; do { ReferenceBinding[] itsInterfaces = currentType.superInterfaces(); if (itsInterfaces != NoSuperInterfaces) { if (++lastPosition == interfacesToVisit.length) System.arraycopy(interfacesToVisit, 0, interfacesToVisit = new ReferenceBinding[lastPosition * 2][], 0, lastPosition); interfacesToVisit[lastPosition] = itsInterfaces; } } while ((currentType = currentType.superclass()) != null); for (int i = 0; i <= lastPosition; i++) { ReferenceBinding[] interfaces = interfacesToVisit[i]; for (int j = 0, length = interfaces.length; j < length; j++) { currentType = interfaces[j]; if (currentType.erasure() == newErasure) if (currentType != newInterface) return currentType; ReferenceBinding[] itsInterfaces = currentType.superInterfaces(); if (itsInterfaces != NoSuperInterfaces) { if (++lastPosition == interfacesToVisit.length) System.arraycopy(interfacesToVisit, 0, interfacesToVisit = new ReferenceBinding[lastPosition * 2][], 0, lastPosition); interfacesToVisit[lastPosition] = itsInterfaces; } } } return null; } private ReferenceBinding findSupertype(TypeReference typeReference) { try { typeReference.aboutToResolve(this); // allows us to trap completion & selection nodes compilationUnitScope().recordQualifiedReference(typeReference.getTypeName()); this.superTypeReference = typeReference; ReferenceBinding superType = (ReferenceBinding) typeReference.resolveSuperType(this); this.superTypeReference = null; return superType; } catch (AbortCompilation e) { e.updateContext(typeReference, referenceCompilationUnit().compilationResult); throw e; } } /* Answer the problem reporter to use for raising new problems. * * Note that as a side-effect, this updates the current reference context * (unit, type or method) in case the problem handler decides it is necessary * to abort. */ public ProblemReporter problemReporter() { MethodScope outerMethodScope; if ((outerMethodScope = outerMostMethodScope()) == null) { ProblemReporter problemReporter = referenceCompilationUnit().problemReporter; problemReporter.referenceContext = referenceContext; return problemReporter; } return outerMethodScope.problemReporter(); } /* Answer the reference type of this scope. * It is the nearest enclosing type of this scope. */ public TypeDeclaration referenceType() { return referenceContext; } public String toString() { if (referenceContext != null) return "--- Class Scope ---\n\n" //$NON-NLS-1$ + referenceContext.binding.toString(); return "--- Class Scope ---\n\n Binding not initialized" ; //$NON-NLS-1$ } }
Niky4000/UsefulUtils
projects/others/eclipse-platform-parent/eclipse.jdt.core-master/org.eclipse.jdt.core.tests.model/workspace/Compiler/src/org/eclipse/jdt/internal/compiler/lookup/ClassScope.java
Java
gpl-3.0
40,473
# Copyright (C) 2007, One Laptop Per Child # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>.
AbrahmAB/sugar
src/jarabe/journal/__init__.py
Python
gpl-3.0
679
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <jni.h> #include <vector> #include "base/android/jni_android.h" #include "base/android/jni_string.h" #include "base/android/scoped_java_ref.h" #include "base/lazy_instance.h" #include "base/logging.h" #include "content/browser/android/content_view_statics.h" #include "content/browser/renderer_host/render_process_host_impl.h" #include "content/common/android/address_parser.h" #include "content/common/view_messages.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/render_process_host_observer.h" #include "jni/ContentViewStatics_jni.h" using base::android::ConvertJavaStringToUTF16; using base::android::ConvertUTF16ToJavaString; using base::android::JavaParamRef; using base::android::ScopedJavaLocalRef; namespace { // TODO(pliard): http://crbug.com/235909. Move WebKit shared timer toggling // functionality out of ContentViewStatistics and not be build on top of // blink::Platform::SuspendSharedTimer. // TODO(pliard): http://crbug.com/235912. Add unit tests for WebKit shared timer // toggling. // This tracks the renderer processes that received a suspend request. It's // important on resume to only resume the renderer processes that were actually // suspended as opposed to all the current renderer processes because the // suspend calls are refcounted within BlinkPlatformImpl and it expects a // perfectly matched number of resume calls. // Note that this class is only accessed from the UI thread. class SuspendedProcessWatcher : public content::RenderProcessHostObserver { public: // If the process crashes, stop watching the corresponding RenderProcessHost // and ensure it doesn't get over-resumed. void RenderProcessExited(content::RenderProcessHost* host, base::TerminationStatus status, int exit_code) override { StopWatching(host); } void RenderProcessHostDestroyed(content::RenderProcessHost* host) override { StopWatching(host); } // Suspends timers in all current render processes. void SuspendWebKitSharedTimers() { DCHECK(suspended_processes_.empty()); for (content::RenderProcessHost::iterator i( content::RenderProcessHost::AllHostsIterator()); !i.IsAtEnd(); i.Advance()) { content::RenderProcessHost* host = i.GetCurrentValue(); host->AddObserver(this); host->GetRendererInterface()->SetWebKitSharedTimersSuspended(true); suspended_processes_.push_back(host->GetID()); } } // Resumes timers in processes that were previously stopped. void ResumeWebkitSharedTimers() { for (std::vector<int>::const_iterator it = suspended_processes_.begin(); it != suspended_processes_.end(); ++it) { content::RenderProcessHost* host = content::RenderProcessHost::FromID(*it); DCHECK(host); host->RemoveObserver(this); host->GetRendererInterface()->SetWebKitSharedTimersSuspended(false); } suspended_processes_.clear(); } private: void StopWatching(content::RenderProcessHost* host) { std::vector<int>::iterator pos = std::find(suspended_processes_.begin(), suspended_processes_.end(), host->GetID()); DCHECK(pos != suspended_processes_.end()); host->RemoveObserver(this); suspended_processes_.erase(pos); } std::vector<int /* RenderProcessHost id */> suspended_processes_; }; base::LazyInstance<SuspendedProcessWatcher> g_suspended_processes_watcher = LAZY_INSTANCE_INITIALIZER; } // namespace // Returns the first substring consisting of the address of a physical location. static ScopedJavaLocalRef<jstring> FindAddress( JNIEnv* env, const JavaParamRef<jclass>& clazz, const JavaParamRef<jstring>& addr) { base::string16 content_16 = ConvertJavaStringToUTF16(env, addr); base::string16 result_16; if (content::address_parser::FindAddress(content_16, &result_16)) return ConvertUTF16ToJavaString(env, result_16); return ScopedJavaLocalRef<jstring>(); } static void SetWebKitSharedTimersSuspended(JNIEnv* env, const JavaParamRef<jclass>& obj, jboolean suspend) { if (suspend) { g_suspended_processes_watcher.Pointer()->SuspendWebKitSharedTimers(); } else { g_suspended_processes_watcher.Pointer()->ResumeWebkitSharedTimers(); } } namespace content { bool RegisterWebViewStatics(JNIEnv* env) { return RegisterNativesImpl(env); } } // namespace content
geminy/aidear
oss/qt/qt-everywhere-opensource-src-5.9.0/qtwebengine/src/3rdparty/chromium/content/browser/android/content_view_statics.cc
C++
gpl-3.0
4,753
#!/usr/bin/python # Copyright (c) 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Certificate chain with 1 intermediate and a non-self-signed trust anchor. Verification should succeed, it doesn't matter that the root was not self-signed if it is designated as the trust anchor.""" import common uber_root = common.create_self_signed_root_certificate('UberRoot') # Non-self-signed root certificate (used as trust anchor) root = common.create_intermediate_certificate('Root', uber_root) # Intermediate certificate. intermediate = common.create_intermediate_certificate('Intermediate', root) # Target certificate. target = common.create_end_entity_certificate('Target', intermediate) chain = [target, intermediate] trusted = common.TrustAnchor(root, constrained=False) time = common.DEFAULT_TIME verify_result = True errors = None common.write_test_file(__doc__, chain, trusted, time, verify_result, errors)
geminy/aidear
oss/qt/qt-everywhere-opensource-src-5.9.0/qtwebengine/src/3rdparty/chromium/net/data/verify_certificate_chain_unittest/generate-unconstrained-non-self-signed-root.py
Python
gpl-3.0
1,019
var searchData= [ ['matrix_5fbase',['MATRIX_BASE',['../memorymap_8h.html#a096dcc80deb3676aeb5d5b8db13cfeba',1,'memorymap.h']]] ];
Aghosh993/TARS_codebase
libopencm3/doc/sam3x/html/search/defines_7.js
JavaScript
gpl-3.0
132
namespace MissionPlanner { partial class GridUI { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(GridUI)); this.groupBox5 = new System.Windows.Forms.GroupBox(); this.lbl_turnrad = new System.Windows.Forms.Label(); this.label36 = new System.Windows.Forms.Label(); this.lbl_photoevery = new System.Windows.Forms.Label(); this.label35 = new System.Windows.Forms.Label(); this.lbl_flighttime = new System.Windows.Forms.Label(); this.label31 = new System.Windows.Forms.Label(); this.lbl_distbetweenlines = new System.Windows.Forms.Label(); this.label25 = new System.Windows.Forms.Label(); this.lbl_footprint = new System.Windows.Forms.Label(); this.label30 = new System.Windows.Forms.Label(); this.lbl_strips = new System.Windows.Forms.Label(); this.lbl_pictures = new System.Windows.Forms.Label(); this.label33 = new System.Windows.Forms.Label(); this.label34 = new System.Windows.Forms.Label(); this.lbl_grndres = new System.Windows.Forms.Label(); this.label29 = new System.Windows.Forms.Label(); this.lbl_spacing = new System.Windows.Forms.Label(); this.label27 = new System.Windows.Forms.Label(); this.lbl_distance = new System.Windows.Forms.Label(); this.lbl_area = new System.Windows.Forms.Label(); this.label23 = new System.Windows.Forms.Label(); this.label22 = new System.Windows.Forms.Label(); this.tabCamera = new System.Windows.Forms.TabPage(); this.groupBox3 = new System.Windows.Forms.GroupBox(); this.label18 = new System.Windows.Forms.Label(); this.label17 = new System.Windows.Forms.Label(); this.label16 = new System.Windows.Forms.Label(); this.NUM_repttime = new System.Windows.Forms.NumericUpDown(); this.num_reptpwm = new System.Windows.Forms.NumericUpDown(); this.NUM_reptservo = new System.Windows.Forms.NumericUpDown(); this.rad_digicam = new System.Windows.Forms.RadioButton(); this.rad_repeatservo = new System.Windows.Forms.RadioButton(); this.rad_trigdist = new System.Windows.Forms.RadioButton(); this.groupBox2 = new System.Windows.Forms.GroupBox(); this.BUT_samplephoto = new MissionPlanner.Controls.MyButton(); this.label21 = new System.Windows.Forms.Label(); this.label19 = new System.Windows.Forms.Label(); this.label20 = new System.Windows.Forms.Label(); this.TXT_fovV = new System.Windows.Forms.TextBox(); this.TXT_fovH = new System.Windows.Forms.TextBox(); this.label12 = new System.Windows.Forms.Label(); this.TXT_cmpixel = new System.Windows.Forms.TextBox(); this.TXT_sensheight = new System.Windows.Forms.TextBox(); this.TXT_senswidth = new System.Windows.Forms.TextBox(); this.TXT_imgheight = new System.Windows.Forms.TextBox(); this.TXT_imgwidth = new System.Windows.Forms.TextBox(); this.NUM_focallength = new System.Windows.Forms.NumericUpDown(); this.label9 = new System.Windows.Forms.Label(); this.label10 = new System.Windows.Forms.Label(); this.label14 = new System.Windows.Forms.Label(); this.label13 = new System.Windows.Forms.Label(); this.label11 = new System.Windows.Forms.Label(); this.BUT_save = new MissionPlanner.Controls.MyButton(); this.tabGrid = new System.Windows.Forms.TabPage(); this.groupBox7 = new System.Windows.Forms.GroupBox(); this.LBL_Alternating_lanes = new System.Windows.Forms.Label(); this.LBL_Lane_Dist = new System.Windows.Forms.Label(); this.NUM_Lane_Dist = new System.Windows.Forms.NumericUpDown(); this.label28 = new System.Windows.Forms.Label(); this.groupBox_copter = new System.Windows.Forms.GroupBox(); this.TXT_headinghold = new System.Windows.Forms.TextBox(); this.BUT_headingholdminus = new System.Windows.Forms.Button(); this.BUT_headingholdplus = new System.Windows.Forms.Button(); this.CHK_copter_headingholdlock = new System.Windows.Forms.CheckBox(); this.CHK_copter_headinghold = new System.Windows.Forms.CheckBox(); this.LBL_copter_delay = new System.Windows.Forms.Label(); this.NUM_copter_delay = new System.Windows.Forms.NumericUpDown(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.label32 = new System.Windows.Forms.Label(); this.NUM_leadin = new System.Windows.Forms.NumericUpDown(); this.label3 = new System.Windows.Forms.Label(); this.NUM_spacing = new System.Windows.Forms.NumericUpDown(); this.label7 = new System.Windows.Forms.Label(); this.NUM_overshoot2 = new System.Windows.Forms.NumericUpDown(); this.label8 = new System.Windows.Forms.Label(); this.label6 = new System.Windows.Forms.Label(); this.label15 = new System.Windows.Forms.Label(); this.CMB_startfrom = new System.Windows.Forms.ComboBox(); this.num_overlap = new System.Windows.Forms.NumericUpDown(); this.num_sidelap = new System.Windows.Forms.NumericUpDown(); this.label5 = new System.Windows.Forms.Label(); this.NUM_overshoot = new System.Windows.Forms.NumericUpDown(); this.label2 = new System.Windows.Forms.Label(); this.NUM_Distance = new System.Windows.Forms.NumericUpDown(); this.tabSimple = new System.Windows.Forms.TabPage(); this.groupBox6 = new System.Windows.Forms.GroupBox(); this.label37 = new System.Windows.Forms.Label(); this.NUM_split = new System.Windows.Forms.NumericUpDown(); this.CHK_usespeed = new System.Windows.Forms.CheckBox(); this.CHK_toandland_RTL = new System.Windows.Forms.CheckBox(); this.CHK_toandland = new System.Windows.Forms.CheckBox(); this.label24 = new System.Windows.Forms.Label(); this.NUM_UpDownFlySpeed = new System.Windows.Forms.NumericUpDown(); this.label26 = new System.Windows.Forms.Label(); this.label4 = new System.Windows.Forms.Label(); this.NUM_angle = new System.Windows.Forms.NumericUpDown(); this.CMB_camera = new System.Windows.Forms.ComboBox(); this.CHK_camdirection = new System.Windows.Forms.CheckBox(); this.NUM_altitude = new System.Windows.Forms.NumericUpDown(); this.label1 = new System.Windows.Forms.Label(); this.groupBox4 = new System.Windows.Forms.GroupBox(); this.CHK_advanced = new System.Windows.Forms.CheckBox(); this.CHK_footprints = new System.Windows.Forms.CheckBox(); this.CHK_internals = new System.Windows.Forms.CheckBox(); this.CHK_grid = new System.Windows.Forms.CheckBox(); this.CHK_markers = new System.Windows.Forms.CheckBox(); this.CHK_boundary = new System.Windows.Forms.CheckBox(); this.BUT_Accept = new MissionPlanner.Controls.MyButton(); this.tabControl1 = new System.Windows.Forms.TabControl(); this.map = new MissionPlanner.Controls.myGMAP(); this.TRK_zoom = new MissionPlanner.Controls.MyTrackBar(); this.groupBox5.SuspendLayout(); this.tabCamera.SuspendLayout(); this.groupBox3.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.NUM_repttime)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.num_reptpwm)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.NUM_reptservo)).BeginInit(); this.groupBox2.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.NUM_focallength)).BeginInit(); this.tabGrid.SuspendLayout(); this.groupBox7.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.NUM_Lane_Dist)).BeginInit(); this.groupBox_copter.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.NUM_copter_delay)).BeginInit(); this.groupBox1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.NUM_leadin)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.NUM_spacing)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.NUM_overshoot2)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.num_overlap)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.num_sidelap)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.NUM_overshoot)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.NUM_Distance)).BeginInit(); this.tabSimple.SuspendLayout(); this.groupBox6.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.NUM_split)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.NUM_UpDownFlySpeed)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.NUM_angle)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.NUM_altitude)).BeginInit(); this.groupBox4.SuspendLayout(); this.tabControl1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.TRK_zoom)).BeginInit(); this.SuspendLayout(); // // groupBox5 // this.groupBox5.Controls.Add(this.lbl_turnrad); this.groupBox5.Controls.Add(this.label36); this.groupBox5.Controls.Add(this.lbl_photoevery); this.groupBox5.Controls.Add(this.label35); this.groupBox5.Controls.Add(this.lbl_flighttime); this.groupBox5.Controls.Add(this.label31); this.groupBox5.Controls.Add(this.lbl_distbetweenlines); this.groupBox5.Controls.Add(this.label25); this.groupBox5.Controls.Add(this.lbl_footprint); this.groupBox5.Controls.Add(this.label30); this.groupBox5.Controls.Add(this.lbl_strips); this.groupBox5.Controls.Add(this.lbl_pictures); this.groupBox5.Controls.Add(this.label33); this.groupBox5.Controls.Add(this.label34); this.groupBox5.Controls.Add(this.lbl_grndres); this.groupBox5.Controls.Add(this.label29); this.groupBox5.Controls.Add(this.lbl_spacing); this.groupBox5.Controls.Add(this.label27); this.groupBox5.Controls.Add(this.lbl_distance); this.groupBox5.Controls.Add(this.lbl_area); this.groupBox5.Controls.Add(this.label23); this.groupBox5.Controls.Add(this.label22); resources.ApplyResources(this.groupBox5, "groupBox5"); this.groupBox5.Name = "groupBox5"; this.groupBox5.TabStop = false; // // lbl_turnrad // resources.ApplyResources(this.lbl_turnrad, "lbl_turnrad"); this.lbl_turnrad.Name = "lbl_turnrad"; // // label36 // resources.ApplyResources(this.label36, "label36"); this.label36.Name = "label36"; // // lbl_photoevery // resources.ApplyResources(this.lbl_photoevery, "lbl_photoevery"); this.lbl_photoevery.Name = "lbl_photoevery"; // // label35 // resources.ApplyResources(this.label35, "label35"); this.label35.Name = "label35"; // // lbl_flighttime // resources.ApplyResources(this.lbl_flighttime, "lbl_flighttime"); this.lbl_flighttime.Name = "lbl_flighttime"; // // label31 // resources.ApplyResources(this.label31, "label31"); this.label31.Name = "label31"; // // lbl_distbetweenlines // resources.ApplyResources(this.lbl_distbetweenlines, "lbl_distbetweenlines"); this.lbl_distbetweenlines.Name = "lbl_distbetweenlines"; // // label25 // resources.ApplyResources(this.label25, "label25"); this.label25.Name = "label25"; // // lbl_footprint // resources.ApplyResources(this.lbl_footprint, "lbl_footprint"); this.lbl_footprint.Name = "lbl_footprint"; // // label30 // resources.ApplyResources(this.label30, "label30"); this.label30.Name = "label30"; // // lbl_strips // resources.ApplyResources(this.lbl_strips, "lbl_strips"); this.lbl_strips.Name = "lbl_strips"; // // lbl_pictures // resources.ApplyResources(this.lbl_pictures, "lbl_pictures"); this.lbl_pictures.Name = "lbl_pictures"; // // label33 // resources.ApplyResources(this.label33, "label33"); this.label33.Name = "label33"; // // label34 // resources.ApplyResources(this.label34, "label34"); this.label34.Name = "label34"; // // lbl_grndres // resources.ApplyResources(this.lbl_grndres, "lbl_grndres"); this.lbl_grndres.Name = "lbl_grndres"; // // label29 // resources.ApplyResources(this.label29, "label29"); this.label29.Name = "label29"; // // lbl_spacing // resources.ApplyResources(this.lbl_spacing, "lbl_spacing"); this.lbl_spacing.Name = "lbl_spacing"; // // label27 // resources.ApplyResources(this.label27, "label27"); this.label27.Name = "label27"; // // lbl_distance // resources.ApplyResources(this.lbl_distance, "lbl_distance"); this.lbl_distance.Name = "lbl_distance"; // // lbl_area // resources.ApplyResources(this.lbl_area, "lbl_area"); this.lbl_area.Name = "lbl_area"; // // label23 // resources.ApplyResources(this.label23, "label23"); this.label23.Name = "label23"; // // label22 // resources.ApplyResources(this.label22, "label22"); this.label22.Name = "label22"; // // tabCamera // this.tabCamera.Controls.Add(this.groupBox3); this.tabCamera.Controls.Add(this.groupBox2); resources.ApplyResources(this.tabCamera, "tabCamera"); this.tabCamera.Name = "tabCamera"; this.tabCamera.UseVisualStyleBackColor = true; // // groupBox3 // this.groupBox3.Controls.Add(this.label18); this.groupBox3.Controls.Add(this.label17); this.groupBox3.Controls.Add(this.label16); this.groupBox3.Controls.Add(this.NUM_repttime); this.groupBox3.Controls.Add(this.num_reptpwm); this.groupBox3.Controls.Add(this.NUM_reptservo); this.groupBox3.Controls.Add(this.rad_digicam); this.groupBox3.Controls.Add(this.rad_repeatservo); this.groupBox3.Controls.Add(this.rad_trigdist); resources.ApplyResources(this.groupBox3, "groupBox3"); this.groupBox3.Name = "groupBox3"; this.groupBox3.TabStop = false; // // label18 // resources.ApplyResources(this.label18, "label18"); this.label18.Name = "label18"; // // label17 // resources.ApplyResources(this.label17, "label17"); this.label17.Name = "label17"; // // label16 // resources.ApplyResources(this.label16, "label16"); this.label16.Name = "label16"; // // NUM_repttime // resources.ApplyResources(this.NUM_repttime, "NUM_repttime"); this.NUM_repttime.Maximum = new decimal(new int[] { 5000, 0, 0, 0}); this.NUM_repttime.Minimum = new decimal(new int[] { 1, 0, 0, 0}); this.NUM_repttime.Name = "NUM_repttime"; this.NUM_repttime.Value = new decimal(new int[] { 2, 0, 0, 0}); // // num_reptpwm // resources.ApplyResources(this.num_reptpwm, "num_reptpwm"); this.num_reptpwm.Maximum = new decimal(new int[] { 5000, 0, 0, 0}); this.num_reptpwm.Name = "num_reptpwm"; this.num_reptpwm.Value = new decimal(new int[] { 1100, 0, 0, 0}); // // NUM_reptservo // resources.ApplyResources(this.NUM_reptservo, "NUM_reptservo"); this.NUM_reptservo.Maximum = new decimal(new int[] { 12, 0, 0, 0}); this.NUM_reptservo.Minimum = new decimal(new int[] { 5, 0, 0, 0}); this.NUM_reptservo.Name = "NUM_reptservo"; this.NUM_reptservo.Value = new decimal(new int[] { 5, 0, 0, 0}); // // rad_digicam // resources.ApplyResources(this.rad_digicam, "rad_digicam"); this.rad_digicam.Name = "rad_digicam"; this.rad_digicam.Tag = ""; this.rad_digicam.UseVisualStyleBackColor = true; // // rad_repeatservo // resources.ApplyResources(this.rad_repeatservo, "rad_repeatservo"); this.rad_repeatservo.Name = "rad_repeatservo"; this.rad_repeatservo.Tag = ""; this.rad_repeatservo.UseVisualStyleBackColor = true; // // rad_trigdist // resources.ApplyResources(this.rad_trigdist, "rad_trigdist"); this.rad_trigdist.Checked = true; this.rad_trigdist.Name = "rad_trigdist"; this.rad_trigdist.TabStop = true; this.rad_trigdist.Tag = ""; this.rad_trigdist.UseVisualStyleBackColor = true; // // groupBox2 // resources.ApplyResources(this.groupBox2, "groupBox2"); this.groupBox2.Controls.Add(this.BUT_samplephoto); this.groupBox2.Controls.Add(this.label21); this.groupBox2.Controls.Add(this.label19); this.groupBox2.Controls.Add(this.label20); this.groupBox2.Controls.Add(this.TXT_fovV); this.groupBox2.Controls.Add(this.TXT_fovH); this.groupBox2.Controls.Add(this.label12); this.groupBox2.Controls.Add(this.TXT_cmpixel); this.groupBox2.Controls.Add(this.TXT_sensheight); this.groupBox2.Controls.Add(this.TXT_senswidth); this.groupBox2.Controls.Add(this.TXT_imgheight); this.groupBox2.Controls.Add(this.TXT_imgwidth); this.groupBox2.Controls.Add(this.NUM_focallength); this.groupBox2.Controls.Add(this.label9); this.groupBox2.Controls.Add(this.label10); this.groupBox2.Controls.Add(this.label14); this.groupBox2.Controls.Add(this.label13); this.groupBox2.Controls.Add(this.label11); this.groupBox2.Controls.Add(this.BUT_save); this.groupBox2.Name = "groupBox2"; this.groupBox2.TabStop = false; // // BUT_samplephoto // resources.ApplyResources(this.BUT_samplephoto, "BUT_samplephoto"); this.BUT_samplephoto.Name = "BUT_samplephoto"; this.BUT_samplephoto.UseVisualStyleBackColor = true; this.BUT_samplephoto.Click += new System.EventHandler(this.BUT_samplephoto_Click); // // label21 // resources.ApplyResources(this.label21, "label21"); this.label21.Name = "label21"; // // label19 // resources.ApplyResources(this.label19, "label19"); this.label19.Name = "label19"; // // label20 // resources.ApplyResources(this.label20, "label20"); this.label20.Name = "label20"; // // TXT_fovV // resources.ApplyResources(this.TXT_fovV, "TXT_fovV"); this.TXT_fovV.Name = "TXT_fovV"; // // TXT_fovH // resources.ApplyResources(this.TXT_fovH, "TXT_fovH"); this.TXT_fovH.Name = "TXT_fovH"; // // label12 // resources.ApplyResources(this.label12, "label12"); this.label12.Name = "label12"; // // TXT_cmpixel // resources.ApplyResources(this.TXT_cmpixel, "TXT_cmpixel"); this.TXT_cmpixel.Name = "TXT_cmpixel"; // // TXT_sensheight // resources.ApplyResources(this.TXT_sensheight, "TXT_sensheight"); this.TXT_sensheight.Name = "TXT_sensheight"; this.TXT_sensheight.TextChanged += new System.EventHandler(this.TXT_TextChanged); // // TXT_senswidth // resources.ApplyResources(this.TXT_senswidth, "TXT_senswidth"); this.TXT_senswidth.Name = "TXT_senswidth"; this.TXT_senswidth.TextChanged += new System.EventHandler(this.TXT_TextChanged); // // TXT_imgheight // resources.ApplyResources(this.TXT_imgheight, "TXT_imgheight"); this.TXT_imgheight.Name = "TXT_imgheight"; this.TXT_imgheight.TextChanged += new System.EventHandler(this.TXT_TextChanged); // // TXT_imgwidth // resources.ApplyResources(this.TXT_imgwidth, "TXT_imgwidth"); this.TXT_imgwidth.Name = "TXT_imgwidth"; this.TXT_imgwidth.TextChanged += new System.EventHandler(this.TXT_TextChanged); // // NUM_focallength // this.NUM_focallength.DecimalPlaces = 1; this.NUM_focallength.Increment = new decimal(new int[] { 1, 0, 0, 65536}); resources.ApplyResources(this.NUM_focallength, "NUM_focallength"); this.NUM_focallength.Maximum = new decimal(new int[] { 180, 0, 0, 0}); this.NUM_focallength.Minimum = new decimal(new int[] { 1, 0, 0, 0}); this.NUM_focallength.Name = "NUM_focallength"; this.NUM_focallength.Value = new decimal(new int[] { 5, 0, 0, 0}); this.NUM_focallength.ValueChanged += new System.EventHandler(this.NUM_ValueChanged); // // label9 // resources.ApplyResources(this.label9, "label9"); this.label9.Name = "label9"; // // label10 // resources.ApplyResources(this.label10, "label10"); this.label10.Name = "label10"; // // label14 // resources.ApplyResources(this.label14, "label14"); this.label14.Name = "label14"; // // label13 // resources.ApplyResources(this.label13, "label13"); this.label13.Name = "label13"; // // label11 // resources.ApplyResources(this.label11, "label11"); this.label11.Name = "label11"; // // BUT_save // resources.ApplyResources(this.BUT_save, "BUT_save"); this.BUT_save.Name = "BUT_save"; this.BUT_save.UseVisualStyleBackColor = true; this.BUT_save.Click += new System.EventHandler(this.BUT_save_Click); // // tabGrid // this.tabGrid.Controls.Add(this.groupBox7); this.tabGrid.Controls.Add(this.groupBox_copter); this.tabGrid.Controls.Add(this.groupBox1); resources.ApplyResources(this.tabGrid, "tabGrid"); this.tabGrid.Name = "tabGrid"; this.tabGrid.UseVisualStyleBackColor = true; // // groupBox7 // resources.ApplyResources(this.groupBox7, "groupBox7"); this.groupBox7.Controls.Add(this.LBL_Alternating_lanes); this.groupBox7.Controls.Add(this.LBL_Lane_Dist); this.groupBox7.Controls.Add(this.NUM_Lane_Dist); this.groupBox7.Controls.Add(this.label28); this.groupBox7.Name = "groupBox7"; this.groupBox7.TabStop = false; // // LBL_Alternating_lanes // resources.ApplyResources(this.LBL_Alternating_lanes, "LBL_Alternating_lanes"); this.LBL_Alternating_lanes.Name = "LBL_Alternating_lanes"; // // LBL_Lane_Dist // resources.ApplyResources(this.LBL_Lane_Dist, "LBL_Lane_Dist"); this.LBL_Lane_Dist.Name = "LBL_Lane_Dist"; // // NUM_Lane_Dist // resources.ApplyResources(this.NUM_Lane_Dist, "NUM_Lane_Dist"); this.NUM_Lane_Dist.Maximum = new decimal(new int[] { 9999, 0, 0, 0}); this.NUM_Lane_Dist.Name = "NUM_Lane_Dist"; this.NUM_Lane_Dist.ValueChanged += new System.EventHandler(this.NUM_Lane_Dist_ValueChanged); // // label28 // resources.ApplyResources(this.label28, "label28"); this.label28.Name = "label28"; // // groupBox_copter // resources.ApplyResources(this.groupBox_copter, "groupBox_copter"); this.groupBox_copter.Controls.Add(this.TXT_headinghold); this.groupBox_copter.Controls.Add(this.BUT_headingholdminus); this.groupBox_copter.Controls.Add(this.BUT_headingholdplus); this.groupBox_copter.Controls.Add(this.CHK_copter_headingholdlock); this.groupBox_copter.Controls.Add(this.CHK_copter_headinghold); this.groupBox_copter.Controls.Add(this.LBL_copter_delay); this.groupBox_copter.Controls.Add(this.NUM_copter_delay); this.groupBox_copter.Name = "groupBox_copter"; this.groupBox_copter.TabStop = false; // // TXT_headinghold // resources.ApplyResources(this.TXT_headinghold, "TXT_headinghold"); this.TXT_headinghold.Name = "TXT_headinghold"; this.TXT_headinghold.ReadOnly = true; // // BUT_headingholdminus // resources.ApplyResources(this.BUT_headingholdminus, "BUT_headingholdminus"); this.BUT_headingholdminus.Name = "BUT_headingholdminus"; this.BUT_headingholdminus.UseVisualStyleBackColor = true; this.BUT_headingholdminus.Click += new System.EventHandler(this.BUT_headingholdminus_Click); // // BUT_headingholdplus // resources.ApplyResources(this.BUT_headingholdplus, "BUT_headingholdplus"); this.BUT_headingholdplus.Name = "BUT_headingholdplus"; this.BUT_headingholdplus.UseVisualStyleBackColor = true; this.BUT_headingholdplus.Click += new System.EventHandler(this.BUT_headingholdplus_Click); // // CHK_copter_headingholdlock // resources.ApplyResources(this.CHK_copter_headingholdlock, "CHK_copter_headingholdlock"); this.CHK_copter_headingholdlock.Name = "CHK_copter_headingholdlock"; this.CHK_copter_headingholdlock.UseVisualStyleBackColor = true; this.CHK_copter_headingholdlock.CheckedChanged += new System.EventHandler(this.CHK_copter_headingholdlock_CheckedChanged); // // CHK_copter_headinghold // resources.ApplyResources(this.CHK_copter_headinghold, "CHK_copter_headinghold"); this.CHK_copter_headinghold.Name = "CHK_copter_headinghold"; this.CHK_copter_headinghold.UseVisualStyleBackColor = true; this.CHK_copter_headinghold.CheckedChanged += new System.EventHandler(this.CHK_copter_headinghold_CheckedChanged); // // LBL_copter_delay // resources.ApplyResources(this.LBL_copter_delay, "LBL_copter_delay"); this.LBL_copter_delay.Name = "LBL_copter_delay"; // // NUM_copter_delay // this.NUM_copter_delay.DecimalPlaces = 1; this.NUM_copter_delay.Increment = new decimal(new int[] { 1, 0, 0, 65536}); resources.ApplyResources(this.NUM_copter_delay, "NUM_copter_delay"); this.NUM_copter_delay.Maximum = new decimal(new int[] { 9999, 0, 0, 0}); this.NUM_copter_delay.Name = "NUM_copter_delay"; // // groupBox1 // resources.ApplyResources(this.groupBox1, "groupBox1"); this.groupBox1.Controls.Add(this.label32); this.groupBox1.Controls.Add(this.NUM_leadin); this.groupBox1.Controls.Add(this.label3); this.groupBox1.Controls.Add(this.NUM_spacing); this.groupBox1.Controls.Add(this.label7); this.groupBox1.Controls.Add(this.NUM_overshoot2); this.groupBox1.Controls.Add(this.label8); this.groupBox1.Controls.Add(this.label6); this.groupBox1.Controls.Add(this.label15); this.groupBox1.Controls.Add(this.CMB_startfrom); this.groupBox1.Controls.Add(this.num_overlap); this.groupBox1.Controls.Add(this.num_sidelap); this.groupBox1.Controls.Add(this.label5); this.groupBox1.Controls.Add(this.NUM_overshoot); this.groupBox1.Controls.Add(this.label2); this.groupBox1.Controls.Add(this.NUM_Distance); this.groupBox1.Name = "groupBox1"; this.groupBox1.TabStop = false; // // label32 // resources.ApplyResources(this.label32, "label32"); this.label32.Name = "label32"; // // NUM_leadin // resources.ApplyResources(this.NUM_leadin, "NUM_leadin"); this.NUM_leadin.Maximum = new decimal(new int[] { 9999, 0, 0, 0}); this.NUM_leadin.Name = "NUM_leadin"; this.NUM_leadin.ValueChanged += new System.EventHandler(this.domainUpDown1_ValueChanged); // // label3 // resources.ApplyResources(this.label3, "label3"); this.label3.Name = "label3"; // // NUM_spacing // resources.ApplyResources(this.NUM_spacing, "NUM_spacing"); this.NUM_spacing.Maximum = new decimal(new int[] { 5000, 0, 0, 0}); this.NUM_spacing.Name = "NUM_spacing"; this.NUM_spacing.ValueChanged += new System.EventHandler(this.domainUpDown1_ValueChanged); // // label7 // resources.ApplyResources(this.label7, "label7"); this.label7.Name = "label7"; // // NUM_overshoot2 // resources.ApplyResources(this.NUM_overshoot2, "NUM_overshoot2"); this.NUM_overshoot2.Maximum = new decimal(new int[] { 9999, 0, 0, 0}); this.NUM_overshoot2.Name = "NUM_overshoot2"; this.NUM_overshoot2.ValueChanged += new System.EventHandler(this.domainUpDown1_ValueChanged); // // label8 // resources.ApplyResources(this.label8, "label8"); this.label8.Name = "label8"; // // label6 // resources.ApplyResources(this.label6, "label6"); this.label6.Name = "label6"; // // label15 // resources.ApplyResources(this.label15, "label15"); this.label15.Name = "label15"; // // CMB_startfrom // this.CMB_startfrom.FormattingEnabled = true; resources.ApplyResources(this.CMB_startfrom, "CMB_startfrom"); this.CMB_startfrom.Name = "CMB_startfrom"; this.CMB_startfrom.SelectedIndexChanged += new System.EventHandler(this.domainUpDown1_ValueChanged); // // num_overlap // this.num_overlap.DecimalPlaces = 1; resources.ApplyResources(this.num_overlap, "num_overlap"); this.num_overlap.Name = "num_overlap"; this.num_overlap.Value = new decimal(new int[] { 50, 0, 0, 0}); this.num_overlap.ValueChanged += new System.EventHandler(this.NUM_ValueChanged); // // num_sidelap // this.num_sidelap.DecimalPlaces = 1; resources.ApplyResources(this.num_sidelap, "num_sidelap"); this.num_sidelap.Name = "num_sidelap"; this.num_sidelap.Value = new decimal(new int[] { 60, 0, 0, 0}); this.num_sidelap.ValueChanged += new System.EventHandler(this.NUM_ValueChanged); // // label5 // resources.ApplyResources(this.label5, "label5"); this.label5.Name = "label5"; // // NUM_overshoot // resources.ApplyResources(this.NUM_overshoot, "NUM_overshoot"); this.NUM_overshoot.Maximum = new decimal(new int[] { 9999, 0, 0, 0}); this.NUM_overshoot.Name = "NUM_overshoot"; this.NUM_overshoot.ValueChanged += new System.EventHandler(this.domainUpDown1_ValueChanged); // // label2 // resources.ApplyResources(this.label2, "label2"); this.label2.Name = "label2"; // // NUM_Distance // this.NUM_Distance.DecimalPlaces = 2; resources.ApplyResources(this.NUM_Distance, "NUM_Distance"); this.NUM_Distance.Maximum = new decimal(new int[] { 9999, 0, 0, 0}); this.NUM_Distance.Minimum = new decimal(new int[] { 3, 0, 0, 65536}); this.NUM_Distance.Name = "NUM_Distance"; this.NUM_Distance.Value = new decimal(new int[] { 50, 0, 0, 0}); this.NUM_Distance.ValueChanged += new System.EventHandler(this.domainUpDown1_ValueChanged); // // tabSimple // this.tabSimple.Controls.Add(this.groupBox6); this.tabSimple.Controls.Add(this.groupBox4); this.tabSimple.Controls.Add(this.BUT_Accept); resources.ApplyResources(this.tabSimple, "tabSimple"); this.tabSimple.Name = "tabSimple"; this.tabSimple.UseVisualStyleBackColor = true; // // groupBox6 // this.groupBox6.Controls.Add(this.label37); this.groupBox6.Controls.Add(this.NUM_split); this.groupBox6.Controls.Add(this.CHK_usespeed); this.groupBox6.Controls.Add(this.CHK_toandland_RTL); this.groupBox6.Controls.Add(this.CHK_toandland); this.groupBox6.Controls.Add(this.label24); this.groupBox6.Controls.Add(this.NUM_UpDownFlySpeed); this.groupBox6.Controls.Add(this.label26); this.groupBox6.Controls.Add(this.label4); this.groupBox6.Controls.Add(this.NUM_angle); this.groupBox6.Controls.Add(this.CMB_camera); this.groupBox6.Controls.Add(this.CHK_camdirection); this.groupBox6.Controls.Add(this.NUM_altitude); this.groupBox6.Controls.Add(this.label1); resources.ApplyResources(this.groupBox6, "groupBox6"); this.groupBox6.Name = "groupBox6"; this.groupBox6.TabStop = false; // // label37 // resources.ApplyResources(this.label37, "label37"); this.label37.Name = "label37"; // // NUM_split // resources.ApplyResources(this.NUM_split, "NUM_split"); this.NUM_split.Maximum = new decimal(new int[] { 300, 0, 0, 0}); this.NUM_split.Minimum = new decimal(new int[] { 1, 0, 0, 0}); this.NUM_split.Name = "NUM_split"; this.NUM_split.Value = new decimal(new int[] { 1, 0, 0, 0}); this.NUM_split.ValueChanged += new System.EventHandler(this.domainUpDown1_ValueChanged); // // CHK_usespeed // resources.ApplyResources(this.CHK_usespeed, "CHK_usespeed"); this.CHK_usespeed.Name = "CHK_usespeed"; this.CHK_usespeed.UseVisualStyleBackColor = true; // // CHK_toandland_RTL // resources.ApplyResources(this.CHK_toandland_RTL, "CHK_toandland_RTL"); this.CHK_toandland_RTL.Checked = true; this.CHK_toandland_RTL.CheckState = System.Windows.Forms.CheckState.Checked; this.CHK_toandland_RTL.Name = "CHK_toandland_RTL"; this.CHK_toandland_RTL.UseVisualStyleBackColor = true; // // CHK_toandland // resources.ApplyResources(this.CHK_toandland, "CHK_toandland"); this.CHK_toandland.Checked = true; this.CHK_toandland.CheckState = System.Windows.Forms.CheckState.Checked; this.CHK_toandland.Name = "CHK_toandland"; this.CHK_toandland.UseVisualStyleBackColor = true; // // label24 // resources.ApplyResources(this.label24, "label24"); this.label24.Name = "label24"; // // NUM_UpDownFlySpeed // resources.ApplyResources(this.NUM_UpDownFlySpeed, "NUM_UpDownFlySpeed"); this.NUM_UpDownFlySpeed.Maximum = new decimal(new int[] { 360, 0, 0, 0}); this.NUM_UpDownFlySpeed.Name = "NUM_UpDownFlySpeed"; this.NUM_UpDownFlySpeed.Value = new decimal(new int[] { 5, 0, 0, 0}); this.NUM_UpDownFlySpeed.ValueChanged += new System.EventHandler(this.domainUpDown1_ValueChanged); // // label26 // resources.ApplyResources(this.label26, "label26"); this.label26.Name = "label26"; // // label4 // resources.ApplyResources(this.label4, "label4"); this.label4.Name = "label4"; // // NUM_angle // resources.ApplyResources(this.NUM_angle, "NUM_angle"); this.NUM_angle.Maximum = new decimal(new int[] { 360, 0, 0, 0}); this.NUM_angle.Name = "NUM_angle"; this.NUM_angle.ValueChanged += new System.EventHandler(this.domainUpDown1_ValueChanged); // // CMB_camera // this.CMB_camera.FormattingEnabled = true; resources.ApplyResources(this.CMB_camera, "CMB_camera"); this.CMB_camera.Name = "CMB_camera"; this.CMB_camera.SelectedIndexChanged += new System.EventHandler(this.CMB_camera_SelectedIndexChanged); // // CHK_camdirection // resources.ApplyResources(this.CHK_camdirection, "CHK_camdirection"); this.CHK_camdirection.Checked = true; this.CHK_camdirection.CheckState = System.Windows.Forms.CheckState.Checked; this.CHK_camdirection.Name = "CHK_camdirection"; this.CHK_camdirection.UseVisualStyleBackColor = true; this.CHK_camdirection.CheckedChanged += new System.EventHandler(this.CHK_camdirection_CheckedChanged); // // NUM_altitude // this.NUM_altitude.Increment = new decimal(new int[] { 10, 0, 0, 0}); resources.ApplyResources(this.NUM_altitude, "NUM_altitude"); this.NUM_altitude.Maximum = new decimal(new int[] { 9999, 0, 0, 0}); this.NUM_altitude.Minimum = new decimal(new int[] { 5, 0, 0, 0}); this.NUM_altitude.Name = "NUM_altitude"; this.NUM_altitude.Value = new decimal(new int[] { 100, 0, 0, 0}); this.NUM_altitude.ValueChanged += new System.EventHandler(this.domainUpDown1_ValueChanged); // // label1 // resources.ApplyResources(this.label1, "label1"); this.label1.Name = "label1"; // // groupBox4 // this.groupBox4.Controls.Add(this.CHK_advanced); this.groupBox4.Controls.Add(this.CHK_footprints); this.groupBox4.Controls.Add(this.CHK_internals); this.groupBox4.Controls.Add(this.CHK_grid); this.groupBox4.Controls.Add(this.CHK_markers); this.groupBox4.Controls.Add(this.CHK_boundary); resources.ApplyResources(this.groupBox4, "groupBox4"); this.groupBox4.Name = "groupBox4"; this.groupBox4.TabStop = false; // // CHK_advanced // resources.ApplyResources(this.CHK_advanced, "CHK_advanced"); this.CHK_advanced.Name = "CHK_advanced"; this.CHK_advanced.UseVisualStyleBackColor = true; this.CHK_advanced.CheckedChanged += new System.EventHandler(this.CHK_advanced_CheckedChanged); // // CHK_footprints // resources.ApplyResources(this.CHK_footprints, "CHK_footprints"); this.CHK_footprints.Name = "CHK_footprints"; this.CHK_footprints.UseVisualStyleBackColor = true; this.CHK_footprints.CheckedChanged += new System.EventHandler(this.domainUpDown1_ValueChanged); // // CHK_internals // resources.ApplyResources(this.CHK_internals, "CHK_internals"); this.CHK_internals.Name = "CHK_internals"; this.CHK_internals.UseVisualStyleBackColor = true; this.CHK_internals.CheckedChanged += new System.EventHandler(this.domainUpDown1_ValueChanged); // // CHK_grid // resources.ApplyResources(this.CHK_grid, "CHK_grid"); this.CHK_grid.Checked = true; this.CHK_grid.CheckState = System.Windows.Forms.CheckState.Checked; this.CHK_grid.Name = "CHK_grid"; this.CHK_grid.UseVisualStyleBackColor = true; this.CHK_grid.CheckedChanged += new System.EventHandler(this.domainUpDown1_ValueChanged); // // CHK_markers // resources.ApplyResources(this.CHK_markers, "CHK_markers"); this.CHK_markers.Checked = true; this.CHK_markers.CheckState = System.Windows.Forms.CheckState.Checked; this.CHK_markers.Name = "CHK_markers"; this.CHK_markers.UseVisualStyleBackColor = true; this.CHK_markers.CheckedChanged += new System.EventHandler(this.domainUpDown1_ValueChanged); // // CHK_boundary // resources.ApplyResources(this.CHK_boundary, "CHK_boundary"); this.CHK_boundary.Checked = true; this.CHK_boundary.CheckState = System.Windows.Forms.CheckState.Checked; this.CHK_boundary.Name = "CHK_boundary"; this.CHK_boundary.UseVisualStyleBackColor = true; this.CHK_boundary.CheckedChanged += new System.EventHandler(this.domainUpDown1_ValueChanged); // // BUT_Accept // resources.ApplyResources(this.BUT_Accept, "BUT_Accept"); this.BUT_Accept.Name = "BUT_Accept"; this.BUT_Accept.UseVisualStyleBackColor = true; this.BUT_Accept.Click += new System.EventHandler(this.BUT_Accept_Click); // // tabControl1 // this.tabControl1.Controls.Add(this.tabSimple); this.tabControl1.Controls.Add(this.tabGrid); this.tabControl1.Controls.Add(this.tabCamera); resources.ApplyResources(this.tabControl1, "tabControl1"); this.tabControl1.Name = "tabControl1"; this.tabControl1.SelectedIndex = 0; // // map // resources.ApplyResources(this.map, "map"); this.map.Bearing = 0F; this.map.CanDragMap = true; this.map.EmptyTileColor = System.Drawing.Color.Gray; this.map.GrayScaleMode = false; this.map.HelperLineOption = GMap.NET.WindowsForms.HelperLineOptions.DontShow; this.map.LevelsKeepInMemmory = 5; this.map.MarkersEnabled = true; this.map.MaxZoom = 19; this.map.MinZoom = 2; this.map.MouseWheelZoomType = GMap.NET.MouseWheelZoomType.MousePositionAndCenter; this.map.Name = "map"; this.map.NegativeMode = false; this.map.PolygonsEnabled = true; this.map.RetryLoadTile = 0; this.map.RoutesEnabled = true; this.map.ScaleMode = GMap.NET.WindowsForms.ScaleModes.Fractional; this.map.SelectedAreaFillColor = System.Drawing.Color.FromArgb(((int)(((byte)(33)))), ((int)(((byte)(65)))), ((int)(((byte)(105)))), ((int)(((byte)(225))))); this.map.ShowTileGridLines = false; this.map.Zoom = 3D; this.map.MouseDown += new System.Windows.Forms.MouseEventHandler(this.map_MouseDown); this.map.MouseMove += new System.Windows.Forms.MouseEventHandler(this.map_MouseMove); // // TRK_zoom // resources.ApplyResources(this.TRK_zoom, "TRK_zoom"); this.TRK_zoom.LargeChange = 0.005F; this.TRK_zoom.Maximum = 19F; this.TRK_zoom.Minimum = 2F; this.TRK_zoom.Name = "TRK_zoom"; this.TRK_zoom.SmallChange = 0.001F; this.TRK_zoom.TickFrequency = 1F; this.TRK_zoom.TickStyle = System.Windows.Forms.TickStyle.TopLeft; this.TRK_zoom.Value = 2F; this.TRK_zoom.Scroll += new System.EventHandler(this.trackBar1_Scroll); // // GridUI // this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.None; resources.ApplyResources(this, "$this"); this.Controls.Add(this.TRK_zoom); this.Controls.Add(this.map); this.Controls.Add(this.groupBox5); this.Controls.Add(this.tabControl1); this.Name = "GridUI"; this.Load += new System.EventHandler(this.GridUI_Load); this.Resize += new System.EventHandler(this.GridUI_Resize); this.groupBox5.ResumeLayout(false); this.groupBox5.PerformLayout(); this.tabCamera.ResumeLayout(false); this.groupBox3.ResumeLayout(false); this.groupBox3.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.NUM_repttime)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.num_reptpwm)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.NUM_reptservo)).EndInit(); this.groupBox2.ResumeLayout(false); this.groupBox2.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.NUM_focallength)).EndInit(); this.tabGrid.ResumeLayout(false); this.groupBox7.ResumeLayout(false); this.groupBox7.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.NUM_Lane_Dist)).EndInit(); this.groupBox_copter.ResumeLayout(false); this.groupBox_copter.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.NUM_copter_delay)).EndInit(); this.groupBox1.ResumeLayout(false); this.groupBox1.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.NUM_leadin)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.NUM_spacing)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.NUM_overshoot2)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.num_overlap)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.num_sidelap)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.NUM_overshoot)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.NUM_Distance)).EndInit(); this.tabSimple.ResumeLayout(false); this.groupBox6.ResumeLayout(false); this.groupBox6.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.NUM_split)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.NUM_UpDownFlySpeed)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.NUM_angle)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.NUM_altitude)).EndInit(); this.groupBox4.ResumeLayout(false); this.groupBox4.PerformLayout(); this.tabControl1.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.TRK_zoom)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private Controls.myGMAP map; private System.Windows.Forms.GroupBox groupBox5; private System.Windows.Forms.Label label22; private System.Windows.Forms.Label label23; private System.Windows.Forms.Label lbl_distance; private System.Windows.Forms.Label lbl_area; private System.Windows.Forms.Label lbl_spacing; private System.Windows.Forms.Label label27; private System.Windows.Forms.Label lbl_grndres; private System.Windows.Forms.Label label29; private System.Windows.Forms.Label lbl_distbetweenlines; private System.Windows.Forms.Label label25; private System.Windows.Forms.Label lbl_footprint; private System.Windows.Forms.Label label30; private System.Windows.Forms.Label lbl_strips; private System.Windows.Forms.Label lbl_pictures; private System.Windows.Forms.Label label33; private System.Windows.Forms.Label label34; private System.Windows.Forms.Label lbl_flighttime; private System.Windows.Forms.Label label31; private System.Windows.Forms.Label lbl_photoevery; private System.Windows.Forms.Label label35; private System.Windows.Forms.TabPage tabCamera; private System.Windows.Forms.GroupBox groupBox3; private System.Windows.Forms.Label label18; private System.Windows.Forms.Label label17; private System.Windows.Forms.Label label16; private System.Windows.Forms.NumericUpDown NUM_repttime; private System.Windows.Forms.NumericUpDown num_reptpwm; private System.Windows.Forms.NumericUpDown NUM_reptservo; private System.Windows.Forms.RadioButton rad_digicam; private System.Windows.Forms.RadioButton rad_repeatservo; private System.Windows.Forms.RadioButton rad_trigdist; private System.Windows.Forms.GroupBox groupBox2; private Controls.MyButton BUT_samplephoto; private System.Windows.Forms.Label label21; private System.Windows.Forms.Label label19; private System.Windows.Forms.Label label20; private System.Windows.Forms.TextBox TXT_fovV; private System.Windows.Forms.TextBox TXT_fovH; private System.Windows.Forms.Label label12; private System.Windows.Forms.TextBox TXT_cmpixel; private System.Windows.Forms.TextBox TXT_sensheight; private System.Windows.Forms.TextBox TXT_senswidth; private System.Windows.Forms.TextBox TXT_imgheight; private System.Windows.Forms.TextBox TXT_imgwidth; private System.Windows.Forms.NumericUpDown NUM_focallength; private System.Windows.Forms.Label label9; private System.Windows.Forms.Label label10; private System.Windows.Forms.Label label14; private System.Windows.Forms.Label label13; private System.Windows.Forms.Label label11; private Controls.MyButton BUT_save; private System.Windows.Forms.TabPage tabGrid; private System.Windows.Forms.GroupBox groupBox_copter; private System.Windows.Forms.CheckBox CHK_copter_headinghold; private System.Windows.Forms.Label LBL_copter_delay; private System.Windows.Forms.NumericUpDown NUM_copter_delay; private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.Label label3; private System.Windows.Forms.NumericUpDown NUM_spacing; private System.Windows.Forms.Label label7; private System.Windows.Forms.NumericUpDown NUM_overshoot2; private System.Windows.Forms.Label label8; private System.Windows.Forms.Label label6; private System.Windows.Forms.Label label15; private System.Windows.Forms.ComboBox CMB_startfrom; private System.Windows.Forms.NumericUpDown num_overlap; private System.Windows.Forms.NumericUpDown num_sidelap; private System.Windows.Forms.Label label5; private System.Windows.Forms.NumericUpDown NUM_overshoot; private System.Windows.Forms.Label label2; private System.Windows.Forms.NumericUpDown NUM_Distance; private System.Windows.Forms.TabPage tabSimple; private System.Windows.Forms.GroupBox groupBox6; private System.Windows.Forms.CheckBox CHK_usespeed; private System.Windows.Forms.CheckBox CHK_toandland_RTL; private System.Windows.Forms.CheckBox CHK_toandland; private System.Windows.Forms.Label label24; private System.Windows.Forms.NumericUpDown NUM_UpDownFlySpeed; private System.Windows.Forms.Label label26; private System.Windows.Forms.Label label4; private System.Windows.Forms.NumericUpDown NUM_angle; private System.Windows.Forms.ComboBox CMB_camera; private System.Windows.Forms.CheckBox CHK_camdirection; private System.Windows.Forms.NumericUpDown NUM_altitude; private System.Windows.Forms.Label label1; private System.Windows.Forms.GroupBox groupBox4; private System.Windows.Forms.CheckBox CHK_advanced; private System.Windows.Forms.CheckBox CHK_footprints; private System.Windows.Forms.CheckBox CHK_internals; private System.Windows.Forms.CheckBox CHK_grid; private System.Windows.Forms.CheckBox CHK_markers; private System.Windows.Forms.CheckBox CHK_boundary; private Controls.MyButton BUT_Accept; private System.Windows.Forms.TabControl tabControl1; private Controls.MyTrackBar TRK_zoom; private System.Windows.Forms.CheckBox CHK_copter_headingholdlock; private System.Windows.Forms.TextBox TXT_headinghold; private System.Windows.Forms.Button BUT_headingholdminus; private System.Windows.Forms.Button BUT_headingholdplus; private System.Windows.Forms.GroupBox groupBox7; private System.Windows.Forms.Label label28; private System.Windows.Forms.Label LBL_Lane_Dist; private System.Windows.Forms.NumericUpDown NUM_Lane_Dist; private System.Windows.Forms.Label LBL_Alternating_lanes; private System.Windows.Forms.Label lbl_turnrad; private System.Windows.Forms.Label label36; private System.Windows.Forms.Label label32; private System.Windows.Forms.NumericUpDown NUM_leadin; private System.Windows.Forms.Label label37; private System.Windows.Forms.NumericUpDown NUM_split; } }
marcoarruda/MissionPlanner
ExtLibs/Grid/GridUI.Designer.cs
C#
gpl-3.0
60,645
/* eslint-disable jest/no-export, jest/no-disabled-tests */ /** * Internal dependencies */ const { shopper, merchant, createVariableProduct, } = require( '@woocommerce/e2e-utils' ); let variablePostIdValue; const cartDialogMessage = 'Please select some product options before adding this product to your cart.'; const runVariableProductUpdateTest = () => { describe('Shopper > Update variable product',() => { beforeAll(async () => { await merchant.login(); variablePostIdValue = await createVariableProduct(); await merchant.logout(); }); it('shopper can change variable attributes to the same value', async () => { await shopper.goToProduct(variablePostIdValue); await expect(page).toSelect('#attr-1', 'val1'); await expect(page).toSelect('#attr-2', 'val1'); await expect(page).toSelect('#attr-3', 'val1'); await expect(page).toMatchElement('.woocommerce-variation-price', { text: '9.99' }); }); it('shopper can change attributes to combination with dimensions and weight', async () => { await shopper.goToProduct(variablePostIdValue); await expect(page).toSelect('#attr-1', 'val1'); await expect(page).toSelect('#attr-2', 'val2'); await expect(page).toSelect('#attr-3', 'val1'); await expect(page).toMatchElement('.woocommerce-variation-price', { text: '20.00' }); await expect(page).toMatchElement('.woocommerce-variation-availability', { text: 'Out of stock' }); await expect(page).toMatchElement('.woocommerce-product-attributes-item--weight', { text: '200 kg' }); await expect(page).toMatchElement('.woocommerce-product-attributes-item--dimensions', { text: '10 × 20 × 15 cm' }); }); it('shopper can change variable product attributes to variation with a different price', async () => { await shopper.goToProduct(variablePostIdValue); await expect(page).toSelect('#attr-1', 'val1'); await expect(page).toSelect('#attr-2', 'val1'); await expect(page).toSelect('#attr-3', 'val2'); await expect(page).toMatchElement('.woocommerce-variation-price', { text: '11.99' }); }); it('shopper can reset variations', async () => { await shopper.goToProduct(variablePostIdValue); await expect(page).toSelect('#attr-1', 'val1'); await expect(page).toSelect('#attr-2', 'val2'); await expect(page).toSelect('#attr-3', 'val1'); await expect(page).toClick('.reset_variations'); // Verify the reset by attempting to add the product to the cart const couponDialog = await expect(page).toDisplayDialog(async () => { await expect(page).toClick('.single_add_to_cart_button'); }); expect(couponDialog.message()).toMatch(cartDialogMessage); // Accept the dialog await couponDialog.accept(); }); }); }; module.exports = runVariableProductUpdateTest;
Ninos/woocommerce
tests/e2e/core-tests/specs/shopper/front-end-variable-product-updates.test.js
JavaScript
gpl-3.0
2,776
<?php /* * Copyright 2014 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ class Google_Service_DataFusion_DataAccessOptions extends Google_Model { public $logMode; public function setLogMode($logMode) { $this->logMode = $logMode; } public function getLogMode() { return $this->logMode; } }
Merrick28/delain
web/vendor/google/apiclient-services/src/Google/Service/DataFusion/DataAccessOptions.php
PHP
gpl-3.0
837
package module // no syscall.Stat_t on windows, return 0 for inodes func inode(path string) (uint64, error) { return 0, nil }
grange74/terraform
config/module/inode_windows.go
GO
mpl-2.0
128
package profitbricks import ( "encoding/json" "errors" "fmt" "strconv" "strings" "time" "github.com/hashicorp/packer/packer" "github.com/mitchellh/multistep" "github.com/profitbricks/profitbricks-sdk-go" ) type stepCreateServer struct{} func (s *stepCreateServer) Run(state multistep.StateBag) multistep.StepAction { ui := state.Get("ui").(packer.Ui) c := state.Get("config").(*Config) profitbricks.SetAuth(c.PBUsername, c.PBPassword) profitbricks.SetDepth("5") if sshkey, ok := state.GetOk("publicKey"); ok { c.SSHKey = sshkey.(string) } ui.Say("Creating Virtual Data Center...") img := s.getImageId(c.Image, c) datacenter := profitbricks.Datacenter{ Properties: profitbricks.DatacenterProperties{ Name: c.SnapshotName, Location: c.Region, }, Entities: profitbricks.DatacenterEntities{ Servers: &profitbricks.Servers{ Items: []profitbricks.Server{ { Properties: profitbricks.ServerProperties{ Name: c.SnapshotName, Ram: c.Ram, Cores: c.Cores, }, Entities: &profitbricks.ServerEntities{ Volumes: &profitbricks.Volumes{ Items: []profitbricks.Volume{ { Properties: profitbricks.VolumeProperties{ Type: c.DiskType, Size: c.DiskSize, Name: c.SnapshotName, Image: img, }, }, }, }, }, }, }, }, }, } if c.SSHKey != "" { datacenter.Entities.Servers.Items[0].Entities.Volumes.Items[0].Properties.SshKeys = []string{c.SSHKey} } if c.Comm.SSHPassword != "" { datacenter.Entities.Servers.Items[0].Entities.Volumes.Items[0].Properties.ImagePassword = c.Comm.SSHPassword } datacenter = profitbricks.CompositeCreateDatacenter(datacenter) if datacenter.StatusCode > 299 { if datacenter.StatusCode > 299 { var restError RestError err := json.Unmarshal([]byte(datacenter.Response), &restError) if err != nil { ui.Error(fmt.Sprintf("Error decoding json response: %s", err.Error())) return multistep.ActionHalt } if len(restError.Messages) > 0 { ui.Error(restError.Messages[0].Message) } else { ui.Error(datacenter.Response) } return multistep.ActionHalt } } err := s.waitTillProvisioned(datacenter.Headers.Get("Location"), *c) if err != nil { ui.Error(fmt.Sprintf("Error occurred while creating a datacenter %s", err.Error())) return multistep.ActionHalt } state.Put("datacenter_id", datacenter.Id) lan := profitbricks.CreateLan(datacenter.Id, profitbricks.Lan{ Properties: profitbricks.LanProperties{ Public: true, Name: c.SnapshotName, }, }) if lan.StatusCode > 299 { ui.Error(fmt.Sprintf("Error occurred %s", parseErrorMessage(lan.Response))) return multistep.ActionHalt } err = s.waitTillProvisioned(lan.Headers.Get("Location"), *c) if err != nil { ui.Error(fmt.Sprintf("Error occurred while creating a LAN %s", err.Error())) return multistep.ActionHalt } lanId, _ := strconv.Atoi(lan.Id) nic := profitbricks.CreateNic(datacenter.Id, datacenter.Entities.Servers.Items[0].Id, profitbricks.Nic{ Properties: profitbricks.NicProperties{ Name: c.SnapshotName, Lan: lanId, Dhcp: true, }, }) if lan.StatusCode > 299 { ui.Error(fmt.Sprintf("Error occurred %s", parseErrorMessage(nic.Response))) return multistep.ActionHalt } err = s.waitTillProvisioned(nic.Headers.Get("Location"), *c) if err != nil { ui.Error(fmt.Sprintf("Error occurred while creating a NIC %s", err.Error())) return multistep.ActionHalt } state.Put("volume_id", datacenter.Entities.Servers.Items[0].Entities.Volumes.Items[0].Id) server := profitbricks.GetServer(datacenter.Id, datacenter.Entities.Servers.Items[0].Id) state.Put("server_ip", server.Entities.Nics.Items[0].Properties.Ips[0]) return multistep.ActionContinue } func (s *stepCreateServer) Cleanup(state multistep.StateBag) { c := state.Get("config").(*Config) ui := state.Get("ui").(packer.Ui) ui.Say("Removing Virtual Data Center...") profitbricks.SetAuth(c.PBUsername, c.PBPassword) if dcId, ok := state.GetOk("datacenter_id"); ok { resp := profitbricks.DeleteDatacenter(dcId.(string)) if err := s.checkForErrors(resp); err != nil { ui.Error(fmt.Sprintf( "Error deleting Virtual Data Center. Please destroy it manually: %s", err)) } if err := s.waitTillProvisioned(resp.Headers.Get("Location"), *c); err != nil { ui.Error(fmt.Sprintf( "Error deleting Virtual Data Center. Please destroy it manually: %s", err)) } } } func (d *stepCreateServer) waitTillProvisioned(path string, config Config) error { d.setPB(config.PBUsername, config.PBPassword, config.PBUrl) waitCount := 120 if config.Retries > 0 { waitCount = config.Retries } for i := 0; i < waitCount; i++ { request := profitbricks.GetRequestStatus(path) if request.Metadata.Status == "DONE" { return nil } if request.Metadata.Status == "FAILED" { return errors.New(request.Metadata.Message) } time.Sleep(1 * time.Second) i++ } return nil } func (d *stepCreateServer) setPB(username string, password string, url string) { profitbricks.SetAuth(username, password) profitbricks.SetEndpoint(url) } func (d *stepCreateServer) checkForErrors(instance profitbricks.Resp) error { if instance.StatusCode > 299 { return errors.New(fmt.Sprintf("Error occurred %s", string(instance.Body))) } return nil } type RestError struct { HttpStatus int `json:"httpStatus,omitempty"` Messages []Message `json:"messages,omitempty"` } type Message struct { ErrorCode string `json:"errorCode,omitempty"` Message string `json:"message,omitempty"` } func (d *stepCreateServer) getImageId(imageName string, c *Config) string { d.setPB(c.PBUsername, c.PBPassword, c.PBUrl) images := profitbricks.ListImages() for i := 0; i < len(images.Items); i++ { imgName := "" if images.Items[i].Properties.Name != "" { imgName = images.Items[i].Properties.Name } diskType := c.DiskType if c.DiskType == "SSD" { diskType = "HDD" } if imgName != "" && strings.Contains(strings.ToLower(imgName), strings.ToLower(imageName)) && images.Items[i].Properties.ImageType == diskType && images.Items[i].Properties.Location == c.Region && images.Items[i].Properties.Public == true { return images.Items[i].Id } } return "" } func parseErrorMessage(raw string) (toreturn string) { var tmp map[string]interface{} json.Unmarshal([]byte(raw), &tmp) for _, v := range tmp["messages"].([]interface{}) { for index, i := range v.(map[string]interface{}) { if index == "message" { toreturn = toreturn + i.(string) + "\n" } } } return toreturn }
dayglojesus/packer
builder/profitbricks/step_create_server.go
GO
mpl-2.0
6,663
/** * <p> * The scrollview module does not add any new classes. It simply plugs the ScrollViewScrollbars plugin into the * base ScrollView class implementation provided by the scrollview-base module, so that all scrollview instances * have scrollbars enabled. * </p> * * <ul> * <li><a href="../classes/ScrollView.html">ScrollView API documentation</a></li> * <li><a href="scrollview-base.html">scrollview-base Module documentation</a></li> * </ul> * * @module scrollview */ Y.Base.plug(Y.ScrollView, Y.Plugin.ScrollViewScrollbars);
co-ment/comt
src/cm/media/js/lib/yui/yui3-3.15.0/src/scrollview/js/scrollview.js
JavaScript
agpl-3.0
556
<?php /* * Spring Signage Ltd - http://www.springsignage.com * Copyright (C) 2015 Spring Signage Ltd * (CommandFactory.php) */ namespace Xibo\Factory; use Xibo\Entity\Command; use Xibo\Entity\User; use Xibo\Exception\NotFoundException; use Xibo\Service\LogServiceInterface; use Xibo\Service\SanitizerServiceInterface; use Xibo\Storage\StorageServiceInterface; /** * Class CommandFactory * @package Xibo\Factory */ class CommandFactory extends BaseFactory { /** * @var DisplayProfileFactory */ private $displayProfileFactory; /** * Construct a factory * @param StorageServiceInterface $store * @param LogServiceInterface $log * @param SanitizerServiceInterface $sanitizerService * @param User $user * @param UserFactory $userFactory */ public function __construct($store, $log, $sanitizerService, $user, $userFactory) { $this->setCommonDependencies($store, $log, $sanitizerService); $this->setAclDependencies($user, $userFactory); } /** * Create Command * @return Command */ public function create() { return new Command($this->getStore(), $this->getLog()); } /** * Get by Id * @param $commandId * @return Command * @throws NotFoundException */ public function getById($commandId) { $commands = $this->query(null, ['commandId' => $commandId]); if (count($commands) <= 0) throw new NotFoundException(); return $commands[0]; } /** * Get by Display Profile Id * @param $displayProfileId * @return array[Command] */ public function getByDisplayProfileId($displayProfileId) { return $this->query(null, ['displayProfileId' => $displayProfileId]); } /** * @param array $sortOrder * @param array $filterBy * @return array */ public function query($sortOrder = null, $filterBy = null) { $entries = array(); if ($sortOrder == null) $sortOrder = ['command']; $params = array(); $select = 'SELECT `command`.commandId, `command`.command, `command`.code, `command`.description, `command`.userId '; if ($this->getSanitizer()->getInt('displayProfileId', $filterBy) !== null) { $select .= ', commandString, validationString '; } $body = ' FROM `command` '; if ($this->getSanitizer()->getInt('displayProfileId', $filterBy) !== null) { $body .= ' INNER JOIN `lkcommanddisplayprofile` ON `lkcommanddisplayprofile`.commandId = `command`.commandId AND `lkcommanddisplayprofile`.displayProfileId = :displayProfileId '; $params['displayProfileId'] = $this->getSanitizer()->getInt('displayProfileId', $filterBy); } $body .= ' WHERE 1 = 1 '; if ($this->getSanitizer()->getInt('commandId', $filterBy) !== null) { $body .= ' AND `command`.commandId = :commandId '; $params['commandId'] = $this->getSanitizer()->getInt('commandId', $filterBy); } if ($this->getSanitizer()->getString('command', $filterBy) != null) { $body .= ' AND `command`.command = :command '; $params['command'] = $this->getSanitizer()->getString('command', $filterBy); } if ($this->getSanitizer()->getString('code', $filterBy) != null) { $body .= ' AND `code`.code = :code '; $params['code'] = $this->getSanitizer()->getString('code', $filterBy); } // Sorting? $order = ''; if (is_array($sortOrder)) $order .= 'ORDER BY ' . implode(',', $sortOrder); $limit = ''; // Paging if ($filterBy !== null && $this->getSanitizer()->getInt('start', $filterBy) !== null && $this->getSanitizer()->getInt('length', $filterBy) !== null) { $limit = ' LIMIT ' . intval($this->getSanitizer()->getInt('start', $filterBy), 0) . ', ' . $this->getSanitizer()->getInt('length', 10, $filterBy); } $sql = $select . $body . $order . $limit; foreach ($this->getStore()->select($sql, $params) as $row) { $entries[] = (new Command($this->getStore(), $this->getLog(), $this->displayProfileFactory))->hydrate($row); } // Paging if ($limit != '' && count($entries) > 0) { $results = $this->getStore()->select('SELECT COUNT(*) AS total ' . $body, $params); $this->_countLast = intval($results[0]['total']); } return $entries; } }
alexhuang888/xibo-cms
lib/Factory/CommandFactory.php
PHP
agpl-3.0
4,638
/* -*- Mode: C; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* Copyright (C) 2009 Red Hat, Inc. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, see <http://www.gnu.org/licenses/>. */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include "common.h" #include "red_channel.h" #include "red_client.h" #include "application.h" #include "debug.h" #include "utils.h" #include "openssl/rsa.h" #include "openssl/evp.h" #include "openssl/x509.h" void MigrationDisconnectSrcEvent::response(AbstractProcessLoop& events_loop) { static_cast<RedChannel*>(events_loop.get_owner())->do_migration_disconnect_src(); } void MigrationConnectTargetEvent::response(AbstractProcessLoop& events_loop) { static_cast<RedChannel*>(events_loop.get_owner())->do_migration_connect_target(); } RedChannelBase::RedChannelBase(uint8_t type, uint8_t id, const ChannelCaps& common_caps, const ChannelCaps& caps) : RedPeer() , _type (type) , _id (id) , _common_caps (common_caps) , _caps (caps) { } RedChannelBase::~RedChannelBase() { } static const char *spice_link_error_string(int err) { switch (err) { case SPICE_LINK_ERR_OK: return "no error"; case SPICE_LINK_ERR_ERROR: return "general error"; case SPICE_LINK_ERR_INVALID_MAGIC: return "invalid magic"; case SPICE_LINK_ERR_INVALID_DATA: return "invalid data"; case SPICE_LINK_ERR_VERSION_MISMATCH: return "version mismatch"; case SPICE_LINK_ERR_NEED_SECURED: return "need secured connection"; case SPICE_LINK_ERR_NEED_UNSECURED: return "need unsecured connection"; case SPICE_LINK_ERR_PERMISSION_DENIED: return "permission denied"; case SPICE_LINK_ERR_BAD_CONNECTION_ID: return "bad connection id"; case SPICE_LINK_ERR_CHANNEL_NOT_AVAILABLE: return "channel not available"; } return ""; } void RedChannelBase::link(uint32_t connection_id, const std::string& password, int protocol) { SpiceLinkHeader header; SpiceLinkMess link_mess; SpiceLinkReply* reply; uint32_t link_res; uint32_t i; BIO *bioKey; uint8_t *buffer, *p; uint32_t expected_major; header.magic = SPICE_MAGIC; header.size = sizeof(link_mess); if (protocol == 1) { /* protocol 1 == major 1, old 0.4 protocol, last active minor */ expected_major = header.major_version = 1; header.minor_version = 3; } else if (protocol == 2) { /* protocol 2 == current */ expected_major = header.major_version = SPICE_VERSION_MAJOR; header.minor_version = SPICE_VERSION_MINOR; } else { THROW("unsupported protocol version specified"); } link_mess.connection_id = connection_id; link_mess.channel_type = _type; link_mess.channel_id = _id; link_mess.num_common_caps = get_common_caps().size(); link_mess.num_channel_caps = get_caps().size(); link_mess.caps_offset = sizeof(link_mess); header.size += (link_mess.num_common_caps + link_mess.num_channel_caps) * sizeof(uint32_t); buffer = new uint8_t[sizeof(header) + sizeof(link_mess) + _common_caps.size() * sizeof(uint32_t) + _caps.size() * sizeof(uint32_t)]; p = buffer; memcpy(p, (uint8_t*)&header, sizeof(header)); p += sizeof(header); memcpy(p, (uint8_t*)&link_mess, sizeof(link_mess)); p += sizeof(link_mess); for (i = 0; i < _common_caps.size(); i++) { *(uint32_t *)p = _common_caps[i]; p += sizeof(uint32_t); } for (i = 0; i < _caps.size(); i++) { *(uint32_t *)p = _caps[i]; p += sizeof(uint32_t); } send(buffer, p - buffer); delete [] buffer; receive((uint8_t*)&header, sizeof(header)); if (header.magic != SPICE_MAGIC) { THROW_ERR(SPICEC_ERROR_CODE_CONNECT_FAILED, "bad magic"); } if (header.major_version != expected_major) { THROW_ERR(SPICEC_ERROR_CODE_VERSION_MISMATCH, "version mismatch: expect %u got %u", expected_major, header.major_version); } _remote_major = header.major_version; _remote_minor = header.minor_version; AutoArray<uint8_t> reply_buf(new uint8_t[header.size]); receive(reply_buf.get(), header.size); reply = (SpiceLinkReply *)reply_buf.get(); if (reply->error != SPICE_LINK_ERR_OK) { THROW_ERR(SPICEC_ERROR_CODE_CONNECT_FAILED, "connect error %u - %s", reply->error, spice_link_error_string(reply->error)); } uint32_t num_caps = reply->num_channel_caps + reply->num_common_caps; if ((uint8_t *)(reply + 1) > reply_buf.get() + header.size || (uint8_t *)reply + reply->caps_offset + num_caps * sizeof(uint32_t) > reply_buf.get() + header.size) { THROW_ERR(SPICEC_ERROR_CODE_CONNECT_FAILED, "access violation"); } uint32_t *caps = (uint32_t *)((uint8_t *)reply + reply->caps_offset); _remote_common_caps.clear(); for (i = 0; i < reply->num_common_caps; i++, caps++) { _remote_common_caps.resize(i + 1); _remote_common_caps[i] = *caps; } _remote_caps.clear(); for (i = 0; i < reply->num_channel_caps; i++, caps++) { _remote_caps.resize(i + 1); _remote_caps[i] = *caps; } bioKey = BIO_new(BIO_s_mem()); if (bioKey != NULL) { EVP_PKEY *pubkey; int nRSASize; RSA *rsa; BIO_write(bioKey, reply->pub_key, SPICE_TICKET_PUBKEY_BYTES); pubkey = d2i_PUBKEY_bio(bioKey, NULL); rsa = pubkey->pkey.rsa; nRSASize = RSA_size(rsa); AutoArray<unsigned char> bufEncrypted(new unsigned char[nRSASize]); /* The use of RSA encryption limit the potential maximum password length. for RSA_PKCS1_OAEP_PADDING it is RSA_size(rsa) - 41. */ if (RSA_public_encrypt(password.length() + 1, (unsigned char *)password.c_str(), (uint8_t *)bufEncrypted.get(), rsa, RSA_PKCS1_OAEP_PADDING) > 0) { send((uint8_t*)bufEncrypted.get(), nRSASize); } else { EVP_PKEY_free(pubkey); BIO_free(bioKey); THROW("could not encrypt password"); } memset(bufEncrypted.get(), 0, nRSASize); EVP_PKEY_free(pubkey); } else { THROW("Could not initiate BIO"); } BIO_free(bioKey); receive((uint8_t*)&link_res, sizeof(link_res)); if (link_res != SPICE_LINK_ERR_OK) { int error_code = (link_res == SPICE_LINK_ERR_PERMISSION_DENIED) ? SPICEC_ERROR_CODE_CONNECT_FAILED : SPICEC_ERROR_CODE_CONNECT_FAILED; THROW_ERR(error_code, "connect failed %u", link_res); } } void RedChannelBase::connect(const ConnectionOptions& options, uint32_t connection_id, const char* host, std::string password) { int protocol = options.protocol; if (protocol == 0) { /* AUTO, try major 2 first */ protocol = 2; } retry: try { if (options.allow_unsecure()) { try { RedPeer::connect_unsecure(host, options.unsecure_port); link(connection_id, password, protocol); return; } catch (Exception& e) { // On protocol version mismatch, don't connect_secure with the same version if (e.get_error_code() == SPICEC_ERROR_CODE_VERSION_MISMATCH || !options.allow_secure()) { throw; } RedPeer::close(); } } ASSERT(options.allow_secure()); RedPeer::connect_secure(options, host); link(connection_id, password, protocol); } catch (Exception& e) { // On protocol version mismatch, retry with older version if (e.get_error_code() == SPICEC_ERROR_CODE_VERSION_MISMATCH && protocol == 2 && options.protocol == 0) { RedPeer::cleanup(); protocol = 1; goto retry; } throw; } } void RedChannelBase::set_capability(ChannelCaps& caps, uint32_t cap) { uint32_t word_index = cap / 32; if (caps.size() < word_index + 1) { caps.resize(word_index + 1); } caps[word_index] |= 1 << (cap % 32); } void RedChannelBase::set_common_capability(uint32_t cap) { set_capability(_common_caps, cap); } void RedChannelBase::set_capability(uint32_t cap) { set_capability(_caps, cap); } bool RedChannelBase::test_capability(const ChannelCaps& caps, uint32_t cap) { uint32_t word_index = cap / 32; if (caps.size() < word_index + 1) { return false; } return (caps[word_index] & (1 << (cap % 32))) != 0; } bool RedChannelBase::test_common_capability(uint32_t cap) { return test_capability(_remote_common_caps, cap); } bool RedChannelBase::test_capability(uint32_t cap) { return test_capability(_remote_caps, cap); } void RedChannelBase::swap(RedChannelBase* other) { int tmp_ver; RedPeer::swap(other); tmp_ver = _remote_major; _remote_major = other->_remote_major; other->_remote_major = tmp_ver; tmp_ver = _remote_minor; _remote_minor = other->_remote_minor; other->_remote_minor = tmp_ver; } SendTrigger::SendTrigger(RedChannel& channel) : _channel (channel) { } void SendTrigger::on_event() { _channel.on_send_trigger(); } SPICE_GNUC_NORETURN void AbortTrigger::on_event() { THROW("abort"); } RedChannel::RedChannel(RedClient& client, uint8_t type, uint8_t id, RedChannel::MessageHandler* handler, Platform::ThreadPriority worker_priority) : RedChannelBase(type, id, ChannelCaps(), ChannelCaps()) , _marshallers (NULL) , _client (client) , _state (PASSIVE_STATE) , _action (WAIT_ACTION) , _error (SPICEC_ERROR_CODE_SUCCESS) , _wait_for_threads (true) , _socket_in_loop (false) , _worker (NULL) , _worker_priority (worker_priority) , _message_handler (handler) , _outgoing_message (NULL) , _incomming_header_pos (0) , _incomming_message (NULL) , _message_ack_count (0) , _message_ack_window (0) , _loop (this) , _send_trigger (*this) , _disconnect_stamp (0) , _disconnect_reason (SPICE_LINK_ERR_OK) { _loop.add_trigger(_send_trigger); _loop.add_trigger(_abort_trigger); } RedChannel::~RedChannel() { ASSERT(_state == TERMINATED_STATE || _state == PASSIVE_STATE); delete _worker; } void* RedChannel::worker_main(void *data) { try { RedChannel* channel = static_cast<RedChannel*>(data); channel->set_state(DISCONNECTED_STATE); Platform::set_thread_priority(NULL, channel->get_worker_priority()); channel->run(); } catch (Exception& e) { LOG_ERROR("unhandled exception: %s", e.what()); } catch (std::exception& e) { LOG_ERROR("unhandled exception: %s", e.what()); } catch (...) { LOG_ERROR("unhandled exception"); } return NULL; } void RedChannel::post_message(RedChannel::OutMessage* message) { Lock lock(_outgoing_lock); _outgoing_messages.push_back(message); lock.unlock(); _send_trigger.trigger(); } RedPeer::CompoundInMessage *RedChannel::receive() { CompoundInMessage *message = RedChannelBase::receive(); on_message_received(); return message; } RedChannel::OutMessage* RedChannel::get_outgoing_message() { if (_state != CONNECTED_STATE || _outgoing_messages.empty()) { return NULL; } RedChannel::OutMessage* message = _outgoing_messages.front(); _outgoing_messages.pop_front(); return message; } class AutoMessage { public: AutoMessage(RedChannel::OutMessage* message) : _message (message) {} ~AutoMessage() {if (_message) _message->release();} void set(RedChannel::OutMessage* message) { _message = message;} RedChannel::OutMessage* get() { return _message;} RedChannel::OutMessage* release(); private: RedChannel::OutMessage* _message; }; RedChannel::OutMessage* AutoMessage::release() { RedChannel::OutMessage* ret = _message; _message = NULL; return ret; } void RedChannel::start() { ASSERT(!_worker); _worker = new Thread(RedChannel::worker_main, this); Lock lock(_state_lock); while (_state == PASSIVE_STATE) { _state_cond.wait(lock); } } void RedChannel::set_state(int state) { Lock lock(_state_lock); _state = state; _state_cond.notify_all(); } void RedChannel::connect() { Lock lock(_action_lock); if (_state != DISCONNECTED_STATE && _state != PASSIVE_STATE) { return; } _action = CONNECT_ACTION; _action_cond.notify_one(); } void RedChannel::disconnect() { clear_outgoing_messages(); Lock lock(_action_lock); if (_state != CONNECTING_STATE && _state != CONNECTED_STATE) { return; } _action = DISCONNECT_ACTION; RedPeer::disconnect(); _action_cond.notify_one(); } void RedChannel::disconnect_migration_src() { clear_outgoing_messages(); Lock lock(_action_lock); if (_state == CONNECTING_STATE || _state == CONNECTED_STATE) { AutoRef<MigrationDisconnectSrcEvent> migrate_event(new MigrationDisconnectSrcEvent()); _loop.push_event(*migrate_event); } } void RedChannel::connect_migration_target() { LOG_INFO(""); AutoRef<MigrationConnectTargetEvent> migrate_event(new MigrationConnectTargetEvent()); _loop.push_event(*migrate_event); } void RedChannel::do_migration_disconnect_src() { if (_socket_in_loop) { _socket_in_loop = false; _loop.remove_socket(*this); } clear_outgoing_messages(); if (_outgoing_message) { _outgoing_message->release(); _outgoing_message = NULL; } _incomming_header_pos = 0; if (_incomming_message) { _incomming_message->unref(); _incomming_message = NULL; } on_disconnect_mig_src(); get_client().migrate_channel(*this); get_client().on_channel_disconnect_mig_src_completed(*this); } void RedChannel::do_migration_connect_target() { LOG_INFO(""); ASSERT(get_client().get_protocol() != 0); if (get_client().get_protocol() == 1) { _marshallers = spice_message_marshallers_get1(); } else { _marshallers = spice_message_marshallers_get(); } _loop.add_socket(*this); _socket_in_loop = true; on_connect_mig_target(); set_state(CONNECTED_STATE); on_event(); } void RedChannel::clear_outgoing_messages() { Lock lock(_outgoing_lock); while (!_outgoing_messages.empty()) { RedChannel::OutMessage* message = _outgoing_messages.front(); _outgoing_messages.pop_front(); message->release(); } } void RedChannel::run() { for (;;) { Lock lock(_action_lock); if (_action == WAIT_ACTION) { _action_cond.wait(lock); } int action = _action; _action = WAIT_ACTION; lock.unlock(); switch (action) { case CONNECT_ACTION: try { get_client().get_sync_info(get_type(), get_id(), _sync_info); on_connecting(); set_state(CONNECTING_STATE); ConnectionOptions con_options(_client.get_connection_options(get_type()), _client.get_port(), _client.get_sport(), _client.get_protocol(), _client.get_host_auth_options(), _client.get_connection_ciphers()); RedChannelBase::connect(con_options, _client.get_connection_id(), _client.get_host().c_str(), _client.get_password().c_str()); /* If automatic protocol, remember the first connect protocol type */ if (_client.get_protocol() == 0) { if (get_peer_major() == 1) { _client.set_protocol(1); } else { /* Major is 2 or unstable high value, use 2 */ _client.set_protocol(2); } } /* Initialize when we know the remote major version */ if (_client.get_peer_major() == 1) { _marshallers = spice_message_marshallers_get1(); } else { _marshallers = spice_message_marshallers_get(); } on_connect(); set_state(CONNECTED_STATE); _loop.add_socket(*this); _socket_in_loop = true; on_event(); _loop.run(); } catch (RedPeer::DisconnectedException&) { _error = SPICEC_ERROR_CODE_SUCCESS; } catch (Exception& e) { LOG_WARN("%s", e.what()); _error = e.get_error_code(); } catch (std::exception& e) { LOG_WARN("%s", e.what()); _error = SPICEC_ERROR_CODE_ERROR; } if (_socket_in_loop) { _socket_in_loop = false; _loop.remove_socket(*this); } if (_outgoing_message) { _outgoing_message->release(); _outgoing_message = NULL; } _incomming_header_pos = 0; if (_incomming_message) { _incomming_message->unref(); _incomming_message = NULL; } case DISCONNECT_ACTION: close(); on_disconnect(); set_state(DISCONNECTED_STATE); _client.on_channel_disconnected(*this); continue; case QUIT_ACTION: set_state(TERMINATED_STATE); return; } } } bool RedChannel::abort() { clear_outgoing_messages(); Lock lock(_action_lock); if (_state == TERMINATED_STATE) { if (_wait_for_threads) { _wait_for_threads = false; _worker->join(); } return true; } _action = QUIT_ACTION; _action_cond.notify_one(); lock.unlock(); RedPeer::disconnect(); _abort_trigger.trigger(); for (;;) { Lock state_lock(_state_lock); if (_state == TERMINATED_STATE) { break; } uint64_t timout = 1000 * 1000 * 100; // 100ms if (!_state_cond.timed_wait(state_lock, timout)) { return false; } } if (_wait_for_threads) { _wait_for_threads = false; _worker->join(); } return true; } void RedChannel::send_messages() { if (_outgoing_message) { return; } for (;;) { Lock lock(_outgoing_lock); AutoMessage message(get_outgoing_message()); if (!message.get()) { return; } RedPeer::OutMessage& peer_message = message.get()->peer_message(); uint32_t n = send(peer_message); if (n != peer_message.message_size()) { _outgoing_message = message.release(); _outgoing_pos = n; return; } } } void RedChannel::on_send_trigger() { send_messages(); } void RedChannel::on_message_received() { if (_message_ack_count && !--_message_ack_count) { post_message(new Message(SPICE_MSGC_ACK)); _message_ack_count = _message_ack_window; } } void RedChannel::on_message_complition(uint64_t serial) { Lock lock(*_sync_info.lock); *_sync_info.message_serial = serial; _sync_info.condition->notify_all(); } void RedChannel::receive_messages() { for (;;) { uint32_t n = RedPeer::receive((uint8_t*)&_incomming_header, sizeof(SpiceDataHeader)); if (n != sizeof(SpiceDataHeader)) { _incomming_header_pos = n; return; } AutoRef<CompoundInMessage> message(new CompoundInMessage(_incomming_header.serial, _incomming_header.type, _incomming_header.size, _incomming_header.sub_list)); n = RedPeer::receive((*message)->data(), (*message)->compound_size()); if (n != (*message)->compound_size()) { _incomming_message = message.release(); _incomming_message_pos = n; return; } on_message_received(); _message_handler->handle_message(*(*message)); on_message_complition((*message)->serial()); } } void RedChannel::on_event() { if (_outgoing_message) { RedPeer::OutMessage& peer_message = _outgoing_message->peer_message(); _outgoing_pos += do_send(peer_message, _outgoing_pos); if (_outgoing_pos == peer_message.message_size()) { _outgoing_message->release(); _outgoing_message = NULL; } } send_messages(); if (_incomming_header_pos) { _incomming_header_pos += RedPeer::receive(((uint8_t*)&_incomming_header) + _incomming_header_pos, sizeof(SpiceDataHeader) - _incomming_header_pos); if (_incomming_header_pos != sizeof(SpiceDataHeader)) { return; } _incomming_header_pos = 0; _incomming_message = new CompoundInMessage(_incomming_header.serial, _incomming_header.type, _incomming_header.size, _incomming_header.sub_list); _incomming_message_pos = 0; } if (_incomming_message) { _incomming_message_pos += RedPeer::receive(_incomming_message->data() + _incomming_message_pos, _incomming_message->compound_size() - _incomming_message_pos); if (_incomming_message_pos != _incomming_message->compound_size()) { return; } AutoRef<CompoundInMessage> message(_incomming_message); _incomming_message = NULL; on_message_received(); _message_handler->handle_message(*(*message)); on_message_complition((*message)->serial()); } receive_messages(); } void RedChannel::send_migrate_flush_mark() { if (_outgoing_message) { RedPeer::OutMessage& peer_message = _outgoing_message->peer_message(); do_send(peer_message, _outgoing_pos); _outgoing_message->release(); _outgoing_message = NULL; } Lock lock(_outgoing_lock); for (;;) { AutoMessage message(get_outgoing_message()); if (!message.get()) { break; } send(message.get()->peer_message()); } lock.unlock(); std::auto_ptr<RedPeer::OutMessage> message(new RedPeer::OutMessage(SPICE_MSGC_MIGRATE_FLUSH_MARK)); send(*message); } void RedChannel::handle_migrate(RedPeer::InMessage* message) { DBG(0, "channel type %u id %u", get_type(), get_id()); _socket_in_loop = false; _loop.remove_socket(*this); SpiceMsgMigrate* migrate = (SpiceMsgMigrate*)message->data(); if (migrate->flags & SPICE_MIGRATE_NEED_FLUSH) { send_migrate_flush_mark(); } AutoRef<CompoundInMessage> data_message; if (migrate->flags & SPICE_MIGRATE_NEED_DATA_TRANSFER) { data_message.reset(receive()); } _client.migrate_channel(*this); if (migrate->flags & SPICE_MIGRATE_NEED_DATA_TRANSFER) { if ((*data_message)->type() != SPICE_MSG_MIGRATE_DATA) { THROW("expect SPICE_MSG_MIGRATE_DATA"); } std::auto_ptr<RedPeer::OutMessage> message(new RedPeer::OutMessage(SPICE_MSGC_MIGRATE_DATA)); spice_marshaller_add(message->marshaller(), (*data_message)->data(), (*data_message)->size()); send(*message); } _loop.add_socket(*this); _socket_in_loop = true; on_migrate(); set_state(CONNECTED_STATE); on_event(); } void RedChannel::handle_set_ack(RedPeer::InMessage* message) { SpiceMsgSetAck* ack = (SpiceMsgSetAck*)message->data(); _message_ack_window = _message_ack_count = ack->window; Message *response = new Message(SPICE_MSGC_ACK_SYNC); SpiceMsgcAckSync sync; sync.generation = ack->generation; _marshallers->msgc_ack_sync(response->marshaller(), &sync); post_message(response); } void RedChannel::handle_ping(RedPeer::InMessage* message) { SpiceMsgPing *ping = (SpiceMsgPing *)message->data(); Message *pong = new Message(SPICE_MSGC_PONG); _marshallers->msgc_pong(pong->marshaller(), ping); post_message(pong); } void RedChannel::handle_disconnect(RedPeer::InMessage* message) { SpiceMsgDisconnect *disconnect = (SpiceMsgDisconnect *)message->data(); _disconnect_stamp = disconnect->time_stamp; _disconnect_reason = disconnect->reason; } void RedChannel::handle_notify(RedPeer::InMessage* message) { SpiceMsgNotify *notify = (SpiceMsgNotify *)message->data(); const char *severity; const char *visibility; char *message_str = (char *)""; const char *message_prefix = ""; static const char* severity_strings[] = {"info", "warn", "error"}; static const char* visibility_strings[] = {"!", "!!", "!!!"}; if (notify->severity > SPICE_NOTIFY_SEVERITY_ERROR) { THROW("bad severity"); } severity = severity_strings[notify->severity]; if (notify->visibilty > SPICE_NOTIFY_VISIBILITY_HIGH) { THROW("bad visibility"); } visibility = visibility_strings[notify->visibilty]; if (notify->message_len) { if ((message->size() - sizeof(*notify) < notify->message_len)) { THROW("access violation"); } message_str = new char[notify->message_len + 1]; memcpy(message_str, notify->message, notify->message_len); message_str[notify->message_len] = 0; message_prefix = ": "; } LOG_INFO("remote channel %u:%u %s%s #%u%s%s", get_type(), get_id(), severity, visibility, notify->what, message_prefix, message_str); if (notify->message_len) { delete [] message_str; } } void RedChannel::handle_wait_for_channels(RedPeer::InMessage* message) { SpiceMsgWaitForChannels *wait = (SpiceMsgWaitForChannels *)message->data(); if (message->size() < sizeof(*wait) + wait->wait_count * sizeof(wait->wait_list[0])) { THROW("access violation"); } _client.wait_for_channels(wait->wait_count, wait->wait_list); }
Open365/spice-web-client
misc/spice-0.12.0/client/red_channel.cpp
C++
agpl-3.0
27,728
<?php namespace Safe; use Safe\Exceptions\SwooleException; /** * * * @param string $filename The filename being written. * @param string $content The content writing to the file. * @param int $offset The offset. * @param callable $callback * @throws SwooleException * */ function swoole_async_write(string $filename, string $content, int $offset = null, callable $callback = null): void { error_clear_last(); if ($callback !== null) { $result = \swoole_async_write($filename, $content, $offset, $callback); } elseif ($offset !== null) { $result = \swoole_async_write($filename, $content, $offset); } else { $result = \swoole_async_write($filename, $content); } if ($result === false) { throw SwooleException::createFromPhpError(); } } /** * * * @param string $filename The filename being written. * @param string $content The content writing to the file. * @param callable $callback * @param int $flags * @throws SwooleException * */ function swoole_async_writefile(string $filename, string $content, callable $callback = null, int $flags = 0): void { error_clear_last(); if ($flags !== 0) { $result = \swoole_async_writefile($filename, $content, $callback, $flags); } elseif ($callback !== null) { $result = \swoole_async_writefile($filename, $content, $callback); } else { $result = \swoole_async_writefile($filename, $content); } if ($result === false) { throw SwooleException::createFromPhpError(); } } /** * * * @param callable $callback * @throws SwooleException * */ function swoole_event_defer(callable $callback): void { error_clear_last(); $result = \swoole_event_defer($callback); if ($result === false) { throw SwooleException::createFromPhpError(); } } /** * * * @param int $fd * @throws SwooleException * */ function swoole_event_del(int $fd): void { error_clear_last(); $result = \swoole_event_del($fd); if ($result === false) { throw SwooleException::createFromPhpError(); } } /** * * * @param int $fd * @param string $data * @throws SwooleException * */ function swoole_event_write(int $fd, string $data): void { error_clear_last(); $result = \swoole_event_write($fd, $data); if ($result === false) { throw SwooleException::createFromPhpError(); } }
Irstea/collec
vendor/thecodingmachine/safe/generated/swoole.php
PHP
agpl-3.0
2,407
/* * BrainBrowser: Web-based Neurological Visualization Tools * (https://brainbrowser.cbrain.mcgill.ca) * * Copyright (C) 2011 * The Royal Institution for the Advancement of Learning * McGill University * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * BrainBrowser v2.1.1 * * Author: Tarek Sherif <tsherif@gmail.com> (http://tareksherif.ca/) * Author: Nicolas Kassis * Author: Paul Mougel */ !function(){"use strict";function a(a){var b,c,d,e,f={};for(f.values=a.replace(/^\s+/,"").replace(/\s+$/,"").split(/\s+/).map(parseFloat),d=f.values[0],e=f.values[0],b=1,c=f.values.length;c>b;b++)d=Math.min(d,f.values[b]),e=Math.max(e,f.values[b]);return f.min=d,f.max=e,f}self.addEventListener("message",function(b){var c=b.data,d=c.data;self.postMessage(a(d))})}();
rdvincent/brainbrowser
build/brainbrowser-2.1.1/workers/mniobj.intensity.worker.js
JavaScript
agpl-3.0
1,377
/* * Copyright (c) 2015 Memorial Sloan-Kettering Cancer Center. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY, WITHOUT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS * FOR A PARTICULAR PURPOSE. The software and documentation provided hereunder * is on an "as is" basis, and Memorial Sloan-Kettering Cancer Center has no * obligations to provide maintenance, support, updates, enhancements or * modifications. In no event shall Memorial Sloan-Kettering Cancer Center be * liable to any party for direct, indirect, special, incidental or * consequential damages, including lost profits, arising out of the use of this * software and its documentation, even if Memorial Sloan-Kettering Cancer * Center has been advised of the possibility of such damage. */ /* * This file is part of cBioPortal. * * cBioPortal is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.mskcc.cbio.portal.util; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.commons.lang3.StringUtils; import java.util.Collections; import java.util.Enumeration; import java.util.Map; import java.util.HashMap; import javax.servlet.*; import javax.servlet.http.*; /** * * @author Manda Wilson */ public class SessionServiceRequestWrapper extends HttpServletRequestWrapper { public static final String SESSION_ERROR = "session_error"; public static final String SESSION_ID_PARAM = "session_id"; private static Log LOG = LogFactory.getLog(SessionServiceRequestWrapper.class); private Map<String, String[]> storedParameters; private String sessionId; /** * If session_id is a request parameter, calls session-service API to retrieve * stored session. Stores SESSION_ERROR as a request attribute if the session is * not found, or the session service returns an error. Stored session parameters * override current request parameters. If session_id is not a request parameter, * request behaves as normal. * * @param request wrapped HttpServletRequest */ public SessionServiceRequestWrapper(final HttpServletRequest request) { super(request); LOG.debug("new SessionServiceRequestWrapper()"); sessionId = super.getParameter(SESSION_ID_PARAM); LOG.debug("new SessionServiceRequestWrapper(): request parameter '" + SESSION_ID_PARAM + "' = '" + sessionId + "'"); if (!StringUtils.isBlank(sessionId)) { LOG.debug("new SessionServiceRequestWrapper(): retrieved parameters = '" + storedParameters + "'"); try { storedParameters = SessionServiceUtil.getSession(sessionId); if (storedParameters == null || storedParameters.size() == 0) { request.setAttribute(SESSION_ERROR, "Session with id '" + sessionId + "' not found."); } } catch (Exception e) { request.setAttribute(SESSION_ERROR, "Session service error. Session with id '" + sessionId + "' not loaded. Try again later. If problem persists contact site administrator."); } } } @Override public String getParameter(final String name) { if (storedParameters != null && !SESSION_ID_PARAM.equals(name)) { LOG.debug("SessionServiceRequestWrapper.getParameter(" + name + "): accessing parameters from stored session with id '" + sessionId + "'"); if (storedParameters.containsKey(name)) { String value = storedParameters.get(name)[0]; LOG.debug("SessionServiceRequestWrapper.getParameter(" + name + "): returning '" + value + "'"); return value; } LOG.debug("SessionServiceRequestWrapper.getParameter(" + name + "): returning null - parameter name not found"); return null; } LOG.debug("SessionServiceRequestWrapper.getParameter(" + name + "): accessing current request parameters"); return super.getParameter(name); } @Override public Map<String, String[]> getParameterMap() { if (storedParameters != null) { LOG.debug("SessionServiceRequestWrapper.getParameterMap(): accessing parameters from stored session with id '" + sessionId + "'"); return Collections.unmodifiableMap(storedParameters); } LOG.debug("SessionServiceRequestWrapper.getParameterMap(): accessing current request parameters"); return super.getParameterMap(); } @Override public Enumeration<String> getParameterNames() { if (storedParameters != null) { LOG.debug("SessionServiceRequestWrapper.getParameterNames(): accessing parameters from stored session with id '" + sessionId + "'"); return Collections.enumeration(storedParameters.keySet()); } LOG.debug("SessionServiceRequestWrapper.getParameterNames(): accessing current request parameters"); return super.getParameterNames(); } @Override public String[] getParameterValues(final String name) { if (storedParameters != null) { LOG.debug("SessionServiceRequestWrapper.getParameterValues(): accessing parameters from stored session with id '" + sessionId + "'"); return storedParameters.get(name); } LOG.debug("SessionServiceRequestWrapper.getParameterValues(): accessing current request parameters"); return super.getParameterValues(name); } }
onursumer/cbioportal
core/src/main/java/org/mskcc/cbio/portal/util/SessionServiceRequestWrapper.java
Java
agpl-3.0
6,093
/* * Kuali Coeus, a comprehensive research administration system for higher education. * * Copyright 2005-2015 Kuali, Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kuali.coeus.common.budget.framework.period; import org.kuali.coeus.common.budget.framework.core.Budget; public class GenerateBudgetPeriodEvent extends BudgetPeriodEventBase { public GenerateBudgetPeriodEvent(Budget budget, BudgetPeriod budgetPeriod) { super(budget, budgetPeriod); } }
sanjupolus/KC6.oLatest
coeus-impl/src/main/java/org/kuali/coeus/common/budget/framework/period/GenerateBudgetPeriodEvent.java
Java
agpl-3.0
1,109
odoo.define('website_slides/static/src/tests/activity_tests.js', function (require) { 'use strict'; const components = { Activity: require('mail/static/src/components/activity/activity.js'), }; const { afterEach, beforeEach, createRootComponent, start, } = require('mail/static/src/utils/test_utils.js'); QUnit.module('website_slides', {}, function () { QUnit.module('components', {}, function () { QUnit.module('activity', {}, function () { QUnit.module('activity_tests.js', { beforeEach() { beforeEach(this); this.createActivityComponent = async activity => { await createRootComponent(this, components.Activity, { props: { activityLocalId: activity.localId }, target: this.widget.el, }); }; this.start = async params => { const { env, widget } = await start(Object.assign({}, params, { data: this.data, })); this.env = env; this.widget = widget; }; }, afterEach() { afterEach(this); }, }); QUnit.test('grant course access', async function (assert) { assert.expect(8); await this.start({ async mockRPC(route, args) { if (args.method === 'action_grant_access') { assert.strictEqual(args.args.length, 1); assert.strictEqual(args.args[0].length, 1); assert.strictEqual(args.args[0][0], 100); assert.strictEqual(args.kwargs.partner_id, 5); assert.step('access_grant'); } return this._super(...arguments); }, }); const activity = this.env.models['mail.activity'].create({ id: 100, canWrite: true, thread: [['insert', { id: 100, model: 'slide.channel', }]], requestingPartner: [['insert', { id: 5, displayName: "Pauvre pomme", }]], type: [['insert', { id: 1, displayName: "Access Request", }]], }); await this.createActivityComponent(activity); assert.containsOnce(document.body, '.o_Activity', "should have activity component"); assert.containsOnce(document.body, '.o_Activity_grantAccessButton', "should have grant access button"); document.querySelector('.o_Activity_grantAccessButton').click(); assert.verifySteps(['access_grant'], "Grant button should trigger the right rpc call"); }); QUnit.test('refuse course access', async function (assert) { assert.expect(8); await this.start({ async mockRPC(route, args) { if (args.method === 'action_refuse_access') { assert.strictEqual(args.args.length, 1); assert.strictEqual(args.args[0].length, 1); assert.strictEqual(args.args[0][0], 100); assert.strictEqual(args.kwargs.partner_id, 5); assert.step('access_refuse'); } return this._super(...arguments); }, }); const activity = this.env.models['mail.activity'].create({ id: 100, canWrite: true, thread: [['insert', { id: 100, model: 'slide.channel', }]], requestingPartner: [['insert', { id: 5, displayName: "Pauvre pomme", }]], type: [['insert', { id: 1, displayName: "Access Request", }]], }); await this.createActivityComponent(activity); assert.containsOnce(document.body, '.o_Activity', "should have activity component"); assert.containsOnce(document.body, '.o_Activity_refuseAccessButton', "should have refuse access button"); document.querySelector('.o_Activity_refuseAccessButton').click(); assert.verifySteps(['access_refuse'], "refuse button should trigger the right rpc call"); }); }); }); }); });
rven/odoo
addons/website_slides/static/src/components/activity/activity_tests.js
JavaScript
agpl-3.0
3,940