code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
3
942
language
stringclasses
30 values
license
stringclasses
15 values
size
int32
3
1.05M
/* * Copyright 2013 Netflix, 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. */ package feign; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.Collection; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.zip.DeflaterOutputStream; import java.util.zip.GZIPOutputStream; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLSocketFactory; import feign.Request.Options; import static feign.Util.CONTENT_ENCODING; import static feign.Util.CONTENT_LENGTH; import static feign.Util.ENCODING_DEFLATE; import static feign.Util.ENCODING_GZIP; /** * Submits HTTP {@link Request requests}. Implementations are expected to be thread-safe. */ public interface Client { /** * Executes a request against its {@link Request#url() url} and returns a response. * * @param request safe to replay. * @param options options to apply to this request. * @return connected response, {@link Response.Body} is absent or unread. * @throws IOException on a network error connecting to {@link Request#url()}. */ Response execute(Request request, Options options) throws IOException; public static class Default implements Client { private final SSLSocketFactory sslContextFactory; private final HostnameVerifier hostnameVerifier; /** * Null parameters imply platform defaults. */ public Default(SSLSocketFactory sslContextFactory, HostnameVerifier hostnameVerifier) { this.sslContextFactory = sslContextFactory; this.hostnameVerifier = hostnameVerifier; } @Override public Response execute(Request request, Options options) throws IOException { HttpURLConnection connection = convertAndSend(request, options); return convertResponse(connection); } HttpURLConnection convertAndSend(Request request, Options options) throws IOException { final HttpURLConnection connection = (HttpURLConnection) new URL(request.url()).openConnection(); if (connection instanceof HttpsURLConnection) { HttpsURLConnection sslCon = (HttpsURLConnection) connection; if (sslContextFactory != null) { sslCon.setSSLSocketFactory(sslContextFactory); } if (hostnameVerifier != null) { sslCon.setHostnameVerifier(hostnameVerifier); } } connection.setConnectTimeout(options.connectTimeoutMillis()); connection.setReadTimeout(options.readTimeoutMillis()); connection.setAllowUserInteraction(false); connection.setInstanceFollowRedirects(true); connection.setRequestMethod(request.method()); Collection<String> contentEncodingValues = request.headers().get(CONTENT_ENCODING); boolean gzipEncodedRequest = contentEncodingValues != null && contentEncodingValues.contains(ENCODING_GZIP); boolean deflateEncodedRequest = contentEncodingValues != null && contentEncodingValues.contains(ENCODING_DEFLATE); boolean hasAcceptHeader = false; Integer contentLength = null; for (String field : request.headers().keySet()) { if (field.equalsIgnoreCase("Accept")) { hasAcceptHeader = true; } for (String value : request.headers().get(field)) { if (field.equals(CONTENT_LENGTH)) { if (!gzipEncodedRequest && !deflateEncodedRequest) { contentLength = Integer.valueOf(value); connection.addRequestProperty(field, value); } } else { connection.addRequestProperty(field, value); } } } // Some servers choke on the default accept string. if (!hasAcceptHeader) { connection.addRequestProperty("Accept", "*/*"); } if (request.body() != null) { if (contentLength != null) { connection.setFixedLengthStreamingMode(contentLength); } else { connection.setChunkedStreamingMode(8196); } connection.setDoOutput(true); OutputStream out = connection.getOutputStream(); if (gzipEncodedRequest) { out = new GZIPOutputStream(out); } else if (deflateEncodedRequest) { out = new DeflaterOutputStream(out); } try { out.write(request.body()); } finally { try { out.close(); } catch (IOException suppressed) { // NOPMD } } } return connection; } Response convertResponse(HttpURLConnection connection) throws IOException { int status = connection.getResponseCode(); String reason = connection.getResponseMessage(); Map<String, Collection<String>> headers = new LinkedHashMap<String, Collection<String>>(); for (Map.Entry<String, List<String>> field : connection.getHeaderFields().entrySet()) { // response message if (field.getKey() != null) { headers.put(field.getKey(), field.getValue()); } } Integer length = connection.getContentLength(); if (length == -1) { length = null; } InputStream stream; if (status >= 400) { stream = connection.getErrorStream(); } else { stream = connection.getInputStream(); } return Response.create(status, reason, headers, stream, length); } } }
olkulyk/feign
core/src/main/java/feign/Client.java
Java
apache-2.0
6,038
/* * Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. 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.wso2.carbon.throttle.core.impl.rolebase; import org.wso2.carbon.throttle.core.CallerConfiguration; import org.wso2.carbon.throttle.core.ThrottleConfiguration; import org.wso2.carbon.throttle.core.ThrottleConstants; import org.wso2.carbon.throttle.core.impl.rolebase.RoleBaseCallerConfiguration; import java.util.HashMap; import java.util.List; import java.util.Map; public class RoleBaseThrottleConfiguration implements ThrottleConfiguration { /* To hold configurations * maps role to The Relevant Caller Configuration * */ private Map configurationsMap; public RoleBaseThrottleConfiguration() { this.configurationsMap = new HashMap(); } public void addCallerConfiguration(CallerConfiguration callerConfiguration) { RoleBaseCallerConfiguration roleBaseCallerConfiguration = (RoleBaseCallerConfiguration) callerConfiguration; List roles = roleBaseCallerConfiguration.getRoles(); if (roles == null) { return; } for (Object role : roles) { String roleKey = ((String) role).trim(); configurationsMap.put(roleKey, roleBaseCallerConfiguration); } } public CallerConfiguration getCallerConfiguration(String roleID) { //get the key for this roleID String key = getConfigurationKeyOfCaller(roleID); return (CallerConfiguration) configurationsMap.get(key); } public String getConfigurationKeyOfCaller(String roleID) { if (roleID != null) { roleID = roleID.trim(); if (configurationsMap.containsKey(roleID)) { return roleID; } } return null; } public int getType() { return ThrottleConstants.ROLE_BASE; } }
wso2/carbon-qos
components/throttling/org.wso2.carbon.throttle.core/src/main/java/org/wso2/carbon/throttle/core/impl/rolebase/RoleBaseThrottleConfiguration.java
Java
apache-2.0
2,525
/* * Copyright 2013 MovingBlocks * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.terasology.logic.inventory; import com.bulletphysics.collision.shapes.BoxShape; import org.terasology.asset.Assets; import org.terasology.audio.events.PlaySoundForOwnerEvent; import org.terasology.entitySystem.entity.EntityBuilder; import org.terasology.entitySystem.entity.EntityRef; import org.terasology.entitySystem.event.ReceiveEvent; import org.terasology.entitySystem.systems.BaseComponentSystem; import org.terasology.entitySystem.systems.RegisterMode; import org.terasology.entitySystem.systems.RegisterSystem; import org.terasology.logic.inventory.events.ItemDroppedEvent; import org.terasology.math.VecMath; import org.terasology.math.geom.Vector3f; import org.terasology.physics.components.RigidBodyComponent; import org.terasology.physics.events.CollideEvent; import org.terasology.physics.shapes.BoxShapeComponent; import org.terasology.registry.In; import org.terasology.rendering.iconmesh.IconMeshFactory; import org.terasology.rendering.logic.LightComponent; import org.terasology.rendering.logic.MeshComponent; import org.terasology.utilities.random.FastRandom; import org.terasology.utilities.random.Random; import org.terasology.world.block.family.BlockFamily; import org.terasology.world.block.items.BlockItemComponent; @RegisterSystem(RegisterMode.AUTHORITY) public class ItemPickupSystem extends BaseComponentSystem { @In private InventoryManager inventoryManager; private Random rand = new FastRandom(); @ReceiveEvent(components = PickupComponent.class) public void onBump(CollideEvent event, EntityRef entity) { PickupComponent pickupComponent = entity.getComponent(PickupComponent.class); if (inventoryManager.giveItem(event.getOtherEntity(), entity, pickupComponent.itemEntity)) { event.getOtherEntity().send(new PlaySoundForOwnerEvent(Assets.getSound("engine:Loot").get(), 1.0f)); pickupComponent.itemEntity = EntityRef.NULL; entity.destroy(); } } @ReceiveEvent public void onBlockItemDropped(ItemDroppedEvent event, EntityRef itemEntity, BlockItemComponent blockItemComponent) { EntityBuilder builder = event.getPickup(); BlockFamily blockFamily = blockItemComponent.blockFamily; if (builder.hasComponent(MeshComponent.class)) { MeshComponent mesh = builder.getComponent(MeshComponent.class); mesh.mesh = blockFamily.getArchetypeBlock().getMesh(); mesh.material = Assets.getMaterial("engine:terrain").get(); } if (blockFamily.getArchetypeBlock().getCollisionShape() instanceof BoxShape && builder.hasComponent(BoxShapeComponent.class)) { javax.vecmath.Vector3f extents = ((BoxShape) blockFamily.getArchetypeBlock().getCollisionShape()).getHalfExtentsWithoutMargin(new javax.vecmath.Vector3f()); extents.scale(2.0f); extents.x = Math.max(extents.x, 0.5f); extents.y = Math.max(extents.y, 0.5f); extents.z = Math.max(extents.z, 0.5f); builder.getComponent(BoxShapeComponent.class).extents.set(VecMath.from(extents)); } if (blockFamily.getArchetypeBlock().getLuminance() > 0 && !builder.hasComponent(LightComponent.class)) { LightComponent lightComponent = builder.addComponent(new LightComponent()); Vector3f randColor = new Vector3f(rand.nextFloat(), rand.nextFloat(), rand.nextFloat()); lightComponent.lightColorDiffuse.set(randColor); lightComponent.lightColorAmbient.set(randColor); } if (builder.hasComponent(RigidBodyComponent.class)) { builder.getComponent(RigidBodyComponent.class).mass = blockItemComponent.blockFamily.getArchetypeBlock().getMass(); } } @ReceiveEvent public void onItemDropped(ItemDroppedEvent event, EntityRef itemEntity, ItemComponent itemComponent) { EntityBuilder builder = event.getPickup(); if (builder.hasComponent(MeshComponent.class)) { MeshComponent mesh = builder.getComponent(MeshComponent.class); if (mesh.mesh == null && itemComponent.icon != null) { builder.getComponent(MeshComponent.class).mesh = IconMeshFactory.getIconMesh(itemComponent.icon); } } } }
leelib/Terasology
engine/src/main/java/org/terasology/logic/inventory/ItemPickupSystem.java
Java
apache-2.0
4,878
/* * * 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. * */ describe("cordova media bridge object", function () { var media = ripple('platform/cordova/2.0.0/bridge/media'), audio = { play: jasmine.createSpy("audio.play"), pause: jasmine.createSpy("audio.pause"), addEventListener: jasmine.createSpy("audio.addEventListener") }; beforeEach(function () { audio.play.reset(); global.Audio = window.Audio = jasmine.createSpy().andReturn(audio); }); describe("when creating", function () { it("creates an audio object for the src", function () { var success = jasmine.createSpy("success"), error = jasmine.createSpy("error"); media.create(success, error, ["id", "foo.mp3"]); expect(window.Audio).toHaveBeenCalled(); expect(audio.src).toBe("foo.mp3"); expect(success).toHaveBeenCalled(); expect(error).not.toHaveBeenCalled(); }); it("calls the error callback when args is empty", function () { var success = jasmine.createSpy("success"), error = jasmine.createSpy("error"); media.create(success, error, []); expect(success).not.toHaveBeenCalled(); expect(error).toHaveBeenCalled(); }); it("can be called without a success callback", function () { expect(function () { media.create(null, null, ["1"]); }).not.toThrow(); }); it("can be called without an error callback", function () { expect(function () { media.create(jasmine.createSpy(), null, ["1"]); }).not.toThrow(); }); it("adds and event listener for error", function () { media.create(null, null, ["1"]); expect(audio.addEventListener).toHaveBeenCalledWith("error", jasmine.any(Function)); }); it("adds and event listener for durationchange", function () { media.create(null, null, ["1"]); expect(audio.addEventListener).toHaveBeenCalledWith("durationchange", jasmine.any(Function)); }); }); describe("when starting audio", function () { it("creates an audio object", function () { media.startPlayingAudio(null, null, ["a", "fred.mp3"]); expect(window.Audio).toHaveBeenCalledWith(); expect(audio.src).toBe("fred.mp3"); }); it("calls play on the audio object", function () { media.startPlayingAudio(null, null, ["b", "bar.mp3"]); expect(audio.play).toHaveBeenCalled(); expect(audio.play.callCount).toBe(1); }); it("calls the error callback when no args", function () { var success = jasmine.createSpy("success"), error = jasmine.createSpy("error"); media.startPlayingAudio(success, error, []); expect(error).toHaveBeenCalled(); expect(success).not.toHaveBeenCalled(); }); it("calls the error callback when just an id arg", function () { var success = jasmine.createSpy("success"), error = jasmine.createSpy("error"); media.startPlayingAudio(success, error, ["larry"]); expect(error).toHaveBeenCalled(); expect(success).not.toHaveBeenCalled(); }); it("calls the pause method when id exists (as well as the play method)", function () { media.startPlayingAudio(null, null, ["c", "crownRoyal.mp3"]); media.startPlayingAudio(null, null, ["c", "wisers.mp3"]); expect(audio.pause).toHaveBeenCalled(); expect(audio.play).toHaveBeenCalled(); expect(audio.pause.callCount).toBe(1); expect(audio.play.callCount).toBe(2); }); it("calls the success callback when things are all rainbows and ponies", function () { var success = jasmine.createSpy("success"), error = jasmine.createSpy("error"); media.startPlayingAudio(success, error, ["chimay", "trios pistolues"]); expect(success).toHaveBeenCalled(); expect(error).not.toHaveBeenCalled(); }); }); describe("when stopping audio", function () { it("calls the error callback when no args", function () { var success = jasmine.createSpy("success"), error = jasmine.createSpy("error"); media.stopPlayingAudio(success, error, []); expect(error).toHaveBeenCalled(); expect(success).not.toHaveBeenCalled(); }); it("calls the error callback when it can't find the audio obj", function () { var success = jasmine.createSpy("success"), error = jasmine.createSpy("error"); media.stopPlayingAudio(success, error, ['lamb_burger']); expect(error).toHaveBeenCalled(); expect(success).not.toHaveBeenCalled(); }); it("calls pause on the audio object when things are 20% cooler", function () { var success = jasmine.createSpy("success"), error = jasmine.createSpy("error"); media.startPlayingAudio(success, error, ['milk_duds', 'yum.mp3']); audio.pause.reset(); media.stopPlayingAudio(success, error, ['milk_duds']); expect(audio.pause).toHaveBeenCalled(); }); it("calls pause on the success callback when things are 20% cooler", function () { var success = jasmine.createSpy("success"), error = jasmine.createSpy("error"); media.startPlayingAudio(success, error, ['nomnomnom', 'yum.mp3']); audio.pause.reset(); media.stopPlayingAudio(success, error, ['nomnomnom']); expect(success).toHaveBeenCalled(); }); }); describe("when seeking the audio", function () { beforeEach(function () { media.create(null, null, ['seek', 'until_it_sleeps.mp3']); }); afterEach(function () { media.stopPlayingAudio(null, null, ['seek']); }); it("calls the error callback when no args", function () { var success = jasmine.createSpy("success"), error = jasmine.createSpy("error"); media.seekToAudio(success, error, []); expect(error).toHaveBeenCalled(); expect(success).not.toHaveBeenCalled(); }); it("calls the error callback when it can't find the id", function () { var success = jasmine.createSpy("success"), error = jasmine.createSpy("error"); media.seekToAudio(success, error, ['hey_you_guys']); expect(error).toHaveBeenCalled(); expect(success).not.toHaveBeenCalled(); }); it("calls the error callback when the seek time isn't provided", function () { var success = jasmine.createSpy("success"), error = jasmine.createSpy("error"); media.seekToAudio(success, error, ['seek']); expect(error).toHaveBeenCalled(); expect(success).not.toHaveBeenCalled(); }); it("sets the currentTime on the audio object", function () { media.seekToAudio(null, null, ['seek', 12345]); expect(audio.currentTime).toBe(12345); }); it("calls the success callback", function () { var success = jasmine.createSpy("success"), error = jasmine.createSpy("error"); media.seekToAudio(success, error, ['seek', 35]); expect(success).toHaveBeenCalled(); expect(error).not.toHaveBeenCalled(); }); }); describe("when pausing audio", function () { beforeEach(function () { media.create(null, null, ['pause', 'hey_jude.mp3']); }); afterEach(function () { media.stopPlayingAudio(null, null, ['pause']); }); it("calls the error callback when no args", function () { var success = jasmine.createSpy("success"), error = jasmine.createSpy("error"); media.pausePlayingAudio(success, error, []); expect(error).toHaveBeenCalled(); expect(success).not.toHaveBeenCalled(); }); it("calls the error callback when it can't find the id", function () { var success = jasmine.createSpy("success"), error = jasmine.createSpy("error"); media.pausePlayingAudio(success, error, ['all along the watchtower']); expect(error).toHaveBeenCalled(); expect(success).not.toHaveBeenCalled(); }); it("calls the pause method on the audio object", function () { media.pausePlayingAudio(null, null, ['pause']); expect(audio.pause).toHaveBeenCalled(); }); it("calls the success callback", function () { var success = jasmine.createSpy("success"), error = jasmine.createSpy("error"); media.pausePlayingAudio(success, error, ['pause']); expect(success).toHaveBeenCalled(); expect(error).not.toHaveBeenCalled(); }); }); describe("when getting the current position", function () { beforeEach(function () { media.create(null, null, ['position', 'space_hog.mp3']); }); afterEach(function () { media.stopPlayingAudio(null, null, ['position']); }); it("calls the error callback when no args", function () { var success = jasmine.createSpy("success"), error = jasmine.createSpy("error"); media.getCurrentPositionAudio(success, error, []); expect(error).toHaveBeenCalled(); expect(success).not.toHaveBeenCalled(); }); it("calls the error callback when it can't find the id", function () { var success = jasmine.createSpy("success"), error = jasmine.createSpy("error"); media.getCurrentPositionAudio(success, error, ['hey you guys']); expect(error).toHaveBeenCalled(); expect(success).not.toHaveBeenCalled(); }); it("calls the success callback with the currentTime", function () { var success = jasmine.createSpy("success"), error = jasmine.createSpy("error"); audio.currentTime = 12; media.getCurrentPositionAudio(success, error, ['position']); expect(success).toHaveBeenCalledWith(12); expect(error).not.toHaveBeenCalled(); }); }); describe("when getting the duration", function () { beforeEach(function () { media.create(null, null, ['duration', 'cum_on_feel_the_noise.mp3']); }); afterEach(function () { media.stopPlayingAudio(null, null, ['duration']); }); it("calls the error callback when no args", function () { var success = jasmine.createSpy("success"), error = jasmine.createSpy("error"); media.getDuration(success, error, []); expect(error).toHaveBeenCalled(); expect(success).not.toHaveBeenCalled(); }); it("calls the error callback when it can't find the id", function () { var success = jasmine.createSpy("success"), error = jasmine.createSpy("error"); media.getDuration(success, error, ['peanuts']); expect(error).toHaveBeenCalled(); expect(success).not.toHaveBeenCalled(); }); it("calls the success callback with the currentTime", function () { var success = jasmine.createSpy("success"), error = jasmine.createSpy("error"); audio.duration = 80000; media.getDuration(success, error, ['duration']); expect(success).toHaveBeenCalledWith(80000); expect(error).not.toHaveBeenCalled(); }); }); describe("when starting to record audio", function () { it("can be called with no callbacks", function () { expect(function () { media.startRecordingAudio(); }).not.toThrow(); }); it("calls the error callback", function () { var success = jasmine.createSpy("success"), error = jasmine.createSpy("error"); media.startRecordingAudio(success, error, []); expect(success).not.toHaveBeenCalled(); expect(error).toHaveBeenCalled(); }); }); describe("when stopping recording audio", function () { it("can be called with no callbacks", function () { expect(function () { media.stopRecordingAudio(); }).not.toThrow(); }); it("calls the error callback", function () { var success = jasmine.createSpy("success"), error = jasmine.createSpy("error"); media.stopRecordingAudio(success, error, []); expect(success).not.toHaveBeenCalled(); expect(error).toHaveBeenCalled(); }); }); describe("when releasing", function () { beforeEach(function () { media.create(null, null, ['release', 'just_beat_it.mp3']); }); it("calls the error callback when no args", function () { var success = jasmine.createSpy("success"), error = jasmine.createSpy("error"); media.release(success, error, []); expect(error).toHaveBeenCalled(); expect(success).not.toHaveBeenCalled(); }); it("calls the success callback when it can't find the id", function () { var success = jasmine.createSpy("success"), error = jasmine.createSpy("error"); media.release(success, error, ['rainbow dash']); expect(success).toHaveBeenCalled(); expect(error).not.toHaveBeenCalled(); }); it("calls the success callback", function () { var success = jasmine.createSpy("success"), error = jasmine.createSpy("error"); audio.duration = 80000; media.release(success, error, ['release']); expect(success).toHaveBeenCalled(); expect(error).not.toHaveBeenCalled(); }); }); });
sangjin3/webida-server
src/server/notify/ext/incubator-ripple/test/unit/client/cordova/media.js
JavaScript
apache-2.0
15,371
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0 and the Server Side Public License, v 1; you may not use this file except * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ package org.elasticsearch.test.test; import org.elasticsearch.Version; import org.elasticsearch.test.ESIntegTestCase; import org.elasticsearch.test.InternalTestCluster; import org.elasticsearch.test.VersionUtils; /** * This test ensures that after a cluster restart, the forbidPrivateIndexSettings value * is kept */ @ESIntegTestCase.ClusterScope(scope = ESIntegTestCase.Scope.SUITE) public class InternalClusterForbiddenSettingIT extends ESIntegTestCase { @Override protected boolean forbidPrivateIndexSettings() { return false; } public void testRestart() throws Exception { final Version version = VersionUtils.randomPreviousCompatibleVersion(random(), Version.CURRENT); // create / delete an index with forbidden setting prepareCreate("test").setSettings(settings(version).build()).get(); client().admin().indices().prepareDelete("test").get(); // full restart internalCluster().fullRestart(); // create / delete an index with forbidden setting prepareCreate("test").setSettings(settings(version).build()).get(); client().admin().indices().prepareDelete("test").get(); } public void testRollingRestart() throws Exception { final Version version = VersionUtils.randomPreviousCompatibleVersion(random(), Version.CURRENT); // create / delete an index with forbidden setting prepareCreate("test").setSettings(settings(version).build()).get(); client().admin().indices().prepareDelete("test").get(); // rolling restart internalCluster().rollingRestart(new InternalTestCluster.RestartCallback()); // create / delete an index with forbidden setting prepareCreate("test").setSettings(settings(version).build()).get(); client().admin().indices().prepareDelete("test").get(); } }
robin13/elasticsearch
test/framework/src/test/java/org/elasticsearch/test/test/InternalClusterForbiddenSettingIT.java
Java
apache-2.0
2,218
package network // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. import ( "context" "github.com/Azure/go-autorest/autorest" "github.com/Azure/go-autorest/autorest/azure" "github.com/Azure/go-autorest/tracing" "net/http" ) // SecurityGroupsClient is the network Client type SecurityGroupsClient struct { BaseClient } // NewSecurityGroupsClient creates an instance of the SecurityGroupsClient client. func NewSecurityGroupsClient(subscriptionID string) SecurityGroupsClient { return NewSecurityGroupsClientWithBaseURI(DefaultBaseURI, subscriptionID) } // NewSecurityGroupsClientWithBaseURI creates an instance of the SecurityGroupsClient client. func NewSecurityGroupsClientWithBaseURI(baseURI string, subscriptionID string) SecurityGroupsClient { return SecurityGroupsClient{NewWithBaseURI(baseURI, subscriptionID)} } // CreateOrUpdate creates or updates a network security group in the specified resource group. // Parameters: // resourceGroupName - the name of the resource group. // networkSecurityGroupName - the name of the network security group. // parameters - parameters supplied to the create or update network security group operation. func (client SecurityGroupsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, networkSecurityGroupName string, parameters SecurityGroup) (result SecurityGroupsCreateOrUpdateFuture, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/SecurityGroupsClient.CreateOrUpdate") defer func() { sc := -1 if result.Response() != nil { sc = result.Response().StatusCode } tracing.EndSpan(ctx, sc, err) }() } req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, networkSecurityGroupName, parameters) if err != nil { err = autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "CreateOrUpdate", nil, "Failure preparing request") return } result, err = client.CreateOrUpdateSender(req) if err != nil { err = autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "CreateOrUpdate", result.Response(), "Failure sending request") return } return } // CreateOrUpdatePreparer prepares the CreateOrUpdate request. func (client SecurityGroupsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, networkSecurityGroupName string, parameters SecurityGroup) (*http.Request, error) { pathParameters := map[string]interface{}{ "networkSecurityGroupName": autorest.Encode("path", networkSecurityGroupName), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2017-09-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsContentType("application/json; charset=utf-8"), autorest.AsPut(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkSecurityGroups/{networkSecurityGroupName}", pathParameters), autorest.WithJSON(parameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the // http.Response Body if it receives an error. func (client SecurityGroupsClient) CreateOrUpdateSender(req *http.Request) (future SecurityGroupsCreateOrUpdateFuture, err error) { sd := autorest.GetSendDecorators(req.Context(), azure.DoRetryWithRegistration(client.Client)) var resp *http.Response resp, err = autorest.SendWithSender(client, req, sd...) if err != nil { return } future.Future, err = azure.NewFutureFromResponse(resp) return } // CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always // closes the http.Response Body. func (client SecurityGroupsClient) CreateOrUpdateResponder(resp *http.Response) (result SecurityGroup, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // Delete deletes the specified network security group. // Parameters: // resourceGroupName - the name of the resource group. // networkSecurityGroupName - the name of the network security group. func (client SecurityGroupsClient) Delete(ctx context.Context, resourceGroupName string, networkSecurityGroupName string) (result SecurityGroupsDeleteFuture, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/SecurityGroupsClient.Delete") defer func() { sc := -1 if result.Response() != nil { sc = result.Response().StatusCode } tracing.EndSpan(ctx, sc, err) }() } req, err := client.DeletePreparer(ctx, resourceGroupName, networkSecurityGroupName) if err != nil { err = autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "Delete", nil, "Failure preparing request") return } result, err = client.DeleteSender(req) if err != nil { err = autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "Delete", result.Response(), "Failure sending request") return } return } // DeletePreparer prepares the Delete request. func (client SecurityGroupsClient) DeletePreparer(ctx context.Context, resourceGroupName string, networkSecurityGroupName string) (*http.Request, error) { pathParameters := map[string]interface{}{ "networkSecurityGroupName": autorest.Encode("path", networkSecurityGroupName), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2017-09-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsDelete(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkSecurityGroups/{networkSecurityGroupName}", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // DeleteSender sends the Delete request. The method will close the // http.Response Body if it receives an error. func (client SecurityGroupsClient) DeleteSender(req *http.Request) (future SecurityGroupsDeleteFuture, err error) { sd := autorest.GetSendDecorators(req.Context(), azure.DoRetryWithRegistration(client.Client)) var resp *http.Response resp, err = autorest.SendWithSender(client, req, sd...) if err != nil { return } future.Future, err = azure.NewFutureFromResponse(resp) return } // DeleteResponder handles the response to the Delete request. The method always // closes the http.Response Body. func (client SecurityGroupsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), autorest.ByClosing()) result.Response = resp return } // Get gets the specified network security group. // Parameters: // resourceGroupName - the name of the resource group. // networkSecurityGroupName - the name of the network security group. // expand - expands referenced resources. func (client SecurityGroupsClient) Get(ctx context.Context, resourceGroupName string, networkSecurityGroupName string, expand string) (result SecurityGroup, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/SecurityGroupsClient.Get") defer func() { sc := -1 if result.Response.Response != nil { sc = result.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } req, err := client.GetPreparer(ctx, resourceGroupName, networkSecurityGroupName, expand) if err != nil { err = autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "Get", nil, "Failure preparing request") return } resp, err := client.GetSender(req) if err != nil { result.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "Get", resp, "Failure sending request") return } result, err = client.GetResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "Get", resp, "Failure responding to request") } return } // GetPreparer prepares the Get request. func (client SecurityGroupsClient) GetPreparer(ctx context.Context, resourceGroupName string, networkSecurityGroupName string, expand string) (*http.Request, error) { pathParameters := map[string]interface{}{ "networkSecurityGroupName": autorest.Encode("path", networkSecurityGroupName), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2017-09-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } if len(expand) > 0 { queryParameters["$expand"] = autorest.Encode("query", expand) } preparer := autorest.CreatePreparer( autorest.AsGet(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkSecurityGroups/{networkSecurityGroupName}", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // GetSender sends the Get request. The method will close the // http.Response Body if it receives an error. func (client SecurityGroupsClient) GetSender(req *http.Request) (*http.Response, error) { sd := autorest.GetSendDecorators(req.Context(), azure.DoRetryWithRegistration(client.Client)) return autorest.SendWithSender(client, req, sd...) } // GetResponder handles the response to the Get request. The method always // closes the http.Response Body. func (client SecurityGroupsClient) GetResponder(resp *http.Response) (result SecurityGroup, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // List gets all network security groups in a resource group. // Parameters: // resourceGroupName - the name of the resource group. func (client SecurityGroupsClient) List(ctx context.Context, resourceGroupName string) (result SecurityGroupListResultPage, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/SecurityGroupsClient.List") defer func() { sc := -1 if result.sglr.Response.Response != nil { sc = result.sglr.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } result.fn = client.listNextResults req, err := client.ListPreparer(ctx, resourceGroupName) if err != nil { err = autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "List", nil, "Failure preparing request") return } resp, err := client.ListSender(req) if err != nil { result.sglr.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "List", resp, "Failure sending request") return } result.sglr, err = client.ListResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "List", resp, "Failure responding to request") } return } // ListPreparer prepares the List request. func (client SecurityGroupsClient) ListPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) { pathParameters := map[string]interface{}{ "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2017-09-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsGet(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkSecurityGroups", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // ListSender sends the List request. The method will close the // http.Response Body if it receives an error. func (client SecurityGroupsClient) ListSender(req *http.Request) (*http.Response, error) { sd := autorest.GetSendDecorators(req.Context(), azure.DoRetryWithRegistration(client.Client)) return autorest.SendWithSender(client, req, sd...) } // ListResponder handles the response to the List request. The method always // closes the http.Response Body. func (client SecurityGroupsClient) ListResponder(resp *http.Response) (result SecurityGroupListResult, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // listNextResults retrieves the next set of results, if any. func (client SecurityGroupsClient) listNextResults(ctx context.Context, lastResults SecurityGroupListResult) (result SecurityGroupListResult, err error) { req, err := lastResults.securityGroupListResultPreparer(ctx) if err != nil { return result, autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "listNextResults", nil, "Failure preparing next results request") } if req == nil { return } resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} return result, autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "listNextResults", resp, "Failure sending next results request") } result, err = client.ListResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "listNextResults", resp, "Failure responding to next results request") } return } // ListComplete enumerates all values, automatically crossing page boundaries as required. func (client SecurityGroupsClient) ListComplete(ctx context.Context, resourceGroupName string) (result SecurityGroupListResultIterator, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/SecurityGroupsClient.List") defer func() { sc := -1 if result.Response().Response.Response != nil { sc = result.page.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } result.page, err = client.List(ctx, resourceGroupName) return } // ListAll gets all network security groups in a subscription. func (client SecurityGroupsClient) ListAll(ctx context.Context) (result SecurityGroupListResultPage, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/SecurityGroupsClient.ListAll") defer func() { sc := -1 if result.sglr.Response.Response != nil { sc = result.sglr.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } result.fn = client.listAllNextResults req, err := client.ListAllPreparer(ctx) if err != nil { err = autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "ListAll", nil, "Failure preparing request") return } resp, err := client.ListAllSender(req) if err != nil { result.sglr.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "ListAll", resp, "Failure sending request") return } result.sglr, err = client.ListAllResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "ListAll", resp, "Failure responding to request") } return } // ListAllPreparer prepares the ListAll request. func (client SecurityGroupsClient) ListAllPreparer(ctx context.Context) (*http.Request, error) { pathParameters := map[string]interface{}{ "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2017-09-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsGet(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/networkSecurityGroups", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // ListAllSender sends the ListAll request. The method will close the // http.Response Body if it receives an error. func (client SecurityGroupsClient) ListAllSender(req *http.Request) (*http.Response, error) { sd := autorest.GetSendDecorators(req.Context(), azure.DoRetryWithRegistration(client.Client)) return autorest.SendWithSender(client, req, sd...) } // ListAllResponder handles the response to the ListAll request. The method always // closes the http.Response Body. func (client SecurityGroupsClient) ListAllResponder(resp *http.Response) (result SecurityGroupListResult, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // listAllNextResults retrieves the next set of results, if any. func (client SecurityGroupsClient) listAllNextResults(ctx context.Context, lastResults SecurityGroupListResult) (result SecurityGroupListResult, err error) { req, err := lastResults.securityGroupListResultPreparer(ctx) if err != nil { return result, autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "listAllNextResults", nil, "Failure preparing next results request") } if req == nil { return } resp, err := client.ListAllSender(req) if err != nil { result.Response = autorest.Response{Response: resp} return result, autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "listAllNextResults", resp, "Failure sending next results request") } result, err = client.ListAllResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "listAllNextResults", resp, "Failure responding to next results request") } return } // ListAllComplete enumerates all values, automatically crossing page boundaries as required. func (client SecurityGroupsClient) ListAllComplete(ctx context.Context) (result SecurityGroupListResultIterator, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/SecurityGroupsClient.ListAll") defer func() { sc := -1 if result.Response().Response.Response != nil { sc = result.page.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } result.page, err = client.ListAll(ctx) return } // UpdateTags updates a network security group tags. // Parameters: // resourceGroupName - the name of the resource group. // networkSecurityGroupName - the name of the network security group. // parameters - parameters supplied to update network security group tags. func (client SecurityGroupsClient) UpdateTags(ctx context.Context, resourceGroupName string, networkSecurityGroupName string, parameters TagsObject) (result SecurityGroupsUpdateTagsFuture, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/SecurityGroupsClient.UpdateTags") defer func() { sc := -1 if result.Response() != nil { sc = result.Response().StatusCode } tracing.EndSpan(ctx, sc, err) }() } req, err := client.UpdateTagsPreparer(ctx, resourceGroupName, networkSecurityGroupName, parameters) if err != nil { err = autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "UpdateTags", nil, "Failure preparing request") return } result, err = client.UpdateTagsSender(req) if err != nil { err = autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "UpdateTags", result.Response(), "Failure sending request") return } return } // UpdateTagsPreparer prepares the UpdateTags request. func (client SecurityGroupsClient) UpdateTagsPreparer(ctx context.Context, resourceGroupName string, networkSecurityGroupName string, parameters TagsObject) (*http.Request, error) { pathParameters := map[string]interface{}{ "networkSecurityGroupName": autorest.Encode("path", networkSecurityGroupName), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2017-09-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsContentType("application/json; charset=utf-8"), autorest.AsPatch(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkSecurityGroups/{networkSecurityGroupName}", pathParameters), autorest.WithJSON(parameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // UpdateTagsSender sends the UpdateTags request. The method will close the // http.Response Body if it receives an error. func (client SecurityGroupsClient) UpdateTagsSender(req *http.Request) (future SecurityGroupsUpdateTagsFuture, err error) { sd := autorest.GetSendDecorators(req.Context(), azure.DoRetryWithRegistration(client.Client)) var resp *http.Response resp, err = autorest.SendWithSender(client, req, sd...) if err != nil { return } future.Future, err = azure.NewFutureFromResponse(resp) return } // UpdateTagsResponder handles the response to the UpdateTags request. The method always // closes the http.Response Body. func (client SecurityGroupsClient) UpdateTagsResponder(resp *http.Response) (result SecurityGroup, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return }
ironcladlou/origin
vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2017-09-01/network/securitygroups.go
GO
apache-2.0
23,083
function f1(): { new(): void; } { return function() { return 1; } }; // this used to not be an error, but is now that we've changed our assignment compatibility rules
bolinfest/typescript
tests/compiler/testCode/targetTypeVoidFunc.ts
TypeScript
apache-2.0
167
/* * 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.wicket.model.lambda; import java.io.Serializable; /** * A test object for lambda related tests */ public class Address implements Serializable { private String street; private int number; public String getStreet() { return street; } public void setStreet(String street) { this.street = street; } public int getNumber() { return number; } public void setNumber(int number) { this.number = number; } }
dashorst/wicket
wicket-core/src/test/java/org/apache/wicket/model/lambda/Address.java
Java
apache-2.0
1,253
package test.export.annotation.testConsumer; import org.osgi.annotation.versioning.ProviderType; import test.export.annotation.testConsumer.used.ConsumerUsed; @ProviderType public interface ConsumerInterface extends ConsumerUsed { }
psoreide/bnd
biz.aQute.bndlib.tests/test/test/export/annotation/testConsumer/ConsumerInterface.java
Java
apache-2.0
237
--- layout: documentation title: Download Block Images --- Starting with version nb177 of MIT App Inventor, it is possible to export individual blocks in the Portable Network Graphics (PNG) image format. This feature makes it easier to write tutorials and curriculum materials by giving high quality images of blocks without needing to crop the larger workspace export image or stitch together screenshots of blocks. ## Exporting Blocks To export a block, right click on the block to bring up the context menu and click on the "Download Blocks as PNG" menu item: ![Right click menu on a block showing the Download Blocks as PNG menu item](download-blocks-menu.png) The browser will prompt you to download a file called blocks.png after selecting this menu item. ## Importing Blocks Blocks images created in this way contain additional metadata in the image that stores the block code in a machine readable format. MIT App Inventor will read the content of this metadata if the image is drag-and-dropped into the blocks workspace. Below is a video demonstrating how you can drag and drop blocks images from the documentation into App Inventor. You can also drag files from your computer to the workspace (similar to cloud storage services). <video width="640" height="320"> <source src="drag-and-drop.mp4" type="video/mp4" /> Your browser does not support playing this video. </video>
ewpatton/appinventor-sources
appinventor/docs/markdown/reference/other/download-pngs.md
Markdown
apache-2.0
1,392
// btlso_timereventmanager.cpp -*-C++-*- // ---------------------------------------------------------------------------- // NOTICE // // This component is not up to date with current BDE coding standards, and // should not be used as an example for new development. // ---------------------------------------------------------------------------- #include <btlso_timereventmanager.h> #include <bsls_ident.h> BSLS_IDENT_RCSID(btlso_timereventmanager_cpp,"$Id$ $CSID$") namespace BloombergLP { namespace btlso { // ----------------------- // class TimerEventManager // ----------------------- TimerEventManager::~TimerEventManager() { } } // close package namespace } // close enterprise namespace // ---------------------------------------------------------------------------- // Copyright 2015 Bloomberg Finance L.P. // // 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. // ----------------------------- END-OF-FILE ----------------------------------
bowlofstew/bde
groups/btl/btlso/btlso_timereventmanager.cpp
C++
apache-2.0
1,596
--- external help file: Microsoft.Azure.Commands.ApiManagement.dll-Help.xml ms.assetid: A7CABC63-2E9C-474B-A4F0-69F13A16F65A online version: schema: 2.0.0 --- # Get-AzureRmApiManagementSsoToken ## SYNOPSIS Gets a link with an SSO token to a deployed management portal of an API Management service. ## SYNTAX ``` Get-AzureRmApiManagementSsoToken -ResourceGroupName <String> -Name <String> [-InformationAction <ActionPreference>] [-InformationVariable <String>] [<CommonParameters>] ``` ## DESCRIPTION The **Get-AzureRmApiManagementSsoToken** cmdlet returns a link (URL) containing a single sign-on (SSO) token to a deployed management portal of an API Management service. ## EXAMPLES ### Example 1: Get the SSO token of an API Management service ``` PS C:\>Get-AzureRmApiManagementSsoToken -ResourceGroupName "Contoso" -Name "ContosoApi" ``` This command gets the SSO token of an API Management service. ## PARAMETERS ### -ResourceGroupName Specifies the name of resource group under which API Management exists. ```yaml Type: String Parameter Sets: (All) Aliases: Required: True Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Name Specifies the name of the API Management instance. ```yaml Type: String Parameter Sets: (All) Aliases: Required: True Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -InformationAction Specifies how this cmdlet responds to an information event. The acceptable values for this parameter are: - Continue - Ignore - Inquire - SilentlyContinue - Stop - Suspend ```yaml Type: ActionPreference Parameter Sets: (All) Aliases: infa Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -InformationVariable Specifies an information variable. ```yaml Type: String Parameter Sets: (All) Aliases: iv Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see about_CommonParameters (http://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ## OUTPUTS ## NOTES ## RELATED LINKS [Get-AzureRmApiManagement](./Get-AzureRmApiManagement.md)
zhencui/azure-powershell
src/ResourceManager/ApiManagement/Commands.ApiManagement/help/Get-AzureRmApiManagementSsoToken.md
Markdown
apache-2.0
2,536
<!DOCTYPE html> <!-- Copyright 2012 Rustici Software 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. --> <html> <head> <title>TinCanJS Tests (TinCan)</title> <link rel="stylesheet" href="../vendor/qunit-1.10.0pre.css" type="text/css" media="screen" /> <script src="../vendor/jquery-1.9.1.js"></script> <script type="text/javascript" src="../vendor/qunit-1.10.0pre.js"></script> <script type="text/javascript" src="../../build/tincan.js"></script> </head> <body> <h1 id="qunit-header">TinCanJS Test Suite (TinCan)</h1> <h2 id="qunit-banner"></h2> <div id="qunit-testrunner-toolbar"></div> <h2 id="qunit-userAgent"></h2> <ol id="qunit-tests"></ol> <script src="../js/BrowserPrep.js"></script> <script src="../config.js"></script> <script src="../js/unit/TinCan.js"></script> </body> </html>
garemoko/TinCanJS
test/single/TinCan.html
HTML
apache-2.0
1,355
//>>built define("dojox/form/nls/tr/Uploader",{label:"Dosyalar\u0131 Se\u00e7..."});
aconyteds/Esri-Ozone-Map-Widget
vendor/js/esri/arcgis_js_api/library/3.12/3.12compact/dojox/form/nls/tr/Uploader.js
JavaScript
apache-2.0
84
// Copyright 2013 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // Declares helper functions for dealing with filters and determining whether or // not a given block, basic block or instruction should be instrumented or // transformed. #ifndef SYZYGY_BLOCK_GRAPH_FILTER_UTIL_H_ #define SYZYGY_BLOCK_GRAPH_FILTER_UTIL_H_ #include "syzygy/block_graph/basic_block.h" #include "syzygy/block_graph/block_graph.h" #include "syzygy/core/address_filter.h" namespace block_graph { typedef core::AddressFilter<core::RelativeAddress, size_t> RelativeAddressFilter; // Determines if the given @p block is filtered. A block is filtered if any of // it's source data is marked in the filter. // @param filter The filter to be checked. // @param block The block to be checked. // @returns true if the block is filtered, false otherwise. bool IsFiltered(const RelativeAddressFilter& filter, const block_graph::BlockGraph::Block* block); // Determines if the given @p basic_block is filtered. A basic block is filtered // if any of its source data is marked in the filter. // @param filter The filter to be checked. // @param basic_block The basic block to be checked. // @returns true if the basic block is filtered, false otherwise. bool IsFiltered(const RelativeAddressFilter& filter, const block_graph::BasicBlock* basic_block); bool IsFiltered(const RelativeAddressFilter& filter, const block_graph::BasicCodeBlock* basic_block); bool IsFiltered(const RelativeAddressFilter& filter, const block_graph::BasicDataBlock* basic_block); // Determines if the given instruction is filtered. An instruction is filtered // if any of its source data is marked in the given filter. // @param filter The filter to be checked. // @param instruction The instruction to be checked. // @returns true if the instruction is filtered, false otherwise. bool IsFiltered(const RelativeAddressFilter& filter, const block_graph::Instruction& instruction); } // namespace block_graph #endif // SYZYGY_BLOCK_GRAPH_FILTER_UTIL_H_
wangming28/syzygy
syzygy/block_graph/filter_util.h
C
apache-2.0
2,634
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.WindowsAzure; using Microsoft.WindowsAzure.Management.ServiceBus.Models; namespace Microsoft.WindowsAzure.Management.ServiceBus { /// <summary> /// The Service Bus Management API includes operations for managing Service /// Bus queues. /// </summary> public partial interface IQueueOperations { /// <summary> /// Creates a new queue. Once created, this queue's resource manifest /// is immutable. This operation is idempotent. Repeating the create /// call, after a queue with same name has been created successfully, /// will result in a 409 Conflict error message. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj856295.aspx /// for more information) /// </summary> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='queue'> /// The service bus queue. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A response to a request for a particular queue. /// </returns> Task<ServiceBusQueueResponse> CreateAsync(string namespaceName, ServiceBusQueueCreateParameters queue, CancellationToken cancellationToken); /// <summary> /// Deletes an existing queue. This operation will also remove all /// associated state including messages in the queue. (see /// http://msdn.microsoft.com/en-us/library/hh780747.aspx for more /// information) /// </summary> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='queueName'> /// The queue name. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> Task<OperationResponse> DeleteAsync(string namespaceName, string queueName, CancellationToken cancellationToken); /// <summary> /// The queue description is an XML AtomPub document that defines the /// desired semantics for a subscription. The queue description /// contains the following properties. For more information, see the /// QueueDescription Properties topic. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/hh780773.aspx /// for more information) /// </summary> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='queueName'> /// The queue name. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A response to a request for a particular queue. /// </returns> Task<ServiceBusQueueResponse> GetAsync(string namespaceName, string queueName, CancellationToken cancellationToken); /// <summary> /// Gets the set of connection strings for a queue. /// </summary> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='queueName'> /// The queue name. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The set of connection details for a service bus entity. /// </returns> Task<ServiceBusConnectionDetailsResponse> GetConnectionDetailsAsync(string namespaceName, string queueName, CancellationToken cancellationToken); /// <summary> /// Enumerates the queues in the service namespace. The result is /// returned in pages, each containing up to 100 queues. If the /// namespace contains more than 100 queues, a feed is returned that /// contains the first page and a next link with the URI to view the /// next page of data. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/hh780759.asp /// for more information) /// </summary> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A response to a request for a list of queues. /// </returns> Task<ServiceBusQueuesResponse> ListAsync(string namespaceName, CancellationToken cancellationToken); /// <summary> /// Updates the queue description and makes a call to update /// corresponding DB entries. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj856305.aspx /// for more information) /// </summary> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='queue'> /// The service bus queue. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A response to a request for a particular queue. /// </returns> Task<ServiceBusQueueResponse> UpdateAsync(string namespaceName, ServiceBusQueue queue, CancellationToken cancellationToken); } }
jianghaolu/azure-sdk-for-net
src/ServiceBusManagement/Generated/IQueueOperations.cs
C#
apache-2.0
6,368
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.orc; import com.facebook.presto.memory.context.LocalMemoryContext; import com.google.common.util.concurrent.ListenableFuture; import static java.util.Objects.requireNonNull; /* * This class is a copy of HiveOrcLocalMemoryContext. * Any changes made to HiveOrcLocalMemoryContext should be made here as well */ public class TestingHiveOrcLocalMemoryContext implements OrcLocalMemoryContext { private final LocalMemoryContext delegate; TestingHiveOrcLocalMemoryContext(LocalMemoryContext delegate) { this.delegate = requireNonNull(delegate, "delegate is null"); } @Override public ListenableFuture<?> setBytes(long bytes) { return delegate.setBytes(bytes); } @Override public void close() { delegate.close(); } }
facebook/presto
presto-orc/src/test/java/com/facebook/presto/orc/TestingHiveOrcLocalMemoryContext.java
Java
apache-2.0
1,389
#-- # 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. #++ module Qpid::Proton # Selectable enables accessing the underlying file descriptors # for Messenger. # # @private class Selectable # @private include Util::SwigHelper # @private PROTON_METHOD_PREFIX = "pn_selectable" # Returns the underlying file descriptor. # # This can be used in conjunction with the IO class. # def fileno Cproton.pn_selectable_get_fd(@impl) end proton_reader :reading, :is_or_get => :is proton_reader :writing, :is_or_get => :is proton_caller :readable proton_caller :writable proton_caller :expired proton_accessor :registered, :is_or_get => :is proton_accessor :terminal, :is_or_get => :is proton_caller :terminate proton_caller :release # @private def self.wrap(impl) return nil if impl.nil? self.fetch_instance(impl, :pn_selectable_attachments) || Selectable.new(impl) end # @private include Util::Wrapper # @private def initialize(impl) @impl = impl self.class.store_instance(self, :pn_selectable_attachments) end private DEFAULT = Object.new public def fileno(fd = DEFAULT) if fd == DEFAULT Cproton.pn_selectable_get_fd(@impl) elsif fd.nil? Cproton.pn_selectable_set_fd(@impl, Cproton::PN_INVALID_SOCKET) else Cproton.pn_selectable_set_fd(@impl, fd) end end def reading=(reading) if reading.nil? reading = false elsif reading == "0" reading = false else reading = true end Cproton.pn_selectable_set_reading(@impl, reading ? true : false) end def writing=(writing) if writing.nil? writing = false elsif writing == "0" writing = false else writing = true end Cproton.pn_selectable_set_writing(@impl, writing ? true : false) end def deadline tstamp = Cproton.pn_selectable_get_deadline(@impl) return nil if tstamp.nil? mills_to_sec(tstamp) end def deadline=(deadline) Cproton.pn_selectable_set_deadline(sec_to_millis(deadline)) end def to_io @io ||= IO.new(fileno) end end end
prestona/qpid-proton
proton-c/bindings/ruby/lib/core/selectable.rb
Ruby
apache-2.0
3,019
/* * Copyright 2015 Netflix, 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. * */ package io.reactivex.netty.threads; import io.netty.util.concurrent.DefaultThreadFactory; public class RxDefaultThreadFactory extends DefaultThreadFactory { public RxDefaultThreadFactory(String threadNamePrefix) { super(threadNamePrefix, true); } }
NiteshKant/RxNetty
rxnetty-common/src/main/java/io/reactivex/netty/threads/RxDefaultThreadFactory.java
Java
apache-2.0
868
package network // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. import ( "context" "github.com/Azure/go-autorest/autorest" "github.com/Azure/go-autorest/autorest/azure" "github.com/Azure/go-autorest/tracing" "net/http" ) // LoadBalancerFrontendIPConfigurationsClient is the network Client type LoadBalancerFrontendIPConfigurationsClient struct { BaseClient } // NewLoadBalancerFrontendIPConfigurationsClient creates an instance of the LoadBalancerFrontendIPConfigurationsClient // client. func NewLoadBalancerFrontendIPConfigurationsClient(subscriptionID string) LoadBalancerFrontendIPConfigurationsClient { return NewLoadBalancerFrontendIPConfigurationsClientWithBaseURI(DefaultBaseURI, subscriptionID) } // NewLoadBalancerFrontendIPConfigurationsClientWithBaseURI creates an instance of the // LoadBalancerFrontendIPConfigurationsClient client. func NewLoadBalancerFrontendIPConfigurationsClientWithBaseURI(baseURI string, subscriptionID string) LoadBalancerFrontendIPConfigurationsClient { return LoadBalancerFrontendIPConfigurationsClient{NewWithBaseURI(baseURI, subscriptionID)} } // Get gets load balancer frontend IP configuration. // Parameters: // resourceGroupName - the name of the resource group. // loadBalancerName - the name of the load balancer. // frontendIPConfigurationName - the name of the frontend IP configuration. func (client LoadBalancerFrontendIPConfigurationsClient) Get(ctx context.Context, resourceGroupName string, loadBalancerName string, frontendIPConfigurationName string) (result FrontendIPConfiguration, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/LoadBalancerFrontendIPConfigurationsClient.Get") defer func() { sc := -1 if result.Response.Response != nil { sc = result.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } req, err := client.GetPreparer(ctx, resourceGroupName, loadBalancerName, frontendIPConfigurationName) if err != nil { err = autorest.NewErrorWithError(err, "network.LoadBalancerFrontendIPConfigurationsClient", "Get", nil, "Failure preparing request") return } resp, err := client.GetSender(req) if err != nil { result.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "network.LoadBalancerFrontendIPConfigurationsClient", "Get", resp, "Failure sending request") return } result, err = client.GetResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "network.LoadBalancerFrontendIPConfigurationsClient", "Get", resp, "Failure responding to request") } return } // GetPreparer prepares the Get request. func (client LoadBalancerFrontendIPConfigurationsClient) GetPreparer(ctx context.Context, resourceGroupName string, loadBalancerName string, frontendIPConfigurationName string) (*http.Request, error) { pathParameters := map[string]interface{}{ "frontendIPConfigurationName": autorest.Encode("path", frontendIPConfigurationName), "loadBalancerName": autorest.Encode("path", loadBalancerName), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2019-04-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsGet(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}/frontendIPConfigurations/{frontendIPConfigurationName}", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // GetSender sends the Get request. The method will close the // http.Response Body if it receives an error. func (client LoadBalancerFrontendIPConfigurationsClient) GetSender(req *http.Request) (*http.Response, error) { sd := autorest.GetSendDecorators(req.Context(), azure.DoRetryWithRegistration(client.Client)) return autorest.SendWithSender(client, req, sd...) } // GetResponder handles the response to the Get request. The method always // closes the http.Response Body. func (client LoadBalancerFrontendIPConfigurationsClient) GetResponder(resp *http.Response) (result FrontendIPConfiguration, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // List gets all the load balancer frontend IP configurations. // Parameters: // resourceGroupName - the name of the resource group. // loadBalancerName - the name of the load balancer. func (client LoadBalancerFrontendIPConfigurationsClient) List(ctx context.Context, resourceGroupName string, loadBalancerName string) (result LoadBalancerFrontendIPConfigurationListResultPage, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/LoadBalancerFrontendIPConfigurationsClient.List") defer func() { sc := -1 if result.lbficlr.Response.Response != nil { sc = result.lbficlr.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } result.fn = client.listNextResults req, err := client.ListPreparer(ctx, resourceGroupName, loadBalancerName) if err != nil { err = autorest.NewErrorWithError(err, "network.LoadBalancerFrontendIPConfigurationsClient", "List", nil, "Failure preparing request") return } resp, err := client.ListSender(req) if err != nil { result.lbficlr.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "network.LoadBalancerFrontendIPConfigurationsClient", "List", resp, "Failure sending request") return } result.lbficlr, err = client.ListResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "network.LoadBalancerFrontendIPConfigurationsClient", "List", resp, "Failure responding to request") } return } // ListPreparer prepares the List request. func (client LoadBalancerFrontendIPConfigurationsClient) ListPreparer(ctx context.Context, resourceGroupName string, loadBalancerName string) (*http.Request, error) { pathParameters := map[string]interface{}{ "loadBalancerName": autorest.Encode("path", loadBalancerName), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2019-04-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsGet(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}/frontendIPConfigurations", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // ListSender sends the List request. The method will close the // http.Response Body if it receives an error. func (client LoadBalancerFrontendIPConfigurationsClient) ListSender(req *http.Request) (*http.Response, error) { sd := autorest.GetSendDecorators(req.Context(), azure.DoRetryWithRegistration(client.Client)) return autorest.SendWithSender(client, req, sd...) } // ListResponder handles the response to the List request. The method always // closes the http.Response Body. func (client LoadBalancerFrontendIPConfigurationsClient) ListResponder(resp *http.Response) (result LoadBalancerFrontendIPConfigurationListResult, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // listNextResults retrieves the next set of results, if any. func (client LoadBalancerFrontendIPConfigurationsClient) listNextResults(ctx context.Context, lastResults LoadBalancerFrontendIPConfigurationListResult) (result LoadBalancerFrontendIPConfigurationListResult, err error) { req, err := lastResults.loadBalancerFrontendIPConfigurationListResultPreparer(ctx) if err != nil { return result, autorest.NewErrorWithError(err, "network.LoadBalancerFrontendIPConfigurationsClient", "listNextResults", nil, "Failure preparing next results request") } if req == nil { return } resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} return result, autorest.NewErrorWithError(err, "network.LoadBalancerFrontendIPConfigurationsClient", "listNextResults", resp, "Failure sending next results request") } result, err = client.ListResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "network.LoadBalancerFrontendIPConfigurationsClient", "listNextResults", resp, "Failure responding to next results request") } return } // ListComplete enumerates all values, automatically crossing page boundaries as required. func (client LoadBalancerFrontendIPConfigurationsClient) ListComplete(ctx context.Context, resourceGroupName string, loadBalancerName string) (result LoadBalancerFrontendIPConfigurationListResultIterator, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/LoadBalancerFrontendIPConfigurationsClient.List") defer func() { sc := -1 if result.Response().Response.Response != nil { sc = result.page.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } result.page, err = client.List(ctx, resourceGroupName, loadBalancerName) return }
pweil-/origin
vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2019-04-01/network/loadbalancerfrontendipconfigurations.go
GO
apache-2.0
10,427
/* * Neighbour Discovery for IPv6 * Linux INET6 implementation * * Authors: * Pedro Roque <[email protected]> * Mike Shaver <[email protected]> * * 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. */ /* * Changes: * * Pierre Ynard : export userland ND options * through netlink (RDNSS support) * Lars Fenneberg : fixed MTU setting on receipt * of an RA. * Janos Farkas : kmalloc failure checks * Alexey Kuznetsov : state machine reworked * and moved to net/core. * Pekka Savola : RFC2461 validation * YOSHIFUJI Hideaki @USAGI : Verify ND options properly */ /* Set to 3 to get tracing... */ #define ND_DEBUG 1 #define ND_PRINTK(fmt, args...) do { if (net_ratelimit()) { printk(fmt, ## args); } } while(0) #define ND_NOPRINTK(x...) do { ; } while(0) #define ND_PRINTK0 ND_PRINTK #define ND_PRINTK1 ND_NOPRINTK #define ND_PRINTK2 ND_NOPRINTK #define ND_PRINTK3 ND_NOPRINTK #if ND_DEBUG >= 1 #undef ND_PRINTK1 #define ND_PRINTK1 ND_PRINTK #endif #if ND_DEBUG >= 2 #undef ND_PRINTK2 #define ND_PRINTK2 ND_PRINTK #endif #if ND_DEBUG >= 3 #undef ND_PRINTK3 #define ND_PRINTK3 ND_PRINTK #endif #include <linux/module.h> #include <linux/errno.h> #include <linux/types.h> #include <linux/socket.h> #include <linux/sockios.h> #include <linux/sched.h> #include <linux/net.h> #include <linux/in6.h> #include <linux/route.h> #include <linux/init.h> #include <linux/rcupdate.h> #include <linux/slab.h> #ifdef CONFIG_SYSCTL #include <linux/sysctl.h> #endif #include <linux/if_addr.h> #include <linux/if_arp.h> #include <linux/ipv6.h> #include <linux/icmpv6.h> #include <linux/jhash.h> #include <net/sock.h> #include <net/snmp.h> #include <net/ipv6.h> #include <net/protocol.h> #include <net/ndisc.h> #include <net/ip6_route.h> #include <net/addrconf.h> #include <net/icmp.h> #include <net/netlink.h> #include <linux/rtnetlink.h> #include <net/flow.h> #include <net/ip6_checksum.h> #include <net/inet_common.h> #include <linux/proc_fs.h> #include <linux/netfilter.h> #include <linux/netfilter_ipv6.h> static u32 ndisc_hash(const void *pkey, const struct net_device *dev, __u32 rnd); static int ndisc_constructor(struct neighbour *neigh); static void ndisc_solicit(struct neighbour *neigh, struct sk_buff *skb); static void ndisc_error_report(struct neighbour *neigh, struct sk_buff *skb); static int pndisc_constructor(struct pneigh_entry *n); static void pndisc_destructor(struct pneigh_entry *n); static void pndisc_redo(struct sk_buff *skb); static const struct neigh_ops ndisc_generic_ops = { .family = AF_INET6, .solicit = ndisc_solicit, .error_report = ndisc_error_report, .output = neigh_resolve_output, .connected_output = neigh_connected_output, }; static const struct neigh_ops ndisc_hh_ops = { .family = AF_INET6, .solicit = ndisc_solicit, .error_report = ndisc_error_report, .output = neigh_resolve_output, .connected_output = neigh_resolve_output, }; static const struct neigh_ops ndisc_direct_ops = { .family = AF_INET6, .output = neigh_direct_output, .connected_output = neigh_direct_output, }; struct neigh_table nd_tbl = { .family = AF_INET6, .entry_size = sizeof(struct neighbour) + sizeof(struct in6_addr), .key_len = sizeof(struct in6_addr), .hash = ndisc_hash, .constructor = ndisc_constructor, .pconstructor = pndisc_constructor, .pdestructor = pndisc_destructor, .proxy_redo = pndisc_redo, .id = "ndisc_cache", .parms = { .tbl = &nd_tbl, .base_reachable_time = ND_REACHABLE_TIME, .retrans_time = ND_RETRANS_TIMER, .gc_staletime = 60 * HZ, .reachable_time = ND_REACHABLE_TIME, .delay_probe_time = 5 * HZ, .queue_len = 3, .ucast_probes = 3, .mcast_probes = 3, .anycast_delay = 1 * HZ, .proxy_delay = (8 * HZ) / 10, .proxy_qlen = 64, }, .gc_interval = 30 * HZ, .gc_thresh1 = 128, .gc_thresh2 = 512, .gc_thresh3 = 1024, }; /* ND options */ struct ndisc_options { struct nd_opt_hdr *nd_opt_array[__ND_OPT_ARRAY_MAX]; #ifdef CONFIG_IPV6_ROUTE_INFO struct nd_opt_hdr *nd_opts_ri; struct nd_opt_hdr *nd_opts_ri_end; #endif struct nd_opt_hdr *nd_useropts; struct nd_opt_hdr *nd_useropts_end; }; #define nd_opts_src_lladdr nd_opt_array[ND_OPT_SOURCE_LL_ADDR] #define nd_opts_tgt_lladdr nd_opt_array[ND_OPT_TARGET_LL_ADDR] #define nd_opts_pi nd_opt_array[ND_OPT_PREFIX_INFO] #define nd_opts_pi_end nd_opt_array[__ND_OPT_PREFIX_INFO_END] #define nd_opts_rh nd_opt_array[ND_OPT_REDIRECT_HDR] #define nd_opts_mtu nd_opt_array[ND_OPT_MTU] #define NDISC_OPT_SPACE(len) (((len)+2+7)&~7) /* * Return the padding between the option length and the start of the * link addr. Currently only IP-over-InfiniBand needs this, although * if RFC 3831 IPv6-over-Fibre Channel is ever implemented it may * also need a pad of 2. */ static int ndisc_addr_option_pad(unsigned short type) { switch (type) { case ARPHRD_INFINIBAND: return 2; default: return 0; } } static inline int ndisc_opt_addr_space(struct net_device *dev) { return NDISC_OPT_SPACE(dev->addr_len + ndisc_addr_option_pad(dev->type)); } static u8 *ndisc_fill_addr_option(u8 *opt, int type, void *data, int data_len, unsigned short addr_type) { int space = NDISC_OPT_SPACE(data_len); int pad = ndisc_addr_option_pad(addr_type); opt[0] = type; opt[1] = space>>3; memset(opt + 2, 0, pad); opt += pad; space -= pad; memcpy(opt+2, data, data_len); data_len += 2; opt += data_len; if ((space -= data_len) > 0) memset(opt, 0, space); return opt + space; } static struct nd_opt_hdr *ndisc_next_option(struct nd_opt_hdr *cur, struct nd_opt_hdr *end) { int type; if (!cur || !end || cur >= end) return NULL; type = cur->nd_opt_type; do { cur = ((void *)cur) + (cur->nd_opt_len << 3); } while(cur < end && cur->nd_opt_type != type); return cur <= end && cur->nd_opt_type == type ? cur : NULL; } static inline int ndisc_is_useropt(struct nd_opt_hdr *opt) { return opt->nd_opt_type == ND_OPT_RDNSS; } static struct nd_opt_hdr *ndisc_next_useropt(struct nd_opt_hdr *cur, struct nd_opt_hdr *end) { if (!cur || !end || cur >= end) return NULL; do { cur = ((void *)cur) + (cur->nd_opt_len << 3); } while(cur < end && !ndisc_is_useropt(cur)); return cur <= end && ndisc_is_useropt(cur) ? cur : NULL; } static struct ndisc_options *ndisc_parse_options(u8 *opt, int opt_len, struct ndisc_options *ndopts) { struct nd_opt_hdr *nd_opt = (struct nd_opt_hdr *)opt; if (!nd_opt || opt_len < 0 || !ndopts) return NULL; memset(ndopts, 0, sizeof(*ndopts)); while (opt_len) { int l; if (opt_len < sizeof(struct nd_opt_hdr)) return NULL; l = nd_opt->nd_opt_len << 3; if (opt_len < l || l == 0) return NULL; switch (nd_opt->nd_opt_type) { case ND_OPT_SOURCE_LL_ADDR: case ND_OPT_TARGET_LL_ADDR: case ND_OPT_MTU: case ND_OPT_REDIRECT_HDR: if (ndopts->nd_opt_array[nd_opt->nd_opt_type]) { ND_PRINTK2(KERN_WARNING "%s(): duplicated ND6 option found: type=%d\n", __func__, nd_opt->nd_opt_type); } else { ndopts->nd_opt_array[nd_opt->nd_opt_type] = nd_opt; } break; case ND_OPT_PREFIX_INFO: ndopts->nd_opts_pi_end = nd_opt; if (!ndopts->nd_opt_array[nd_opt->nd_opt_type]) ndopts->nd_opt_array[nd_opt->nd_opt_type] = nd_opt; break; #ifdef CONFIG_IPV6_ROUTE_INFO case ND_OPT_ROUTE_INFO: ndopts->nd_opts_ri_end = nd_opt; if (!ndopts->nd_opts_ri) ndopts->nd_opts_ri = nd_opt; break; #endif default: if (ndisc_is_useropt(nd_opt)) { ndopts->nd_useropts_end = nd_opt; if (!ndopts->nd_useropts) ndopts->nd_useropts = nd_opt; } else { /* * Unknown options must be silently ignored, * to accommodate future extension to the * protocol. */ ND_PRINTK2(KERN_NOTICE "%s(): ignored unsupported option; type=%d, len=%d\n", __func__, nd_opt->nd_opt_type, nd_opt->nd_opt_len); } } opt_len -= l; nd_opt = ((void *)nd_opt) + l; } return ndopts; } static inline u8 *ndisc_opt_addr_data(struct nd_opt_hdr *p, struct net_device *dev) { u8 *lladdr = (u8 *)(p + 1); int lladdrlen = p->nd_opt_len << 3; int prepad = ndisc_addr_option_pad(dev->type); if (lladdrlen != NDISC_OPT_SPACE(dev->addr_len + prepad)) return NULL; return lladdr + prepad; } int ndisc_mc_map(const struct in6_addr *addr, char *buf, struct net_device *dev, int dir) { switch (dev->type) { case ARPHRD_ETHER: case ARPHRD_IEEE802: /* Not sure. Check it later. --ANK */ case ARPHRD_FDDI: ipv6_eth_mc_map(addr, buf); return 0; case ARPHRD_IEEE802_TR: ipv6_tr_mc_map(addr,buf); return 0; case ARPHRD_ARCNET: ipv6_arcnet_mc_map(addr, buf); return 0; case ARPHRD_INFINIBAND: ipv6_ib_mc_map(addr, dev->broadcast, buf); return 0; case ARPHRD_IPGRE: return ipv6_ipgre_mc_map(addr, dev->broadcast, buf); default: if (dir) { memcpy(buf, dev->broadcast, dev->addr_len); return 0; } } return -EINVAL; } EXPORT_SYMBOL(ndisc_mc_map); static u32 ndisc_hash(const void *pkey, const struct net_device *dev, __u32 hash_rnd) { const u32 *p32 = pkey; u32 addr_hash, i; addr_hash = 0; for (i = 0; i < (sizeof(struct in6_addr) / sizeof(u32)); i++) addr_hash ^= *p32++; return jhash_2words(addr_hash, dev->ifindex, hash_rnd); } static int ndisc_constructor(struct neighbour *neigh) { struct in6_addr *addr = (struct in6_addr*)&neigh->primary_key; struct net_device *dev = neigh->dev; struct inet6_dev *in6_dev; struct neigh_parms *parms; int is_multicast = ipv6_addr_is_multicast(addr); in6_dev = in6_dev_get(dev); if (in6_dev == NULL) { return -EINVAL; } parms = in6_dev->nd_parms; __neigh_parms_put(neigh->parms); neigh->parms = neigh_parms_clone(parms); neigh->type = is_multicast ? RTN_MULTICAST : RTN_UNICAST; if (!dev->header_ops) { neigh->nud_state = NUD_NOARP; neigh->ops = &ndisc_direct_ops; neigh->output = neigh_direct_output; } else { if (is_multicast) { neigh->nud_state = NUD_NOARP; ndisc_mc_map(addr, neigh->ha, dev, 1); } else if (dev->flags&(IFF_NOARP|IFF_LOOPBACK)) { neigh->nud_state = NUD_NOARP; memcpy(neigh->ha, dev->dev_addr, dev->addr_len); if (dev->flags&IFF_LOOPBACK) neigh->type = RTN_LOCAL; } else if (dev->flags&IFF_POINTOPOINT) { neigh->nud_state = NUD_NOARP; memcpy(neigh->ha, dev->broadcast, dev->addr_len); } if (dev->header_ops->cache) neigh->ops = &ndisc_hh_ops; else neigh->ops = &ndisc_generic_ops; if (neigh->nud_state&NUD_VALID) neigh->output = neigh->ops->connected_output; else neigh->output = neigh->ops->output; } in6_dev_put(in6_dev); return 0; } static int pndisc_constructor(struct pneigh_entry *n) { struct in6_addr *addr = (struct in6_addr*)&n->key; struct in6_addr maddr; struct net_device *dev = n->dev; if (dev == NULL || __in6_dev_get(dev) == NULL) return -EINVAL; addrconf_addr_solict_mult(addr, &maddr); ipv6_dev_mc_inc(dev, &maddr); return 0; } static void pndisc_destructor(struct pneigh_entry *n) { struct in6_addr *addr = (struct in6_addr*)&n->key; struct in6_addr maddr; struct net_device *dev = n->dev; if (dev == NULL || __in6_dev_get(dev) == NULL) return; addrconf_addr_solict_mult(addr, &maddr); ipv6_dev_mc_dec(dev, &maddr); } struct sk_buff *ndisc_build_skb(struct net_device *dev, const struct in6_addr *daddr, const struct in6_addr *saddr, struct icmp6hdr *icmp6h, const struct in6_addr *target, int llinfo) { struct net *net = dev_net(dev); struct sock *sk = net->ipv6.ndisc_sk; struct sk_buff *skb; struct icmp6hdr *hdr; int len; int err; u8 *opt; if (!dev->addr_len) llinfo = 0; len = sizeof(struct icmp6hdr) + (target ? sizeof(*target) : 0); if (llinfo) len += ndisc_opt_addr_space(dev); skb = sock_alloc_send_skb(sk, (MAX_HEADER + sizeof(struct ipv6hdr) + len + LL_ALLOCATED_SPACE(dev)), 1, &err); if (!skb) { ND_PRINTK0(KERN_ERR "ICMPv6 ND: %s() failed to allocate an skb, err=%d.\n", __func__, err); return NULL; } skb_reserve(skb, LL_RESERVED_SPACE(dev)); ip6_nd_hdr(sk, skb, dev, saddr, daddr, IPPROTO_ICMPV6, len); skb->transport_header = skb->tail; skb_put(skb, len); hdr = (struct icmp6hdr *)skb_transport_header(skb); memcpy(hdr, icmp6h, sizeof(*hdr)); opt = skb_transport_header(skb) + sizeof(struct icmp6hdr); if (target) { ipv6_addr_copy((struct in6_addr *)opt, target); opt += sizeof(*target); } if (llinfo) ndisc_fill_addr_option(opt, llinfo, dev->dev_addr, dev->addr_len, dev->type); hdr->icmp6_cksum = csum_ipv6_magic(saddr, daddr, len, IPPROTO_ICMPV6, csum_partial(hdr, len, 0)); return skb; } EXPORT_SYMBOL(ndisc_build_skb); void ndisc_send_skb(struct sk_buff *skb, struct net_device *dev, struct neighbour *neigh, const struct in6_addr *daddr, const struct in6_addr *saddr, struct icmp6hdr *icmp6h) { struct flowi6 fl6; struct dst_entry *dst; struct net *net = dev_net(dev); struct sock *sk = net->ipv6.ndisc_sk; struct inet6_dev *idev; int err; u8 type; type = icmp6h->icmp6_type; icmpv6_flow_init(sk, &fl6, type, saddr, daddr, dev->ifindex); dst = icmp6_dst_alloc(dev, neigh, daddr); if (!dst) { kfree_skb(skb); return; } dst = xfrm_lookup(net, dst, flowi6_to_flowi(&fl6), NULL, 0); if (IS_ERR(dst)) { kfree_skb(skb); return; } skb_dst_set(skb, dst); rcu_read_lock(); idev = __in6_dev_get(dst->dev); IP6_UPD_PO_STATS(net, idev, IPSTATS_MIB_OUT, skb->len); err = NF_HOOK(NFPROTO_IPV6, NF_INET_LOCAL_OUT, skb, NULL, dst->dev, dst_output); if (!err) { ICMP6MSGOUT_INC_STATS(net, idev, type); ICMP6_INC_STATS(net, idev, ICMP6_MIB_OUTMSGS); } rcu_read_unlock(); } EXPORT_SYMBOL(ndisc_send_skb); /* * Send a Neighbour Discover packet */ static void __ndisc_send(struct net_device *dev, struct neighbour *neigh, const struct in6_addr *daddr, const struct in6_addr *saddr, struct icmp6hdr *icmp6h, const struct in6_addr *target, int llinfo) { struct sk_buff *skb; skb = ndisc_build_skb(dev, daddr, saddr, icmp6h, target, llinfo); if (!skb) return; ndisc_send_skb(skb, dev, neigh, daddr, saddr, icmp6h); } static void ndisc_send_na(struct net_device *dev, struct neighbour *neigh, const struct in6_addr *daddr, const struct in6_addr *solicited_addr, int router, int solicited, int override, int inc_opt) { struct in6_addr tmpaddr; struct inet6_ifaddr *ifp; const struct in6_addr *src_addr; struct icmp6hdr icmp6h = { .icmp6_type = NDISC_NEIGHBOUR_ADVERTISEMENT, }; /* for anycast or proxy, solicited_addr != src_addr */ ifp = ipv6_get_ifaddr(dev_net(dev), solicited_addr, dev, 1); if (ifp) { src_addr = solicited_addr; if (ifp->flags & IFA_F_OPTIMISTIC) override = 0; inc_opt |= ifp->idev->cnf.force_tllao; in6_ifa_put(ifp); } else { if (ipv6_dev_get_saddr(dev_net(dev), dev, daddr, inet6_sk(dev_net(dev)->ipv6.ndisc_sk)->srcprefs, &tmpaddr)) return; src_addr = &tmpaddr; } icmp6h.icmp6_router = router; icmp6h.icmp6_solicited = solicited; icmp6h.icmp6_override = override; __ndisc_send(dev, neigh, daddr, src_addr, &icmp6h, solicited_addr, inc_opt ? ND_OPT_TARGET_LL_ADDR : 0); } static void ndisc_send_unsol_na(struct net_device *dev) { struct inet6_dev *idev; struct inet6_ifaddr *ifa; struct in6_addr mcaddr = IN6ADDR_LINKLOCAL_ALLNODES_INIT; idev = in6_dev_get(dev); if (!idev) return; read_lock_bh(&idev->lock); list_for_each_entry(ifa, &idev->addr_list, if_list) { ndisc_send_na(dev, NULL, &mcaddr, &ifa->addr, /*router=*/ !!idev->cnf.forwarding, /*solicited=*/ false, /*override=*/ true, /*inc_opt=*/ true); } read_unlock_bh(&idev->lock); in6_dev_put(idev); } void ndisc_send_ns(struct net_device *dev, struct neighbour *neigh, const struct in6_addr *solicit, const struct in6_addr *daddr, const struct in6_addr *saddr) { struct in6_addr addr_buf; struct icmp6hdr icmp6h = { .icmp6_type = NDISC_NEIGHBOUR_SOLICITATION, }; if (saddr == NULL) { if (ipv6_get_lladdr(dev, &addr_buf, (IFA_F_TENTATIVE|IFA_F_OPTIMISTIC))) return; saddr = &addr_buf; } __ndisc_send(dev, neigh, daddr, saddr, &icmp6h, solicit, !ipv6_addr_any(saddr) ? ND_OPT_SOURCE_LL_ADDR : 0); } void ndisc_send_rs(struct net_device *dev, const struct in6_addr *saddr, const struct in6_addr *daddr) { struct icmp6hdr icmp6h = { .icmp6_type = NDISC_ROUTER_SOLICITATION, }; int send_sllao = dev->addr_len; #ifdef CONFIG_IPV6_OPTIMISTIC_DAD /* * According to section 2.2 of RFC 4429, we must not * send router solicitations with a sllao from * optimistic addresses, but we may send the solicitation * if we don't include the sllao. So here we check * if our address is optimistic, and if so, we * suppress the inclusion of the sllao. */ if (send_sllao) { struct inet6_ifaddr *ifp = ipv6_get_ifaddr(dev_net(dev), saddr, dev, 1); if (ifp) { if (ifp->flags & IFA_F_OPTIMISTIC) { send_sllao = 0; } in6_ifa_put(ifp); } else { send_sllao = 0; } } #endif __ndisc_send(dev, NULL, daddr, saddr, &icmp6h, NULL, send_sllao ? ND_OPT_SOURCE_LL_ADDR : 0); } static void ndisc_error_report(struct neighbour *neigh, struct sk_buff *skb) { /* * "The sender MUST return an ICMP * destination unreachable" */ dst_link_failure(skb); kfree_skb(skb); } /* Called with locked neigh: either read or both */ static void ndisc_solicit(struct neighbour *neigh, struct sk_buff *skb) { struct in6_addr *saddr = NULL; struct in6_addr mcaddr; struct net_device *dev = neigh->dev; struct in6_addr *target = (struct in6_addr *)&neigh->primary_key; int probes = atomic_read(&neigh->probes); if (skb && ipv6_chk_addr(dev_net(dev), &ipv6_hdr(skb)->saddr, dev, 1)) saddr = &ipv6_hdr(skb)->saddr; if ((probes -= neigh->parms->ucast_probes) < 0) { if (!(neigh->nud_state & NUD_VALID)) { ND_PRINTK1(KERN_DEBUG "%s(): trying to ucast probe in NUD_INVALID: %pI6\n", __func__, target); } ndisc_send_ns(dev, neigh, target, target, saddr); } else if ((probes -= neigh->parms->app_probes) < 0) { #ifdef CONFIG_ARPD neigh_app_ns(neigh); #endif } else { addrconf_addr_solict_mult(target, &mcaddr); ndisc_send_ns(dev, NULL, target, &mcaddr, saddr); } } static int pndisc_is_router(const void *pkey, struct net_device *dev) { struct pneigh_entry *n; int ret = -1; read_lock_bh(&nd_tbl.lock); n = __pneigh_lookup(&nd_tbl, dev_net(dev), pkey, dev); if (n) ret = !!(n->flags & NTF_ROUTER); read_unlock_bh(&nd_tbl.lock); return ret; } static void ndisc_recv_ns(struct sk_buff *skb) { struct nd_msg *msg = (struct nd_msg *)skb_transport_header(skb); const struct in6_addr *saddr = &ipv6_hdr(skb)->saddr; const struct in6_addr *daddr = &ipv6_hdr(skb)->daddr; u8 *lladdr = NULL; u32 ndoptlen = skb->tail - (skb->transport_header + offsetof(struct nd_msg, opt)); struct ndisc_options ndopts; struct net_device *dev = skb->dev; struct inet6_ifaddr *ifp; struct inet6_dev *idev = NULL; struct neighbour *neigh; int dad = ipv6_addr_any(saddr); int inc; int is_router = -1; if (ipv6_addr_is_multicast(&msg->target)) { ND_PRINTK2(KERN_WARNING "ICMPv6 NS: multicast target address"); return; } /* * RFC2461 7.1.1: * DAD has to be destined for solicited node multicast address. */ if (dad && !(daddr->s6_addr32[0] == htonl(0xff020000) && daddr->s6_addr32[1] == htonl(0x00000000) && daddr->s6_addr32[2] == htonl(0x00000001) && daddr->s6_addr [12] == 0xff )) { ND_PRINTK2(KERN_WARNING "ICMPv6 NS: bad DAD packet (wrong destination)\n"); return; } if (!ndisc_parse_options(msg->opt, ndoptlen, &ndopts)) { ND_PRINTK2(KERN_WARNING "ICMPv6 NS: invalid ND options\n"); return; } if (ndopts.nd_opts_src_lladdr) { lladdr = ndisc_opt_addr_data(ndopts.nd_opts_src_lladdr, dev); if (!lladdr) { ND_PRINTK2(KERN_WARNING "ICMPv6 NS: invalid link-layer address length\n"); return; } /* RFC2461 7.1.1: * If the IP source address is the unspecified address, * there MUST NOT be source link-layer address option * in the message. */ if (dad) { ND_PRINTK2(KERN_WARNING "ICMPv6 NS: bad DAD packet (link-layer address option)\n"); return; } } inc = ipv6_addr_is_multicast(daddr); ifp = ipv6_get_ifaddr(dev_net(dev), &msg->target, dev, 1); if (ifp) { if (ifp->flags & (IFA_F_TENTATIVE|IFA_F_OPTIMISTIC)) { if (dad) { if (dev->type == ARPHRD_IEEE802_TR) { const unsigned char *sadr; sadr = skb_mac_header(skb); if (((sadr[8] ^ dev->dev_addr[0]) & 0x7f) == 0 && sadr[9] == dev->dev_addr[1] && sadr[10] == dev->dev_addr[2] && sadr[11] == dev->dev_addr[3] && sadr[12] == dev->dev_addr[4] && sadr[13] == dev->dev_addr[5]) { /* looped-back to us */ goto out; } } /* * We are colliding with another node * who is doing DAD * so fail our DAD process */ addrconf_dad_failure(ifp); return; } else { /* * This is not a dad solicitation. * If we are an optimistic node, * we should respond. * Otherwise, we should ignore it. */ if (!(ifp->flags & IFA_F_OPTIMISTIC)) goto out; } } idev = ifp->idev; } else { struct net *net = dev_net(dev); idev = in6_dev_get(dev); if (!idev) { /* XXX: count this drop? */ return; } if (ipv6_chk_acast_addr(net, dev, &msg->target) || (idev->cnf.forwarding && (net->ipv6.devconf_all->proxy_ndp || idev->cnf.proxy_ndp) && (is_router = pndisc_is_router(&msg->target, dev)) >= 0)) { if (!(NEIGH_CB(skb)->flags & LOCALLY_ENQUEUED) && skb->pkt_type != PACKET_HOST && inc != 0 && idev->nd_parms->proxy_delay != 0) { /* * for anycast or proxy, * sender should delay its response * by a random time between 0 and * MAX_ANYCAST_DELAY_TIME seconds. * (RFC2461) -- yoshfuji */ struct sk_buff *n = skb_clone(skb, GFP_ATOMIC); if (n) pneigh_enqueue(&nd_tbl, idev->nd_parms, n); goto out; } } else goto out; } if (is_router < 0) is_router = !!idev->cnf.forwarding; if (dad) { ndisc_send_na(dev, NULL, &in6addr_linklocal_allnodes, &msg->target, is_router, 0, (ifp != NULL), 1); goto out; } if (inc) NEIGH_CACHE_STAT_INC(&nd_tbl, rcv_probes_mcast); else NEIGH_CACHE_STAT_INC(&nd_tbl, rcv_probes_ucast); /* * update / create cache entry * for the source address */ neigh = __neigh_lookup(&nd_tbl, saddr, dev, !inc || lladdr || !dev->addr_len); if (neigh) neigh_update(neigh, lladdr, NUD_STALE, NEIGH_UPDATE_F_WEAK_OVERRIDE| NEIGH_UPDATE_F_OVERRIDE); if (neigh || !dev->header_ops) { ndisc_send_na(dev, neigh, saddr, &msg->target, is_router, 1, (ifp != NULL && inc), inc); if (neigh) neigh_release(neigh); } out: if (ifp) in6_ifa_put(ifp); else in6_dev_put(idev); } static void ndisc_recv_na(struct sk_buff *skb) { struct nd_msg *msg = (struct nd_msg *)skb_transport_header(skb); const struct in6_addr *saddr = &ipv6_hdr(skb)->saddr; const struct in6_addr *daddr = &ipv6_hdr(skb)->daddr; u8 *lladdr = NULL; u32 ndoptlen = skb->tail - (skb->transport_header + offsetof(struct nd_msg, opt)); struct ndisc_options ndopts; struct net_device *dev = skb->dev; struct inet6_ifaddr *ifp; struct neighbour *neigh; if (skb->len < sizeof(struct nd_msg)) { ND_PRINTK2(KERN_WARNING "ICMPv6 NA: packet too short\n"); return; } if (ipv6_addr_is_multicast(&msg->target)) { ND_PRINTK2(KERN_WARNING "ICMPv6 NA: target address is multicast.\n"); return; } if (ipv6_addr_is_multicast(daddr) && msg->icmph.icmp6_solicited) { ND_PRINTK2(KERN_WARNING "ICMPv6 NA: solicited NA is multicasted.\n"); return; } if (!ndisc_parse_options(msg->opt, ndoptlen, &ndopts)) { ND_PRINTK2(KERN_WARNING "ICMPv6 NS: invalid ND option\n"); return; } if (ndopts.nd_opts_tgt_lladdr) { lladdr = ndisc_opt_addr_data(ndopts.nd_opts_tgt_lladdr, dev); if (!lladdr) { ND_PRINTK2(KERN_WARNING "ICMPv6 NA: invalid link-layer address length\n"); return; } } ifp = ipv6_get_ifaddr(dev_net(dev), &msg->target, dev, 1); if (ifp) { if (skb->pkt_type != PACKET_LOOPBACK && (ifp->flags & IFA_F_TENTATIVE)) { addrconf_dad_failure(ifp); return; } /* What should we make now? The advertisement is invalid, but ndisc specs say nothing about it. It could be misconfiguration, or an smart proxy agent tries to help us :-) We should not print the error if NA has been received from loopback - it is just our own unsolicited advertisement. */ if (skb->pkt_type != PACKET_LOOPBACK) ND_PRINTK1(KERN_WARNING "ICMPv6 NA: someone advertises our address %pI6 on %s!\n", &ifp->addr, ifp->idev->dev->name); in6_ifa_put(ifp); return; } neigh = neigh_lookup(&nd_tbl, &msg->target, dev); if (neigh) { u8 old_flags = neigh->flags; struct net *net = dev_net(dev); if (neigh->nud_state & NUD_FAILED) goto out; /* * Don't update the neighbor cache entry on a proxy NA from * ourselves because either the proxied node is off link or it * has already sent a NA to us. */ if (lladdr && !memcmp(lladdr, dev->dev_addr, dev->addr_len) && net->ipv6.devconf_all->forwarding && net->ipv6.devconf_all->proxy_ndp && pneigh_lookup(&nd_tbl, net, &msg->target, dev, 0)) { /* XXX: idev->cnf.prixy_ndp */ goto out; } neigh_update(neigh, lladdr, msg->icmph.icmp6_solicited ? NUD_REACHABLE : NUD_STALE, NEIGH_UPDATE_F_WEAK_OVERRIDE| (msg->icmph.icmp6_override ? NEIGH_UPDATE_F_OVERRIDE : 0)| NEIGH_UPDATE_F_OVERRIDE_ISROUTER| (msg->icmph.icmp6_router ? NEIGH_UPDATE_F_ISROUTER : 0)); if ((old_flags & ~neigh->flags) & NTF_ROUTER) { /* * Change: router to host */ struct rt6_info *rt; rt = rt6_get_dflt_router(saddr, dev); if (rt) ip6_del_rt(rt); } out: neigh_release(neigh); } } static void ndisc_recv_rs(struct sk_buff *skb) { struct rs_msg *rs_msg = (struct rs_msg *)skb_transport_header(skb); unsigned long ndoptlen = skb->len - sizeof(*rs_msg); struct neighbour *neigh; struct inet6_dev *idev; const struct in6_addr *saddr = &ipv6_hdr(skb)->saddr; struct ndisc_options ndopts; u8 *lladdr = NULL; if (skb->len < sizeof(*rs_msg)) return; idev = __in6_dev_get(skb->dev); if (!idev) { if (net_ratelimit()) ND_PRINTK1("ICMP6 RS: can't find in6 device\n"); return; } /* Don't accept RS if we're not in router mode */ if (!idev->cnf.forwarding) goto out; /* * Don't update NCE if src = ::; * this implies that the source node has no ip address assigned yet. */ if (ipv6_addr_any(saddr)) goto out; /* Parse ND options */ if (!ndisc_parse_options(rs_msg->opt, ndoptlen, &ndopts)) { if (net_ratelimit()) ND_PRINTK2("ICMP6 NS: invalid ND option, ignored\n"); goto out; } if (ndopts.nd_opts_src_lladdr) { lladdr = ndisc_opt_addr_data(ndopts.nd_opts_src_lladdr, skb->dev); if (!lladdr) goto out; } neigh = __neigh_lookup(&nd_tbl, saddr, skb->dev, 1); if (neigh) { neigh_update(neigh, lladdr, NUD_STALE, NEIGH_UPDATE_F_WEAK_OVERRIDE| NEIGH_UPDATE_F_OVERRIDE| NEIGH_UPDATE_F_OVERRIDE_ISROUTER); neigh_release(neigh); } out: return; } static void ndisc_ra_useropt(struct sk_buff *ra, struct nd_opt_hdr *opt) { struct icmp6hdr *icmp6h = (struct icmp6hdr *)skb_transport_header(ra); struct sk_buff *skb; struct nlmsghdr *nlh; struct nduseroptmsg *ndmsg; struct net *net = dev_net(ra->dev); int err; int base_size = NLMSG_ALIGN(sizeof(struct nduseroptmsg) + (opt->nd_opt_len << 3)); size_t msg_size = base_size + nla_total_size(sizeof(struct in6_addr)); skb = nlmsg_new(msg_size, GFP_ATOMIC); if (skb == NULL) { err = -ENOBUFS; goto errout; } nlh = nlmsg_put(skb, 0, 0, RTM_NEWNDUSEROPT, base_size, 0); if (nlh == NULL) { goto nla_put_failure; } ndmsg = nlmsg_data(nlh); ndmsg->nduseropt_family = AF_INET6; ndmsg->nduseropt_ifindex = ra->dev->ifindex; ndmsg->nduseropt_icmp_type = icmp6h->icmp6_type; ndmsg->nduseropt_icmp_code = icmp6h->icmp6_code; ndmsg->nduseropt_opts_len = opt->nd_opt_len << 3; memcpy(ndmsg + 1, opt, opt->nd_opt_len << 3); NLA_PUT(skb, NDUSEROPT_SRCADDR, sizeof(struct in6_addr), &ipv6_hdr(ra)->saddr); nlmsg_end(skb, nlh); rtnl_notify(skb, net, 0, RTNLGRP_ND_USEROPT, NULL, GFP_ATOMIC); return; nla_put_failure: nlmsg_free(skb); err = -EMSGSIZE; errout: rtnl_set_sk_err(net, RTNLGRP_ND_USEROPT, err); } static inline int accept_ra(struct inet6_dev *in6_dev) { /* * If forwarding is enabled, RA are not accepted unless the special * hybrid mode (accept_ra=2) is enabled. */ if (in6_dev->cnf.forwarding && in6_dev->cnf.accept_ra < 2) return 0; return in6_dev->cnf.accept_ra; } static void ndisc_router_discovery(struct sk_buff *skb) { struct ra_msg *ra_msg = (struct ra_msg *)skb_transport_header(skb); struct neighbour *neigh = NULL; struct inet6_dev *in6_dev; struct rt6_info *rt = NULL; int lifetime; struct ndisc_options ndopts; int optlen; unsigned int pref = 0; __u8 * opt = (__u8 *)(ra_msg + 1); optlen = (skb->tail - skb->transport_header) - sizeof(struct ra_msg); if (!(ipv6_addr_type(&ipv6_hdr(skb)->saddr) & IPV6_ADDR_LINKLOCAL)) { ND_PRINTK2(KERN_WARNING "ICMPv6 RA: source address is not link-local.\n"); return; } if (optlen < 0) { ND_PRINTK2(KERN_WARNING "ICMPv6 RA: packet too short\n"); return; } #ifdef CONFIG_IPV6_NDISC_NODETYPE if (skb->ndisc_nodetype == NDISC_NODETYPE_HOST) { ND_PRINTK2(KERN_WARNING "ICMPv6 RA: from host or unauthorized router\n"); return; } #endif /* * set the RA_RECV flag in the interface */ in6_dev = __in6_dev_get(skb->dev); if (in6_dev == NULL) { ND_PRINTK0(KERN_ERR "ICMPv6 RA: can't find inet6 device for %s.\n", skb->dev->name); return; } if (!ndisc_parse_options(opt, optlen, &ndopts)) { ND_PRINTK2(KERN_WARNING "ICMP6 RA: invalid ND options\n"); return; } if (!accept_ra(in6_dev)) goto skip_linkparms; #ifdef CONFIG_IPV6_NDISC_NODETYPE /* skip link-specific parameters from interior routers */ if (skb->ndisc_nodetype == NDISC_NODETYPE_NODEFAULT) goto skip_linkparms; #endif if (in6_dev->if_flags & IF_RS_SENT) { /* * flag that an RA was received after an RS was sent * out on this interface. */ in6_dev->if_flags |= IF_RA_RCVD; } /* * Remember the managed/otherconf flags from most recently * received RA message (RFC 2462) -- yoshfuji */ in6_dev->if_flags = (in6_dev->if_flags & ~(IF_RA_MANAGED | IF_RA_OTHERCONF)) | (ra_msg->icmph.icmp6_addrconf_managed ? IF_RA_MANAGED : 0) | (ra_msg->icmph.icmp6_addrconf_other ? IF_RA_OTHERCONF : 0); if (!in6_dev->cnf.accept_ra_defrtr) goto skip_defrtr; if (ipv6_chk_addr(dev_net(in6_dev->dev), &ipv6_hdr(skb)->saddr, NULL, 0)) goto skip_defrtr; lifetime = ntohs(ra_msg->icmph.icmp6_rt_lifetime); #ifdef CONFIG_IPV6_ROUTER_PREF pref = ra_msg->icmph.icmp6_router_pref; /* 10b is handled as if it were 00b (medium) */ if (pref == ICMPV6_ROUTER_PREF_INVALID || !in6_dev->cnf.accept_ra_rtr_pref) pref = ICMPV6_ROUTER_PREF_MEDIUM; #endif rt = rt6_get_dflt_router(&ipv6_hdr(skb)->saddr, skb->dev); if (rt) neigh = dst_get_neighbour(&rt->dst); if (rt && lifetime == 0) { neigh_clone(neigh); ip6_del_rt(rt); rt = NULL; } if (rt == NULL && lifetime) { ND_PRINTK3(KERN_DEBUG "ICMPv6 RA: adding default router.\n"); rt = rt6_add_dflt_router(&ipv6_hdr(skb)->saddr, skb->dev, pref); if (rt == NULL) { ND_PRINTK0(KERN_ERR "ICMPv6 RA: %s() failed to add default route.\n", __func__); return; } neigh = dst_get_neighbour(&rt->dst); if (neigh == NULL) { ND_PRINTK0(KERN_ERR "ICMPv6 RA: %s() got default router without neighbour.\n", __func__); dst_release(&rt->dst); return; } neigh->flags |= NTF_ROUTER; } else if (rt) { rt->rt6i_flags = (rt->rt6i_flags & ~RTF_PREF_MASK) | RTF_PREF(pref); } if (rt) rt->rt6i_expires = jiffies + (HZ * lifetime); if (ra_msg->icmph.icmp6_hop_limit) { in6_dev->cnf.hop_limit = ra_msg->icmph.icmp6_hop_limit; if (rt) dst_metric_set(&rt->dst, RTAX_HOPLIMIT, ra_msg->icmph.icmp6_hop_limit); } skip_defrtr: /* * Update Reachable Time and Retrans Timer */ if (in6_dev->nd_parms) { unsigned long rtime = ntohl(ra_msg->retrans_timer); if (rtime && rtime/1000 < MAX_SCHEDULE_TIMEOUT/HZ) { rtime = (rtime*HZ)/1000; if (rtime < HZ/10) rtime = HZ/10; in6_dev->nd_parms->retrans_time = rtime; in6_dev->tstamp = jiffies; inet6_ifinfo_notify(RTM_NEWLINK, in6_dev); } rtime = ntohl(ra_msg->reachable_time); if (rtime && rtime/1000 < MAX_SCHEDULE_TIMEOUT/(3*HZ)) { rtime = (rtime*HZ)/1000; if (rtime < HZ/10) rtime = HZ/10; if (rtime != in6_dev->nd_parms->base_reachable_time) { in6_dev->nd_parms->base_reachable_time = rtime; in6_dev->nd_parms->gc_staletime = 3 * rtime; in6_dev->nd_parms->reachable_time = neigh_rand_reach_time(rtime); in6_dev->tstamp = jiffies; inet6_ifinfo_notify(RTM_NEWLINK, in6_dev); } } } skip_linkparms: /* * Process options. */ if (!neigh) neigh = __neigh_lookup(&nd_tbl, &ipv6_hdr(skb)->saddr, skb->dev, 1); if (neigh) { u8 *lladdr = NULL; if (ndopts.nd_opts_src_lladdr) { lladdr = ndisc_opt_addr_data(ndopts.nd_opts_src_lladdr, skb->dev); if (!lladdr) { ND_PRINTK2(KERN_WARNING "ICMPv6 RA: invalid link-layer address length\n"); goto out; } } neigh_update(neigh, lladdr, NUD_STALE, NEIGH_UPDATE_F_WEAK_OVERRIDE| NEIGH_UPDATE_F_OVERRIDE| NEIGH_UPDATE_F_OVERRIDE_ISROUTER| NEIGH_UPDATE_F_ISROUTER); } if (!accept_ra(in6_dev)) goto out; #ifdef CONFIG_IPV6_ROUTE_INFO if (ipv6_chk_addr(dev_net(in6_dev->dev), &ipv6_hdr(skb)->saddr, NULL, 0)) goto skip_routeinfo; if (in6_dev->cnf.accept_ra_rtr_pref && ndopts.nd_opts_ri) { struct nd_opt_hdr *p; for (p = ndopts.nd_opts_ri; p; p = ndisc_next_option(p, ndopts.nd_opts_ri_end)) { struct route_info *ri = (struct route_info *)p; #ifdef CONFIG_IPV6_NDISC_NODETYPE if (skb->ndisc_nodetype == NDISC_NODETYPE_NODEFAULT && ri->prefix_len == 0) continue; #endif if (ri->prefix_len > in6_dev->cnf.accept_ra_rt_info_max_plen) continue; rt6_route_rcv(skb->dev, (u8*)p, (p->nd_opt_len) << 3, &ipv6_hdr(skb)->saddr); } } skip_routeinfo: #endif #ifdef CONFIG_IPV6_NDISC_NODETYPE /* skip link-specific ndopts from interior routers */ if (skb->ndisc_nodetype == NDISC_NODETYPE_NODEFAULT) goto out; #endif if (in6_dev->cnf.accept_ra_pinfo && ndopts.nd_opts_pi) { struct nd_opt_hdr *p; for (p = ndopts.nd_opts_pi; p; p = ndisc_next_option(p, ndopts.nd_opts_pi_end)) { addrconf_prefix_rcv(skb->dev, (u8*)p, (p->nd_opt_len) << 3); } } if (ndopts.nd_opts_mtu) { __be32 n; u32 mtu; memcpy(&n, ((u8*)(ndopts.nd_opts_mtu+1))+2, sizeof(mtu)); mtu = ntohl(n); if (mtu < IPV6_MIN_MTU || mtu > skb->dev->mtu) { ND_PRINTK2(KERN_WARNING "ICMPv6 RA: invalid mtu: %d\n", mtu); } else if (in6_dev->cnf.mtu6 != mtu) { in6_dev->cnf.mtu6 = mtu; if (rt) dst_metric_set(&rt->dst, RTAX_MTU, mtu); rt6_mtu_change(skb->dev, mtu); } } if (ndopts.nd_useropts) { struct nd_opt_hdr *p; for (p = ndopts.nd_useropts; p; p = ndisc_next_useropt(p, ndopts.nd_useropts_end)) { ndisc_ra_useropt(skb, p); } } if (ndopts.nd_opts_tgt_lladdr || ndopts.nd_opts_rh) { ND_PRINTK2(KERN_WARNING "ICMPv6 RA: invalid RA options"); } out: if (rt) dst_release(&rt->dst); else if (neigh) neigh_release(neigh); } static void ndisc_redirect_rcv(struct sk_buff *skb) { struct inet6_dev *in6_dev; struct icmp6hdr *icmph; const struct in6_addr *dest; const struct in6_addr *target; /* new first hop to destination */ struct neighbour *neigh; int on_link = 0; struct ndisc_options ndopts; int optlen; u8 *lladdr = NULL; #ifdef CONFIG_IPV6_NDISC_NODETYPE switch (skb->ndisc_nodetype) { case NDISC_NODETYPE_HOST: case NDISC_NODETYPE_NODEFAULT: ND_PRINTK2(KERN_WARNING "ICMPv6 Redirect: from host or unauthorized router\n"); return; } #endif if (!(ipv6_addr_type(&ipv6_hdr(skb)->saddr) & IPV6_ADDR_LINKLOCAL)) { ND_PRINTK2(KERN_WARNING "ICMPv6 Redirect: source address is not link-local.\n"); return; } optlen = skb->tail - skb->transport_header; optlen -= sizeof(struct icmp6hdr) + 2 * sizeof(struct in6_addr); if (optlen < 0) { ND_PRINTK2(KERN_WARNING "ICMPv6 Redirect: packet too short\n"); return; } icmph = icmp6_hdr(skb); target = (const struct in6_addr *) (icmph + 1); dest = target + 1; if (ipv6_addr_is_multicast(dest)) { ND_PRINTK2(KERN_WARNING "ICMPv6 Redirect: destination address is multicast.\n"); return; } if (ipv6_addr_equal(dest, target)) { on_link = 1; } else if (ipv6_addr_type(target) != (IPV6_ADDR_UNICAST|IPV6_ADDR_LINKLOCAL)) { ND_PRINTK2(KERN_WARNING "ICMPv6 Redirect: target address is not link-local unicast.\n"); return; } in6_dev = __in6_dev_get(skb->dev); if (!in6_dev) return; if (in6_dev->cnf.forwarding || !in6_dev->cnf.accept_redirects) return; /* RFC2461 8.1: * The IP source address of the Redirect MUST be the same as the current * first-hop router for the specified ICMP Destination Address. */ if (!ndisc_parse_options((u8*)(dest + 1), optlen, &ndopts)) { ND_PRINTK2(KERN_WARNING "ICMPv6 Redirect: invalid ND options\n"); return; } if (ndopts.nd_opts_tgt_lladdr) { lladdr = ndisc_opt_addr_data(ndopts.nd_opts_tgt_lladdr, skb->dev); if (!lladdr) { ND_PRINTK2(KERN_WARNING "ICMPv6 Redirect: invalid link-layer address length\n"); return; } } neigh = __neigh_lookup(&nd_tbl, target, skb->dev, 1); if (neigh) { rt6_redirect(dest, &ipv6_hdr(skb)->daddr, &ipv6_hdr(skb)->saddr, neigh, lladdr, on_link); neigh_release(neigh); } } void ndisc_send_redirect(struct sk_buff *skb, struct neighbour *neigh, const struct in6_addr *target) { struct net_device *dev = skb->dev; struct net *net = dev_net(dev); struct sock *sk = net->ipv6.ndisc_sk; int len = sizeof(struct icmp6hdr) + 2 * sizeof(struct in6_addr); struct sk_buff *buff; struct icmp6hdr *icmph; struct in6_addr saddr_buf; struct in6_addr *addrp; struct rt6_info *rt; struct dst_entry *dst; struct inet6_dev *idev; struct flowi6 fl6; u8 *opt; int rd_len; int err; u8 ha_buf[MAX_ADDR_LEN], *ha = NULL; if (ipv6_get_lladdr(dev, &saddr_buf, IFA_F_TENTATIVE)) { ND_PRINTK2(KERN_WARNING "ICMPv6 Redirect: no link-local address on %s\n", dev->name); return; } if (!ipv6_addr_equal(&ipv6_hdr(skb)->daddr, target) && ipv6_addr_type(target) != (IPV6_ADDR_UNICAST|IPV6_ADDR_LINKLOCAL)) { ND_PRINTK2(KERN_WARNING "ICMPv6 Redirect: target address is not link-local unicast.\n"); return; } icmpv6_flow_init(sk, &fl6, NDISC_REDIRECT, &saddr_buf, &ipv6_hdr(skb)->saddr, dev->ifindex); dst = ip6_route_output(net, NULL, &fl6); if (dst == NULL) return; dst = xfrm_lookup(net, dst, flowi6_to_flowi(&fl6), NULL, 0); if (IS_ERR(dst)) return; rt = (struct rt6_info *) dst; if (rt->rt6i_flags & RTF_GATEWAY) { ND_PRINTK2(KERN_WARNING "ICMPv6 Redirect: destination is not a neighbour.\n"); goto release; } if (!rt->rt6i_peer) rt6_bind_peer(rt, 1); if (!inet_peer_xrlim_allow(rt->rt6i_peer, 1*HZ)) goto release; if (dev->addr_len) { read_lock_bh(&neigh->lock); if (neigh->nud_state & NUD_VALID) { memcpy(ha_buf, neigh->ha, dev->addr_len); read_unlock_bh(&neigh->lock); ha = ha_buf; len += ndisc_opt_addr_space(dev); } else read_unlock_bh(&neigh->lock); } rd_len = min_t(unsigned int, IPV6_MIN_MTU-sizeof(struct ipv6hdr)-len, skb->len + 8); rd_len &= ~0x7; len += rd_len; buff = sock_alloc_send_skb(sk, (MAX_HEADER + sizeof(struct ipv6hdr) + len + LL_ALLOCATED_SPACE(dev)), 1, &err); if (buff == NULL) { ND_PRINTK0(KERN_ERR "ICMPv6 Redirect: %s() failed to allocate an skb, err=%d.\n", __func__, err); goto release; } skb_reserve(buff, LL_RESERVED_SPACE(dev)); ip6_nd_hdr(sk, buff, dev, &saddr_buf, &ipv6_hdr(skb)->saddr, IPPROTO_ICMPV6, len); skb_set_transport_header(buff, skb_tail_pointer(buff) - buff->data); skb_put(buff, len); icmph = icmp6_hdr(buff); memset(icmph, 0, sizeof(struct icmp6hdr)); icmph->icmp6_type = NDISC_REDIRECT; /* * copy target and destination addresses */ addrp = (struct in6_addr *)(icmph + 1); ipv6_addr_copy(addrp, target); addrp++; ipv6_addr_copy(addrp, &ipv6_hdr(skb)->daddr); opt = (u8*) (addrp + 1); /* * include target_address option */ if (ha) opt = ndisc_fill_addr_option(opt, ND_OPT_TARGET_LL_ADDR, ha, dev->addr_len, dev->type); /* * build redirect option and copy skb over to the new packet. */ memset(opt, 0, 8); *(opt++) = ND_OPT_REDIRECT_HDR; *(opt++) = (rd_len >> 3); opt += 6; memcpy(opt, ipv6_hdr(skb), rd_len - 8); icmph->icmp6_cksum = csum_ipv6_magic(&saddr_buf, &ipv6_hdr(skb)->saddr, len, IPPROTO_ICMPV6, csum_partial(icmph, len, 0)); skb_dst_set(buff, dst); rcu_read_lock(); idev = __in6_dev_get(dst->dev); IP6_UPD_PO_STATS(net, idev, IPSTATS_MIB_OUT, skb->len); err = NF_HOOK(NFPROTO_IPV6, NF_INET_LOCAL_OUT, buff, NULL, dst->dev, dst_output); if (!err) { ICMP6MSGOUT_INC_STATS(net, idev, NDISC_REDIRECT); ICMP6_INC_STATS(net, idev, ICMP6_MIB_OUTMSGS); } rcu_read_unlock(); return; release: dst_release(dst); } static void pndisc_redo(struct sk_buff *skb) { ndisc_recv_ns(skb); kfree_skb(skb); } int ndisc_rcv(struct sk_buff *skb) { struct nd_msg *msg; if (!pskb_may_pull(skb, skb->len)) return 0; msg = (struct nd_msg *)skb_transport_header(skb); __skb_push(skb, skb->data - skb_transport_header(skb)); if (ipv6_hdr(skb)->hop_limit != 255) { ND_PRINTK2(KERN_WARNING "ICMPv6 NDISC: invalid hop-limit: %d\n", ipv6_hdr(skb)->hop_limit); return 0; } if (msg->icmph.icmp6_code != 0) { ND_PRINTK2(KERN_WARNING "ICMPv6 NDISC: invalid ICMPv6 code: %d\n", msg->icmph.icmp6_code); return 0; } memset(NEIGH_CB(skb), 0, sizeof(struct neighbour_cb)); switch (msg->icmph.icmp6_type) { case NDISC_NEIGHBOUR_SOLICITATION: ndisc_recv_ns(skb); break; case NDISC_NEIGHBOUR_ADVERTISEMENT: ndisc_recv_na(skb); break; case NDISC_ROUTER_SOLICITATION: ndisc_recv_rs(skb); break; case NDISC_ROUTER_ADVERTISEMENT: ndisc_router_discovery(skb); break; case NDISC_REDIRECT: ndisc_redirect_rcv(skb); break; } return 0; } static int ndisc_netdev_event(struct notifier_block *this, unsigned long event, void *ptr) { struct net_device *dev = ptr; struct net *net = dev_net(dev); switch (event) { case NETDEV_CHANGEADDR: neigh_changeaddr(&nd_tbl, dev); fib6_run_gc(~0UL, net); break; case NETDEV_DOWN: neigh_ifdown(&nd_tbl, dev); fib6_run_gc(~0UL, net); break; case NETDEV_NOTIFY_PEERS: ndisc_send_unsol_na(dev); break; default: break; } return NOTIFY_DONE; } static struct notifier_block ndisc_netdev_notifier = { .notifier_call = ndisc_netdev_event, }; #ifdef CONFIG_SYSCTL static void ndisc_warn_deprecated_sysctl(struct ctl_table *ctl, const char *func, const char *dev_name) { static char warncomm[TASK_COMM_LEN]; static int warned; if (strcmp(warncomm, current->comm) && warned < 5) { strcpy(warncomm, current->comm); printk(KERN_WARNING "process `%s' is using deprecated sysctl (%s) " "net.ipv6.neigh.%s.%s; " "Use net.ipv6.neigh.%s.%s_ms " "instead.\n", warncomm, func, dev_name, ctl->procname, dev_name, ctl->procname); warned++; } } int ndisc_ifinfo_sysctl_change(struct ctl_table *ctl, int write, void __user *buffer, size_t *lenp, loff_t *ppos) { struct net_device *dev = ctl->extra1; struct inet6_dev *idev; int ret; if ((strcmp(ctl->procname, "retrans_time") == 0) || (strcmp(ctl->procname, "base_reachable_time") == 0)) ndisc_warn_deprecated_sysctl(ctl, "syscall", dev ? dev->name : "default"); if (strcmp(ctl->procname, "retrans_time") == 0) ret = proc_dointvec(ctl, write, buffer, lenp, ppos); else if (strcmp(ctl->procname, "base_reachable_time") == 0) ret = proc_dointvec_jiffies(ctl, write, buffer, lenp, ppos); else if ((strcmp(ctl->procname, "retrans_time_ms") == 0) || (strcmp(ctl->procname, "base_reachable_time_ms") == 0)) ret = proc_dointvec_ms_jiffies(ctl, write, buffer, lenp, ppos); else ret = -1; if (write && ret == 0 && dev && (idev = in6_dev_get(dev)) != NULL) { if (ctl->data == &idev->nd_parms->base_reachable_time) idev->nd_parms->reachable_time = neigh_rand_reach_time(idev->nd_parms->base_reachable_time); idev->tstamp = jiffies; inet6_ifinfo_notify(RTM_NEWLINK, idev); in6_dev_put(idev); } return ret; } #endif static int __net_init ndisc_net_init(struct net *net) { struct ipv6_pinfo *np; struct sock *sk; int err; err = inet_ctl_sock_create(&sk, PF_INET6, SOCK_RAW, IPPROTO_ICMPV6, net); if (err < 0) { ND_PRINTK0(KERN_ERR "ICMPv6 NDISC: Failed to initialize the control socket (err %d).\n", err); return err; } net->ipv6.ndisc_sk = sk; np = inet6_sk(sk); np->hop_limit = 255; /* Do not loopback ndisc messages */ np->mc_loop = 0; return 0; } static void __net_exit ndisc_net_exit(struct net *net) { inet_ctl_sock_destroy(net->ipv6.ndisc_sk); } static struct pernet_operations ndisc_net_ops = { .init = ndisc_net_init, .exit = ndisc_net_exit, }; int __init ndisc_init(void) { int err; err = register_pernet_subsys(&ndisc_net_ops); if (err) return err; /* * Initialize the neighbour table */ neigh_table_init(&nd_tbl); #ifdef CONFIG_SYSCTL err = neigh_sysctl_register(NULL, &nd_tbl.parms, "ipv6", &ndisc_ifinfo_sysctl_change); if (err) goto out_unregister_pernet; #endif err = register_netdevice_notifier(&ndisc_netdev_notifier); if (err) goto out_unregister_sysctl; out: return err; out_unregister_sysctl: #ifdef CONFIG_SYSCTL neigh_sysctl_unregister(&nd_tbl.parms); out_unregister_pernet: #endif unregister_pernet_subsys(&ndisc_net_ops); goto out; } void ndisc_cleanup(void) { unregister_netdevice_notifier(&ndisc_netdev_notifier); #ifdef CONFIG_SYSCTL neigh_sysctl_unregister(&nd_tbl.parms); #endif neigh_table_clear(&nd_tbl); unregister_pernet_subsys(&ndisc_net_ops); }
WhiteBearSolutions/WBSAirback
packages/wbsairback-kernel-image/wbsairback-kernel-image-3.2.43/net/ipv6/ndisc.c
C
apache-2.0
47,162
import {loadScript, validateData} from '#3p/3p'; /** * @param {!Window} global * @param {!Object} data */ export function flite(global, data) { // TODO: check mandatory fields validateData(data, [], ['guid', 'mixins']); const {guid} = data, o = global, e = encodeURIComponent, x = 0; let r = '', dep = ''; o.FLITE = o.FLITE || {}; o.FLITE.config = o.FLITE.config || {}; o.FLITE.config[guid] = o.FLITE.config[guid] || {}; o.FLITE.config[guid].cb = Math.random(); o.FLITE.config[guid].ts = +Number(new Date()); r = global.context.location.href; const m = r.match(new RegExp('[A-Za-z]+:[/][/][A-Za-z0-9.-]+')); dep = data.mixins ? '&dep=' + data.mixins : ''; const url = [ 'https://r.flite.com/syndication/uscript.js?i=', e(guid), '&v=3', dep, '&x=us', x, '&cb=', o.FLITE.config[guid].cb, '&d=', e((m && m[0]) || r), '&tz=', new Date().getTimezoneOffset(), ].join(''); loadScript(o, url); }
alanorozco/amphtml
ads/vendors/flite.js
JavaScript
apache-2.0
986
/* * Copyright 2008 biaoping.yin * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.frameworkset.spi.support; import java.util.Locale; /** * <p>Title: SimpleLocaleContext.java</p> * <p>Description: </p> * <p>bboss workgroup</p> * <p>Copyright (c) 2007</p> * @Date 2010-9-24 下午05:02:50 * @author biaoping.yin * @version 1.0 */ public class SimpleLocaleContext implements LocaleContext { private Locale locale; public SimpleLocaleContext(Locale locale, String localeName) { super(); this.locale = locale; this.localeName = localeName; } public SimpleLocaleContext(Locale locale) { super(); this.locale = locale; this.localeName = locale.toString(); } private String localeName; public Locale getLocale() { return locale; } public String getLocaleName() { return localeName; } }
besom/bbossgroups-mvn
bboss_core/src/main/java/org/frameworkset/spi/support/SimpleLocaleContext.java
Java
apache-2.0
1,410
--- MAC address handling object. -- depends on LuaJIT's 64-bit capabilities, -- both for numbers and bit.* library local bit = require "bit" local ffi = require "ffi" local mac_t = ffi.typeof('union { int64_t bits; uint8_t bytes[6];}') local mac_mt = {} mac_mt.__index = mac_mt function mac_mt:new (m) if ffi.istype(mac_t, m) then return m end local macobj = mac_t() if type(m) == 'string' then local i = 0; for b in m:gmatch('%x%x') do if i == 6 then -- avoid out of bound array index return nil, "malformed MAC address: " .. m end macobj.bytes[i] = tonumber(b, 16) i = i + 1 end if i < 6 then return nil, "malformed MAC address: " .. m end else macobj.bits = m end return macobj end function mac_mt:__tostring () return string.format('%02X:%02X:%02X:%02X:%02X:%02X', self.bytes[0], self.bytes[1], self.bytes[2], self.bytes[3], self.bytes[4], self.bytes[5]) end function mac_mt.__eq (a, b) return a.bits == b.bits end function mac_mt:subbits (i,j) local b = bit.rshift(self.bits, i) local mask = bit.bnot(bit.lshift(0xffffffffffffLL, j-i)) return tonumber(bit.band(b, mask)) end mac_t = ffi.metatype(mac_t, mac_mt) return mac_mt
mixflowtech/logsensor
src/lib/macaddress.lua
Lua
apache-2.0
1,296
import copy import json import multiprocessing import os.path import random import shutil import string import tempfile from contextlib import contextmanager from os import chdir, getcwd, mkdir from os.path import exists from subprocess import CalledProcessError, check_call, check_output import pkgpanda.build.constants import pkgpanda.build.src_fetchers from pkgpanda import expand_require as expand_require_exceptions from pkgpanda import Install, PackageId, Repository from pkgpanda.actions import add_package_file from pkgpanda.constants import RESERVED_UNIT_NAMES from pkgpanda.exceptions import FetchError, PackageError, ValidationError from pkgpanda.util import (check_forbidden_services, download_atomic, hash_checkout, load_json, load_string, logger, make_file, make_tar, rewrite_symlinks, write_json, write_string) class BuildError(Exception): """An error while building something.""" def __init__(self, msg: str): self.msg = msg def __str__(self): return self.msg class DockerCmd: def __init__(self): self.volumes = dict() self.environment = dict() self.container = str() def run(self, name, cmd): container_name = "{}-{}".format( name, ''.join( random.choice(string.ascii_lowercase) for _ in range(10) ) ) docker = ["docker", "run", "--name={}".format(container_name)] for host_path, container_path in self.volumes.items(): docker += ["-v", "{0}:{1}".format(host_path, container_path)] for k, v in self.environment.items(): docker += ["-e", "{0}={1}".format(k, v)] docker.append(self.container) docker += cmd check_call(docker) DockerCmd.clean(container_name) @staticmethod def clean(name): """Cleans up the specified container""" check_call(["docker", "rm", "-v", name]) def get_variants_from_filesystem(directory, extension): results = set() for filename in os.listdir(directory): # Skip things that don't end in the extension if not filename.endswith(extension): continue variant = filename[:-len(extension)] # Empty name variant shouldn't have a `.` following it if variant == '.': raise BuildError("Invalid filename {}. The \"default\" variant file should be just {}".format( filename, extension)) # Empty / default variant is represented as 'None'. if variant == '': variant = None else: # Should be foo. since we've moved the extension. if variant[-1] != '.': raise BuildError("Invalid variant filename {}. Expected a '.' separating the " "variant name and extension '{}'.".format(filename, extension)) variant = variant[:-1] results.add(variant) return results def get_src_fetcher(src_info, cache_dir, working_directory): try: kind = src_info['kind'] if kind not in pkgpanda.build.src_fetchers.all_fetchers: raise ValidationError("No known way to catch src with kind '{}'. Known kinds: {}".format( kind, pkgpanda.src_fetchers.all_fetchers.keys())) args = { 'src_info': src_info, 'cache_dir': cache_dir } if src_info['kind'] in ['git_local', 'url', 'url_extract']: args['working_directory'] = working_directory return pkgpanda.build.src_fetchers.all_fetchers[kind](**args) except ValidationError as ex: raise BuildError("Validation error when fetching sources for package: {}".format(ex)) class TreeInfo: ALLOWED_TREEINFO_KEYS = {'exclude', 'variants', 'core_package_list', 'bootstrap_package_list'} def __init__(self, treeinfo_dict): if treeinfo_dict.keys() > self.ALLOWED_TREEINFO_KEYS: raise BuildError( "treeinfo can only include the keys {}. Found {}".format( self.ALLOWED_TREEINFO_KEYS, treeinfo_dict.keys())) self.excludes = set(self._get_package_list(treeinfo_dict, 'exclude')) self.core_package_list = set(self._get_package_list(treeinfo_dict, 'core_package_list', self.excludes)) self.bootstrap_package_list = set(self._get_package_list( treeinfo_dict, 'bootstrap_package_list', self.excludes)) # List of mandatory package variants to include in the buildinfo. self.variants = treeinfo_dict.get('variants', dict()) if not isinstance(self.variants, dict): raise BuildError("treeinfo variants must be a dictionary of package name to variant name") @staticmethod def _get_package_list(treeinfo_dict, key, excludes=None): """Return a list of package name strings from treeinfo_dict by key. If key isn't present in treeinfo_dict, an empty list is returned. """ excludes = excludes or list() package_list = treeinfo_dict.get(key, list()) # Validate package list. if not isinstance(package_list, list): raise BuildError("{} must be either null (meaning don't use) or a list of package names.".format(key)) for package_name in package_list: if not isinstance(package_name, str): raise BuildError("{} must be a list of strings. Found a {} with the value: {}".format( key, type(package_name), package_name)) try: PackageId.validate_name(package_name) except ValidationError as ex: raise BuildError("Invalid package name in {}: {}".format(key, package_name)) from ex if package_name in excludes: raise BuildError("Package found in both exclude and {}: {}".format(key, package_name)) return package_list class PackageSet: def __init__(self, variant, treeinfo, package_store): self.variant = variant self.all_packages = self.package_tuples_with_dependencies( # If core_package_list is empty, default to all non-excluded packages. treeinfo.core_package_list or (package_store.packages_by_name.keys() - treeinfo.excludes), treeinfo, package_store ) self.validate_package_tuples(self.all_packages, treeinfo, package_store) if treeinfo.bootstrap_package_list: self.bootstrap_packages = self.package_tuples_with_dependencies( treeinfo.bootstrap_package_list, treeinfo, package_store ) self.validate_package_tuples(self.bootstrap_packages, treeinfo, package_store) else: self.bootstrap_packages = self.all_packages # Validate bootstrap packages are a subset of all packages. for package_name, variant in self.bootstrap_packages: if (package_name, variant) not in self.all_packages: raise BuildError("Bootstrap package {} (variant {}) not found in set of all packages".format( package_name, pkgpanda.util.variant_name(variant))) @staticmethod def package_tuples_with_dependencies(package_names, treeinfo, package_store): package_tuples = set((name, treeinfo.variants.get(name)) for name in set(package_names)) to_visit = list(package_tuples) while to_visit: package_tuple = to_visit.pop() for require in package_store.get_buildinfo(*package_tuple)['requires']: require_tuple = expand_require(require) if require_tuple not in package_tuples: to_visit.append(require_tuple) package_tuples.add(require_tuple) return package_tuples @staticmethod def validate_package_tuples(package_tuples, treeinfo, package_store): # Validate that all packages have the variant specified in treeinfo. for package_name, variant in package_tuples: treeinfo_variant = treeinfo.variants.get(package_name) if variant != treeinfo_variant: raise BuildError( "package {} is supposed to have variant {} included in the tree according to the treeinfo, " "but variant {} was found.".format( package_name, pkgpanda.util.variant_name(treeinfo_variant), pkgpanda.util.variant_name(variant), ) ) # Validate that all needed packages are built and not excluded by treeinfo. for package_name, variant in package_tuples: if (package_name, variant) not in package_store.packages: raise BuildError( "package {} variant {} is needed (explicitly requested or as a requires) " "but is not in the set of built packages.".format( package_name, pkgpanda.util.variant_name(variant), ) ) if package_name in treeinfo.excludes: raise BuildError("package {} is needed (explicitly requested or as a requires) " "but is excluded according to the treeinfo.json.".format(package_name)) class PackageStore: def __init__(self, packages_dir, repository_url): self._builders = {} self._repository_url = repository_url.rstrip('/') if repository_url is not None else None self._packages_dir = packages_dir.rstrip('/') # Load all possible packages, making a dictionary from (name, variant) -> buildinfo self._packages = dict() self._packages_by_name = dict() self._package_folders = dict() # Load an upstream if one exists # TODO(cmaloney): Allow upstreams to have upstreams self._package_cache_dir = self._packages_dir + "/cache/packages" self._upstream_dir = self._packages_dir + "/cache/upstream/checkout" self._upstream = None self._upstream_package_dir = self._upstream_dir + "/packages" # TODO(cmaloney): Make it so the upstream directory can be kept around check_call(['rm', '-rf', self._upstream_dir]) upstream_config = self._packages_dir + '/upstream.json' if os.path.exists(upstream_config): try: self._upstream = get_src_fetcher( load_optional_json(upstream_config), self._packages_dir + '/cache/upstream', packages_dir) self._upstream.checkout_to(self._upstream_dir) if os.path.exists(self._upstream_package_dir + "/upstream.json"): raise Exception("Support for upstreams which have upstreams is not currently implemented") except Exception as ex: raise BuildError("Error fetching upstream: {}".format(ex)) # Iterate through the packages directory finding all packages. Note this package dir comes # first, then we ignore duplicate definitions of the same package package_dirs = [self._packages_dir] if self._upstream: package_dirs.append(self._upstream_package_dir) for directory in package_dirs: for name in os.listdir(directory): package_folder = directory + '/' + name # Ignore files / non-directories if not os.path.isdir(package_folder): continue # If we've already found this package, it means 1+ versions have been defined. Use # those and ignore everything in the upstreams. if name in self._packages_by_name: continue builder_folder = os.path.join(directory, name, 'docker') if os.path.exists(builder_folder): self._builders[name] = builder_folder # Search the directory for buildinfo.json files, record the variants for variant in get_variants_from_filesystem(package_folder, 'buildinfo.json'): # Only adding the default dictionary once we know we have a package. self._packages_by_name.setdefault(name, dict()) buildinfo = load_buildinfo(package_folder, variant) self._packages[(name, variant)] = buildinfo self._packages_by_name[name][variant] = buildinfo if name in self._package_folders: assert self._package_folders[name] == package_folder else: self._package_folders[name] = package_folder def get_package_folder(self, name): return self._package_folders[name] def get_bootstrap_cache_dir(self): return self._packages_dir + "/cache/bootstrap" def get_complete_cache_dir(self): return self._packages_dir + "/cache/complete" def get_buildinfo(self, name, variant): return self._packages[(name, variant)] def get_last_complete_set(self): def get_last_complete(variant): complete_latest = ( self.get_complete_cache_dir() + '/' + pkgpanda.util.variant_prefix(variant) + 'complete.latest.json') if not os.path.exists(complete_latest): raise BuildError("No last complete found for variant {}. Expected to find {} to match " "{}".format(pkgpanda.util.variant_name(variant), complete_latest, pkgpanda.util.variant_prefix(variant) + 'treeinfo.json')) return load_json(complete_latest) result = {} for variant in self.list_trees(): result[variant] = get_last_complete(variant) return result def get_last_build_filename(self, name, variant): return self.get_package_cache_folder(name) + '/{}latest'.format(pkgpanda.util.variant_prefix(variant)) def get_package_path(self, pkg_id): return self.get_package_cache_folder(pkg_id.name) + '/{}.tar.xz'.format(pkg_id) def get_package_cache_folder(self, name): directory = self._package_cache_dir + '/' + name check_call(['mkdir', '-p', directory]) return directory def list_trees(self): return get_variants_from_filesystem(self._packages_dir, 'treeinfo.json') def get_package_set(self, variant): return PackageSet(variant, TreeInfo(load_config_variant(self._packages_dir, variant, 'treeinfo.json')), self) def get_all_package_sets(self): return [self.get_package_set(variant) for variant in sorted(self.list_trees(), key=pkgpanda.util.variant_str)] @property def packages(self): return self._packages @property def builders(self): return self._builders.copy() @property def packages_by_name(self): return self._packages_by_name @property def packages_dir(self): return self._packages_dir def try_fetch_by_id(self, pkg_id: PackageId): if self._repository_url is None: return False # TODO(cmaloney): Use storage providers to download instead of open coding. pkg_path = "{}.tar.xz".format(pkg_id) url = self._repository_url + '/packages/{0}/{1}'.format(pkg_id.name, pkg_path) try: directory = self.get_package_cache_folder(pkg_id.name) # TODO(cmaloney): Move to some sort of logging mechanism? print("Attempting to download", pkg_id, "from", url, "to", directory) download_atomic(directory + '/' + pkg_path, url, directory) assert os.path.exists(directory + '/' + pkg_path) return directory + '/' + pkg_path except FetchError: return False def try_fetch_bootstrap_and_active(self, bootstrap_id): if self._repository_url is None: return False try: bootstrap_name = '{}.bootstrap.tar.xz'.format(bootstrap_id) active_name = '{}.active.json'.format(bootstrap_id) # TODO(cmaloney): Use storage providers to download instead of open coding. bootstrap_url = self._repository_url + '/bootstrap/' + bootstrap_name active_url = self._repository_url + '/bootstrap/' + active_name print("Attempting to download", bootstrap_name, "from", bootstrap_url) dest_dir = self.get_bootstrap_cache_dir() # Normalize to no trailing slash for repository_url download_atomic(dest_dir + '/' + bootstrap_name, bootstrap_url, self._packages_dir) print("Attempting to download", active_name, "from", active_url) download_atomic(dest_dir + '/' + active_name, active_url, self._packages_dir) return True except FetchError: return False def expand_require(require): try: return expand_require_exceptions(require) except ValidationError as ex: raise BuildError(str(ex)) from ex def get_docker_id(docker_name): return check_output(["docker", "inspect", "-f", "{{ .Id }}", docker_name]).decode('utf-8').strip() def hash_files_in_folder(directory): """Given a relative path, hashes all files inside that folder and subfolders Returns a dictionary from filename to the hash of that file. If that whole dictionary is hashed, you get a hash of all the contents of the folder. This is split out from calculating the whole folder hash so that the behavior in different walking corner cases can be more easily tested. """ assert not directory.startswith('/'), \ "For the hash to be reproducible on other machines relative paths must always be used. " \ "Got path: {}".format(directory) directory = directory.rstrip('/') file_hash_dict = {} # TODO(cmaloney): Disallow symlinks as they're hard to hash, people can symlink / copy in their # build steps if needed. for root, dirs, filenames in os.walk(directory): assert not root.startswith('/') for name in filenames: path = root + '/' + name base = path[len(directory) + 1:] file_hash_dict[base] = pkgpanda.util.sha1(path) # If the directory has files inside of it, then it'll be picked up implicitly. by the files # or folders inside of it. If it contains nothing, it wouldn't be picked up but the existence # is important, so added it with a value for it's hash not-makeable via sha1 (empty string). if len(filenames) == 0 and len(dirs) == 0: path = root[len(directory) + 1:] # Empty path means it is the root directory, in which case we want no entries, not a # single entry "": "" if path: file_hash_dict[root[len(directory) + 1:]] = "" return file_hash_dict @contextmanager def as_cwd(path): start_dir = getcwd() chdir(path) yield chdir(start_dir) def hash_folder_abs(directory, work_dir): assert directory.startswith(work_dir), "directory must be inside work_dir: {} {}".format(directory, work_dir) assert not work_dir[-1] == '/', "This code assumes no trailing slash on the work_dir" with as_cwd(work_dir): return hash_folder(directory[len(work_dir) + 1:]) def hash_folder(directory): return hash_checkout(hash_files_in_folder(directory)) # Try to read json from the given file. If it is an empty file, then return an # empty json dictionary. def load_optional_json(filename): try: with open(filename) as f: text = f.read().strip() if text: return json.loads(text) return {} except OSError as ex: raise BuildError("Failed to open JSON file {}: {}".format(filename, ex)) except ValueError as ex: raise BuildError("Unable to parse json in {}: {}".format(filename, ex)) def load_config_variant(directory, variant, extension): assert directory[-1] != '/' return load_optional_json(directory + '/' + pkgpanda.util.variant_prefix(variant) + extension) def load_buildinfo(path, variant): buildinfo = load_config_variant(path, variant, 'buildinfo.json') # Fill in default / guaranteed members so code everywhere doesn't have to guard around it. buildinfo.setdefault('build_script', 'build') buildinfo.setdefault('docker', 'dcos/dcos-builder:dcos-builder_dockerdir-latest') buildinfo.setdefault('environment', dict()) buildinfo.setdefault('requires', list()) buildinfo.setdefault('state_directory', False) return buildinfo def make_bootstrap_tarball(package_store, packages, variant): # Convert filenames to package ids pkg_ids = list() for pkg_path in packages: # Get the package id from the given package path filename = os.path.basename(pkg_path) if not filename.endswith(".tar.xz"): raise BuildError("Packages must be packaged / end with a .tar.xz. Got {}".format(filename)) pkg_id = filename[:-len(".tar.xz")] pkg_ids.append(pkg_id) bootstrap_cache_dir = package_store.get_bootstrap_cache_dir() # Filename is output_name.<sha-1>.{active.json|.bootstrap.tar.xz} bootstrap_id = hash_checkout(pkg_ids) latest_name = "{}/{}bootstrap.latest".format(bootstrap_cache_dir, pkgpanda.util.variant_prefix(variant)) output_name = bootstrap_cache_dir + '/' + bootstrap_id + '.' # bootstrap tarball = <sha1 of packages in tarball>.bootstrap.tar.xz bootstrap_name = "{}bootstrap.tar.xz".format(output_name) active_name = "{}active.json".format(output_name) def mark_latest(): # Ensure latest is always written write_string(latest_name, bootstrap_id) print("bootstrap: {}".format(bootstrap_name)) print("active: {}".format(active_name)) print("latest: {}".format(latest_name)) return bootstrap_id if (os.path.exists(bootstrap_name)): print("Bootstrap already up to date, not recreating") return mark_latest() check_call(['mkdir', '-p', bootstrap_cache_dir]) # Try downloading. if package_store.try_fetch_bootstrap_and_active(bootstrap_id): print("Bootstrap already up to date, Not recreating. Downloaded from repository-url.") return mark_latest() print("Unable to download from cache. Building.") print("Creating bootstrap tarball for variant {}".format(variant)) work_dir = tempfile.mkdtemp(prefix='mkpanda_bootstrap_tmp') def make_abs(path): return os.path.join(work_dir, path) pkgpanda_root = make_abs("opt/mesosphere") repository = Repository(os.path.join(pkgpanda_root, "packages")) # Fetch all the packages to the root for pkg_path in packages: filename = os.path.basename(pkg_path) pkg_id = filename[:-len(".tar.xz")] def local_fetcher(id, target): shutil.unpack_archive(pkg_path, target, "gztar") repository.add(local_fetcher, pkg_id, False) # Activate the packages inside the repository. # Do generate dcos.target.wants inside the root so that we don't # try messing with /etc/systemd/system. install = Install( root=pkgpanda_root, config_dir=None, rooted_systemd=True, manage_systemd=False, block_systemd=True, fake_path=True, skip_systemd_dirs=True, manage_users=False, manage_state_dir=False) install.activate(repository.load_packages(pkg_ids)) # Mark the tarball as a bootstrap tarball/filesystem so that # dcos-setup.service will fire. make_file(make_abs("opt/mesosphere/bootstrap")) # Write out an active.json for the bootstrap tarball write_json(active_name, pkg_ids) # Rewrite all the symlinks to point to /opt/mesosphere rewrite_symlinks(work_dir, work_dir, "/") make_tar(bootstrap_name, pkgpanda_root) shutil.rmtree(work_dir) # Update latest last so that we don't ever use partially-built things. write_string(latest_name, bootstrap_id) print("Built bootstrap") return mark_latest() def build_tree_variants(package_store, mkbootstrap): """ Builds all possible tree variants in a given package store """ result = dict() tree_variants = get_variants_from_filesystem(package_store.packages_dir, 'treeinfo.json') if len(tree_variants) == 0: raise Exception('No treeinfo.json can be found in {}'.format(package_store.packages_dir)) for variant in tree_variants: result[variant] = pkgpanda.build.build_tree(package_store, mkbootstrap, variant) return result def build_tree(package_store, mkbootstrap, tree_variant): """Build packages and bootstrap tarballs for one or all tree variants. Returns a dict mapping tree variants to bootstrap IDs. If tree_variant is None, builds all available tree variants. """ # TODO(cmaloney): Add support for circular dependencies. They are doable # long as there is a pre-built version of enough of the packages. # TODO(cmaloney): Make it so when we're building a treeinfo which has a # explicit package list we don't build all the other packages. build_order = list() visited = set() built = set() def visit(pkg_tuple: tuple): """Add a package and its requires to the build order. Raises AssertionError if pkg_tuple is in the set of visited packages. If the package has any requires, they're recursively visited and added to the build order depth-first. Then the package itself is added. """ # Visit the node for the first (and only) time. assert pkg_tuple not in visited visited.add(pkg_tuple) # Ensure all dependencies are built. Sorted for stability for require in sorted(package_store.packages[pkg_tuple]['requires']): require_tuple = expand_require(require) # If the dependency has already been built, we can move on. if require_tuple in built: continue # If the dependency has not been built but has been visited, then # there's a cycle in the dependency graph. if require_tuple in visited: raise BuildError("Circular dependency. Circular link {0} -> {1}".format(pkg_tuple, require_tuple)) if PackageId.is_id(require_tuple[0]): raise BuildError("Depending on a specific package id is not supported. Package {} " "depends on {}".format(pkg_tuple, require_tuple)) if require_tuple not in package_store.packages: raise BuildError("Package {0} require {1} not buildable from tree.".format(pkg_tuple, require_tuple)) # Add the dependency (after its dependencies, if any) to the build # order. visit(require_tuple) build_order.append(pkg_tuple) built.add(pkg_tuple) # Can't compare none to string, so expand none -> "true" / "false", then put # the string in a field after "" if none, the string if not. def key_func(elem): return elem[0], elem[1] is None, elem[1] or "" def visit_packages(package_tuples): for pkg_tuple in sorted(package_tuples, key=key_func): if pkg_tuple in visited: continue visit(pkg_tuple) if tree_variant: package_sets = [package_store.get_package_set(tree_variant)] else: package_sets = package_store.get_all_package_sets() with logger.scope("resolve package graph"): # Build all required packages for all tree variants. for package_set in package_sets: visit_packages(package_set.all_packages) built_packages = dict() for (name, variant) in build_order: built_packages.setdefault(name, dict()) # Run the build, store the built package path for later use. # TODO(cmaloney): Only build the requested variants, rather than all variants. built_packages[name][variant] = build( package_store, name, variant, True) # Build bootstrap tarballs for all tree variants. def make_bootstrap(package_set): with logger.scope("Making bootstrap variant: {}".format(pkgpanda.util.variant_name(package_set.variant))): package_paths = list() for name, pkg_variant in package_set.bootstrap_packages: package_paths.append(built_packages[name][pkg_variant]) if mkbootstrap: return make_bootstrap_tarball( package_store, list(sorted(package_paths)), package_set.variant) # Build bootstraps and and package lists for all variants. # TODO(cmaloney): Allow distinguishing between "build all" and "build the default one". complete_cache_dir = package_store.get_complete_cache_dir() check_call(['mkdir', '-p', complete_cache_dir]) results = {} for package_set in package_sets: info = { 'bootstrap': make_bootstrap(package_set), 'packages': sorted( load_string(package_store.get_last_build_filename(*pkg_tuple)) for pkg_tuple in package_set.all_packages)} write_json( complete_cache_dir + '/' + pkgpanda.util.variant_prefix(package_set.variant) + 'complete.latest.json', info) results[package_set.variant] = info return results def assert_no_duplicate_keys(lhs, rhs): if len(lhs.keys() & rhs.keys()) != 0: print("ASSERTION FAILED: Duplicate keys between {} and {}".format(lhs, rhs)) assert len(lhs.keys() & rhs.keys()) == 0 # Find all build variants and build them def build_package_variants(package_store, name, clean_after_build=True, recursive=False): # Find the packages dir / root of the packages tree, and create a PackageStore results = dict() for variant in package_store.packages_by_name[name].keys(): results[variant] = build( package_store, name, variant, clean_after_build=clean_after_build, recursive=recursive) return results class IdBuilder(): def __init__(self, buildinfo): self._start_keys = set(buildinfo.keys()) self._buildinfo = copy.deepcopy(buildinfo) self._taken = set() def _check_no_key(self, field): if field in self._buildinfo: raise BuildError("Key {} shouldn't be in buildinfo, but was".format(field)) def add(self, field, value): self._check_no_key(field) self._buildinfo[field] = value def has(self, field): return field in self._buildinfo def take(self, field): self._taken.add(field) return self._buildinfo[field] def replace(self, taken_field, new_field, new_value): assert taken_field in self._buildinfo self._check_no_key(new_field) del self._buildinfo[taken_field] self._buildinfo[new_field] = new_value self._taken.add(new_field) def update(self, field, new_value): assert field in self._buildinfo self._buildinfo[field] = new_value def get_build_ids(self): # If any keys are left in the buildinfo, error that there were unused keys remaining_keys = self._start_keys - self._taken if remaining_keys: raise BuildError("ERROR: Unknown keys {} in buildinfo.json".format(remaining_keys)) return self._buildinfo def build(package_store: PackageStore, name: str, variant, clean_after_build, recursive=False): msg = "Building package {} variant {}".format(name, pkgpanda.util.variant_name(variant)) with logger.scope(msg): return _build(package_store, name, variant, clean_after_build, recursive) def _build(package_store, name, variant, clean_after_build, recursive): assert isinstance(package_store, PackageStore) tmpdir = tempfile.TemporaryDirectory(prefix="pkgpanda_repo") repository = Repository(tmpdir.name) package_dir = package_store.get_package_folder(name) def src_abs(name): return package_dir + '/' + name def cache_abs(filename): return package_store.get_package_cache_folder(name) + '/' + filename # Build pkginfo over time, translating fields from buildinfo. pkginfo = {} # Build up the docker command arguments over time, translating fields as needed. cmd = DockerCmd() assert (name, variant) in package_store.packages, \ "Programming error: name, variant should have been validated to be valid before calling build()." builder = IdBuilder(package_store.get_buildinfo(name, variant)) final_buildinfo = dict() builder.add('name', name) builder.add('variant', pkgpanda.util.variant_str(variant)) # Convert single_source -> sources if builder.has('sources'): if builder.has('single_source'): raise BuildError('Both sources and single_source cannot be specified at the same time') sources = builder.take('sources') elif builder.has('single_source'): sources = {name: builder.take('single_source')} builder.replace('single_source', 'sources', sources) else: builder.add('sources', {}) sources = dict() print("NOTICE: No sources specified") final_buildinfo['sources'] = sources # Construct the source fetchers, gather the checkout ids from them checkout_ids = dict() fetchers = dict() try: for src_name, src_info in sorted(sources.items()): # TODO(cmaloney): Switch to a unified top level cache directory shared by all packages cache_dir = package_store.get_package_cache_folder(name) + '/' + src_name check_call(['mkdir', '-p', cache_dir]) fetcher = get_src_fetcher(src_info, cache_dir, package_dir) fetchers[src_name] = fetcher checkout_ids[src_name] = fetcher.get_id() except ValidationError as ex: raise BuildError("Validation error when fetching sources for package: {}".format(ex)) for src_name, checkout_id in checkout_ids.items(): # NOTE: single_source buildinfo was expanded above so the src_name is # always correct here. # Make sure we never accidentally overwrite something which might be # important. Fields should match if specified (And that should be # tested at some point). For now disallowing identical saves hassle. assert_no_duplicate_keys(checkout_id, final_buildinfo['sources'][src_name]) final_buildinfo['sources'][src_name].update(checkout_id) # Add the sha1 of the buildinfo.json + build file to the build ids builder.update('sources', checkout_ids) build_script = src_abs(builder.take('build_script')) # TODO(cmaloney): Change dest name to build_script_sha1 builder.replace('build_script', 'build', pkgpanda.util.sha1(build_script)) builder.add('pkgpanda_version', pkgpanda.build.constants.version) extra_dir = src_abs("extra") # Add the "extra" folder inside the package as an additional source if it # exists if os.path.exists(extra_dir): extra_id = hash_folder_abs(extra_dir, package_dir) builder.add('extra_source', extra_id) final_buildinfo['extra_source'] = extra_id # Figure out the docker name. docker_name = builder.take('docker') cmd.container = docker_name # Add the id of the docker build environment to the build_ids. try: docker_id = get_docker_id(docker_name) except CalledProcessError: # docker pull the container and try again check_call(['docker', 'pull', docker_name]) docker_id = get_docker_id(docker_name) builder.update('docker', docker_id) # TODO(cmaloney): The environment variables should be generated during build # not live in buildinfo.json. pkginfo['environment'] = builder.take('environment') # Whether pkgpanda should on the host make sure a `/var/lib` state directory is available pkginfo['state_directory'] = builder.take('state_directory') if pkginfo['state_directory'] not in [True, False]: raise BuildError("state_directory in buildinfo.json must be a boolean `true` or `false`") username = None if builder.has('username'): username = builder.take('username') if not isinstance(username, str): raise BuildError("username in buildinfo.json must be either not set (no user for this" " package), or a user name string") try: pkgpanda.UserManagement.validate_username(username) except ValidationError as ex: raise BuildError("username in buildinfo.json didn't meet the validation rules. {}".format(ex)) pkginfo['username'] = username group = None if builder.has('group'): group = builder.take('group') if not isinstance(group, str): raise BuildError("group in buildinfo.json must be either not set (use default group for this user)" ", or group must be a string") try: pkgpanda.UserManagement.validate_group_name(group) except ValidationError as ex: raise BuildError("group in buildinfo.json didn't meet the validation rules. {}".format(ex)) pkginfo['group'] = group # Packages need directories inside the fake install root (otherwise docker # will try making the directories on a readonly filesystem), so build the # install root now, and make the package directories in it as we go. install_dir = tempfile.mkdtemp(prefix="pkgpanda-") active_packages = list() active_package_ids = set() active_package_variants = dict() auto_deps = set() # Final package has the same requires as the build. requires = builder.take('requires') pkginfo['requires'] = requires if builder.has("sysctl"): pkginfo["sysctl"] = builder.take("sysctl") # TODO(cmaloney): Pull generating the full set of requires a function. to_check = copy.deepcopy(requires) if type(to_check) != list: raise BuildError("`requires` in buildinfo.json must be an array of dependencies.") while to_check: requires_info = to_check.pop(0) requires_name, requires_variant = expand_require(requires_info) if requires_name in active_package_variants: # TODO(cmaloney): If one package depends on the <default> # variant of a package and 1+ others depends on a non-<default> # variant then update the dependency to the non-default variant # rather than erroring. if requires_variant != active_package_variants[requires_name]: # TODO(cmaloney): Make this contain the chains of # dependencies which contain the conflicting packages. # a -> b -> c -> d {foo} # e {bar} -> d {baz} raise BuildError( "Dependncy on multiple variants of the same package {}. variants: {} {}".format( requires_name, requires_variant, active_package_variants[requires_name])) # The variant has package {requires_name, variant} already is a # dependency, don't process it again / move on to the next. continue active_package_variants[requires_name] = requires_variant # Figure out the last build of the dependency, add that as the # fully expanded dependency. requires_last_build = package_store.get_last_build_filename(requires_name, requires_variant) if not os.path.exists(requires_last_build): if recursive: # Build the dependency build(package_store, requires_name, requires_variant, clean_after_build, recursive) else: raise BuildError("No last build file found for dependency {} variant {}. Rebuild " "the dependency".format(requires_name, requires_variant)) try: pkg_id_str = load_string(requires_last_build) auto_deps.add(pkg_id_str) pkg_buildinfo = package_store.get_buildinfo(requires_name, requires_variant) pkg_requires = pkg_buildinfo['requires'] pkg_path = repository.package_path(pkg_id_str) pkg_tar = pkg_id_str + '.tar.xz' if not os.path.exists(package_store.get_package_cache_folder(requires_name) + '/' + pkg_tar): raise BuildError( "The build tarball {} refered to by the last_build file of the dependency {} " "variant {} doesn't exist. Rebuild the dependency.".format( pkg_tar, requires_name, requires_variant)) active_package_ids.add(pkg_id_str) # Mount the package into the docker container. cmd.volumes[pkg_path] = "/opt/mesosphere/packages/{}:ro".format(pkg_id_str) os.makedirs(os.path.join(install_dir, "packages/{}".format(pkg_id_str))) # Add the dependencies of the package to the set which will be # activated. # TODO(cmaloney): All these 'transitive' dependencies shouldn't # be available to the package being built, only what depends on # them directly. to_check += pkg_requires except ValidationError as ex: raise BuildError("validating package needed as dependency {0}: {1}".format(requires_name, ex)) from ex except PackageError as ex: raise BuildError("loading package needed as dependency {0}: {1}".format(requires_name, ex)) from ex # Add requires to the package id, calculate the final package id. # NOTE: active_packages isn't fully constructed here since we lazily load # packages not already in the repository. builder.update('requires', list(active_package_ids)) version_extra = None if builder.has('version_extra'): version_extra = builder.take('version_extra') build_ids = builder.get_build_ids() version_base = hash_checkout(build_ids) version = None if builder.has('version_extra'): version = "{0}-{1}".format(version_extra, version_base) else: version = version_base pkg_id = PackageId.from_parts(name, version) # Everything must have been extracted by now. If it wasn't, then we just # had a hard error that it was set but not used, as well as didn't include # it in the caluclation of the PackageId. builder = None # Save the build_ids. Useful for verify exactly what went into the # package build hash. final_buildinfo['build_ids'] = build_ids final_buildinfo['package_version'] = version # Save the package name and variant. The variant is used when installing # packages to validate dependencies. final_buildinfo['name'] = name final_buildinfo['variant'] = variant # If the package is already built, don't do anything. pkg_path = package_store.get_package_cache_folder(name) + '/{}.tar.xz'.format(pkg_id) # Done if it exists locally if exists(pkg_path): print("Package up to date. Not re-building.") # TODO(cmaloney): Updating / filling last_build should be moved out of # the build function. write_string(package_store.get_last_build_filename(name, variant), str(pkg_id)) return pkg_path # Try downloading. dl_path = package_store.try_fetch_by_id(pkg_id) if dl_path: print("Package up to date. Not re-building. Downloaded from repository-url.") # TODO(cmaloney): Updating / filling last_build should be moved out of # the build function. write_string(package_store.get_last_build_filename(name, variant), str(pkg_id)) print(dl_path, pkg_path) assert dl_path == pkg_path return pkg_path # Fall out and do the build since it couldn't be downloaded print("Unable to download from cache. Proceeding to build") print("Building package {} with buildinfo: {}".format( pkg_id, json.dumps(final_buildinfo, indent=2, sort_keys=True))) # Clean out src, result so later steps can use them freely for building. def clean(): # Run a docker container to remove src/ and result/ cmd = DockerCmd() cmd.volumes = { package_store.get_package_cache_folder(name): "/pkg/:rw", } cmd.container = "ubuntu:14.04.4" cmd.run("package-cleaner", ["rm", "-rf", "/pkg/src", "/pkg/result"]) clean() # Only fresh builds are allowed which don't overlap existing artifacts. result_dir = cache_abs("result") if exists(result_dir): raise BuildError("result folder must not exist. It will be made when the package is " "built. {}".format(result_dir)) # 'mkpanda add' all implicit dependencies since we actually need to build. for dep in auto_deps: print("Auto-adding dependency: {}".format(dep)) # NOTE: Not using the name pkg_id because that overrides the outer one. id_obj = PackageId(dep) add_package_file(repository, package_store.get_package_path(id_obj)) package = repository.load(dep) active_packages.append(package) # Checkout all the sources int their respective 'src/' folders. try: src_dir = cache_abs('src') if os.path.exists(src_dir): raise ValidationError( "'src' directory already exists, did you have a previous build? " + "Currently all builds must be from scratch. Support should be " + "added for re-using a src directory when possible. src={}".format(src_dir)) os.mkdir(src_dir) for src_name, fetcher in sorted(fetchers.items()): root = cache_abs('src/' + src_name) os.mkdir(root) fetcher.checkout_to(root) except ValidationError as ex: raise BuildError("Validation error when fetching sources for package: {}".format(ex)) # Activate the packages so that we have a proper path, environment # variables. # TODO(cmaloney): RAII type thing for temproary directory so if we # don't get all the way through things will be cleaned up? install = Install( root=install_dir, config_dir=None, rooted_systemd=True, manage_systemd=False, block_systemd=True, fake_path=True, manage_users=False, manage_state_dir=False) install.activate(active_packages) # Rewrite all the symlinks inside the active path because we will # be mounting the folder into a docker container, and the absolute # paths to the packages will change. # TODO(cmaloney): This isn't very clean, it would be much nicer to # just run pkgpanda inside the package. rewrite_symlinks(install_dir, repository.path, "/opt/mesosphere/packages/") print("Building package in docker") # TODO(cmaloney): Run as a specific non-root user, make it possible # for non-root to cleanup afterwards. # Run the build, prepping the environment as necessary. mkdir(cache_abs("result")) # Copy the build info to the resulting tarball write_json(cache_abs("src/buildinfo.full.json"), final_buildinfo) write_json(cache_abs("result/buildinfo.full.json"), final_buildinfo) write_json(cache_abs("result/pkginfo.json"), pkginfo) # Make the folder for the package we are building. If docker does it, it # gets auto-created with root permissions and we can't actually delete it. os.makedirs(os.path.join(install_dir, "packages", str(pkg_id))) # TOOD(cmaloney): Disallow writing to well known files and directories? # Source we checked out cmd.volumes.update({ # TODO(cmaloney): src should be read only... cache_abs("src"): "/pkg/src:rw", # The build script build_script: "/pkg/build:ro", # Getting the result out cache_abs("result"): "/opt/mesosphere/packages/{}:rw".format(pkg_id), install_dir: "/opt/mesosphere:ro" }) if os.path.exists(extra_dir): cmd.volumes[extra_dir] = "/pkg/extra:ro" cmd.environment = { "PKG_VERSION": version, "PKG_NAME": name, "PKG_ID": pkg_id, "PKG_PATH": "/opt/mesosphere/packages/{}".format(pkg_id), "PKG_VARIANT": variant if variant is not None else "<default>", "NUM_CORES": multiprocessing.cpu_count() } try: # TODO(cmaloney): Run a wrapper which sources # /opt/mesosphere/environment then runs a build. Also should fix # ownership of /opt/mesosphere/packages/{pkg_id} post build. cmd.run("package-builder", [ "/bin/bash", "-o", "nounset", "-o", "pipefail", "-o", "errexit", "/pkg/build"]) except CalledProcessError as ex: raise BuildError("docker exited non-zero: {}\nCommand: {}".format(ex.returncode, ' '.join(ex.cmd))) # Clean up the temporary install dir used for dependencies. # TODO(cmaloney): Move to an RAII wrapper. check_call(['rm', '-rf', install_dir]) with logger.scope("Build package tarball"): # Check for forbidden services before packaging the tarball: try: check_forbidden_services(cache_abs("result"), RESERVED_UNIT_NAMES) except ValidationError as ex: raise BuildError("Package validation failed: {}".format(ex)) # TODO(cmaloney): Updating / filling last_build should be moved out of # the build function. write_string(package_store.get_last_build_filename(name, variant), str(pkg_id)) # Bundle the artifacts into the pkgpanda package tmp_name = pkg_path + "-tmp.tar.xz" make_tar(tmp_name, cache_abs("result")) os.rename(tmp_name, pkg_path) print("Package built.") if clean_after_build: clean() return pkg_path
BenWhitehead/dcos
pkgpanda/build/__init__.py
Python
apache-2.0
50,458
/** * Copyright (C) 2012 Ryan W Tenney ([email protected]) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ryantenney.metrics.spring.reporter; import static com.ryantenney.metrics.spring.reporter.JmxReporterFactoryBean.*; public class JmxReporterElementParser extends AbstractReporterElementParser { @Override public String getType() { return "jmx"; } @Override protected Class<?> getBeanClass() { return JmxReporterFactoryBean.class; } @Override protected void validate(ValidationContext c) { c.optional(DOMAIN); c.optional(MBEAN_SERVER_REF); c.optional(RATE_UNIT, TIMEUNIT_STRING_REGEX, "Rate unit must be one of the enum constants from java.util.concurrent.TimeUnit"); c.optional(DURATION_UNIT, TIMEUNIT_STRING_REGEX, "Duration unit must be one of the enum constants from java.util.concurrent.TimeUnit"); c.optional(FILTER_PATTERN); c.optional(FILTER_REF); if (c.has(FILTER_PATTERN) && c.has(FILTER_REF)) { c.reject(FILTER_REF, "Reporter element must not specify both the 'filter' and 'filter-ref' attributes"); } c.rejectUnmatchedProperties(); } }
wyzssw/metrics-spring
src/main/java/com/ryantenney/metrics/spring/reporter/JmxReporterElementParser.java
Java
apache-2.0
1,620
/* * Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ #pragma once #include <aws/elasticloadbalancing/ElasticLoadBalancing_EXPORTS.h> #include <aws/core/utils/memory/stl/AWSStreamFwd.h> #include <aws/core/utils/memory/stl/AWSString.h> namespace Aws { namespace Utils { namespace Xml { class XmlNode; } // namespace Xml } // namespace Utils namespace ElasticLoadBalancing { namespace Model { /* <p>Information about a tag.</p> */ class AWS_ELASTICLOADBALANCING_API Tag { public: Tag(); Tag(const Aws::Utils::Xml::XmlNode& xmlNode); Tag& operator=(const Aws::Utils::Xml::XmlNode& xmlNode); void OutputToStream(Aws::OStream& ostream, const char* location, unsigned index, const char* locationValue) const; void OutputToStream(Aws::OStream& oStream, const char* location) const; /* <p>The key of the tag.</p> */ inline const Aws::String& GetKey() const{ return m_key; } /* <p>The key of the tag.</p> */ inline void SetKey(const Aws::String& value) { m_keyHasBeenSet = true; m_key = value; } /* <p>The key of the tag.</p> */ inline void SetKey(Aws::String&& value) { m_keyHasBeenSet = true; m_key = value; } /* <p>The key of the tag.</p> */ inline void SetKey(const char* value) { m_keyHasBeenSet = true; m_key.assign(value); } /* <p>The key of the tag.</p> */ inline Tag& WithKey(const Aws::String& value) { SetKey(value); return *this;} /* <p>The key of the tag.</p> */ inline Tag& WithKey(Aws::String&& value) { SetKey(value); return *this;} /* <p>The key of the tag.</p> */ inline Tag& WithKey(const char* value) { SetKey(value); return *this;} /* <p>The value of the tag.</p> */ inline const Aws::String& GetValue() const{ return m_value; } /* <p>The value of the tag.</p> */ inline void SetValue(const Aws::String& value) { m_valueHasBeenSet = true; m_value = value; } /* <p>The value of the tag.</p> */ inline void SetValue(Aws::String&& value) { m_valueHasBeenSet = true; m_value = value; } /* <p>The value of the tag.</p> */ inline void SetValue(const char* value) { m_valueHasBeenSet = true; m_value.assign(value); } /* <p>The value of the tag.</p> */ inline Tag& WithValue(const Aws::String& value) { SetValue(value); return *this;} /* <p>The value of the tag.</p> */ inline Tag& WithValue(Aws::String&& value) { SetValue(value); return *this;} /* <p>The value of the tag.</p> */ inline Tag& WithValue(const char* value) { SetValue(value); return *this;} private: Aws::String m_key; bool m_keyHasBeenSet; Aws::String m_value; bool m_valueHasBeenSet; }; } // namespace Model } // namespace ElasticLoadBalancing } // namespace Aws
zeliard/aws-sdk-cpp
windows-build/include/aws/elasticloadbalancing/model/Tag.h
C
apache-2.0
3,365
"""Closures channels module for Zigbee Home Automation.""" from zigpy.zcl.clusters import closures from homeassistant.core import callback from .. import registries from ..const import REPORT_CONFIG_IMMEDIATE, SIGNAL_ATTR_UPDATED from .base import ClientChannel, ZigbeeChannel @registries.ZIGBEE_CHANNEL_REGISTRY.register(closures.DoorLock.cluster_id) class DoorLockChannel(ZigbeeChannel): """Door lock channel.""" _value_attribute = 0 REPORT_CONFIG = ({"attr": "lock_state", "config": REPORT_CONFIG_IMMEDIATE},) async def async_update(self): """Retrieve latest state.""" result = await self.get_attribute_value("lock_state", from_cache=True) if result is not None: self.async_send_signal( f"{self.unique_id}_{SIGNAL_ATTR_UPDATED}", 0, "lock_state", result ) @callback def cluster_command(self, tsn, command_id, args): """Handle a cluster command received on this cluster.""" if ( self._cluster.client_commands is None or self._cluster.client_commands.get(command_id) is None ): return command_name = self._cluster.client_commands.get(command_id, [command_id])[0] if command_name == "operation_event_notification": self.zha_send_event( command_name, { "source": args[0].name, "operation": args[1].name, "code_slot": (args[2] + 1), # start code slots at 1 }, ) @callback def attribute_updated(self, attrid, value): """Handle attribute update from lock cluster.""" attr_name = self.cluster.attributes.get(attrid, [attrid])[0] self.debug( "Attribute report '%s'[%s] = %s", self.cluster.name, attr_name, value ) if attrid == self._value_attribute: self.async_send_signal( f"{self.unique_id}_{SIGNAL_ATTR_UPDATED}", attrid, attr_name, value ) async def async_set_user_code(self, code_slot: int, user_code: str) -> None: """Set the user code for the code slot.""" await self.set_pin_code( code_slot - 1, # start code slots at 1, Zigbee internals use 0 closures.DoorLock.UserStatus.Enabled, closures.DoorLock.UserType.Unrestricted, user_code, ) async def async_enable_user_code(self, code_slot: int) -> None: """Enable the code slot.""" await self.set_user_status(code_slot - 1, closures.DoorLock.UserStatus.Enabled) async def async_disable_user_code(self, code_slot: int) -> None: """Disable the code slot.""" await self.set_user_status(code_slot - 1, closures.DoorLock.UserStatus.Disabled) async def async_get_user_code(self, code_slot: int) -> int: """Get the user code from the code slot.""" result = await self.get_pin_code(code_slot - 1) return result async def async_clear_user_code(self, code_slot: int) -> None: """Clear the code slot.""" await self.clear_pin_code(code_slot - 1) async def async_clear_all_user_codes(self) -> None: """Clear all code slots.""" await self.clear_all_pin_codes() async def async_set_user_type(self, code_slot: int, user_type: str) -> None: """Set user type.""" await self.set_user_type(code_slot - 1, user_type) async def async_get_user_type(self, code_slot: int) -> str: """Get user type.""" result = await self.get_user_type(code_slot - 1) return result @registries.ZIGBEE_CHANNEL_REGISTRY.register(closures.Shade.cluster_id) class Shade(ZigbeeChannel): """Shade channel.""" @registries.CLIENT_CHANNELS_REGISTRY.register(closures.WindowCovering.cluster_id) class WindowCoveringClient(ClientChannel): """Window client channel.""" @registries.ZIGBEE_CHANNEL_REGISTRY.register(closures.WindowCovering.cluster_id) class WindowCovering(ZigbeeChannel): """Window channel.""" _value_attribute = 8 REPORT_CONFIG = ( {"attr": "current_position_lift_percentage", "config": REPORT_CONFIG_IMMEDIATE}, ) async def async_update(self): """Retrieve latest state.""" result = await self.get_attribute_value( "current_position_lift_percentage", from_cache=False ) self.debug("read current position: %s", result) if result is not None: self.async_send_signal( f"{self.unique_id}_{SIGNAL_ATTR_UPDATED}", 8, "current_position_lift_percentage", result, ) @callback def attribute_updated(self, attrid, value): """Handle attribute update from window_covering cluster.""" attr_name = self.cluster.attributes.get(attrid, [attrid])[0] self.debug( "Attribute report '%s'[%s] = %s", self.cluster.name, attr_name, value ) if attrid == self._value_attribute: self.async_send_signal( f"{self.unique_id}_{SIGNAL_ATTR_UPDATED}", attrid, attr_name, value )
lukas-hetzenecker/home-assistant
homeassistant/components/zha/core/channels/closures.py
Python
apache-2.0
5,197
# coding=utf-8 # Copyright 2015 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import json import os from hashlib import sha1 from pants.base.build_environment import get_buildroot from pants.option.custom_types import dict_with_files_option, file_option, target_option def stable_json_dumps(obj): return json.dumps(obj, ensure_ascii=True, allow_nan=False, sort_keys=True) def stable_json_sha1(obj): return sha1(stable_json_dumps(obj)).hexdigest() class OptionsFingerprinter(object): """Handles fingerprinting options under a given build_graph. :API: public """ def __init__(self, build_graph): self._build_graph = build_graph def fingerprint(self, option_type, option_val): """Returns a hash of the given option_val based on the option_type. :API: public Returns None if option_val is None. """ if option_val is None: return None # For simplicity, we always fingerprint a list. For non-list-valued options, # this will be a singleton list. if not isinstance(option_val, (list, tuple)): option_val = [option_val] if option_type == target_option: return self._fingerprint_target_specs(option_val) elif option_type == file_option: return self._fingerprint_files(option_val) elif option_type == dict_with_files_option: return self._fingerprint_dict_with_files(option_val) else: return self._fingerprint_primitives(option_val) def _fingerprint_target_specs(self, specs): """Returns a fingerprint of the targets resolved from given target specs.""" hasher = sha1() for spec in sorted(specs): for target in sorted(self._build_graph.resolve(spec)): # Not all targets have hashes; in particular, `Dependencies` targets don't. h = target.compute_invalidation_hash() if h: hasher.update(h) return hasher.hexdigest() def _assert_in_buildroot(self, filepath): """Raises an error if the given filepath isn't in the buildroot. Returns the normalized, absolute form of the path. """ filepath = os.path.normpath(filepath) root = get_buildroot() if not os.path.abspath(filepath) == filepath: # If not absolute, assume relative to the build root. return os.path.join(root, filepath) else: if '..' in os.path.relpath(filepath, root).split(os.path.sep): # The path wasn't in the buildroot. This is an error because it violates the pants being # hermetic. raise ValueError('Received a file_option that was not inside the build root:\n' ' file_option: {filepath}\n' ' build_root: {buildroot}\n' .format(filepath=filepath, buildroot=root)) return filepath def _fingerprint_files(self, filepaths): """Returns a fingerprint of the given filepaths and their contents. This assumes the files are small enough to be read into memory. """ hasher = sha1() # Note that we don't sort the filepaths, as their order may have meaning. for filepath in filepaths: filepath = self._assert_in_buildroot(filepath) hasher.update(os.path.relpath(filepath, get_buildroot())) with open(filepath, 'rb') as f: hasher.update(f.read()) return hasher.hexdigest() def _fingerprint_primitives(self, val): return stable_json_sha1(val) def _fingerprint_dict_with_files(self, option_val): """Returns a fingerprint of the given dictionary containing file paths. Any value which is a file path which exists on disk will be fingerprinted by that file's contents rather than by its path. This assumes the files are small enough to be read into memory. """ # Dicts are wrapped in singleton lists. See the "For simplicity..." comment in `fingerprint()`. option_val = option_val[0] return stable_json_sha1({k: self._expand_possible_file_value(v) for k, v in option_val.items()}) def _expand_possible_file_value(self, value): """If the value is a file, returns its contents. Otherwise return the original value.""" if value and os.path.isfile(str(value)): with open(value, 'r') as f: return f.read() return value
pombredanne/pants
src/python/pants/option/options_fingerprinter.py
Python
apache-2.0
4,437
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is part of dcm4che, an implementation of DICOM(TM) in * Java(TM), available at http://sourceforge.net/projects/dcm4che. * * The Initial Developer of the Original Code is * TIANI Medgraph AG. * Portions created by the Initial Developer are Copyright (C) 2003-2005 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Gunter Zeilinger <[email protected]> * Franz Willer <[email protected]> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ package org.dcm4chex.archive.dcm; import java.io.IOException; import javax.management.Notification; import javax.management.NotificationListener; import javax.management.ObjectName; import org.dcm4che.net.AcceptorPolicy; import org.dcm4che.net.AssociationFactory; import org.dcm4che.net.DcmServiceRegistry; import org.dcm4che.net.UserIdentityNegotiator; import org.dcm4che.server.DcmHandler; import org.dcm4che.server.Server; import org.dcm4che.server.ServerFactory; import org.dcm4che.util.DcmProtocol; import org.dcm4chex.archive.mbean.DicomSecurityDelegate; import org.dcm4chex.archive.mbean.TLSConfigDelegate; import org.dcm4chex.archive.notif.CallingAetChanged; import org.jboss.system.ServiceMBeanSupport; import org.jboss.system.server.ServerImplMBean; /** * @author [email protected] * @version $Revision: 14117 $ * @since 02.08.2003 */ public class DcmServerService extends ServiceMBeanSupport implements NotificationListener { private ServerFactory sf = ServerFactory.getInstance(); private AssociationFactory af = AssociationFactory.getInstance(); private AcceptorPolicy policy = af.newAcceptorPolicy(); private DcmServiceRegistry services = af.newDcmServiceRegistry(); private DcmHandler handler = sf.newDcmHandler(policy, services); private Server dcmsrv = sf.newServer(handler); private DcmProtocol protocol = DcmProtocol.DICOM; private TLSConfigDelegate tlsConfig = new TLSConfigDelegate(this); private DicomSecurityDelegate dicomSecurity = new DicomSecurityDelegate(this); public final ObjectName getTLSConfigName() { return tlsConfig.getTLSConfigName(); } public final void setTLSConfigName(ObjectName tlsConfigName) { tlsConfig.setTLSConfigName(tlsConfigName); } public final ObjectName getDicomSecurityServiceName() { return dicomSecurity.getDicomSecurityServiceName(); } public final void setDicomSecurityServiceName(ObjectName serviceName) { this.dicomSecurity.setDicomSecurityServiceName(serviceName); } public int getPort() { return dcmsrv.getPort(); } public void setPort(int port) { dcmsrv.setPort(port); } public String getLocalAddress() { return dcmsrv.getLocalAddress(); } public void setLocalAddress(String localAddress) { dcmsrv.setLocalAddress(localAddress); } public String getProtocolName() { return protocol.toString(); } public void setProtocolName(String protocolName) { this.protocol = DcmProtocol.valueOf(protocolName); } public DcmHandler dcmHandler() { return handler; } public int getRqTimeout() { return handler.getRqTimeout(); } public void setRqTimeout(int newRqTimeout) { handler.setRqTimeout(newRqTimeout); } public int getDimseTimeout() { return handler.getDimseTimeout(); } public void setDimseTimeout(int newDimseTimeout) { handler.setDimseTimeout(newDimseTimeout); } public int getSoCloseDelay() { return handler.getSoCloseDelay(); } public void setSoCloseDelay(int newSoCloseDelay) { handler.setSoCloseDelay(newSoCloseDelay); } public boolean isPackPDVs() { return handler.isPackPDVs(); } public void setPackPDVs(boolean newPackPDVs) { handler.setPackPDVs(newPackPDVs); } public final int getReceiveBufferSize() { return dcmsrv.getReceiveBufferSize(); } public final void setReceiveBufferSize(int size) { dcmsrv.setReceiveBufferSize(size); } public final int getSendBufferSize() { return dcmsrv.getSendBufferSize(); } public final void setSendBufferSize(int size) { dcmsrv.setSendBufferSize(size); } public final boolean isTcpNoDelay() { return dcmsrv.isTcpNoDelay(); } public final void setTcpNoDelay(boolean on) { dcmsrv.setTcpNoDelay(on); } public int getMaxClients() { return dcmsrv.getMaxClients(); } public void setMaxClients(int newMaxClients) { dcmsrv.setMaxClients(newMaxClients); } public int getNumClients() { return dcmsrv.getNumClients(); } public int getMaxIdleThreads() { return dcmsrv.getMaxIdleThreads(); } public int getNumIdleThreads() { return dcmsrv.getNumIdleThreads(); } public void setMaxIdleThreads(int max) { dcmsrv.setMaxIdleThreads(max); } public String[] getCallingAETs() { return policy.getCallingAETs(); } public void setCallingAETs(String[] newCallingAETs) { policy.setCallingAETs(newCallingAETs); } public String[] getCalledAETs() { return policy.getCalledAETs(); } public void setCalledAETs(String[] newCalledAETs) { policy.setCalledAETs(newCalledAETs); } public int getMaxPDULength() { return policy.getMaxPDULength(); } public void setMaxPDULength(int newMaxPDULength) { policy.setMaxPDULength(newMaxPDULength); } public void notifyCallingAETchange(String[] affectedCalledAETs, String[] newCallingAETs) { long eventID = this.getNextNotificationSequenceNumber(); Notification notif = new Notification(CallingAetChanged.class.getName(), this, eventID ); notif.setUserData( new CallingAetChanged(affectedCalledAETs, newCallingAETs) ); log.debug("send callingAET changed notif:"+notif); this.sendNotification( notif ); } public UserIdentityNegotiator userIdentityNegotiator() { return dicomSecurity.userIdentityNegotiator(); } protected void startService() throws Exception { dcmsrv.addHandshakeFailedListener(tlsConfig.handshakeFailedListener()); dcmsrv.addHandshakeCompletedListener(tlsConfig.handshakeCompletedListener()); dcmsrv.setServerSocketFactory(tlsConfig.serverSocketFactory(protocol .getCipherSuites())); server.addNotificationListener(ServerImplMBean.OBJECT_NAME, this, null, null); } public void handleNotification(Notification msg, Object arg1) { if (msg.getType().equals(org.jboss.system.server.Server.START_NOTIFICATION_TYPE)) { try { dcmsrv.start(); } catch (IOException x) { log.error("Start DICOM Server failed!", x); } } } protected void stopService() throws Exception { dcmsrv.stop(); server.removeNotificationListener(ServerImplMBean.OBJECT_NAME, this); } }
medicayun/medicayundicom
dcm4jboss-all/tags/DCM4CHEE_2_17_0/dcm4jboss-sar/src/java/org/dcm4chex/archive/dcm/DcmServerService.java
Java
apache-2.0
8,550
/* * 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.camel.component.olingo2; import java.io.InputStream; import java.util.Map; import javax.ws.rs.HttpMethod; import okhttp3.HttpUrl; import okhttp3.mockwebserver.Dispatcher; import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.MockWebServer; import okhttp3.mockwebserver.RecordedRequest; import okio.Buffer; import org.apache.camel.component.olingo2.api.Olingo2App; import org.apache.camel.component.olingo2.api.impl.Olingo2AppImpl; import org.apache.olingo.odata2.api.commons.HttpStatusCodes; import org.apache.olingo.odata2.api.commons.ODataHttpHeaders; import org.apache.olingo.odata2.api.edm.Edm; import org.apache.olingo.odata2.api.edm.EdmEntityContainer; import org.apache.olingo.odata2.api.edm.EdmEntitySet; import org.apache.olingo.odata2.api.edm.EdmEntityType; import org.apache.olingo.odata2.api.edm.EdmProperty; import org.apache.olingo.odata2.api.edm.EdmServiceMetadata; import org.apache.olingo.odata2.api.ep.EntityProvider; import org.apache.olingo.odata2.api.ep.EntityProviderWriteProperties; import org.apache.olingo.odata2.api.processor.ODataResponse; import org.eclipse.jetty.http.HttpHeader; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.fail; /** * Tests support for concurrency properties which generate and require reading eTags before patch, update and delete * operations. Since the embedded olingo2 odata service does not contain any concurrency properties, it is necessary to * mock up a new server. Uses a cutdown version of the reference odata service and adds in extra concurrency properties. * Service's dispatcher only tests the correct calls are made and whether the eTags are correctly added as headers to * the requisite requests. */ public class Olingo2AppAPIETagEnabledTest extends AbstractOlingo2AppAPITestSupport { private static MockWebServer server; private static Olingo2App olingoApp; private static Edm edm; private static EdmEntitySet manufacturersSet; @BeforeAll public static void scaffold() throws Exception { initEdm(); initServer(); } @AfterAll public static void unscaffold() throws Exception { if (olingoApp != null) { olingoApp.close(); } if (server != null) { server.shutdown(); } } private static void initEdm() throws Exception { InputStream edmXml = Olingo2AppAPIETagEnabledTest.class.getResourceAsStream("etag-enabled-service.xml"); edm = EntityProvider.readMetadata(edmXml, true); assertNotNull(edm); EdmEntityContainer entityContainer = edm.getDefaultEntityContainer(); assertNotNull(entityContainer); manufacturersSet = entityContainer.getEntitySet(MANUFACTURERS); assertNotNull(manufacturersSet); EdmEntityType entityType = manufacturersSet.getEntityType(); assertNotNull(entityType); // // Check we have enabled eTag properties // EdmProperty property = (EdmProperty) entityType.getProperty("Id"); assertNotNull(property.getFacets()); } private static void initServer() throws Exception { server = new MockWebServer(); // // Init dispatcher prior to start of server // server.setDispatcher(new Dispatcher() { @SuppressWarnings("resource") @Override public MockResponse dispatch(RecordedRequest recordedRequest) throws InterruptedException { MockResponse mockResponse = new MockResponse(); switch (recordedRequest.getMethod()) { case HttpMethod.GET: try { if (recordedRequest.getPath().endsWith("/" + TEST_CREATE_MANUFACTURER)) { ODataResponse odataResponse = EntityProvider.writeEntry(TEST_FORMAT.getMimeType(), manufacturersSet, getEntityData(), EntityProviderWriteProperties.serviceRoot(getServiceUrl().uri()).build()); InputStream entityStream = odataResponse.getEntityAsStream(); mockResponse.setResponseCode(HttpStatusCodes.OK.getStatusCode()); mockResponse.setBody(new Buffer().readFrom(entityStream)); return mockResponse; } else if (recordedRequest.getPath().endsWith("/" + Olingo2AppImpl.METADATA)) { EdmServiceMetadata serviceMetadata = edm.getServiceMetadata(); return mockResponse.setResponseCode(HttpStatusCodes.OK.getStatusCode()) .addHeader(ODataHttpHeaders.DATASERVICEVERSION, serviceMetadata.getDataServiceVersion()) .setBody(new Buffer().readFrom(serviceMetadata.getMetadata())); } } catch (Exception ex) { throw new RuntimeException(ex); } break; case HttpMethod.PATCH: case HttpMethod.PUT: case HttpMethod.POST: case HttpMethod.DELETE: // // Objective of the test: // The Read has to have been called by // Olingo2AppImpl.argumentWithETag // which should then populate the IF-MATCH header with the // eTag value. // Verify the eTag value is present. // assertNotNull(recordedRequest.getHeader(HttpHeader.IF_MATCH.asString())); return mockResponse.setResponseCode(HttpStatusCodes.NO_CONTENT.getStatusCode()); default: break; } mockResponse.setResponseCode(HttpStatusCodes.NOT_FOUND.getStatusCode()).setBody("{ status: \"Not Found\"}"); return mockResponse; } }); server.start(); // // have to init olingoApp after start of server // since getBaseUrl() will call server start // olingoApp = new Olingo2AppImpl(getServiceUrl() + "/"); olingoApp.setContentType(TEST_FORMAT_STRING); } private static HttpUrl getServiceUrl() { if (server == null) { fail("Test programming failure. Server not initialised"); } return server.url(SERVICE_NAME); } @Test public void testPatchEntityWithETag() throws Exception { TestOlingo2ResponseHandler<HttpStatusCodes> statusHandler = new TestOlingo2ResponseHandler<>(); Map<String, Object> data = getEntityData(); @SuppressWarnings("unchecked") Map<String, Object> address = (Map<String, Object>) data.get(ADDRESS); data.put("Name", "MyCarManufacturer Renamed"); address.put("Street", "Main Street"); // // Call patch // olingoApp.patch(edm, TEST_CREATE_MANUFACTURER, null, data, statusHandler); HttpStatusCodes statusCode = statusHandler.await(); assertEquals(HttpStatusCodes.NO_CONTENT, statusCode); } @Test public void testUpdateEntityWithETag() throws Exception { TestOlingo2ResponseHandler<HttpStatusCodes> statusHandler = new TestOlingo2ResponseHandler<>(); Map<String, Object> data = getEntityData(); @SuppressWarnings("unchecked") Map<String, Object> address = (Map<String, Object>) data.get(ADDRESS); data.put("Name", "MyCarManufacturer Renamed"); address.put("Street", "Main Street"); // // Call update // olingoApp.update(edm, TEST_CREATE_MANUFACTURER, null, data, statusHandler); HttpStatusCodes statusCode = statusHandler.await(); assertEquals(HttpStatusCodes.NO_CONTENT, statusCode); } @Test public void testDeleteEntityWithETag() throws Exception { TestOlingo2ResponseHandler<HttpStatusCodes> statusHandler = new TestOlingo2ResponseHandler<>(); Map<String, Object> data = getEntityData(); @SuppressWarnings("unchecked") Map<String, Object> address = (Map<String, Object>) data.get(ADDRESS); data.put("Name", "MyCarManufacturer Renamed"); address.put("Street", "Main Street"); // // Call delete // olingoApp.delete(TEST_CREATE_MANUFACTURER, null, statusHandler); HttpStatusCodes statusCode = statusHandler.await(); assertEquals(HttpStatusCodes.NO_CONTENT, statusCode); } }
nikhilvibhav/camel
components/camel-olingo2/camel-olingo2-component/src/test/java/org/apache/camel/component/olingo2/Olingo2AppAPIETagEnabledTest.java
Java
apache-2.0
9,833
/* * MiraWeightVector.h * kbmira - k-best Batch MIRA * * A self-averaging weight-vector. Good for * perceptron learning as well. * */ #ifndef MERT_MIRA_WEIGHT_VECTOR_H #define MERT_MIRA_WEIGHT_VECTOR_H #include <vector> #include <iostream> #include "MiraFeatureVector.h" namespace MosesTuning { class AvgWeightVector; class MiraWeightVector { public: /** * Constructor, initializes to the zero vector */ MiraWeightVector(); /** * Constructor with provided initial vector * \param init Initial feature values */ MiraWeightVector(const std::vector<ValType>& init); /** * Update a the model * \param fv Feature vector to be added to the weights * \param tau FV will be scaled by this value before update */ void update(const MiraFeatureVector& fv, float tau); /** * Perform an empty update (affects averaging) */ void tick(); /** * Score a feature vector according to the model * \param fv Feature vector to be scored */ ValType score(const MiraFeatureVector& fv) const; /** * Squared norm of the weight vector */ ValType sqrNorm() const; /** * Return an averaged view of this weight vector */ AvgWeightVector avg(); /** * Convert to sparse vector, interpreting all features as sparse. Only used by hgmira. **/ void ToSparse(SparseVector* sparse, size_t denseSize) const; friend class AvgWeightVector; friend std::ostream& operator<<(std::ostream& o, const MiraWeightVector& e); private: /** * Updates a weight and lazily updates its total */ void update(std::size_t index, ValType delta); /** * Make sure everyone's total is up-to-date */ void fixTotals(); /** * Helper to handle out-of-range weights */ ValType weight(std::size_t index) const; std::vector<ValType> m_weights; std::vector<ValType> m_totals; std::vector<std::size_t> m_lastUpdated; std::size_t m_numUpdates; }; /** * Averaged view of a weight vector */ class AvgWeightVector { public: AvgWeightVector(const MiraWeightVector& wv); ValType score(const MiraFeatureVector& fv) const; ValType weight(std::size_t index) const; std::size_t size() const; void ToSparse(SparseVector* sparse, size_t num_dense) const; private: const MiraWeightVector& m_wv; }; // --Emacs trickery-- // Local Variables: // mode:c++ // c-basic-offset:2 // End: } #endif // MERT_WEIGHT_VECTOR_H
letconex/MMT
src/decoder-phrasebased/src/native/decoder/mert/MiraWeightVector.h
C
apache-2.0
2,411
/* Generated By:JavaCC: Do not edit this line. Token.java Version 5.0 */ /* JavaCCOptions:TOKEN_EXTENDS=,KEEP_LINE_COL=null,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */ package org.apache.camel.component.sql.stored.template.generated; /** * Describes the input token stream. */ public class Token implements java.io.Serializable { /** * The version identifier for this Serializable class. Increment only if the <i>serialized</i> form of the class * changes. */ private static final long serialVersionUID = 1L; /** * An integer that describes the kind of this token. This numbering system is determined by JavaCCParser, and a * table of these numbers is stored in the file ...Constants.java. */ public int kind; /** The line number of the first character of this Token. */ public int beginLine; /** The column number of the first character of this Token. */ public int beginColumn; /** The line number of the last character of this Token. */ public int endLine; /** The column number of the last character of this Token. */ public int endColumn; /** * The string image of the token. */ public String image; /** * A reference to the next regular (non-special) token from the input stream. If this is the last token from the * input stream, or if the token manager has not read tokens beyond this one, this field is set to null. This is * true only if this token is also a regular token. Otherwise, see below for a description of the contents of this * field. */ public Token next; /** * This field is used to access special tokens that occur prior to this token, but after the immediately preceding * regular (non-special) token. If there are no such special tokens, this field is set to null. When there are more * than one such special token, this field refers to the last of these special tokens, which in turn refers to the * next previous special token through its specialToken field, and so on until the first special token (whose * specialToken field is null). The next fields of special tokens refer to other special tokens that immediately * follow it (without an intervening regular token). If there is no such token, this field is null. */ public Token specialToken; /** * An optional attribute value of the Token. Tokens which are not used as syntactic sugar will often contain * meaningful values that will be used later on by the compiler or interpreter. This attribute value is often * different from the image. Any subclass of Token that actually wants to return a non-null value can override this * method as appropriate. */ public Object getValue() { return null; } /** * No-argument constructor */ public Token() { } /** * Constructs a new token for the specified Image. */ public Token(int kind) { this(kind, null); } /** * Constructs a new token for the specified Image and Kind. */ public Token(int kind, String image) { this.kind = kind; this.image = image; } /** * Returns the image. */ public String toString() { return image; } /** * Returns a new Token object, by default. However, if you want, you can create and return subclass objects based on * the value of ofKind. Simply add the cases to the switch for all those special cases. For example, if you have a * subclass of Token called IDToken that you want to create if ofKind is ID, simply add something like : * * case MyParserConstants.ID : return new IDToken(ofKind, image); * * to the following switch statement. Then you can cast matchedToken variable to the appropriate type and use sit in * your lexical actions. */ public static Token newToken(int ofKind, String image) { switch (ofKind) { default: return new Token(ofKind, image); } } public static Token newToken(int ofKind) { return newToken(ofKind, null); } } /* JavaCC - OriginalChecksum=7e8baa74d8a01b01496421112dcea294 (do not edit this line) */
nikhilvibhav/camel
components/camel-sql/src/main/java/org/apache/camel/component/sql/stored/template/generated/Token.java
Java
apache-2.0
4,257
/* include/graphics/SkRefCnt.h ** ** Copyright 2006, 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. */ #ifndef SkRefCnt_DEFINED #define SkRefCnt_DEFINED #include "SkNoncopyable.h" /** \class SkRefCnt SkRefCnt is the base class for objects that may be shared by multiple objects. When a new owner wants a reference, it calls ref(). When an owner wants to release its reference, it calls unref(). When the shared object's reference count goes to zero as the result of an unref() call, its (virtual) destructor is called. It is an error for the destructor to be called explicitly (or via the object going out of scope on the stack or calling delete) if getRefCnt() > 1. */ class SkRefCnt : SkNoncopyable { public: /** Default construct, initializing the reference count to 1. */ SkRefCnt() : fRefCnt(1) {} /** Destruct, asserting that the reference count is 1. */ virtual ~SkRefCnt() { SkASSERT(fRefCnt == 1); } /** Return the reference count. */ int getRefCnt() const { return fRefCnt; } /** Increment the reference count. Must be balanced by a call to unref(). */ void ref() const { SkASSERT(fRefCnt > 0); ++fRefCnt; } /** Decrement the reference count. If the reference count is 1 before the decrement, then call delete on the object. Note that if this is the case, then the object needs to have been allocated via new, and not on the stack. */ void unref() const { SkASSERT(fRefCnt > 0); if (fRefCnt == 1) delete this; else --fRefCnt; } /** Helper version of ref(), that first checks to see if this is not nil. If this is nil, then do nothing. */ void safeRef() const { if (this) this->ref(); } /** Helper version of unref(), that first checks to see if this is not nil. If this is nil, then do nothing. */ void safeUnref() const { if (this) this->unref(); } private: mutable int fRefCnt; }; /** \class SkAutoUnref SkAutoUnref is a stack-helper class that will automatically call unref() on the object it points to when the SkAutoUnref object goes out of scope. */ class SkAutoUnref : SkNoncopyable { public: SkAutoUnref(SkRefCnt* obj) : fObj(obj) {} ~SkAutoUnref(); SkRefCnt* get() const { return fObj; } bool ref(); bool unref(); SkRefCnt* detach(); private: SkRefCnt* fObj; }; /** Helper macro to safely assign one SkRefCnt* to another, checking for nil in on each side of the assignment, and ensuring that ref() is called before unref(), in case the two pointers point to the same object. */ #define SkRefCnt_SafeAssign(dst, src) \ do { \ if (src) src->ref(); \ if (dst) dst->unref(); \ dst = src; \ } while (0) #endif
tst-ppenev/earthenterprise
earth_enterprise/src/third_party/sgl/v0_8_6/include/SkRefCnt.h
C
apache-2.0
3,440
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ package org.elasticsearch.xpack.ccr.action; import org.elasticsearch.cluster.ClusterName; import org.elasticsearch.cluster.ClusterState; import org.elasticsearch.cluster.metadata.MetaData; import org.elasticsearch.common.unit.ByteSizeUnit; import org.elasticsearch.common.unit.ByteSizeValue; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.index.shard.ShardId; import org.elasticsearch.persistent.PersistentTasksCustomMetaData; import org.elasticsearch.test.ESTestCase; import java.util.Collections; import java.util.Set; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; public class TransportFollowStatsActionTests extends ESTestCase { public void testFindFollowerIndicesFromShardFollowTasks() { PersistentTasksCustomMetaData.Builder persistentTasks = PersistentTasksCustomMetaData.builder() .addTask("1", ShardFollowTask.NAME, createShardFollowTask("abc"), null) .addTask("2", ShardFollowTask.NAME, createShardFollowTask("def"), null); ClusterState clusterState = ClusterState.builder(new ClusterName("_cluster")) .metaData(MetaData.builder().putCustom(PersistentTasksCustomMetaData.TYPE, persistentTasks.build()).build()) .build(); Set<String> result = TransportFollowStatsAction.findFollowerIndicesFromShardFollowTasks(clusterState, null); assertThat(result.size(), equalTo(2)); assertThat(result.contains("abc"), is(true)); assertThat(result.contains("def"), is(true)); result = TransportFollowStatsAction.findFollowerIndicesFromShardFollowTasks(clusterState, new String[]{"def"}); assertThat(result.size(), equalTo(1)); assertThat(result.contains("def"), is(true)); result = TransportFollowStatsAction.findFollowerIndicesFromShardFollowTasks(clusterState, new String[]{"ghi"}); assertThat(result.size(), equalTo(0)); } static ShardFollowTask createShardFollowTask(String followerIndex) { return new ShardFollowTask( null, new ShardId(followerIndex, "", 0), new ShardId("leader_index", "", 0), 1024, 1024, 1, 1, TransportResumeFollowAction.DEFAULT_MAX_READ_REQUEST_SIZE, TransportResumeFollowAction.DEFAULT_MAX_READ_REQUEST_SIZE, 10240, new ByteSizeValue(512, ByteSizeUnit.MB), TimeValue.timeValueMillis(10), TimeValue.timeValueMillis(10), Collections.emptyMap() ); } }
coding0011/elasticsearch
x-pack/plugin/ccr/src/test/java/org/elasticsearch/xpack/ccr/action/TransportFollowStatsActionTests.java
Java
apache-2.0
2,824
# Distributed under the OSI-approved BSD 3-Clause License. See accompanying # file Copyright.txt or https://cmake.org/licensing for details. # This file sets the basic flags for the C++ language in CMake. # It also loads the available platform file for the system-compiler # if it exists. # It also loads a system - compiler - processor (or target hardware) # specific file, which is mainly useful for crosscompiling and embedded systems. include(CMakeLanguageInformation) # some compilers use different extensions (e.g. sdcc uses .rel) # so set the extension here first so it can be overridden by the compiler specific file if(UNIX) set(CMAKE_CXX_OUTPUT_EXTENSION .o) else() set(CMAKE_CXX_OUTPUT_EXTENSION .obj) endif() set(_INCLUDED_FILE 0) # Load compiler-specific information. if(CMAKE_CXX_COMPILER_ID) include(Compiler/${CMAKE_CXX_COMPILER_ID}-CXX OPTIONAL) endif() set(CMAKE_BASE_NAME) get_filename_component(CMAKE_BASE_NAME "${CMAKE_CXX_COMPILER}" NAME_WE) # since the gnu compiler has several names force g++ if(CMAKE_COMPILER_IS_GNUCXX) set(CMAKE_BASE_NAME g++) endif() # load a hardware specific file, mostly useful for embedded compilers if(CMAKE_SYSTEM_PROCESSOR) if(CMAKE_CXX_COMPILER_ID) include(Platform/${CMAKE_SYSTEM_NAME}-${CMAKE_CXX_COMPILER_ID}-CXX-${CMAKE_SYSTEM_PROCESSOR} OPTIONAL RESULT_VARIABLE _INCLUDED_FILE) endif() if (NOT _INCLUDED_FILE) include(Platform/${CMAKE_SYSTEM_NAME}-${CMAKE_BASE_NAME}-${CMAKE_SYSTEM_PROCESSOR} OPTIONAL) endif () endif() # load the system- and compiler specific files if(CMAKE_CXX_COMPILER_ID) include(Platform/${CMAKE_SYSTEM_NAME}-${CMAKE_CXX_COMPILER_ID}-CXX OPTIONAL RESULT_VARIABLE _INCLUDED_FILE) endif() if (NOT _INCLUDED_FILE) include(Platform/${CMAKE_SYSTEM_NAME}-${CMAKE_BASE_NAME} OPTIONAL RESULT_VARIABLE _INCLUDED_FILE) endif () # load any compiler-wrapper specific information if (CMAKE_CXX_COMPILER_WRAPPER) __cmake_include_compiler_wrapper(CXX) endif () # We specify the compiler information in the system file for some # platforms, but this language may not have been enabled when the file # was first included. Include it again to get the language info. # Remove this when all compiler info is removed from system files. if (NOT _INCLUDED_FILE) include(Platform/${CMAKE_SYSTEM_NAME} OPTIONAL) endif () if(CMAKE_CXX_SIZEOF_DATA_PTR) foreach(f ${CMAKE_CXX_ABI_FILES}) include(${f}) endforeach() unset(CMAKE_CXX_ABI_FILES) endif() # This should be included before the _INIT variables are # used to initialize the cache. Since the rule variables # have if blocks on them, users can still define them here. # But, it should still be after the platform file so changes can # be made to those values. if(CMAKE_USER_MAKE_RULES_OVERRIDE) # Save the full path of the file so try_compile can use it. include(${CMAKE_USER_MAKE_RULES_OVERRIDE} RESULT_VARIABLE _override) set(CMAKE_USER_MAKE_RULES_OVERRIDE "${_override}") endif() if(CMAKE_USER_MAKE_RULES_OVERRIDE_CXX) # Save the full path of the file so try_compile can use it. include(${CMAKE_USER_MAKE_RULES_OVERRIDE_CXX} RESULT_VARIABLE _override) set(CMAKE_USER_MAKE_RULES_OVERRIDE_CXX "${_override}") endif() # Create a set of shared library variable specific to C++ # For 90% of the systems, these are the same flags as the C versions # so if these are not set just copy the flags from the c version if(NOT CMAKE_SHARED_LIBRARY_CREATE_CXX_FLAGS) set(CMAKE_SHARED_LIBRARY_CREATE_CXX_FLAGS ${CMAKE_SHARED_LIBRARY_CREATE_C_FLAGS}) endif() if(NOT CMAKE_CXX_COMPILE_OPTIONS_PIC) set(CMAKE_CXX_COMPILE_OPTIONS_PIC ${CMAKE_C_COMPILE_OPTIONS_PIC}) endif() if(NOT CMAKE_CXX_COMPILE_OPTIONS_PIE) set(CMAKE_CXX_COMPILE_OPTIONS_PIE ${CMAKE_C_COMPILE_OPTIONS_PIE}) endif() if(NOT CMAKE_CXX_COMPILE_OPTIONS_DLL) set(CMAKE_CXX_COMPILE_OPTIONS_DLL ${CMAKE_C_COMPILE_OPTIONS_DLL}) endif() if(NOT CMAKE_SHARED_LIBRARY_CXX_FLAGS) set(CMAKE_SHARED_LIBRARY_CXX_FLAGS ${CMAKE_SHARED_LIBRARY_C_FLAGS}) endif() if(NOT DEFINED CMAKE_SHARED_LIBRARY_LINK_CXX_FLAGS) set(CMAKE_SHARED_LIBRARY_LINK_CXX_FLAGS ${CMAKE_SHARED_LIBRARY_LINK_C_FLAGS}) endif() if(NOT CMAKE_SHARED_LIBRARY_RUNTIME_CXX_FLAG) set(CMAKE_SHARED_LIBRARY_RUNTIME_CXX_FLAG ${CMAKE_SHARED_LIBRARY_RUNTIME_C_FLAG}) endif() if(NOT CMAKE_SHARED_LIBRARY_RUNTIME_CXX_FLAG_SEP) set(CMAKE_SHARED_LIBRARY_RUNTIME_CXX_FLAG_SEP ${CMAKE_SHARED_LIBRARY_RUNTIME_C_FLAG_SEP}) endif() if(NOT CMAKE_SHARED_LIBRARY_RPATH_LINK_CXX_FLAG) set(CMAKE_SHARED_LIBRARY_RPATH_LINK_CXX_FLAG ${CMAKE_SHARED_LIBRARY_RPATH_LINK_C_FLAG}) endif() if(NOT DEFINED CMAKE_EXE_EXPORTS_CXX_FLAG) set(CMAKE_EXE_EXPORTS_CXX_FLAG ${CMAKE_EXE_EXPORTS_C_FLAG}) endif() if(NOT DEFINED CMAKE_SHARED_LIBRARY_SONAME_CXX_FLAG) set(CMAKE_SHARED_LIBRARY_SONAME_CXX_FLAG ${CMAKE_SHARED_LIBRARY_SONAME_C_FLAG}) endif() if(NOT CMAKE_EXECUTABLE_RUNTIME_CXX_FLAG) set(CMAKE_EXECUTABLE_RUNTIME_CXX_FLAG ${CMAKE_SHARED_LIBRARY_RUNTIME_CXX_FLAG}) endif() if(NOT CMAKE_EXECUTABLE_RUNTIME_CXX_FLAG_SEP) set(CMAKE_EXECUTABLE_RUNTIME_CXX_FLAG_SEP ${CMAKE_SHARED_LIBRARY_RUNTIME_CXX_FLAG_SEP}) endif() if(NOT CMAKE_EXECUTABLE_RPATH_LINK_CXX_FLAG) set(CMAKE_EXECUTABLE_RPATH_LINK_CXX_FLAG ${CMAKE_SHARED_LIBRARY_RPATH_LINK_CXX_FLAG}) endif() if(NOT DEFINED CMAKE_SHARED_LIBRARY_LINK_CXX_WITH_RUNTIME_PATH) set(CMAKE_SHARED_LIBRARY_LINK_CXX_WITH_RUNTIME_PATH ${CMAKE_SHARED_LIBRARY_LINK_C_WITH_RUNTIME_PATH}) endif() if(NOT CMAKE_INCLUDE_FLAG_CXX) set(CMAKE_INCLUDE_FLAG_CXX ${CMAKE_INCLUDE_FLAG_C}) endif() if(NOT CMAKE_INCLUDE_FLAG_SEP_CXX) set(CMAKE_INCLUDE_FLAG_SEP_CXX ${CMAKE_INCLUDE_FLAG_SEP_C}) endif() # for most systems a module is the same as a shared library # so unless the variable CMAKE_MODULE_EXISTS is set just # copy the values from the LIBRARY variables if(NOT CMAKE_MODULE_EXISTS) set(CMAKE_SHARED_MODULE_CXX_FLAGS ${CMAKE_SHARED_LIBRARY_CXX_FLAGS}) set(CMAKE_SHARED_MODULE_CREATE_CXX_FLAGS ${CMAKE_SHARED_LIBRARY_CREATE_CXX_FLAGS}) endif() # repeat for modules if(NOT CMAKE_SHARED_MODULE_CREATE_CXX_FLAGS) set(CMAKE_SHARED_MODULE_CREATE_CXX_FLAGS ${CMAKE_SHARED_MODULE_CREATE_C_FLAGS}) endif() if(NOT CMAKE_SHARED_MODULE_CXX_FLAGS) set(CMAKE_SHARED_MODULE_CXX_FLAGS ${CMAKE_SHARED_MODULE_C_FLAGS}) endif() # Initialize CXX link type selection flags from C versions. foreach(type SHARED_LIBRARY SHARED_MODULE EXE) if(NOT CMAKE_${type}_LINK_STATIC_CXX_FLAGS) set(CMAKE_${type}_LINK_STATIC_CXX_FLAGS ${CMAKE_${type}_LINK_STATIC_C_FLAGS}) endif() if(NOT CMAKE_${type}_LINK_DYNAMIC_CXX_FLAGS) set(CMAKE_${type}_LINK_DYNAMIC_CXX_FLAGS ${CMAKE_${type}_LINK_DYNAMIC_C_FLAGS}) endif() endforeach() # add the flags to the cache based # on the initial values computed in the platform/*.cmake files # use _INIT variables so that this only happens the first time # and you can set these flags in the cmake cache set(CMAKE_CXX_FLAGS_INIT "$ENV{CXXFLAGS} ${CMAKE_CXX_FLAGS_INIT}") foreach(c "" _DEBUG _RELEASE _MINSIZEREL _RELWITHDEBINFO) string(STRIP "${CMAKE_CXX_FLAGS${c}_INIT}" CMAKE_CXX_FLAGS${c}_INIT) endforeach() set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS_INIT}" CACHE STRING "Flags used by the compiler during all build types.") if(NOT CMAKE_NOT_USING_CONFIG_FLAGS) set (CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG_INIT}" CACHE STRING "Flags used by the compiler during debug builds.") set (CMAKE_CXX_FLAGS_MINSIZEREL "${CMAKE_CXX_FLAGS_MINSIZEREL_INIT}" CACHE STRING "Flags used by the compiler during release builds for minimum size.") set (CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE_INIT}" CACHE STRING "Flags used by the compiler during release builds.") set (CMAKE_CXX_FLAGS_RELWITHDEBINFO "${CMAKE_CXX_FLAGS_RELWITHDEBINFO_INIT}" CACHE STRING "Flags used by the compiler during release builds with debug info.") endif() if(CMAKE_CXX_STANDARD_LIBRARIES_INIT) set(CMAKE_CXX_STANDARD_LIBRARIES "${CMAKE_CXX_STANDARD_LIBRARIES_INIT}" CACHE STRING "Libraries linked by default with all C++ applications.") mark_as_advanced(CMAKE_CXX_STANDARD_LIBRARIES) endif() include(CMakeCommonLanguageInclude) # now define the following rules: # CMAKE_CXX_CREATE_SHARED_LIBRARY # CMAKE_CXX_CREATE_SHARED_MODULE # CMAKE_CXX_COMPILE_OBJECT # CMAKE_CXX_LINK_EXECUTABLE # variables supplied by the generator at use time # <TARGET> # <TARGET_BASE> the target without the suffix # <OBJECTS> # <OBJECT> # <LINK_LIBRARIES> # <FLAGS> # <LINK_FLAGS> # CXX compiler information # <CMAKE_CXX_COMPILER> # <CMAKE_SHARED_LIBRARY_CREATE_CXX_FLAGS> # <CMAKE_CXX_SHARED_MODULE_CREATE_FLAGS> # <CMAKE_CXX_LINK_FLAGS> # Static library tools # <CMAKE_AR> # <CMAKE_RANLIB> # create a shared C++ library if(NOT CMAKE_CXX_CREATE_SHARED_LIBRARY) set(CMAKE_CXX_CREATE_SHARED_LIBRARY "<CMAKE_CXX_COMPILER> <CMAKE_SHARED_LIBRARY_CXX_FLAGS> <LANGUAGE_COMPILE_FLAGS> <LINK_FLAGS> <CMAKE_SHARED_LIBRARY_CREATE_CXX_FLAGS> <SONAME_FLAG><TARGET_SONAME> -o <TARGET> <OBJECTS> <LINK_LIBRARIES>") endif() # create a c++ shared module copy the shared library rule by default if(NOT CMAKE_CXX_CREATE_SHARED_MODULE) set(CMAKE_CXX_CREATE_SHARED_MODULE ${CMAKE_CXX_CREATE_SHARED_LIBRARY}) endif() # Create a static archive incrementally for large object file counts. # If CMAKE_CXX_CREATE_STATIC_LIBRARY is set it will override these. if(NOT DEFINED CMAKE_CXX_ARCHIVE_CREATE) set(CMAKE_CXX_ARCHIVE_CREATE "<CMAKE_AR> qc <TARGET> <LINK_FLAGS> <OBJECTS>") endif() if(NOT DEFINED CMAKE_CXX_ARCHIVE_APPEND) set(CMAKE_CXX_ARCHIVE_APPEND "<CMAKE_AR> q <TARGET> <LINK_FLAGS> <OBJECTS>") endif() if(NOT DEFINED CMAKE_CXX_ARCHIVE_FINISH) set(CMAKE_CXX_ARCHIVE_FINISH "<CMAKE_RANLIB> <TARGET>") endif() # compile a C++ file into an object file if(NOT CMAKE_CXX_COMPILE_OBJECT) set(CMAKE_CXX_COMPILE_OBJECT "<CMAKE_CXX_COMPILER> <DEFINES> <INCLUDES> <FLAGS> -o <OBJECT> -c <SOURCE>") endif() if(NOT CMAKE_CXX_LINK_EXECUTABLE) set(CMAKE_CXX_LINK_EXECUTABLE "<CMAKE_CXX_COMPILER> <FLAGS> <CMAKE_CXX_LINK_FLAGS> <LINK_FLAGS> <OBJECTS> -o <TARGET> <LINK_LIBRARIES>") endif() mark_as_advanced( CMAKE_VERBOSE_MAKEFILE CMAKE_CXX_FLAGS CMAKE_CXX_FLAGS_RELEASE CMAKE_CXX_FLAGS_RELWITHDEBINFO CMAKE_CXX_FLAGS_MINSIZEREL CMAKE_CXX_FLAGS_DEBUG) set(CMAKE_CXX_INFORMATION_LOADED 1)
jomof/cmake-server-java-bindings
prebuilts/cmake-3.7.1-Windows-x86_64/share/cmake-3.7/Modules/CMakeCXXInformation.cmake
CMake
apache-2.0
10,290
/* * 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.hadoop.hive.metastore.model; /** * MTxnWriteNotificationLog * DN table for ACID write events. */ public class MTxnWriteNotificationLog { private long txnId; private long writeId; private int eventTime; private String database; private String table; private String partition; private String tableObject; private String partObject; private String files; public MTxnWriteNotificationLog() { } public MTxnWriteNotificationLog(long txnId, long writeId, int eventTime, String database, String table, String partition, String tableObject, String partObject, String files) { this.txnId = txnId; this.writeId = writeId; this.eventTime = eventTime; this.database = database; this.table = table; this.partition = partition; this.tableObject = tableObject; this.partObject = partObject; this.files = files; } public long getTxnId() { return txnId; } public void setTxnId(long txnId) { this.txnId = txnId; } public long getWriteId() { return writeId; } public void setWriteId(long writeId) { this.writeId = writeId; } public int getEventTime() { return eventTime; } public void setEventTime(int eventTime) { this.eventTime = eventTime; } public String getDatabase() { return database; } public void setDatabase(String database) { this.database = database; } public String getTable() { return table; } public void setTable(String table) { this.table = table; } public String getPartition() { return partition; } public void setPartition(String partition) { this.partition = partition; } public String getTableObject() { return tableObject; } public void setTableObject(String tableObject) { this.tableObject = tableObject; } public String getPartObject() { return partObject; } public void setPartObject(String partObject) { this.partObject = partObject; } public String getFiles() { return files; } public void setFiles(String files) { this.files = files; } }
vineetgarg02/hive
standalone-metastore/metastore-server/src/main/java/org/apache/hadoop/hive/metastore/model/MTxnWriteNotificationLog.java
Java
apache-2.0
2,934
/* * Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ #pragma once #include <aws/sns/SNS_EXPORTS.h> #include <aws/sns/SNSRequest.h> #include <aws/core/utils/memory/stl/AWSString.h> namespace Aws { namespace SNS { namespace Model { /* <p>Input for GetSubscriptionAttributes.</p> */ class AWS_SNS_API GetSubscriptionAttributesRequest : public SNSRequest { public: GetSubscriptionAttributesRequest(); Aws::String SerializePayload() const override; /* <p>The ARN of the subscription whose properties you want to get.</p> */ inline const Aws::String& GetSubscriptionArn() const{ return m_subscriptionArn; } /* <p>The ARN of the subscription whose properties you want to get.</p> */ inline void SetSubscriptionArn(const Aws::String& value) { m_subscriptionArnHasBeenSet = true; m_subscriptionArn = value; } /* <p>The ARN of the subscription whose properties you want to get.</p> */ inline void SetSubscriptionArn(Aws::String&& value) { m_subscriptionArnHasBeenSet = true; m_subscriptionArn = value; } /* <p>The ARN of the subscription whose properties you want to get.</p> */ inline void SetSubscriptionArn(const char* value) { m_subscriptionArnHasBeenSet = true; m_subscriptionArn.assign(value); } /* <p>The ARN of the subscription whose properties you want to get.</p> */ inline GetSubscriptionAttributesRequest& WithSubscriptionArn(const Aws::String& value) { SetSubscriptionArn(value); return *this;} /* <p>The ARN of the subscription whose properties you want to get.</p> */ inline GetSubscriptionAttributesRequest& WithSubscriptionArn(Aws::String&& value) { SetSubscriptionArn(value); return *this;} /* <p>The ARN of the subscription whose properties you want to get.</p> */ inline GetSubscriptionAttributesRequest& WithSubscriptionArn(const char* value) { SetSubscriptionArn(value); return *this;} private: Aws::String m_subscriptionArn; bool m_subscriptionArnHasBeenSet; }; } // namespace Model } // namespace SNS } // namespace Aws
zeliard/aws-sdk-cpp
windows-build/include/aws/sns/model/GetSubscriptionAttributesRequest.h
C
apache-2.0
2,618
/* * 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.camel.builder.component.dsl; import javax.annotation.Generated; import org.apache.camel.Component; import org.apache.camel.builder.component.AbstractComponentBuilder; import org.apache.camel.builder.component.ComponentBuilder; import org.apache.camel.component.jmx.JMXComponent; /** * Receive JMX notifications. * * Generated by camel-package-maven-plugin - do not edit this file! */ @Generated("org.apache.camel.maven.packaging.ComponentDslMojo") public interface JmxComponentBuilderFactory { /** * JMX (camel-jmx) * Receive JMX notifications. * * Category: monitoring * Since: 2.6 * Maven coordinates: org.apache.camel:camel-jmx * * @return the dsl builder */ static JmxComponentBuilder jmx() { return new JmxComponentBuilderImpl(); } /** * Builder for the JMX component. */ interface JmxComponentBuilder extends ComponentBuilder<JMXComponent> { /** * Allows for bridging the consumer to the Camel routing Error Handler, * which mean any exceptions occurred while the consumer is trying to * pickup incoming messages, or the likes, will now be processed as a * message and handled by the routing Error Handler. By default the * consumer will use the org.apache.camel.spi.ExceptionHandler to deal * with exceptions, that will be logged at WARN or ERROR level and * ignored. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: consumer * * @param bridgeErrorHandler the value to set * @return the dsl builder */ default JmxComponentBuilder bridgeErrorHandler( boolean bridgeErrorHandler) { doSetProperty("bridgeErrorHandler", bridgeErrorHandler); return this; } /** * Whether autowiring is enabled. This is used for automatic autowiring * options (the option must be marked as autowired) by looking up in the * registry to find if there is a single instance of matching type, * which then gets configured on the component. This can be used for * automatic configuring JDBC data sources, JMS connection factories, * AWS Clients, etc. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: true * Group: advanced * * @param autowiredEnabled the value to set * @return the dsl builder */ default JmxComponentBuilder autowiredEnabled(boolean autowiredEnabled) { doSetProperty("autowiredEnabled", autowiredEnabled); return this; } } class JmxComponentBuilderImpl extends AbstractComponentBuilder<JMXComponent> implements JmxComponentBuilder { @Override protected JMXComponent buildConcreteComponent() { return new JMXComponent(); } @Override protected boolean setPropertyOnComponent( Component component, String name, Object value) { switch (name) { case "bridgeErrorHandler": ((JMXComponent) component).setBridgeErrorHandler((boolean) value); return true; case "autowiredEnabled": ((JMXComponent) component).setAutowiredEnabled((boolean) value); return true; default: return false; } } } }
apache/camel
dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/JmxComponentBuilderFactory.java
Java
apache-2.0
4,389
/* Copyright 2017 The Kubernetes Authors. 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. */ // This file was automatically generated by informer-gen package v1beta1 import ( v1 "k8s.io/apimachinery/pkg/apis/meta/v1" runtime "k8s.io/apimachinery/pkg/runtime" watch "k8s.io/apimachinery/pkg/watch" cache "k8s.io/client-go/tools/cache" rbac_v1beta1 "k8s.io/kubernetes/pkg/apis/rbac/v1beta1" clientset "k8s.io/kubernetes/pkg/client/clientset_generated/clientset" internalinterfaces "k8s.io/kubernetes/pkg/client/informers/informers_generated/internalinterfaces" v1beta1 "k8s.io/kubernetes/pkg/client/listers/rbac/v1beta1" time "time" ) // RoleBindingInformer provides access to a shared informer and lister for // RoleBindings. type RoleBindingInformer interface { Informer() cache.SharedIndexInformer Lister() v1beta1.RoleBindingLister } type roleBindingInformer struct { factory internalinterfaces.SharedInformerFactory } func newRoleBindingInformer(client clientset.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { sharedIndexInformer := cache.NewSharedIndexInformer( &cache.ListWatch{ ListFunc: func(options v1.ListOptions) (runtime.Object, error) { return client.RbacV1beta1().RoleBindings(v1.NamespaceAll).List(options) }, WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { return client.RbacV1beta1().RoleBindings(v1.NamespaceAll).Watch(options) }, }, &rbac_v1beta1.RoleBinding{}, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, ) return sharedIndexInformer } func (f *roleBindingInformer) Informer() cache.SharedIndexInformer { return f.factory.VersionedInformerFor(&rbac_v1beta1.RoleBinding{}, newRoleBindingInformer) } func (f *roleBindingInformer) Lister() v1beta1.RoleBindingLister { return v1beta1.NewRoleBindingLister(f.Informer().GetIndexer()) }
ahakanbaba/kubernetes
pkg/client/informers/informers_generated/rbac/v1beta1/rolebinding.go
GO
apache-2.0
2,359
/* 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.flex.forks.batik.css.engine.value.css2; import org.apache.flex.forks.batik.css.engine.value.IdentifierManager; import org.apache.flex.forks.batik.css.engine.value.StringMap; import org.apache.flex.forks.batik.css.engine.value.Value; import org.apache.flex.forks.batik.css.engine.value.ValueConstants; import org.apache.flex.forks.batik.css.engine.value.ValueManager; import org.apache.flex.forks.batik.util.CSSConstants; import org.apache.flex.forks.batik.util.SVGTypes; /** * This class provides a manager for the 'unicode-bidi' property values. * * @author <a href="mailto:[email protected]">Stephane Hillion</a> * @version $Id: UnicodeBidiManager.java 478160 2006-11-22 13:35:06Z dvholten $ */ public class UnicodeBidiManager extends IdentifierManager { /** * The identifier values. */ protected static final StringMap values = new StringMap(); static { values.put(CSSConstants.CSS_BIDI_OVERRIDE_VALUE, ValueConstants.BIDI_OVERRIDE_VALUE); values.put(CSSConstants.CSS_EMBED_VALUE, ValueConstants.EMBED_VALUE); values.put(CSSConstants.CSS_NORMAL_VALUE, ValueConstants.NORMAL_VALUE); } /** * Implements {@link * org.apache.flex.forks.batik.css.engine.value.ValueManager#isInheritedProperty()}. */ public boolean isInheritedProperty() { return false; } /** * Implements {@link ValueManager#isAnimatableProperty()}. */ public boolean isAnimatableProperty() { return false; } /** * Implements {@link ValueManager#isAdditiveProperty()}. */ public boolean isAdditiveProperty() { return false; } /** * Implements {@link ValueManager#getPropertyType()}. */ public int getPropertyType() { return SVGTypes.TYPE_IDENT; } /** * Implements {@link * org.apache.flex.forks.batik.css.engine.value.ValueManager#getPropertyName()}. */ public String getPropertyName() { return CSSConstants.CSS_UNICODE_BIDI_PROPERTY; } /** * Implements {@link * org.apache.flex.forks.batik.css.engine.value.ValueManager#getDefaultValue()}. */ public Value getDefaultValue() { return ValueConstants.NORMAL_VALUE; } /** * Implements {@link IdentifierManager#getIdentifiers()}. */ public StringMap getIdentifiers() { return values; } }
adufilie/flex-sdk
modules/thirdparty/batik/sources/org/apache/flex/forks/batik/css/engine/value/css2/UnicodeBidiManager.java
Java
apache-2.0
3,268
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.java.codeInsight.daemon.quickFix; import com.intellij.codeInsight.daemon.quickFix.LightQuickFixParameterizedTestCase; public class ReplaceInaccessibleFieldWithGetterSetterFixTest extends LightQuickFixParameterizedTestCase { public void test() { doAllTests(); } @Override protected String getBasePath() { return "/codeInsight/daemonCodeAnalyzer/quickFix/replaceFieldWithGetterSetter"; } }
goodwinnk/intellij-community
java/java-tests/testSrc/com/intellij/java/codeInsight/daemon/quickFix/ReplaceInaccessibleFieldWithGetterSetterFixTest.java
Java
apache-2.0
1,025
class Keepassc < Formula desc "Curses-based password manager for KeePass v.1.x and KeePassX" homepage "https://raymontag.github.com/keepassc/" url "https://files.pythonhosted.org/packages/c8/87/a7d40d4a884039e9c967fb2289aa2aefe7165110a425c4fb74ea758e9074/keepassc-1.8.2.tar.gz" sha256 "2e1fc6ccd5325c6f745f2d0a3bb2be26851b90d2095402dd1481a5c197a7b24e" revision 1 bottle do cellar :any_skip_relocation sha256 "af7729059e564b32a9e09947c2bcbcd439a198a10522983acc04fae72a0ed4dd" => :mojave sha256 "b963fd7217761500437a7a25e6e37a38cdd92da088de4a6de4b0d6e0184217fc" => :high_sierra sha256 "762071bc7437e9ecd1d6b036aedef31556da97bfd097560fd53c407e6d7cfc96" => :sierra sha256 "d476806614a7c45de1c6352e03b0d8a680700f6e97597efce1f927208136bf2e" => :el_capitan end depends_on "python" resource "kppy" do url "https://files.pythonhosted.org/packages/c8/d9/6ced04177b4790ccb1ba44e466c5b67f3a1cfe4152fb05ef5f990678f94f/kppy-1.5.2.tar.gz" sha256 "08fc48462541a891debe8254208fe162bcc1cd40aba3f4ca98286401faf65f28" end resource "pycryptodomex" do url "https://files.pythonhosted.org/packages/e6/5a/cf2bd33574f8f8711bad12baee7ef5c9c53a09c338cec241abfc0ba0cf63/pycryptodomex-3.6.3.tar.gz" sha256 "008ad82b8fdd1532dd32a0e0e4204af8e4710fc3d2a76e408cbdb3dddf4f8417" end def install pyver = Language::Python.major_minor_version "python3" ENV.prepend_create_path "PYTHONPATH", libexec+"lib/python#{pyver}/site-packages" install_args = %W[setup.py install --prefix=#{libexec}] resource("pycryptodomex").stage { system "python3", *install_args } resource("kppy").stage { system "python3", *install_args } system "python3", *install_args man1.install Dir["*.1"] bin.install Dir[libexec/"bin/*"] bin.env_script_all_files(libexec+"bin", :PYTHONPATH => ENV["PYTHONPATH"]) end test do # Fetching help is the only non-interactive action we can perform, and since # interactive actions are un-scriptable, there nothing more we can do. system "#{bin}/keepassc", "--help" end end
adamliter/homebrew-core
Formula/keepassc.rb
Ruby
bsd-2-clause
2,071
Vim support for Factor ====================== This directory contains various support files that make editing Factor code more pleasant in Vim. ## Installation The file-layout exactly matches the Vim runtime structure, so you can install them by copying the contents of this directory into `~/.vim/` or the equivalent path on other platforms (Open Vim and type `:help 'runtimepath'` for details). ## File organization The current set of files is as follows: * ftdetect/factor.vim - Teach Vim when to load Factor support files. * ftplugin/factor.vim - Teach Vim to follow the Factor Coding Style guidelines. * plugin/factor.vim - Teach Vim some commands for navigating Factor source code. See below. * syntax/factor.vim - Syntax highlighting for Factor code. ## Commands The `plugin/factor.vim` file implements the following commands for navigating Factor source. ### :FactorVocab factor.vocab.name Opens the source file implementing the `factor.vocab.name` vocabulary. ### :NewFactorVocab factor.vocab.name Creates a new factor vocabulary under the working vocabulary root. ### :FactorVocabImpl Opens the main implementation file for the current vocabulary (name.factor). The keyboard shortcut `<Leader>fi` is bound to this command. ### :FactorVocabDocs Opens the documentation file for the current vocabulary (name-docs.factor). The keyboard shortcut `<Leader>fd` is bound to this command. ### :FactorVocabTests Opens the unit test file for the current vocabulary (name-tests.factor). The keyboard shortcut `<Leader>ft` is bound to this command. ## Configuration In order for the `:FactorVocab` command to work, you'll need to set some variables in your vimrc file. ### g:FactorRoot This variable should be set to the root of your Factor installation. The default value is `~/factor`. ### g:FactorVocabRoots This variable should be set to a list of Factor vocabulary roots. The paths may be either relative to g:FactorRoot or absolute paths. The default value is `["core", "basis", "extra", "work"]`. ### g:FactorNewVocabRoot This variable should be set to the vocabulary root in which vocabularies created with NewFactorVocab should be created. The default value is `work`. ## Note The syntax-highlighting file is automatically generated to include the names of all the vocabularies Factor knows about. To regenerate it manually, run the following code in the listener: "editors.vim.generate-syntax" run or run it from the command line: factor -run=editors.vim.generate-syntax
bjourne/factor
misc/vim/README.md
Markdown
bsd-2-clause
2,521
package de.lessvoid.nifty.render.image.renderstrategy; import de.lessvoid.nifty.layout.Box; import de.lessvoid.nifty.spi.render.RenderDevice; import de.lessvoid.nifty.spi.render.RenderImage; import de.lessvoid.nifty.tools.Color; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.logging.Logger; public class NinePartResizeStrategy implements RenderStrategy { private static final Logger log = Logger.getLogger(NinePartResizeStrategy.class.getName()); private static final int NINE_PART_RESIZE_ARGS_COUNT = 12; private NinePartResizeRow m_row0; private NinePartResizeRow m_row1; private NinePartResizeRow m_row2; @Nonnull private final Box box = new Box(); @Override public void setParameters(String parameters) { String[] args = getArguments(parameters); m_row0 = new NinePartResizeRow(args, 0); m_row1 = new NinePartResizeRow(args, 4); m_row2 = new NinePartResizeRow(args, 8); } @Nullable private String[] getArguments(@Nullable String parameters) { String[] args = null; if (parameters != null) { args = parameters.split(","); } if ((args == null) || (args.length != NINE_PART_RESIZE_ARGS_COUNT)) { int argCount = (args == null) ? 0 : args.length; throw new IllegalArgumentException("Trying to parse [" + this.getClass().getName() + "] : wrong parameter count (" + argCount + "). Expected [w1,w2,w3,h1,w4,w5,w6,h2,w7,w8,w9,h3], found [" + parameters + "]."); } return args; } @Override public void render( @Nonnull RenderDevice device, @Nonnull RenderImage image, @Nonnull Box sourceArea, int x, int y, int width, int height, @Nonnull Color color, float scale) { final int cX = x + width / 2; final int cY = y + height / 2; final int srcX = sourceArea.getX(); final int srcW = sourceArea.getWidth(); if ((m_row0.getWidth() > srcW) || (m_row1.getWidth() > srcW) || (m_row2.getWidth() > srcW)) { log.warning("Defined nine-part resize strategy goes out of source area's bounds."); } final int srcH0 = m_row0.getHeight(); final int srcH1 = m_row1.getHeight(); final int srcH2 = m_row2.getHeight(); final int srcY0 = sourceArea.getY(); final int srcY1 = srcY0 + srcH0; final int srcY2 = srcY1 + srcH1; final int midlH = height - srcH0 - srcH2; final int y1 = y + srcH0; final int y2 = y1 + midlH; box.setX(srcX); box.setY(srcY0); box.setWidth(srcW); box.setHeight(srcH0); renderRow(device, image, m_row0, box, x, y, width, srcH0, color, scale, cX, cY); box.setX(srcX); box.setY(srcY1); box.setWidth(srcW); box.setHeight(srcH1); renderRow(device, image, m_row1, box, x, y1, width, midlH, color, scale, cX, cY); box.setX(srcX); box.setY(srcY2); box.setWidth(srcW); box.setHeight(srcH2); renderRow(device, image, m_row2, box, x, y2, width, srcH2, color, scale, cX, cY); } private void renderRow( @Nonnull final RenderDevice renderDevice, @Nonnull final RenderImage image, @Nonnull final NinePartResizeRow row, @Nonnull final Box sourceArea, final int x, final int y, final int width, final int height, @Nonnull final Color color, final float scale, final int centerX, final int centerY) { final int srcY = sourceArea.getY(); final int srcH = sourceArea.getHeight(); final int srcW0 = row.getLeftWidth(); final int srcW1 = row.getMiddleWidth(); final int srcW2 = row.getRightWidth(); final int srcX0 = sourceArea.getX(); final int srcX1 = srcX0 + srcW0; final int srcX2 = srcX1 + srcW1; final int midlW = width - srcW0 - srcW2; final int x1 = x + srcW0; final int x2 = x1 + midlW; renderDevice.renderImage(image, x, y, srcW0, height, srcX0, srcY, srcW0, srcH, color, scale, centerX, centerY); renderDevice.renderImage(image, x1, y, midlW, height, srcX1, srcY, srcW1, srcH, color, scale, centerX, centerY); renderDevice.renderImage(image, x2, y, srcW2, height, srcX2, srcY, srcW2, srcH, color, scale, centerX, centerY); } private static class NinePartResizeRow { private final int m_leftWidth; private final int m_middleWidth; private final int m_rightWidth; private final int m_height; public NinePartResizeRow(String[] data, int dataOffset) { m_leftWidth = Integer.valueOf(data[dataOffset]); m_middleWidth = Integer.valueOf(data[dataOffset + 1]); m_rightWidth = Integer.valueOf(data[dataOffset + 2]); m_height = Integer.valueOf(data[dataOffset + 3]); } public int getLeftWidth() { return m_leftWidth; } public int getMiddleWidth() { return m_middleWidth; } public int getRightWidth() { return m_rightWidth; } public int getWidth() { return m_leftWidth + m_middleWidth + m_rightWidth; } public int getHeight() { return m_height; } } }
Ryszard-Trojnacki/nifty-gui
nifty-core/src/main/java/de/lessvoid/nifty/render/image/renderstrategy/NinePartResizeStrategy.java
Java
bsd-2-clause
5,206
# typed: false # frozen_string_literal: true require_relative "shared_examples" describe UnpackStrategy::Xar, :needs_macos do let(:path) { TEST_FIXTURE_DIR/"cask/container.xar" } include_examples "UnpackStrategy::detect" include_examples "#extract", children: ["container"] end
vitorgalvao/brew
Library/Homebrew/test/unpack_strategy/xar_spec.rb
Ruby
bsd-2-clause
287
// Copyright 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. #ifndef CHROMECAST_NET_CONNECTIVITY_CHECKER_H_ #define CHROMECAST_NET_CONNECTIVITY_CHECKER_H_ #include <memory> #include "base/macros.h" #include "base/memory/ref_counted.h" #include "base/observer_list_threadsafe.h" class GURL; namespace base { class SingleThreadTaskRunner; } namespace chromecast { // Checks if internet connectivity is available. class ConnectivityChecker : public base::RefCountedThreadSafe<ConnectivityChecker> { public: class ConnectivityObserver { public: // Will be called when internet connectivity changes. virtual void OnConnectivityChanged(bool connected) = 0; protected: ConnectivityObserver() {} virtual ~ConnectivityObserver() {} private: DISALLOW_COPY_AND_ASSIGN(ConnectivityObserver); }; static scoped_refptr<ConnectivityChecker> Create( const scoped_refptr<base::SingleThreadTaskRunner>& task_runner); ConnectivityChecker(); void AddConnectivityObserver(ConnectivityObserver* observer); void RemoveConnectivityObserver(ConnectivityObserver* observer); // Returns if there is internet connectivity. virtual bool Connected() const = 0; // Checks for connectivity. virtual void Check() = 0; protected: virtual ~ConnectivityChecker(); // Notifies observes that connectivity has changed. void Notify(bool connected); private: friend class base::RefCountedThreadSafe<ConnectivityChecker>; const scoped_refptr<base::ObserverListThreadSafe<ConnectivityObserver>> connectivity_observer_list_; DISALLOW_COPY_AND_ASSIGN(ConnectivityChecker); }; } // namespace chromecast #endif // CHROMECAST_NET_CONNECTIVITY_CHECKER_H_
ssaroha/node-webrtc
third_party/webrtc/include/chromium/src/chromecast/net/connectivity_checker.h
C
bsd-2-clause
1,812
/* SPDX-License-Identifier: BSD-2-Clause */ /* * Copyright (c) 2016, Linaro Limited */ #ifndef __PL061_GPIO_H__ #define __PL061_GPIO_H__ #include <gpio.h> #include <types_ext.h> #define PL061_REG_SIZE 0x1000 enum pl061_mode_control { PL061_MC_SW, PL061_MC_HW }; struct pl061_data { struct gpio_chip chip; }; void pl061_register(vaddr_t base_addr, unsigned int gpio_dev); void pl061_init(struct pl061_data *pd); enum pl061_mode_control pl061_get_mode_control(unsigned int gpio_pin); void pl061_set_mode_control(unsigned int gpio_pin, enum pl061_mode_control hw_sw); #endif /* __PL061_GPIO_H__ */
pascal-brand-st-dev/optee_os
core/include/drivers/pl061_gpio.h
C
bsd-2-clause
608
Testing CS render time include file... PreInclude <?cs linclude:'testdata/test2include.cs' ?> PostInclude
bigmaliang/clearsilver
java/org/clearsilver/test/testdata/test2b.cs
C#
bsd-2-clause
107
/*- * Copyright (c) 2012 Varnish Software AS * All rights reserved. * * Author: Poul-Henning Kamp <[email protected]> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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. * */ /*lint -save -e525 -e539 */ // enum sess_close sc_* stat is_err Description SESS_CLOSE(REM_CLOSE, rem_close, 0, "Client Closed") SESS_CLOSE(REQ_CLOSE, req_close, 0, "Client requested close") SESS_CLOSE(REQ_HTTP10, req_http10, 1, "Proto < HTTP/1.1") SESS_CLOSE(RX_BAD, rx_bad, 1, "Received bad req/resp") SESS_CLOSE(RX_BODY, rx_body, 1, "Failure receiving req.body") SESS_CLOSE(RX_JUNK, rx_junk, 1, "Received junk data") SESS_CLOSE(RX_OVERFLOW, rx_overflow, 1, "Received buffer overflow") SESS_CLOSE(RX_TIMEOUT, rx_timeout, 1, "Receive timeout") SESS_CLOSE(TX_PIPE, tx_pipe, 0, "Piped transaction") SESS_CLOSE(TX_ERROR, tx_error, 1, "Error transaction") SESS_CLOSE(TX_EOF, tx_eof, 0, "EOF transmission") SESS_CLOSE(RESP_CLOSE, resp_close, 0, "Backend/VCL requested close") SESS_CLOSE(OVERLOAD, overload, 1, "Out of some resource") SESS_CLOSE(PIPE_OVERFLOW, pipe_overflow,1, "Session pipe overflow") SESS_CLOSE(RANGE_SHORT, range_short, 1, "Insufficient data for range") /*lint -restore */
mrhmouse/Varnish-Cache
include/tbl/sess_close.h
C
bsd-2-clause
2,435
/***************************************************************************** Copyright (c) 2014, Intel Corp. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER 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. ***************************************************************************** * Contents: Native middle-level C interface to LAPACK function csprfs * Author: Intel Corporation * Generated November 2015 *****************************************************************************/ #include "lapacke_utils.h" lapack_int LAPACKE_csprfs_work( int matrix_layout, char uplo, lapack_int n, lapack_int nrhs, const lapack_complex_float* ap, const lapack_complex_float* afp, const lapack_int* ipiv, const lapack_complex_float* b, lapack_int ldb, lapack_complex_float* x, lapack_int ldx, float* ferr, float* berr, lapack_complex_float* work, float* rwork ) { lapack_int info = 0; if( matrix_layout == LAPACK_COL_MAJOR ) { /* Call LAPACK function and adjust info */ LAPACK_csprfs( &uplo, &n, &nrhs, ap, afp, ipiv, b, &ldb, x, &ldx, ferr, berr, work, rwork, &info ); if( info < 0 ) { info = info - 1; } } else if( matrix_layout == LAPACK_ROW_MAJOR ) { lapack_int ldb_t = MAX(1,n); lapack_int ldx_t = MAX(1,n); lapack_complex_float* b_t = NULL; lapack_complex_float* x_t = NULL; lapack_complex_float* ap_t = NULL; lapack_complex_float* afp_t = NULL; /* Check leading dimension(s) */ if( ldb < nrhs ) { info = -9; LAPACKE_xerbla( "LAPACKE_csprfs_work", info ); return info; } if( ldx < nrhs ) { info = -11; LAPACKE_xerbla( "LAPACKE_csprfs_work", info ); return info; } /* Allocate memory for temporary array(s) */ b_t = (lapack_complex_float*) LAPACKE_malloc( sizeof(lapack_complex_float) * ldb_t * MAX(1,nrhs) ); if( b_t == NULL ) { info = LAPACK_TRANSPOSE_MEMORY_ERROR; goto exit_level_0; } x_t = (lapack_complex_float*) LAPACKE_malloc( sizeof(lapack_complex_float) * ldx_t * MAX(1,nrhs) ); if( x_t == NULL ) { info = LAPACK_TRANSPOSE_MEMORY_ERROR; goto exit_level_1; } ap_t = (lapack_complex_float*) LAPACKE_malloc( sizeof(lapack_complex_float) * ( MAX(1,n) * MAX(2,n+1) ) / 2 ); if( ap_t == NULL ) { info = LAPACK_TRANSPOSE_MEMORY_ERROR; goto exit_level_2; } afp_t = (lapack_complex_float*) LAPACKE_malloc( sizeof(lapack_complex_float) * ( MAX(1,n) * MAX(2,n+1) ) / 2 ); if( afp_t == NULL ) { info = LAPACK_TRANSPOSE_MEMORY_ERROR; goto exit_level_3; } /* Transpose input matrices */ LAPACKE_cge_trans( matrix_layout, n, nrhs, b, ldb, b_t, ldb_t ); LAPACKE_cge_trans( matrix_layout, n, nrhs, x, ldx, x_t, ldx_t ); LAPACKE_csp_trans( matrix_layout, uplo, n, ap, ap_t ); LAPACKE_csp_trans( matrix_layout, uplo, n, afp, afp_t ); /* Call LAPACK function and adjust info */ LAPACK_csprfs( &uplo, &n, &nrhs, ap_t, afp_t, ipiv, b_t, &ldb_t, x_t, &ldx_t, ferr, berr, work, rwork, &info ); if( info < 0 ) { info = info - 1; } /* Transpose output matrices */ LAPACKE_cge_trans( LAPACK_COL_MAJOR, n, nrhs, x_t, ldx_t, x, ldx ); /* Release memory and exit */ LAPACKE_free( afp_t ); exit_level_3: LAPACKE_free( ap_t ); exit_level_2: LAPACKE_free( x_t ); exit_level_1: LAPACKE_free( b_t ); exit_level_0: if( info == LAPACK_TRANSPOSE_MEMORY_ERROR ) { LAPACKE_xerbla( "LAPACKE_csprfs_work", info ); } } else { info = -1; LAPACKE_xerbla( "LAPACKE_csprfs_work", info ); } return info; }
ryanrhymes/openblas
lib/OpenBLAS-0.2.19/lapack-netlib/LAPACKE/src/lapacke_csprfs_work.c
C
bsd-3-clause
5,726
<?php namespace Middleware; use Slim\Middleware; use Symfony\Component\Translation\Loader\ArrayLoader; use Symfony\Component\Translation\Loader\XliffFileLoader; use Symfony\Component\Translation\MessageSelector; use Symfony\Component\Translation\Translator; use Symfony\Component\Validator\ConstraintValidatorFactory; use Symfony\Component\Validator\Mapping\ClassMetadataFactory; use Symfony\Component\Validator\Mapping\Loader\StaticMethodLoader; use Symfony\Component\Validator\Validator; use Symfony\Component\Validator\Validation; /** * In this middleware we create the validation services as provided by Symfony and register it as service in the * container of Slim. If this middleware is registered before the FormMiddleware then the validator service is also * added to the Symfony Forms Component; and adding validation capability to the forms. * * This Middleware adds the following services to the slim container: * * - 'translator', translation class; only added if not already present. * - 'validator', the validation service that can be used to verify data against a set of constraints. * * For more information on usage, see the {@see self::call()} method. */ class ValidationMiddleware extends Middleware { const SERVICE_VALIDATOR = 'validator'; /** @var string */ private $locale; /** * Initializes this middleware with the given locale. * * @param string $locale The locale in country_DIALECT notation, for example: en_UK */ public function __construct($locale = 'en_UK') { $this->locale = $locale; } /** * Adds a new 'validator' service to the Slim container. * * This validator must only be called if you are not using the forms functionality; when using forms you * can use the 'constraints' option of a Field Definition to add validation. See the Symfony documentation * for more information. * * @return void */ public function call() { $this->addTranslations($this->getTranslator(), $this->getTranslationsRootFolder()); $middleware = $this; $this->app->container->singleton( self::SERVICE_VALIDATOR, function () use ($middleware) { return $middleware->createValidator(); } ); $this->next->call(); } /** * Returns a new validator instance. * * Generally this method does not need to be called directly; it is used in a callback that created a shared * instance in the container of Slim. * * @see self::call() where this method is used to construct a shared instance in Slim. * * @return Validator */ public function createValidator() { $validator = Validation::createValidatorBuilder() ->setMetadataFactory(new ClassMetadataFactory(new StaticMethodLoader())) ->setConstraintValidatorFactory(new ConstraintValidatorFactory($this->app, array())) ->setTranslator($this->getTranslator()) ->setApiVersion(Validation::API_VERSION_2_5) ->getValidator(); return $validator; } /** * Adds all messages related to validation to the translator. * * @param Translator $translator * @param string $validatorComponentRootFolder * * @return void */ private function addTranslations($translator, $validatorComponentRootFolder) { $translator->addResource( 'xliff', $validatorComponentRootFolder . '/Resources/translations/validators.' . $this->locale . '.xlf', $this->locale, 'validators' ); } /** * Retrieves the translator from the container and creates it if it is absent. * * @return Translator */ private function getTranslator() { if (!$this->app->translator instanceof Translator) { $this->app->translator = new Translator($this->locale, new MessageSelector()); $this->app->translator->addLoader('array', new ArrayLoader()); $this->app->translator->addLoader('xliff', new XliffFileLoader()); } return $this->app->translator; } /** * Returns the folder where the translations for the validator are stored. * * @return string */ private function getTranslationsRootFolder() { $r = new \ReflectionClass('Symfony\Component\Validator\Validator'); return dirname($r->getFilename()); } }
cal-tec/joindin-web2
app/src/Middleware/ValidationMiddleware.php
PHP
bsd-3-clause
4,525
// 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 "remoting/protocol/audio_writer.h" #include <utility> #include "base/bind.h" #include "base/memory/ptr_util.h" #include "net/socket/stream_socket.h" #include "remoting/base/compound_buffer.h" #include "remoting/base/constants.h" #include "remoting/proto/audio.pb.h" #include "remoting/protocol/message_pipe.h" #include "remoting/protocol/session.h" #include "remoting/protocol/session_config.h" namespace remoting { namespace protocol { AudioWriter::AudioWriter() : ChannelDispatcherBase(kAudioChannelName) {} AudioWriter::~AudioWriter() = default; void AudioWriter::ProcessAudioPacket(std::unique_ptr<AudioPacket> packet, base::OnceClosure done) { message_pipe()->Send(packet.get(), std::move(done)); } // static std::unique_ptr<AudioWriter> AudioWriter::Create(const SessionConfig& config) { if (!config.is_audio_enabled()) return nullptr; return base::WrapUnique(new AudioWriter()); } void AudioWriter::OnIncomingMessage(std::unique_ptr<CompoundBuffer> message) { LOG(ERROR) << "Received unexpected message on the audio channel."; } } // namespace protocol } // namespace remoting
scheib/chromium
remoting/protocol/audio_writer.cc
C++
bsd-3-clause
1,322
/************************************************************************** * This file is property of and copyright by the ALICE HLT Project * * All rights reserved. * * * * Primary Authors: Markus Fasel * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ #ifndef ALIHLTEMCALTRIGGERMAKER_H #define ALIHLTEMCALTRIGGERMAKER_H /** * @file AliHLTEMCALTriggerMaker.h * @author Markus Fasel * @date Oct. 30, 2015 * @brief Trigger maker kernel used by the EMCAL HLT trigger maker component */ #include <TObject.h> #include "AliHLTLogging.h" struct AliHLTCaloTriggerPatchDataStruct; class AliHLTEMCALGeometry; class AliEMCALTriggerBitConfig; class AliEMCALTriggerRawPatch; template<typename T> class AliEMCALTriggerDataGrid; template<typename T> class AliEMCALTriggerPatchFinder; /** * @class AliHLTEMCALTriggerMaker * @brief EMCAL Trigger Maker implementation runnin on the HLT * * This class implements the trigger maker for the EMCAL in the * HLT. */ class AliHLTEMCALTriggerMaker : public TObject, public AliHLTLogging { public: enum ELevel0TriggerStatus_t { kNotLevel0, kLevel0Candidate, kLevel0Fired }; enum ThresholdType_t{ kHighThreshold = 0, kLowThreshold = 1, kNthresholds = 2 }; /** * Constructor */ AliHLTEMCALTriggerMaker(); /** * Destructor */ virtual ~AliHLTEMCALTriggerMaker(); /** * Initializes the trigger maker kernel. Sets the geometry ptr, * allocates space for the trigger channels and configures the * trigger patch finder. * * Based on the geometry versions the trigger channel data grid is * allocated and the trigger patch finders in EMCAL (and DCAL if available) * are configured. * * @param geo Pointer to the geometry used in the trigger maker. */ void Initialise(const AliHLTEMCALGeometry *geo); /** * Rest ADC values */ void ResetADC(); /** * Add digit structure to the data grid * @param digit Input digit data */ void AddDigit(const AliHLTCaloDigitDataStruct *digit); /** * Set the adc value for a given col / row combination * @param col Column * @param row Row * @param adc ADC value */ void SetADC(Int_t col, Int_t row, Float_t adc); /** * Set the L0 amplitude for a given col / row combination * @param col Column * @param row Row * @param amp L0 Amplitude */ void SetL0Amplitude(Int_t col, Int_t row, Float_t amp); /** * Set the L0 trigger time for a given col / row combination * @param col Column * @param row Row * @param amp L0 trigger time */ void SetL0Time(Int_t col, Int_t row, UChar_t time); /** * Set the bit mask from the STU for a given col / row combination * @param col Column * @param row Row * @param bitMask Bit mask */ void SetBitMask(Int_t col, Int_t row, Int_t bitMask); /** * Set the pointer to the writeout buffer * @param outputcont Pointer to the writeout buffer */ void SetTriggerPatchDataPtr(AliHLTCaloTriggerPatchDataStruct *outputcont, AliHLTUInt32_t buffersize) { fTriggerPatchDataPtr = outputcont; fBufferSize = buffersize; } /** * Find EMCAL trigger patches. * The trigger patches are internally converted into HLT EMCAL trigger patches and * pushed to the writeout buffer. * @return Number of found patches (-1 in case of buffer overflow) */ Int_t FindPatches(); /** * Set the thresholds for jet trigger patches * @param onlineTh Online threshold to be applied * @param offlineTh Offline threshold to be applied */ void SetJetThresholds(ThresholdType_t threshtype, Float_t onlineTh, Float_t offlineTh) { fJetThresholdOnline[threshtype] = onlineTh; fJetThresholdOffline[threshtype] = offlineTh; } /** * Set the thresholds for gamma trigger patches * @param onlineTh Online threshold to be applied * @param offlineTh Offline threshold to be applied */ void SetGammaThresholds(ThresholdType_t threshtype, Float_t onlineTh, Float_t offlineTh) { fGammaThresholdOnline[threshtype] = onlineTh; fGammaThresholdOffline[threshtype] = offlineTh; } /** * Set the thresholds for bkg trigger patches * @param onlineTh Online threshold to be applied * @param offlineTh Offline threshold to be applied */ void SetBkgThresholds(Float_t onlineTh, Float_t offlineTh) { fBkgThresholdOnline = onlineTh; fBkgThresholdOffline = offlineTh; } /** * Define whether we run the algorithm for background patches * @param doRun Switch for the background algorithm */ void SetRunBkgAlgorithm(Bool_t doRun) { fRunBkgAlgorithm = doRun; } /** * Set the thresholds for level0 trigger patches * @param onlineTh Online Threshold to be applied * @param offlineTh Offline Threshold to be applied */ void SetLevel0Thresholds(Float_t onlineTh, Float_t offlineTh) { fLevel0ThresholdOnline = onlineTh; fLevel0ThresholdOffline = offlineTh; } /** * Set the patch size/subregion for jet trigger patches * @param size Size of the patch in number of FastORs * @param subregion Subregion of the sliding window */ void SetJetPatch(Int_t size, Int_t subregion) { fJetPatchSize = size ; fJetSubregionSize = subregion ; } /** * Set the patch size/subregion for gamma trigger patches * @param size Size of the patch in number of FastORs * @param subregion Subregion of the sliding window */ void SetGammaPatch(Int_t size, Int_t subregion) { fGammaPatchSize = size; fGammaSubregionSize = subregion; } /** * Set the patch size/subregion for background trigger patches * @param size Size of the patch in number of FastORs * @param subregion Subregion of the sliding window */ void SetBkgPatch(Int_t size, Int_t subregion) { fBkgPatchSize = size ; fBkgSubregionSize = subregion ; } protected: /** * Convert raw patches found by the trigger patch finders into HLT EMCAL trigger patches. * @param inputpatch EMCAL raw patch to be converted into an EMCAL HLT patch * @param output HLT trigger patch obtaied using the information in the EMCAL raw patch */ void MakeHLTPatch(const AliEMCALTriggerRawPatch &inputpatch, AliHLTCaloTriggerPatchDataStruct &output, UInt_t offlinebits, UInt_t onlinebitmask, UInt_t level0bits) const; /** * Initialise trigger patch finders in the EMCAL or DCAL at Level1 * @param isDCAL Switch distinguishing between DCAL (true) and EMCAL (false) */ void InitializeLevel1PatchFinders(Bool_t isDCAL); /** Initialize L0 Patch finders in EMCAL and DCAL */ void InitializeLevel0PatchFinders(Bool_t isDCAL); /** * Initialize the lookup tables used by the trigger maker */ void InitializeLookupTables(); /** * Check whether all fastors are in the same TRU. This * is a condition to accept the patch as valid Level0 * patch. * @param patch Patch to check * @return True if all fastors are in the same TRU, false * otherwise */ ELevel0TriggerStatus_t CheckForL0(Int_t col, Int_t row) const; /** * Check if the patch has overlap in channles with the PHOS * region. * @param Patch to check * @return True if the patch has overlap with PHOS */ bool HasPHOSOverlap(const AliEMCALTriggerRawPatch & patch) const; private: /** Pointer to the output buffer */ AliHLTCaloTriggerPatchDataStruct *fTriggerPatchDataPtr; /** Underlying EMCAL geometry*/ const AliHLTEMCALGeometry *fkGeometryPtr; /** EMCAL trigger algorithms used to find trigger patches */ AliEMCALTriggerPatchFinder<float> *fPatchFinder; /** EMCAL Level0 patch finder (operating on different data */ AliEMCALTriggerPatchFinder<float> *fL0PatchFinder; /** Grid with ADC values used for the trigger patch finding */ AliEMCALTriggerDataGrid<float> *fADCValues; /** Grid with ADC values used for the trigger patch finding */ AliEMCALTriggerDataGrid<float> *fADCOfflineValues; /** Grid with L0 Amplitude values used for L0 trigger patch finding */ AliEMCALTriggerDataGrid<float> *fL0Amplitudes; /** Grid with trigger bit mask from STU */ AliEMCALTriggerDataGrid<int> *fTriggerBitMasks; /** Grid with L0 trigger time values used to retrieve L0 decision */ AliEMCALTriggerDataGrid<unsigned char> *fLevel0TimeMap; /** Lookup table with TRU indices */ AliEMCALTriggerDataGrid<int> *fTRUIndexMap; /** Trigger bit configurtion */ AliEMCALTriggerBitConfig *fTriggerBitConfig; /** Jet patch size **/ Int_t fJetPatchSize; /** Jet subregion size **/ Int_t fJetSubregionSize; /** Gamma patch size **/ Int_t fGammaPatchSize; /** Gamme subregion size **/ Int_t fGammaSubregionSize; /** Background patch size **/ Int_t fBkgPatchSize; /** Background subregion size **/ Int_t fBkgSubregionSize; /** Minimum time bin for a valid L0 trigger decision **/ Char_t fL0MinTime; /** Maximum time bin for a valid L0 trigger decision **/ Char_t fL0MaxTime; /** Available space in buffer */ AliHLTUInt32_t fBufferSize; /** online threshold for gamma patches */ Float_t fGammaThresholdOnline[2]; /** offline threshold for gamma patches */ Float_t fGammaThresholdOffline[2]; /** online threshold for jet patches */ Float_t fJetThresholdOnline[2]; /** offline threshold for jet patches */ Float_t fJetThresholdOffline[2]; /** online threshold for bkg patches */ Float_t fBkgThresholdOnline; /** offline threshold for bkg patches */ Float_t fBkgThresholdOffline; /** Switch for running the background trigger algorithm */ Bool_t fRunBkgAlgorithm; /** Threshold for accepting level0 online patches */ Float_t fLevel0ThresholdOnline; /** Threshold for accepting level0 offline patches */ Float_t fLevel0ThresholdOffline; ClassDef(AliHLTEMCALTriggerMaker, 3); }; #endif
miranov25/AliRoot
HLT/EMCAL/AliHLTEMCALTriggerMaker.h
C
bsd-3-clause
11,344
SUBROUTINE DCHKGT( DOTYPE, NN, NVAL, NNS, NSVAL, THRESH, TSTERR, $ A, AF, B, X, XACT, WORK, RWORK, IWORK, NOUT ) * * -- LAPACK test routine (version 3.1) -- * Univ. of Tennessee, Univ. of California Berkeley and NAG Ltd.. * November 2006 * * .. Scalar Arguments .. LOGICAL TSTERR INTEGER NN, NNS, NOUT DOUBLE PRECISION THRESH * .. * .. Array Arguments .. LOGICAL DOTYPE( * ) INTEGER IWORK( * ), NSVAL( * ), NVAL( * ) DOUBLE PRECISION A( * ), AF( * ), B( * ), RWORK( * ), WORK( * ), $ X( * ), XACT( * ) * .. * * Purpose * ======= * * DCHKGT tests DGTTRF, -TRS, -RFS, and -CON * * Arguments * ========= * * DOTYPE (input) LOGICAL array, dimension (NTYPES) * The matrix types to be used for testing. Matrices of type j * (for 1 <= j <= NTYPES) are used for testing if DOTYPE(j) = * .TRUE.; if DOTYPE(j) = .FALSE., then type j is not used. * * NN (input) INTEGER * The number of values of N contained in the vector NVAL. * * NVAL (input) INTEGER array, dimension (NN) * The values of the matrix dimension N. * * NNS (input) INTEGER * The number of values of NRHS contained in the vector NSVAL. * * NSVAL (input) INTEGER array, dimension (NNS) * The values of the number of right hand sides NRHS. * * THRESH (input) DOUBLE PRECISION * The threshold value for the test ratios. A result is * included in the output file if RESULT >= THRESH. To have * every test ratio printed, use THRESH = 0. * * TSTERR (input) LOGICAL * Flag that indicates whether error exits are to be tested. * * A (workspace) DOUBLE PRECISION array, dimension (NMAX*4) * * AF (workspace) DOUBLE PRECISION array, dimension (NMAX*4) * * B (workspace) DOUBLE PRECISION array, dimension (NMAX*NSMAX) * where NSMAX is the largest entry in NSVAL. * * X (workspace) DOUBLE PRECISION array, dimension (NMAX*NSMAX) * * XACT (workspace) DOUBLE PRECISION array, dimension (NMAX*NSMAX) * * WORK (workspace) DOUBLE PRECISION array, dimension * (NMAX*max(3,NSMAX)) * * RWORK (workspace) DOUBLE PRECISION array, dimension * (max(NMAX,2*NSMAX)) * * IWORK (workspace) INTEGER array, dimension (2*NMAX) * * NOUT (input) INTEGER * The unit number for output. * * ===================================================================== * * .. Parameters .. DOUBLE PRECISION ONE, ZERO PARAMETER ( ONE = 1.0D+0, ZERO = 0.0D+0 ) INTEGER NTYPES PARAMETER ( NTYPES = 12 ) INTEGER NTESTS PARAMETER ( NTESTS = 7 ) * .. * .. Local Scalars .. LOGICAL TRFCON, ZEROT CHARACTER DIST, NORM, TRANS, TYPE CHARACTER*3 PATH INTEGER I, IMAT, IN, INFO, IRHS, ITRAN, IX, IZERO, J, $ K, KL, KOFF, KU, LDA, M, MODE, N, NERRS, NFAIL, $ NIMAT, NRHS, NRUN DOUBLE PRECISION AINVNM, ANORM, COND, RCOND, RCONDC, RCONDI, $ RCONDO * .. * .. Local Arrays .. CHARACTER TRANSS( 3 ) INTEGER ISEED( 4 ), ISEEDY( 4 ) DOUBLE PRECISION RESULT( NTESTS ), Z( 3 ) * .. * .. External Functions .. DOUBLE PRECISION DASUM, DGET06, DLANGT EXTERNAL DASUM, DGET06, DLANGT * .. * .. External Subroutines .. EXTERNAL ALAERH, ALAHD, ALASUM, DCOPY, DERRGE, DGET04, $ DGTCON, DGTRFS, DGTT01, DGTT02, DGTT05, DGTTRF, $ DGTTRS, DLACPY, DLAGTM, DLARNV, DLATB4, DLATMS, $ DSCAL * .. * .. Intrinsic Functions .. INTRINSIC MAX * .. * .. Scalars in Common .. LOGICAL LERR, OK CHARACTER*32 SRNAMT INTEGER INFOT, NUNIT * .. * .. Common blocks .. COMMON / INFOC / INFOT, NUNIT, OK, LERR COMMON / SRNAMC / SRNAMT * .. * .. Data statements .. DATA ISEEDY / 0, 0, 0, 1 / , TRANSS / 'N', 'T', $ 'C' / * .. * .. Executable Statements .. * PATH( 1: 1 ) = 'Double precision' PATH( 2: 3 ) = 'GT' NRUN = 0 NFAIL = 0 NERRS = 0 DO 10 I = 1, 4 ISEED( I ) = ISEEDY( I ) 10 CONTINUE * * Test the error exits * IF( TSTERR ) $ CALL DERRGE( PATH, NOUT ) INFOT = 0 * DO 110 IN = 1, NN * * Do for each value of N in NVAL. * N = NVAL( IN ) M = MAX( N-1, 0 ) LDA = MAX( 1, N ) NIMAT = NTYPES IF( N.LE.0 ) $ NIMAT = 1 * DO 100 IMAT = 1, NIMAT * * Do the tests only if DOTYPE( IMAT ) is true. * IF( .NOT.DOTYPE( IMAT ) ) $ GO TO 100 * * Set up parameters with DLATB4. * CALL DLATB4( PATH, IMAT, N, N, TYPE, KL, KU, ANORM, MODE, $ COND, DIST ) * ZEROT = IMAT.GE.8 .AND. IMAT.LE.10 IF( IMAT.LE.6 ) THEN * * Types 1-6: generate matrices of known condition number. * KOFF = MAX( 2-KU, 3-MAX( 1, N ) ) SRNAMT = 'DLATMS' CALL DLATMS( N, N, DIST, ISEED, TYPE, RWORK, MODE, COND, $ ANORM, KL, KU, 'Z', AF( KOFF ), 3, WORK, $ INFO ) * * Check the error code from DLATMS. * IF( INFO.NE.0 ) THEN CALL ALAERH( PATH, 'DLATMS', INFO, 0, ' ', N, N, KL, $ KU, -1, IMAT, NFAIL, NERRS, NOUT ) GO TO 100 END IF IZERO = 0 * IF( N.GT.1 ) THEN CALL DCOPY( N-1, AF( 4 ), 3, A, 1 ) CALL DCOPY( N-1, AF( 3 ), 3, A( N+M+1 ), 1 ) END IF CALL DCOPY( N, AF( 2 ), 3, A( M+1 ), 1 ) ELSE * * Types 7-12: generate tridiagonal matrices with * unknown condition numbers. * IF( .NOT.ZEROT .OR. .NOT.DOTYPE( 7 ) ) THEN * * Generate a matrix with elements from [-1,1]. * CALL DLARNV( 2, ISEED, N+2*M, A ) IF( ANORM.NE.ONE ) $ CALL DSCAL( N+2*M, ANORM, A, 1 ) ELSE IF( IZERO.GT.0 ) THEN * * Reuse the last matrix by copying back the zeroed out * elements. * IF( IZERO.EQ.1 ) THEN A( N ) = Z( 2 ) IF( N.GT.1 ) $ A( 1 ) = Z( 3 ) ELSE IF( IZERO.EQ.N ) THEN A( 3*N-2 ) = Z( 1 ) A( 2*N-1 ) = Z( 2 ) ELSE A( 2*N-2+IZERO ) = Z( 1 ) A( N-1+IZERO ) = Z( 2 ) A( IZERO ) = Z( 3 ) END IF END IF * * If IMAT > 7, set one column of the matrix to 0. * IF( .NOT.ZEROT ) THEN IZERO = 0 ELSE IF( IMAT.EQ.8 ) THEN IZERO = 1 Z( 2 ) = A( N ) A( N ) = ZERO IF( N.GT.1 ) THEN Z( 3 ) = A( 1 ) A( 1 ) = ZERO END IF ELSE IF( IMAT.EQ.9 ) THEN IZERO = N Z( 1 ) = A( 3*N-2 ) Z( 2 ) = A( 2*N-1 ) A( 3*N-2 ) = ZERO A( 2*N-1 ) = ZERO ELSE IZERO = ( N+1 ) / 2 DO 20 I = IZERO, N - 1 A( 2*N-2+I ) = ZERO A( N-1+I ) = ZERO A( I ) = ZERO 20 CONTINUE A( 3*N-2 ) = ZERO A( 2*N-1 ) = ZERO END IF END IF * *+ TEST 1 * Factor A as L*U and compute the ratio * norm(L*U - A) / (n * norm(A) * EPS ) * CALL DCOPY( N+2*M, A, 1, AF, 1 ) SRNAMT = 'DGTTRF' CALL DGTTRF( N, AF, AF( M+1 ), AF( N+M+1 ), AF( N+2*M+1 ), $ IWORK, INFO ) * * Check error code from DGTTRF. * IF( INFO.NE.IZERO ) $ CALL ALAERH( PATH, 'DGTTRF', INFO, IZERO, ' ', N, N, 1, $ 1, -1, IMAT, NFAIL, NERRS, NOUT ) TRFCON = INFO.NE.0 * CALL DGTT01( N, A, A( M+1 ), A( N+M+1 ), AF, AF( M+1 ), $ AF( N+M+1 ), AF( N+2*M+1 ), IWORK, WORK, LDA, $ RWORK, RESULT( 1 ) ) * * Print the test ratio if it is .GE. THRESH. * IF( RESULT( 1 ).GE.THRESH ) THEN IF( NFAIL.EQ.0 .AND. NERRS.EQ.0 ) $ CALL ALAHD( NOUT, PATH ) WRITE( NOUT, FMT = 9999 )N, IMAT, 1, RESULT( 1 ) NFAIL = NFAIL + 1 END IF NRUN = NRUN + 1 * DO 50 ITRAN = 1, 2 TRANS = TRANSS( ITRAN ) IF( ITRAN.EQ.1 ) THEN NORM = 'O' ELSE NORM = 'I' END IF ANORM = DLANGT( NORM, N, A, A( M+1 ), A( N+M+1 ) ) * IF( .NOT.TRFCON ) THEN * * Use DGTTRS to solve for one column at a time of inv(A) * or inv(A^T), computing the maximum column sum as we * go. * AINVNM = ZERO DO 40 I = 1, N DO 30 J = 1, N X( J ) = ZERO 30 CONTINUE X( I ) = ONE CALL DGTTRS( TRANS, N, 1, AF, AF( M+1 ), $ AF( N+M+1 ), AF( N+2*M+1 ), IWORK, X, $ LDA, INFO ) AINVNM = MAX( AINVNM, DASUM( N, X, 1 ) ) 40 CONTINUE * * Compute RCONDC = 1 / (norm(A) * norm(inv(A)) * IF( ANORM.LE.ZERO .OR. AINVNM.LE.ZERO ) THEN RCONDC = ONE ELSE RCONDC = ( ONE / ANORM ) / AINVNM END IF IF( ITRAN.EQ.1 ) THEN RCONDO = RCONDC ELSE RCONDI = RCONDC END IF ELSE RCONDC = ZERO END IF * *+ TEST 7 * Estimate the reciprocal of the condition number of the * matrix. * SRNAMT = 'DGTCON' CALL DGTCON( NORM, N, AF, AF( M+1 ), AF( N+M+1 ), $ AF( N+2*M+1 ), IWORK, ANORM, RCOND, WORK, $ IWORK( N+1 ), INFO ) * * Check error code from DGTCON. * IF( INFO.NE.0 ) $ CALL ALAERH( PATH, 'DGTCON', INFO, 0, NORM, N, N, -1, $ -1, -1, IMAT, NFAIL, NERRS, NOUT ) * RESULT( 7 ) = DGET06( RCOND, RCONDC ) * * Print the test ratio if it is .GE. THRESH. * IF( RESULT( 7 ).GE.THRESH ) THEN IF( NFAIL.EQ.0 .AND. NERRS.EQ.0 ) $ CALL ALAHD( NOUT, PATH ) WRITE( NOUT, FMT = 9997 )NORM, N, IMAT, 7, $ RESULT( 7 ) NFAIL = NFAIL + 1 END IF NRUN = NRUN + 1 50 CONTINUE * * Skip the remaining tests if the matrix is singular. * IF( TRFCON ) $ GO TO 100 * DO 90 IRHS = 1, NNS NRHS = NSVAL( IRHS ) * * Generate NRHS random solution vectors. * IX = 1 DO 60 J = 1, NRHS CALL DLARNV( 2, ISEED, N, XACT( IX ) ) IX = IX + LDA 60 CONTINUE * DO 80 ITRAN = 1, 3 TRANS = TRANSS( ITRAN ) IF( ITRAN.EQ.1 ) THEN RCONDC = RCONDO ELSE RCONDC = RCONDI END IF * * Set the right hand side. * CALL DLAGTM( TRANS, N, NRHS, ONE, A, A( M+1 ), $ A( N+M+1 ), XACT, LDA, ZERO, B, LDA ) * *+ TEST 2 * Solve op(A) * X = B and compute the residual. * CALL DLACPY( 'Full', N, NRHS, B, LDA, X, LDA ) SRNAMT = 'DGTTRS' CALL DGTTRS( TRANS, N, NRHS, AF, AF( M+1 ), $ AF( N+M+1 ), AF( N+2*M+1 ), IWORK, X, $ LDA, INFO ) * * Check error code from DGTTRS. * IF( INFO.NE.0 ) $ CALL ALAERH( PATH, 'DGTTRS', INFO, 0, TRANS, N, N, $ -1, -1, NRHS, IMAT, NFAIL, NERRS, $ NOUT ) * CALL DLACPY( 'Full', N, NRHS, B, LDA, WORK, LDA ) CALL DGTT02( TRANS, N, NRHS, A, A( M+1 ), A( N+M+1 ), $ X, LDA, WORK, LDA, RWORK, RESULT( 2 ) ) * *+ TEST 3 * Check solution from generated exact solution. * CALL DGET04( N, NRHS, X, LDA, XACT, LDA, RCONDC, $ RESULT( 3 ) ) * *+ TESTS 4, 5, and 6 * Use iterative refinement to improve the solution. * SRNAMT = 'DGTRFS' CALL DGTRFS( TRANS, N, NRHS, A, A( M+1 ), A( N+M+1 ), $ AF, AF( M+1 ), AF( N+M+1 ), $ AF( N+2*M+1 ), IWORK, B, LDA, X, LDA, $ RWORK, RWORK( NRHS+1 ), WORK, $ IWORK( N+1 ), INFO ) * * Check error code from DGTRFS. * IF( INFO.NE.0 ) $ CALL ALAERH( PATH, 'DGTRFS', INFO, 0, TRANS, N, N, $ -1, -1, NRHS, IMAT, NFAIL, NERRS, $ NOUT ) * CALL DGET04( N, NRHS, X, LDA, XACT, LDA, RCONDC, $ RESULT( 4 ) ) CALL DGTT05( TRANS, N, NRHS, A, A( M+1 ), A( N+M+1 ), $ B, LDA, X, LDA, XACT, LDA, RWORK, $ RWORK( NRHS+1 ), RESULT( 5 ) ) * * Print information about the tests that did not pass * the threshold. * DO 70 K = 2, 6 IF( RESULT( K ).GE.THRESH ) THEN IF( NFAIL.EQ.0 .AND. NERRS.EQ.0 ) $ CALL ALAHD( NOUT, PATH ) WRITE( NOUT, FMT = 9998 )TRANS, N, NRHS, IMAT, $ K, RESULT( K ) NFAIL = NFAIL + 1 END IF 70 CONTINUE NRUN = NRUN + 5 80 CONTINUE 90 CONTINUE * 100 CONTINUE 110 CONTINUE * * Print a summary of the results. * CALL ALASUM( PATH, NOUT, NFAIL, NRUN, NERRS ) * 9999 FORMAT( 12X, 'N =', I5, ',', 10X, ' type ', I2, ', test(', I2, $ ') = ', G12.5 ) 9998 FORMAT( ' TRANS=''', A1, ''', N =', I5, ', NRHS=', I3, ', type ', $ I2, ', test(', I2, ') = ', G12.5 ) 9997 FORMAT( ' NORM =''', A1, ''', N =', I5, ',', 10X, ' type ', I2, $ ', test(', I2, ') = ', G12.5 ) RETURN * * End of DCHKGT * END
shengren/magma-1.6.1
testing/lin/dchkgt.f
FORTRAN
bsd-3-clause
15,690
package edu.gemini.spModel.data.property; import edu.gemini.shared.util.StringUtil; import edu.gemini.shared.util.immutable.None; import edu.gemini.shared.util.immutable.Option; import edu.gemini.shared.util.immutable.Some; import edu.gemini.spModel.type.SpTypeUtil; import java.beans.IntrospectionException; import java.beans.PropertyDescriptor; import java.beans.PropertyEditor; import java.beans.PropertyEditorManager; import java.lang.reflect.Method; import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; import java.util.stream.Collectors; /** * */ public final class PropertySupport { private static final Logger LOG = Logger.getLogger(PropertySupport.class.getName()); private static final String ENGINEERING_ATTR = "engineering"; private static final String QUERYABLE_ATTR = "queryable"; private static final String ITERABLE_ATTR = "iterable"; private static final String VOLATILE_ATTR = "volatile"; private static final String WRAPPED_TYPE_ATTR = "wrappedType"; // Gets the value of a boolean custom attribute, using defaultVal if not // specified. private static boolean isBooleanAttr(PropertyDescriptor pd, String attr, boolean defaultVal) { Boolean b = (Boolean) pd.getValue(attr); if (b == null) return defaultVal; return b; } // Sets the value of a boolean custom attribute. private static void setBooleanAttr(PropertyDescriptor pd, String attr, boolean newValue) { pd.setValue(attr, newValue); } public static boolean isEngineering(PropertyDescriptor pd) { return isBooleanAttr(pd, ENGINEERING_ATTR, false); } public static void setEngineering(PropertyDescriptor pd, boolean isEngineering) { setBooleanAttr(pd, ENGINEERING_ATTR, isEngineering); } /** * Returns <code>true</code> if the property changes automatically as a * result of updates to other properties in the same bean. */ public static boolean isVolatile(PropertyDescriptor pd) { return isBooleanAttr(pd, VOLATILE_ATTR, false); } /** * Sets whether this property changes automatically as a result of updates * to other properties in the same bean. */ public static void setVolatile(PropertyDescriptor pd, boolean isVolatile) { setBooleanAttr(pd, VOLATILE_ATTR, isVolatile); } public static boolean isQueryable(PropertyDescriptor pd) { return isBooleanAttr(pd, QUERYABLE_ATTR, true); } public static void setQueryable(PropertyDescriptor pd, boolean isQueryable) { setBooleanAttr(pd, QUERYABLE_ATTR, isQueryable); } public static boolean isIterable(PropertyDescriptor pd) { return isBooleanAttr(pd, ITERABLE_ATTR, true); } public static void setIterable(PropertyDescriptor pd, boolean isIterable) { setBooleanAttr(pd, ITERABLE_ATTR, isIterable); } /** * Returns the type of properties whose first order type wraps another * object. For example, {@link edu.gemini.shared.util.immutable.Option Option} * types contain other types. Given a property whose type is, for instance, * <code>Option&lt;UtilityWheel&gt;</code>, due to type erasure we have no * way at runtime to know the fundamental underlying type is actually * <code>UtilityWheel</code>. * * <p>The "wrapped type" attribute of property descriptors will be used to * keep this information so that it is available at runtime. */ public static Class<?> getWrappedType(PropertyDescriptor pd) { return (Class<?>) pd.getValue(WRAPPED_TYPE_ATTR); } /** * See {@link #getWrappedType(java.beans.PropertyDescriptor)}. */ public static void setWrappedType(PropertyDescriptor pd, Class<?> type) { pd.setValue(WRAPPED_TYPE_ATTR, type); } public static Map<String, PropertyDescriptor> map(Collection<PropertyDescriptor> props) { Map<String, PropertyDescriptor> res; res = new TreeMap<>(); for (PropertyDescriptor pd : props) { res.put(pd.getName(), pd); } return res; } public static Collection<PropertyDescriptor> filter(PropertyFilter filter, Collection<PropertyDescriptor> props) { ArrayList<PropertyDescriptor> res; res = new ArrayList<>(props.size()); for (PropertyDescriptor pd : props) { if (filter.accept(pd)) res.add(pd); } res.trimToSize(); return res; } public static Map<String, PropertyDescriptor> filter(PropertyFilter filter, Map<String, PropertyDescriptor> props) { return map(filter(filter, props.values())); } private static void _logEnumConvertFailure(String text, Class<Enum> propertyType) { LOG.log(Level.WARNING, "Could not convert '" + text + "' for type: " + propertyType.getName()); } private static Object getEnumValue(String text, Class<Enum> propertyType) { // Handle empty strings. if (text == null) return null; text = text.trim(); if ("".equals(text)) return null; // For backwards compatibility, call this method instead of just // Enum.valueOf(). Maybe after 2006B we can drop this. It will try // Enum.valueOf(), but failing that attempt to look up the corresponding // enum value based upon the display name (which is what we stored in // XML prior to 2006B). Object val = SpTypeUtil.oldValueOf(propertyType, text, null, false); if (val != null) return val; // Now we get a bit whacky and try to call a static method which has // to be called "get<propertytype>". This method is where conversion // from old SPType values that are no longer supported to new values // typically takes place. This is another thing that would be nice to // get rid of for 2007A. String tmp = propertyType.getName(); // trim off everything up to the last . For example, turn // edu.gemini.spModel.gemini.niri.Niri$Filter into // Niri$Filter int i = tmp.lastIndexOf('.'); tmp = tmp.substring(i+1); // Now trim everything before and including the last $ i = tmp.lastIndexOf('$'); tmp = tmp.substring(i + 1); String methodName = "get" + tmp; try { // ex: Filter.getFilter("H", Filter.J); // explicit default value Method m = propertyType.getMethod(methodName, String.class, propertyType); if (m != null) { Object res = m.invoke(null, text, null); if (res != null) return res; } } catch(Exception ex) { // give up } _logEnumConvertFailure(text, propertyType); return null; } private static final String NONE_STR = ""; private static Object _stringToValue(String text, PropertyEditor ed) { if (ed == null) return null; try { ed.setAsText(text); return ed.getValue(); } catch (IllegalArgumentException ex) { return null; } } private static Object _stringToValue(String text, Class<?> propertyType) { if (propertyType.isEnum()) { //noinspection unchecked return getEnumValue(text, (Class<Enum>) propertyType); } return _stringToValue(text, PropertyEditorManager.findEditor(propertyType)); } public static Object stringToValue(String text, PropertyDescriptor pd) { if (text == null) return null; Class<?> propertyType = pd.getPropertyType(); if (Option.class.isAssignableFrom(propertyType)) { if (NONE_STR.equals(text)) return None.instance(); propertyType = getWrappedType(pd); Object res = _stringToValue(text, propertyType); if (res == null) return None.instance(); return new Some<>(res); } return _stringToValue(text, propertyType); } public static List<Object> stringToValue(Collection<String> strings, PropertyDescriptor desc) { List<Object> res = new ArrayList<>(strings.size()); res.addAll(strings.stream().map(str -> stringToValue(str, desc)).collect(Collectors.toList())); return res; } private static String _valueToString(Object value, PropertyEditor ed) { if (ed == null) { return (value == null) ? "" : value.toString(); } else if (value == null) { return ""; } ed.setValue(value); return ed.getAsText(); } public static String valueToString(Object value, PropertyDescriptor desc) { if (value == null) return ""; if (desc == null) return value.toString(); Class<?> propertyType = desc.getPropertyType(); if (Option.class.isAssignableFrom(propertyType)) { if (None.instance().equals(value)) return NONE_STR; propertyType = getWrappedType(desc); // Unwrap the value value = ((Some<?>) value).getValue(); } if (propertyType.isEnum()) { return ((Enum) value).name(); } PropertyEditor ed = PropertyEditorManager.findEditor(propertyType); return _valueToString(value, ed); } public static List<String> valueToString(Collection<Object> values, PropertyDescriptor desc) { List<String> res = new ArrayList<>(values.size()); res.addAll(values.stream().map(val -> valueToString(val, desc)).collect(Collectors.toList())); return res; } public static PropertyDescriptor init(String propertyName, Class<?> beanClass, boolean isQueryable, boolean isIterable) { try { PropertyDescriptor pd = new PropertyDescriptor(propertyName, beanClass); pd.setDisplayName(StringUtil.toDisplayName(propertyName)); setQueryable(pd, isQueryable); setIterable(pd, isIterable); return pd; } catch (IntrospectionException ex) { throw new RuntimeException(ex); } } public static PropertyDescriptor init(String propertyName, String displayName, Class<?> beanClass, boolean isQueryable, boolean isIterable) { try { PropertyDescriptor pd = new PropertyDescriptor(propertyName, beanClass); pd.setDisplayName(displayName); setQueryable(pd, isQueryable); setIterable(pd, isIterable); return pd; } catch (IntrospectionException ex) { throw new RuntimeException(ex); } } }
arturog8m/ocs
bundle/edu.gemini.pot/src/main/java/edu/gemini/spModel/data/property/PropertySupport.java
Java
bsd-3-clause
10,774
// Copyright 2017 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 "gpu/command_buffer/client/command_buffer_direct_locked.h" namespace gpu { void CommandBufferDirectLocked::Flush(int32_t put_offset) { flush_count_++; client_put_offset_ = put_offset; if (!flush_locked_) DoFlush(); } CommandBuffer::State CommandBufferDirectLocked::WaitForTokenInRange( int32_t start, int32_t end) { State state = GetLastState(); if (state.error != error::kNoError || InRange(start, end, state.token)) { return state; } else { DoFlush(); return CommandBufferDirect::WaitForTokenInRange(start, end); } } CommandBuffer::State CommandBufferDirectLocked::WaitForGetOffsetInRange( uint32_t set_get_buffer_count, int32_t start, int32_t end) { State state = GetLastState(); if (state.error != error::kNoError || (InRange(start, end, state.get_offset) && (set_get_buffer_count == state.set_get_buffer_count))) { return state; } else { DoFlush(); return CommandBufferDirect::WaitForGetOffsetInRange(set_get_buffer_count, start, end); } } scoped_refptr<Buffer> CommandBufferDirectLocked::CreateTransferBuffer( uint32_t size, int32_t* id, TransferBufferAllocationOption option) { if (fail_create_transfer_buffer_) { *id = -1; return nullptr; } else { return CommandBufferDirect::CreateTransferBuffer(size, id, option); } } } // namespace gpu
nwjs/chromium.src
gpu/command_buffer/client/command_buffer_direct_locked.cc
C++
bsd-3-clause
1,598
////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2007-2013, Image Engine Design Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // * Neither the name of Image Engine Design nor the names of any // other contributors to this software may be used to endorse or // promote products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER 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. // ////////////////////////////////////////////////////////////////////////// #ifndef IE_CORE_MATRIXMULTIPLYOP_H #define IE_CORE_MATRIXMULTIPLYOP_H #include "IECore/ModifyOp.h" #include "IECore/ObjectParameter.h" #include "IECore/NumericParameter.h" namespace IECore { /// The MatrixMultiplyOp applies a matrix transformation to an array of vectors. /// It will transform the vectors according to their GeometricData::Interpretation. class MatrixMultiplyOp : public ModifyOp { public : IE_CORE_DECLARERUNTIMETYPED( MatrixMultiplyOp, ModifyOp ); MatrixMultiplyOp(); virtual ~MatrixMultiplyOp(); ObjectParameter * matrixParameter(); const ObjectParameter * matrixParameter() const; protected : virtual void modify( Object * toModify, const CompoundObject * operands ); private : ObjectParameterPtr m_matrixParameter; }; IE_CORE_DECLAREPTR( MatrixMultiplyOp ); } // namespace IECore #endif // IE_CORE_MATRIXMULTIPLYOP_H
code-google-com/cortex-vfx
include/IECore/MatrixMultiplyOp.h
C
bsd-3-clause
2,692
# -*- coding: utf-8 -*- # -*- coding: utf8 -*- """Autogenerated file - DO NOT EDIT If you spot a bug, please report it on the mailing list and/or change the generator.""" import os from ...base import (CommandLine, CommandLineInputSpec, SEMLikeCommandLine, TraitedSpec, File, Directory, traits, isdefined, InputMultiPath, OutputMultiPath) class BRAINSResizeInputSpec(CommandLineInputSpec): inputVolume = File(desc="Image To Scale", exists=True, argstr="--inputVolume %s") outputVolume = traits.Either(traits.Bool, File(), hash_files=False, desc="Resulting scaled image", argstr="--outputVolume %s") pixelType = traits.Enum("float", "short", "ushort", "int", "uint", "uchar", "binary", desc="Specifies the pixel type for the input/output images. The \'binary\' pixel type uses a modified algorithm whereby the image is read in as unsigned char, a signed distance map is created, signed distance map is resampled, and then a thresholded image of type unsigned char is written to disk.", argstr="--pixelType %s") scaleFactor = traits.Float(desc="The scale factor for the image spacing.", argstr="--scaleFactor %f") class BRAINSResizeOutputSpec(TraitedSpec): outputVolume = File(desc="Resulting scaled image", exists=True) class BRAINSResize(SEMLikeCommandLine): """title: Resize Image (BRAINS) category: Registration description: This program is useful for downsampling an image by a constant scale factor. version: 3.0.0 license: https://www.nitrc.org/svn/brains/BuildScripts/trunk/License.txt contributor: This tool was developed by Hans Johnson. acknowledgements: The development of this tool was supported by funding from grants NS050568 and NS40068 from the National Institute of Neurological Disorders and Stroke and grants MH31593, MH40856, from the National Institute of Mental Health. """ input_spec = BRAINSResizeInputSpec output_spec = BRAINSResizeOutputSpec _cmd = " BRAINSResize " _outputs_filenames = {'outputVolume': 'outputVolume.nii'} _redirect_x = False
mick-d/nipype
nipype/interfaces/semtools/registration/brainsresize.py
Python
bsd-3-clause
2,101
// Copyright 2014 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 "sync/internal_api/public/attachments/attachment_uploader_impl.h" #include <string> #include <utility> #include <vector> #include "base/bind.h" #include "base/callback.h" #include "base/memory/ref_counted.h" #include "base/memory/ref_counted_memory.h" #include "base/message_loop/message_loop.h" #include "base/run_loop.h" #include "base/strings/string_number_conversions.h" #include "base/strings/stringprintf.h" #include "base/synchronization/lock.h" #include "base/test/histogram_tester.h" #include "base/thread_task_runner_handle.h" #include "base/threading/non_thread_safe.h" #include "base/threading/thread.h" #include "google_apis/gaia/fake_oauth2_token_service.h" #include "google_apis/gaia/gaia_constants.h" #include "google_apis/gaia/oauth2_token_service_request.h" #include "net/http/http_status_code.h" #include "net/test/embedded_test_server/embedded_test_server.h" #include "net/test/embedded_test_server/http_request.h" #include "net/test/embedded_test_server/http_response.h" #include "net/url_request/url_request_test_util.h" #include "sync/api/attachments/attachment.h" #include "sync/internal_api/public/attachments/attachment_util.h" #include "sync/internal_api/public/base/model_type.h" #include "sync/protocol/sync.pb.h" #include "testing/gmock/include/gmock/gmock-matchers.h" #include "testing/gtest/include/gtest/gtest.h" namespace { const char kAttachmentData[] = "some data"; const char kAccountId[] = "some-account-id"; const char kAccessToken[] = "some-access-token"; const char kContentTypeValue[] = "application/octet-stream"; const char kXGoogHash[] = "X-Goog-Hash"; const char kAttachments[] = "/attachments/"; const char kStoreBirthday[] = "\x46\xFF\xDD\xE0\x74\x3A\x48\xFD\x9D\x06\x93\x3C\x61\x8E\xA5\x70\x09\x59" "\x99\x05\x61\x46\x21\x61\x1B\x03\xD3\x02\x60\xCD\x41\x55\xFE\x26\x15\xD7" "\x0C"; const char kBase64URLSafeStoreBirthday[] = "Rv_d4HQ6SP2dBpM8YY6lcAlZmQVhRiFhGwPTAmDNQVX-JhXXDA"; const char kSyncStoreBirthdayHeader[] = "X-Sync-Store-Birthday"; const char kSyncDataTypeIdHeader[] = "X-Sync-Data-Type-Id"; const syncer::ModelType kModelType = syncer::ModelType::ARTICLES; } // namespace namespace syncer { using net::test_server::BasicHttpResponse; using net::test_server::HttpRequest; using net::test_server::HttpResponse; class RequestHandler; // A mock implementation of an OAuth2TokenService. // // Use |SetResponse| to vary the response to token requests. // // Use |num_invalidate_token| and |last_token_invalidated| to check the number // of invalidate token operations performed and the last token invalidated. class MockOAuth2TokenService : public FakeOAuth2TokenService { public: MockOAuth2TokenService(); ~MockOAuth2TokenService() override; void SetResponse(const GoogleServiceAuthError& error, const std::string& access_token, const base::Time& expiration); int num_invalidate_token() const { return num_invalidate_token_; } const std::string& last_token_invalidated() const { return last_token_invalidated_; } protected: void FetchOAuth2Token(RequestImpl* request, const std::string& account_id, net::URLRequestContextGetter* getter, const std::string& client_id, const std::string& client_secret, const ScopeSet& scopes) override; void InvalidateAccessTokenImpl(const std::string& account_id, const std::string& client_id, const ScopeSet& scopes, const std::string& access_token) override; private: GoogleServiceAuthError response_error_; std::string response_access_token_; base::Time response_expiration_; int num_invalidate_token_; std::string last_token_invalidated_; }; MockOAuth2TokenService::MockOAuth2TokenService() : response_error_(GoogleServiceAuthError::AuthErrorNone()), response_access_token_(kAccessToken), response_expiration_(base::Time::Max()), num_invalidate_token_(0) { } MockOAuth2TokenService::~MockOAuth2TokenService() { } void MockOAuth2TokenService::SetResponse(const GoogleServiceAuthError& error, const std::string& access_token, const base::Time& expiration) { response_error_ = error; response_access_token_ = access_token; response_expiration_ = expiration; } void MockOAuth2TokenService::FetchOAuth2Token( RequestImpl* request, const std::string& account_id, net::URLRequestContextGetter* getter, const std::string& client_id, const std::string& client_secret, const ScopeSet& scopes) { base::MessageLoop::current()->PostTask( FROM_HERE, base::Bind(&OAuth2TokenService::RequestImpl::InformConsumer, request->AsWeakPtr(), response_error_, response_access_token_, response_expiration_)); } void MockOAuth2TokenService::InvalidateAccessTokenImpl( const std::string& account_id, const std::string& client_id, const ScopeSet& scopes, const std::string& access_token) { ++num_invalidate_token_; last_token_invalidated_ = access_token; } class TokenServiceProvider : public OAuth2TokenServiceRequest::TokenServiceProvider, base::NonThreadSafe { public: explicit TokenServiceProvider(OAuth2TokenService* token_service); // OAuth2TokenService::TokenServiceProvider implementation. scoped_refptr<base::SingleThreadTaskRunner> GetTokenServiceTaskRunner() override; OAuth2TokenService* GetTokenService() override; private: ~TokenServiceProvider() override; scoped_refptr<base::SingleThreadTaskRunner> task_runner_; OAuth2TokenService* token_service_; }; TokenServiceProvider::TokenServiceProvider(OAuth2TokenService* token_service) : task_runner_(base::ThreadTaskRunnerHandle::Get()), token_service_(token_service) { DCHECK(token_service_); } TokenServiceProvider::~TokenServiceProvider() { } scoped_refptr<base::SingleThreadTaskRunner> TokenServiceProvider::GetTokenServiceTaskRunner() { return task_runner_; } OAuth2TokenService* TokenServiceProvider::GetTokenService() { DCHECK(task_runner_->BelongsToCurrentThread()); return token_service_; } // Text fixture for AttachmentUploaderImpl test. // // This fixture provides an embedded HTTP server and a mock OAuth2 token service // for interacting with AttachmentUploaderImpl class AttachmentUploaderImplTest : public testing::Test, public base::NonThreadSafe { public: void OnRequestReceived(const HttpRequest& request); protected: AttachmentUploaderImplTest(); void SetUp() override; void TearDown() override; // Run the message loop until UploadDone has been invoked |num_uploads| times. void RunAndWaitFor(int num_uploads); // Upload an attachment and have the server respond with |status_code|. // // Returns the attachment that was uploaded. Attachment UploadAndRespondWith(const net::HttpStatusCode& status_code); scoped_ptr<AttachmentUploader>& uploader(); const AttachmentUploader::UploadCallback& upload_callback() const; std::vector<HttpRequest>& http_requests_received(); std::vector<AttachmentUploader::UploadResult>& upload_results(); std::vector<AttachmentId>& attachment_ids(); MockOAuth2TokenService& token_service(); base::MessageLoopForIO& message_loop(); RequestHandler& request_handler(); private: // An UploadCallback invoked by AttachmentUploaderImpl. void UploadDone(const AttachmentUploader::UploadResult& result, const AttachmentId& attachment_id); base::MessageLoopForIO message_loop_; scoped_refptr<net::URLRequestContextGetter> url_request_context_getter_; scoped_ptr<RequestHandler> request_handler_; scoped_ptr<AttachmentUploader> uploader_; AttachmentUploader::UploadCallback upload_callback_; net::EmbeddedTestServer server_; // A closure that signals an upload has finished. base::Closure signal_upload_done_; std::vector<HttpRequest> http_requests_received_; std::vector<AttachmentUploader::UploadResult> upload_results_; std::vector<AttachmentId> attachment_ids_; scoped_ptr<MockOAuth2TokenService> token_service_; // Must be last data member. base::WeakPtrFactory<AttachmentUploaderImplTest> weak_ptr_factory_; }; // Handles HTTP requests received by the EmbeddedTestServer. // // Responds with HTTP_OK by default. See |SetStatusCode|. class RequestHandler : public base::NonThreadSafe { public: // Construct a RequestHandler that will PostTask to |test| using // |test_task_runner|. RequestHandler( const scoped_refptr<base::SingleThreadTaskRunner>& test_task_runner, const base::WeakPtr<AttachmentUploaderImplTest>& test); ~RequestHandler(); scoped_ptr<HttpResponse> HandleRequest(const HttpRequest& request); // Set the HTTP status code to respond with. void SetStatusCode(const net::HttpStatusCode& status_code); // Returns the HTTP status code that will be used in responses. net::HttpStatusCode GetStatusCode() const; private: // Protects status_code_. mutable base::Lock mutex_; net::HttpStatusCode status_code_; scoped_refptr<base::SingleThreadTaskRunner> test_task_runner_; base::WeakPtr<AttachmentUploaderImplTest> test_; }; AttachmentUploaderImplTest::AttachmentUploaderImplTest() : weak_ptr_factory_(this) { } void AttachmentUploaderImplTest::OnRequestReceived(const HttpRequest& request) { DCHECK(CalledOnValidThread()); http_requests_received_.push_back(request); } void AttachmentUploaderImplTest::SetUp() { DCHECK(CalledOnValidThread()); request_handler_.reset(new RequestHandler(message_loop_.task_runner(), weak_ptr_factory_.GetWeakPtr())); url_request_context_getter_ = new net::TestURLRequestContextGetter(message_loop_.task_runner()); ASSERT_TRUE(server_.Start()); server_.RegisterRequestHandler( base::Bind(&RequestHandler::HandleRequest, base::Unretained(request_handler_.get()))); GURL url(base::StringPrintf("http://localhost:%u/", server_.port())); token_service_.reset(new MockOAuth2TokenService); scoped_refptr<OAuth2TokenServiceRequest::TokenServiceProvider> token_service_provider(new TokenServiceProvider(token_service_.get())); OAuth2TokenService::ScopeSet scopes; scopes.insert(GaiaConstants::kChromeSyncOAuth2Scope); uploader().reset(new AttachmentUploaderImpl( url, url_request_context_getter_, kAccountId, scopes, token_service_provider, std::string(kStoreBirthday), kModelType)); upload_callback_ = base::Bind(&AttachmentUploaderImplTest::UploadDone, base::Unretained(this)); } void AttachmentUploaderImplTest::TearDown() { base::RunLoop().RunUntilIdle(); } void AttachmentUploaderImplTest::RunAndWaitFor(int num_uploads) { for (int i = 0; i < num_uploads; ++i) { // Run the loop until one upload completes. base::RunLoop run_loop; signal_upload_done_ = run_loop.QuitClosure(); run_loop.Run(); } } Attachment AttachmentUploaderImplTest::UploadAndRespondWith( const net::HttpStatusCode& status_code) { token_service().AddAccount(kAccountId); request_handler().SetStatusCode(status_code); scoped_refptr<base::RefCountedString> some_data(new base::RefCountedString); some_data->data() = kAttachmentData; Attachment attachment = Attachment::Create(some_data); uploader()->UploadAttachment(attachment, upload_callback()); return attachment; } scoped_ptr<AttachmentUploader>& AttachmentUploaderImplTest::uploader() { return uploader_; } const AttachmentUploader::UploadCallback& AttachmentUploaderImplTest::upload_callback() const { return upload_callback_; } std::vector<HttpRequest>& AttachmentUploaderImplTest::http_requests_received() { return http_requests_received_; } std::vector<AttachmentUploader::UploadResult>& AttachmentUploaderImplTest::upload_results() { return upload_results_; } std::vector<AttachmentId>& AttachmentUploaderImplTest::attachment_ids() { return attachment_ids_; } MockOAuth2TokenService& AttachmentUploaderImplTest::token_service() { return *token_service_; } base::MessageLoopForIO& AttachmentUploaderImplTest::message_loop() { return message_loop_; } RequestHandler& AttachmentUploaderImplTest::request_handler() { return *request_handler_; } void AttachmentUploaderImplTest::UploadDone( const AttachmentUploader::UploadResult& result, const AttachmentId& attachment_id) { DCHECK(CalledOnValidThread()); upload_results_.push_back(result); attachment_ids_.push_back(attachment_id); DCHECK(!signal_upload_done_.is_null()); signal_upload_done_.Run(); } RequestHandler::RequestHandler( const scoped_refptr<base::SingleThreadTaskRunner>& test_task_runner, const base::WeakPtr<AttachmentUploaderImplTest>& test) : status_code_(net::HTTP_OK), test_task_runner_(test_task_runner), test_(test) { DetachFromThread(); } RequestHandler::~RequestHandler() { DetachFromThread(); } scoped_ptr<HttpResponse> RequestHandler::HandleRequest( const HttpRequest& request) { DCHECK(CalledOnValidThread()); test_task_runner_->PostTask( FROM_HERE, base::Bind( &AttachmentUploaderImplTest::OnRequestReceived, test_, request)); scoped_ptr<BasicHttpResponse> response(new BasicHttpResponse); response->set_code(GetStatusCode()); response->set_content_type("text/plain"); return std::move(response); } void RequestHandler::SetStatusCode(const net::HttpStatusCode& status_code) { base::AutoLock lock(mutex_); status_code_ = status_code; } net::HttpStatusCode RequestHandler::GetStatusCode() const { base::AutoLock lock(mutex_); return status_code_; } TEST_F(AttachmentUploaderImplTest, GetURLForAttachmentId_NoPath) { AttachmentId id = AttachmentId::Create(0, 0); std::string unique_id = id.GetProto().unique_id(); GURL sync_service_url("https://example.com"); EXPECT_EQ("https://example.com/attachments/" + unique_id, AttachmentUploaderImpl::GetURLForAttachmentId(sync_service_url, id) .spec()); } TEST_F(AttachmentUploaderImplTest, GetURLForAttachmentId_JustSlash) { AttachmentId id = AttachmentId::Create(0, 0); std::string unique_id = id.GetProto().unique_id(); GURL sync_service_url("https://example.com/"); EXPECT_EQ("https://example.com/attachments/" + unique_id, AttachmentUploaderImpl::GetURLForAttachmentId(sync_service_url, id) .spec()); } TEST_F(AttachmentUploaderImplTest, GetURLForAttachmentId_Path) { AttachmentId id = AttachmentId::Create(0, 0); std::string unique_id = id.GetProto().unique_id(); GURL sync_service_url("https://example.com/service"); EXPECT_EQ("https://example.com/service/attachments/" + unique_id, AttachmentUploaderImpl::GetURLForAttachmentId(sync_service_url, id) .spec()); } TEST_F(AttachmentUploaderImplTest, GetURLForAttachmentId_PathAndSlash) { AttachmentId id = AttachmentId::Create(0, 0); std::string unique_id = id.GetProto().unique_id(); GURL sync_service_url("https://example.com/service/"); EXPECT_EQ("https://example.com/service/attachments/" + unique_id, AttachmentUploaderImpl::GetURLForAttachmentId(sync_service_url, id) .spec()); } // Verify the "happy case" of uploading an attachment. // // Token is requested, token is returned, HTTP request is made, attachment is // received by server. TEST_F(AttachmentUploaderImplTest, UploadAttachment_HappyCase) { Attachment attachment = UploadAndRespondWith(net::HTTP_OK); base::HistogramTester histogram_tester; // Run until the done callback is invoked. RunAndWaitFor(1); // See that the done callback was invoked with the right arguments. ASSERT_EQ(1U, upload_results().size()); EXPECT_EQ(AttachmentUploader::UPLOAD_SUCCESS, upload_results()[0]); ASSERT_EQ(1U, attachment_ids().size()); EXPECT_EQ(attachment.GetId(), attachment_ids()[0]); histogram_tester.ExpectUniqueSample("Sync.Attachments.UploadResponseCode", net::HTTP_OK, 1); // See that the HTTP server received one request. ASSERT_EQ(1U, http_requests_received().size()); const HttpRequest& http_request = http_requests_received().front(); EXPECT_EQ(net::test_server::METHOD_POST, http_request.method); std::string expected_relative_url(kAttachments + attachment.GetId().GetProto().unique_id()); EXPECT_EQ(expected_relative_url, http_request.relative_url); EXPECT_TRUE(http_request.has_content); EXPECT_EQ(kAttachmentData, http_request.content); } // Verify the request contains the appropriate headers. TEST_F(AttachmentUploaderImplTest, UploadAttachment_Headers) { Attachment attachment = UploadAndRespondWith(net::HTTP_OK); // Run until the done callback is invoked. RunAndWaitFor(1); // See that the done callback was invoked with the right arguments. ASSERT_EQ(1U, upload_results().size()); EXPECT_EQ(AttachmentUploader::UPLOAD_SUCCESS, upload_results()[0]); ASSERT_EQ(1U, attachment_ids().size()); EXPECT_EQ(attachment.GetId(), attachment_ids()[0]); // See that the HTTP server received one request. ASSERT_EQ(1U, http_requests_received().size()); const HttpRequest& http_request = http_requests_received().front(); const std::string auth_header_value(std::string("Bearer ") + kAccessToken); EXPECT_THAT(http_request.headers, testing::Contains(testing::Pair( net::HttpRequestHeaders::kAuthorization, auth_header_value))); EXPECT_THAT( http_request.headers, testing::Contains(testing::Key(net::HttpRequestHeaders::kContentLength))); EXPECT_THAT(http_request.headers, testing::Contains(testing::Pair( net::HttpRequestHeaders::kContentType, kContentTypeValue))); EXPECT_THAT(http_request.headers, testing::Contains(testing::Key(kXGoogHash))); EXPECT_THAT( http_request.headers, testing::Contains(testing::Key(net::HttpRequestHeaders::kUserAgent))); EXPECT_THAT(http_request.headers, testing::Contains(testing::Pair(kSyncStoreBirthdayHeader, kBase64URLSafeStoreBirthday))); EXPECT_THAT(http_request.headers, testing::Contains(testing::Pair( kSyncDataTypeIdHeader, base::IntToString( GetSpecificsFieldNumberFromModelType(kModelType))))); } // Verify two overlapping calls to upload the same attachment result in only one // HTTP request. TEST_F(AttachmentUploaderImplTest, UploadAttachment_Collapse) { Attachment attachment1 = UploadAndRespondWith(net::HTTP_OK); Attachment attachment2 = attachment1; uploader()->UploadAttachment(attachment2, upload_callback()); // Wait for upload_callback() to be invoked twice. RunAndWaitFor(2); // See there was only one request. EXPECT_EQ(1U, http_requests_received().size()); } // Verify that the internal state associated with an upload is removed when the // uplaod finishes. We do this by issuing two non-overlapping uploads for the // same attachment and see that it results in two HTTP requests. TEST_F(AttachmentUploaderImplTest, UploadAttachment_CleanUpAfterUpload) { Attachment attachment1 = UploadAndRespondWith(net::HTTP_OK); // Wait for upload_callback() to be invoked before starting the second upload. RunAndWaitFor(1); Attachment attachment2 = attachment1; uploader()->UploadAttachment(attachment2, upload_callback()); // Wait for upload_callback() to be invoked a second time. RunAndWaitFor(1); // See there were two requests. ASSERT_EQ(2U, http_requests_received().size()); } // Verify that we do not issue an HTTP request when we fail to receive an access // token. // // Token is requested, no token is returned, no HTTP request is made TEST_F(AttachmentUploaderImplTest, UploadAttachment_FailToGetToken) { // Note, we won't receive a token because we did not add kAccountId to the // token service. scoped_refptr<base::RefCountedString> some_data(new base::RefCountedString); some_data->data() = kAttachmentData; Attachment attachment = Attachment::Create(some_data); uploader()->UploadAttachment(attachment, upload_callback()); base::HistogramTester histogram_tester; RunAndWaitFor(1); // See that the done callback was invoked. ASSERT_EQ(1U, upload_results().size()); EXPECT_EQ(AttachmentUploader::UPLOAD_TRANSIENT_ERROR, upload_results()[0]); ASSERT_EQ(1U, attachment_ids().size()); EXPECT_EQ(attachment.GetId(), attachment_ids()[0]); histogram_tester.ExpectTotalCount("Sync.Attachments.UploadResponseCode", 0); // See that no HTTP request was received. ASSERT_EQ(0U, http_requests_received().size()); } // Verify behavior when the server returns "503 Service Unavailable". TEST_F(AttachmentUploaderImplTest, UploadAttachment_ServiceUnavilable) { Attachment attachment = UploadAndRespondWith(net::HTTP_SERVICE_UNAVAILABLE); base::HistogramTester histogram_tester; RunAndWaitFor(1); // See that the done callback was invoked. ASSERT_EQ(1U, upload_results().size()); EXPECT_EQ(AttachmentUploader::UPLOAD_TRANSIENT_ERROR, upload_results()[0]); ASSERT_EQ(1U, attachment_ids().size()); EXPECT_EQ(attachment.GetId(), attachment_ids()[0]); histogram_tester.ExpectUniqueSample("Sync.Attachments.UploadResponseCode", net::HTTP_SERVICE_UNAVAILABLE, 1); // See that the HTTP server received one request. ASSERT_EQ(1U, http_requests_received().size()); const HttpRequest& http_request = http_requests_received().front(); EXPECT_EQ(net::test_server::METHOD_POST, http_request.method); std::string expected_relative_url(kAttachments + attachment.GetId().GetProto().unique_id()); EXPECT_EQ(expected_relative_url, http_request.relative_url); EXPECT_TRUE(http_request.has_content); EXPECT_EQ(kAttachmentData, http_request.content); // See that we did not invalidate the token. ASSERT_EQ(0, token_service().num_invalidate_token()); } // Verify that we "403 Forbidden" as a non-transient error. TEST_F(AttachmentUploaderImplTest, UploadAttachment_Forbidden) { Attachment attachment = UploadAndRespondWith(net::HTTP_FORBIDDEN); base::HistogramTester histogram_tester; RunAndWaitFor(1); // See that the done callback was invoked. ASSERT_EQ(1U, upload_results().size()); EXPECT_EQ(AttachmentUploader::UPLOAD_UNSPECIFIED_ERROR, upload_results()[0]); ASSERT_EQ(1U, attachment_ids().size()); EXPECT_EQ(attachment.GetId(), attachment_ids()[0]); histogram_tester.ExpectUniqueSample("Sync.Attachments.UploadResponseCode", net::HTTP_FORBIDDEN, 1); // See that the HTTP server received one request. ASSERT_EQ(1U, http_requests_received().size()); const HttpRequest& http_request = http_requests_received().front(); EXPECT_EQ(net::test_server::METHOD_POST, http_request.method); std::string expected_relative_url(kAttachments + attachment.GetId().GetProto().unique_id()); EXPECT_EQ(expected_relative_url, http_request.relative_url); EXPECT_TRUE(http_request.has_content); EXPECT_EQ(kAttachmentData, http_request.content); // See that we did not invalidate the token. ASSERT_EQ(0, token_service().num_invalidate_token()); } // Verify that when we receive an "401 Unauthorized" we invalidate the access // token. TEST_F(AttachmentUploaderImplTest, UploadAttachment_BadToken) { Attachment attachment = UploadAndRespondWith(net::HTTP_UNAUTHORIZED); base::HistogramTester histogram_tester; RunAndWaitFor(1); // See that the done callback was invoked. ASSERT_EQ(1U, upload_results().size()); EXPECT_EQ(AttachmentUploader::UPLOAD_TRANSIENT_ERROR, upload_results()[0]); ASSERT_EQ(1U, attachment_ids().size()); EXPECT_EQ(attachment.GetId(), attachment_ids()[0]); histogram_tester.ExpectUniqueSample("Sync.Attachments.UploadResponseCode", net::HTTP_UNAUTHORIZED, 1); // See that the HTTP server received one request. ASSERT_EQ(1U, http_requests_received().size()); const HttpRequest& http_request = http_requests_received().front(); EXPECT_EQ(net::test_server::METHOD_POST, http_request.method); std::string expected_relative_url(kAttachments + attachment.GetId().GetProto().unique_id()); EXPECT_EQ(expected_relative_url, http_request.relative_url); EXPECT_TRUE(http_request.has_content); EXPECT_EQ(kAttachmentData, http_request.content); // See that we invalidated the token. ASSERT_EQ(1, token_service().num_invalidate_token()); } TEST_F(AttachmentUploaderImplTest, FormatCrc32cHash) { scoped_refptr<base::RefCountedString> empty(new base::RefCountedString); empty->data() = ""; EXPECT_EQ("AAAAAA==", AttachmentUploaderImpl::FormatCrc32cHash(ComputeCrc32c(empty))); scoped_refptr<base::RefCountedString> hello_world(new base::RefCountedString); hello_world->data() = "hello world"; EXPECT_EQ("yZRlqg==", AttachmentUploaderImpl::FormatCrc32cHash( ComputeCrc32c(hello_world))); } // TODO(maniscalco): Add test case for when we are uploading an attachment that // already exists. 409 Conflict? (bug 379825) } // namespace syncer
js0701/chromium-crosswalk
sync/internal_api/attachments/attachment_uploader_impl_unittest.cc
C++
bsd-3-clause
25,738
#!/usr/bin/env 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 where the target certificate is a CA rather than an end-entity certificate (based on the basic constraints extension).""" import sys sys.path += ['../..'] import gencerts # Self-signed root certificate. root = gencerts.create_self_signed_root_certificate('Root') # Intermediate certificate. intermediate = gencerts.create_intermediate_certificate('Intermediate', root) # Target certificate (is also a CA) target = gencerts.create_intermediate_certificate('Target', intermediate) chain = [target, intermediate, root] gencerts.write_chain(__doc__, chain, 'chain.pem')
chromium/chromium
net/data/verify_certificate_chain_unittest/target-not-end-entity/generate-chains.py
Python
bsd-3-clause
782
module If where -- what's a reasonable type to give to `if_` so that we can verify `bog` ? {-@ type TT = {v: Bool | (Prop v)} @-} {-@ type FF = {v: Bool | not (Prop v)} @-} {-@ if_ :: b:Bool -> x:a -> y:a -> a @-} if_ :: Bool -> a -> a -> a if_ True x _ = x if_ False _ y = y {-@ bog :: Nat @-} bog :: Int bog = let b = (0 < 1) -- :: TT xs = [1 , 2, 3] -- :: [Nat] ys = [-1, -2, -3] -- :: [Int] zs = if_ b xs ys -- :: [Nat] in case xs of h:_ -> h _ -> 0
mightymoose/liquidhaskell
tests/todo/if.hs
Haskell
bsd-3-clause
527
// Copyright 2013 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 "base/command_line.h" #include "base/files/file_path.h" #include "base/message_loop/message_loop.h" #include "base/run_loop.h" #include "base/strings/utf_string_conversions.h" #include "chrome/browser/chrome_notification_types.h" #include "chrome/browser/content_settings/tab_specific_content_settings.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/search_engines/template_url_service_factory.h" #include "chrome/browser/ui/blocked_content/popup_blocker_tab_helper.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_commands.h" #include "chrome/browser/ui/browser_finder.h" #include "chrome/browser/ui/browser_list.h" #include "chrome/browser/ui/browser_window.h" #include "chrome/browser/ui/location_bar/location_bar.h" #include "chrome/browser/ui/omnibox/omnibox_edit_model.h" #include "chrome/browser/ui/omnibox/omnibox_view.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/test_switches.h" #include "chrome/test/base/ui_test_utils.h" #include "components/app_modal/javascript_app_modal_dialog.h" #include "components/app_modal/native_app_modal_dialog.h" #include "components/content_settings/core/browser/host_content_settings_map.h" #include "components/omnibox/autocomplete_match.h" #include "components/omnibox/autocomplete_result.h" #include "content/public/browser/navigation_controller.h" #include "content/public/browser/notification_registrar.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_contents_observer.h" #include "content/public/common/url_constants.h" #include "content/public/test/browser_test_utils.h" #include "content/public/test/test_navigation_observer.h" #include "net/dns/mock_host_resolver.h" #include "net/test/embedded_test_server/embedded_test_server.h" #include "testing/gtest/include/gtest/gtest.h" using content::WebContents; namespace { // Counts the number of RenderViewHosts created. class CountRenderViewHosts : public content::NotificationObserver { public: CountRenderViewHosts() : count_(0) { registrar_.Add(this, content::NOTIFICATION_WEB_CONTENTS_RENDER_VIEW_HOST_CREATED, content::NotificationService::AllSources()); } ~CountRenderViewHosts() override {} int GetRenderViewHostCreatedCount() const { return count_; } private: void Observe(int type, const content::NotificationSource& source, const content::NotificationDetails& details) override { count_++; } content::NotificationRegistrar registrar_; int count_; DISALLOW_COPY_AND_ASSIGN(CountRenderViewHosts); }; class CloseObserver : public content::WebContentsObserver { public: explicit CloseObserver(WebContents* contents) : content::WebContentsObserver(contents) {} void Wait() { close_loop_.Run(); } void WebContentsDestroyed() override { close_loop_.Quit(); } private: base::RunLoop close_loop_; DISALLOW_COPY_AND_ASSIGN(CloseObserver); }; class BrowserActivationObserver : public chrome::BrowserListObserver { public: explicit BrowserActivationObserver(chrome::HostDesktopType desktop_type) : browser_(chrome::FindLastActiveWithHostDesktopType(desktop_type)), observed_(false) { BrowserList::AddObserver(this); } ~BrowserActivationObserver() override { BrowserList::RemoveObserver(this); } void WaitForActivation() { if (observed_) return; message_loop_runner_ = new content::MessageLoopRunner; message_loop_runner_->Run(); } private: // chrome::BrowserListObserver: void OnBrowserSetLastActive(Browser* browser) override { if (browser == browser_) return; if (browser->host_desktop_type() != browser_->host_desktop_type()) return; observed_ = true; if (message_loop_runner_.get() && message_loop_runner_->loop_running()) message_loop_runner_->Quit(); } Browser* browser_; bool observed_; scoped_refptr<content::MessageLoopRunner> message_loop_runner_; DISALLOW_COPY_AND_ASSIGN(BrowserActivationObserver); }; class PopupBlockerBrowserTest : public InProcessBrowserTest { public: PopupBlockerBrowserTest() {} ~PopupBlockerBrowserTest() override {} void SetUpOnMainThread() override { InProcessBrowserTest::SetUpOnMainThread(); host_resolver()->AddRule("*", "127.0.0.1"); ASSERT_TRUE(embedded_test_server()->InitializeAndWaitUntilReady()); } int GetBlockedContentsCount() { // Do a round trip to the renderer first to flush any in-flight IPCs to // create a to-be-blocked window. WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents(); CHECK(content::ExecuteScript(tab, std::string())); PopupBlockerTabHelper* popup_blocker_helper = PopupBlockerTabHelper::FromWebContents(tab); return popup_blocker_helper->GetBlockedPopupsCount(); } enum WhatToExpect { ExpectPopup, ExpectTab }; enum ShouldCheckTitle { CheckTitle, DontCheckTitle }; void NavigateAndCheckPopupShown(const GURL& url, WhatToExpect what_to_expect) { content::WindowedNotificationObserver observer( chrome::NOTIFICATION_TAB_ADDED, content::NotificationService::AllSources()); ui_test_utils::NavigateToURL(browser(), url); observer.Wait(); if (what_to_expect == ExpectPopup) { ASSERT_EQ(2u, chrome::GetBrowserCount(browser()->profile(), browser()->host_desktop_type())); } else { ASSERT_EQ(1u, chrome::GetBrowserCount(browser()->profile(), browser()->host_desktop_type())); ASSERT_EQ(2, browser()->tab_strip_model()->count()); // Check that we always create foreground tabs. ASSERT_EQ(1, browser()->tab_strip_model()->active_index()); } ASSERT_EQ(0, GetBlockedContentsCount()); } // Navigates to the test indicated by |test_name| using |browser| which is // expected to try to open a popup. Verifies that the popup was blocked and // then opens the blocked popup. Once the popup stopped loading, verifies // that the title of the page is "PASS" if |check_title| is set. // // If |what_to_expect| is ExpectPopup, the popup is expected to open a new // window, or a background tab if it is false. // // Returns the WebContents of the launched popup. WebContents* RunCheckTest(Browser* browser, const std::string& test_name, WhatToExpect what_to_expect, ShouldCheckTitle check_title) { GURL url(embedded_test_server()->GetURL(test_name)); CountRenderViewHosts counter; ui_test_utils::NavigateToURL(browser, url); // Since the popup blocker blocked the window.open, there should be only one // tab. EXPECT_EQ(1u, chrome::GetBrowserCount(browser->profile(), browser->host_desktop_type())); EXPECT_EQ(1, browser->tab_strip_model()->count()); WebContents* web_contents = browser->tab_strip_model()->GetActiveWebContents(); EXPECT_EQ(url, web_contents->GetURL()); // And no new RVH created. EXPECT_EQ(0, counter.GetRenderViewHostCreatedCount()); content::WindowedNotificationObserver observer( chrome::NOTIFICATION_TAB_ADDED, content::NotificationService::AllSources()); ui_test_utils::BrowserAddedObserver browser_observer; // Launch the blocked popup. PopupBlockerTabHelper* popup_blocker_helper = PopupBlockerTabHelper::FromWebContents(web_contents); if (!popup_blocker_helper->GetBlockedPopupsCount()) { content::WindowedNotificationObserver observer( chrome::NOTIFICATION_WEB_CONTENT_SETTINGS_CHANGED, content::NotificationService::AllSources()); observer.Wait(); } EXPECT_EQ(1u, popup_blocker_helper->GetBlockedPopupsCount()); std::map<int32, GURL> blocked_requests = popup_blocker_helper->GetBlockedPopupRequests(); std::map<int32, GURL>::const_iterator iter = blocked_requests.begin(); popup_blocker_helper->ShowBlockedPopup(iter->first); observer.Wait(); Browser* new_browser; if (what_to_expect == ExpectPopup) { new_browser = browser_observer.WaitForSingleNewBrowser(); web_contents = new_browser->tab_strip_model()->GetActiveWebContents(); } else { new_browser = browser; EXPECT_EQ(2, browser->tab_strip_model()->count()); // Check that we always create foreground tabs. EXPECT_EQ(1, browser->tab_strip_model()->active_index()); web_contents = browser->tab_strip_model()->GetWebContentsAt(1); } if (check_title == CheckTitle) { // Check that the check passed. base::string16 expected_title(base::ASCIIToUTF16("PASS")); content::TitleWatcher title_watcher(web_contents, expected_title); EXPECT_EQ(expected_title, title_watcher.WaitAndGetTitle()); } return web_contents; } private: DISALLOW_COPY_AND_ASSIGN(PopupBlockerBrowserTest); }; IN_PROC_BROWSER_TEST_F(PopupBlockerBrowserTest, BlockWebContentsCreation) { #if defined(OS_WIN) && defined(USE_ASH) // Disable this test in Metro+Ash for now (http://crbug.com/262796). if (base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kAshBrowserTests)) return; #endif RunCheckTest( browser(), "/popup_blocker/popup-blocked-to-post-blank.html", ExpectTab, DontCheckTitle); } IN_PROC_BROWSER_TEST_F(PopupBlockerBrowserTest, BlockWebContentsCreationIncognito) { #if defined(OS_WIN) && defined(USE_ASH) // Disable this test in Metro+Ash for now (http://crbug.com/262796). if (base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kAshBrowserTests)) return; #endif RunCheckTest( CreateIncognitoBrowser(), "/popup_blocker/popup-blocked-to-post-blank.html", ExpectTab, DontCheckTitle); } IN_PROC_BROWSER_TEST_F(PopupBlockerBrowserTest, PopupBlockedFakeClickOnAnchor) { #if defined(OS_WIN) && defined(USE_ASH) // Disable this test in Metro+Ash for now (http://crbug.com/262796). if (base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kAshBrowserTests)) return; #endif RunCheckTest( browser(), "/popup_blocker/popup-fake-click-on-anchor.html", ExpectTab, DontCheckTitle); } IN_PROC_BROWSER_TEST_F(PopupBlockerBrowserTest, PopupBlockedFakeClickOnAnchorNoTarget) { #if defined(OS_WIN) && defined(USE_ASH) // Disable this test in Metro+Ash for now (http://crbug.com/262796). if (base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kAshBrowserTests)) return; #endif RunCheckTest( browser(), "/popup_blocker/popup-fake-click-on-anchor2.html", ExpectTab, DontCheckTitle); } IN_PROC_BROWSER_TEST_F(PopupBlockerBrowserTest, MultiplePopups) { GURL url(embedded_test_server()->GetURL("/popup_blocker/popup-many.html")); ui_test_utils::NavigateToURL(browser(), url); ASSERT_EQ(2, GetBlockedContentsCount()); } // Verify that popups are launched on browser back button. IN_PROC_BROWSER_TEST_F(PopupBlockerBrowserTest, AllowPopupThroughContentSetting) { GURL url(embedded_test_server()->GetURL( "/popup_blocker/popup-blocked-to-post-blank.html")); browser()->profile()->GetHostContentSettingsMap() ->SetContentSetting(ContentSettingsPattern::FromURL(url), ContentSettingsPattern::Wildcard(), CONTENT_SETTINGS_TYPE_POPUPS, std::string(), CONTENT_SETTING_ALLOW); NavigateAndCheckPopupShown(url, ExpectTab); } // Verify that content settings are applied based on the top-level frame URL. IN_PROC_BROWSER_TEST_F(PopupBlockerBrowserTest, AllowPopupThroughContentSettingIFrame) { GURL url(embedded_test_server()->GetURL("/popup_blocker/popup-frames.html")); browser()->profile()->GetHostContentSettingsMap() ->SetContentSetting(ContentSettingsPattern::FromURL(url), ContentSettingsPattern::Wildcard(), CONTENT_SETTINGS_TYPE_POPUPS, std::string(), CONTENT_SETTING_ALLOW); // Popup from the iframe should be allowed since the top-level URL is // whitelisted. NavigateAndCheckPopupShown(url, ExpectTab); // Whitelist iframe URL instead. GURL::Replacements replace_host; std::string host_str("www.a.com"); // Must stay in scope with replace_host replace_host.SetHostStr(host_str); GURL frame_url(embedded_test_server() ->GetURL("/popup_blocker/popup-frames-iframe.html") .ReplaceComponents(replace_host)); browser()->profile()->GetHostContentSettingsMap()->ClearSettingsForOneType( CONTENT_SETTINGS_TYPE_POPUPS); browser()->profile()->GetHostContentSettingsMap() ->SetContentSetting(ContentSettingsPattern::FromURL(frame_url), ContentSettingsPattern::Wildcard(), CONTENT_SETTINGS_TYPE_POPUPS, std::string(), CONTENT_SETTING_ALLOW); // Popup should be blocked. ui_test_utils::NavigateToURL(browser(), url); ASSERT_EQ(1, GetBlockedContentsCount()); } IN_PROC_BROWSER_TEST_F(PopupBlockerBrowserTest, PopupsLaunchWhenTabIsClosed) { base::CommandLine::ForCurrentProcess()->AppendSwitch( switches::kDisablePopupBlocking); GURL url( embedded_test_server()->GetURL("/popup_blocker/popup-on-unload.html")); ui_test_utils::NavigateToURL(browser(), url); NavigateAndCheckPopupShown(embedded_test_server()->GetURL("/popup_blocker/"), ExpectPopup); } // Verify that when you unblock popup, the popup shows in history and omnibox. IN_PROC_BROWSER_TEST_F(PopupBlockerBrowserTest, UnblockedPopupShowsInHistoryAndOmnibox) { base::CommandLine::ForCurrentProcess()->AppendSwitch( switches::kDisablePopupBlocking); GURL url(embedded_test_server()->GetURL( "/popup_blocker/popup-blocked-to-post-blank.html")); NavigateAndCheckPopupShown(url, ExpectTab); std::string search_string = "data:text/html,<title>Popup Success!</title>you should not see this " "message if popup blocker is enabled"; ui_test_utils::HistoryEnumerator history(browser()->profile()); std::vector<GURL>& history_urls = history.urls(); ASSERT_EQ(2u, history_urls.size()); ASSERT_EQ(GURL(search_string), history_urls[0]); ASSERT_EQ(url, history_urls[1]); TemplateURLService* service = TemplateURLServiceFactory::GetForProfile( browser()->profile()); ui_test_utils::WaitForTemplateURLServiceToLoad(service); LocationBar* location_bar = browser()->window()->GetLocationBar(); ui_test_utils::SendToOmniboxAndSubmit(location_bar, search_string); OmniboxEditModel* model = location_bar->GetOmniboxView()->model(); EXPECT_EQ(GURL(search_string), model->CurrentMatch(NULL).destination_url); EXPECT_EQ(base::ASCIIToUTF16(search_string), model->CurrentMatch(NULL).contents); } // This test fails on linux AURA with this change // https://codereview.chromium.org/23903056 // BUG=https://code.google.com/p/chromium/issues/detail?id=295299 // TODO(ananta). Debug and fix this test. #if defined(USE_AURA) && defined(OS_LINUX) #define MAYBE_WindowFeatures DISABLED_WindowFeatures #else #define MAYBE_WindowFeatures WindowFeatures #endif IN_PROC_BROWSER_TEST_F(PopupBlockerBrowserTest, MAYBE_WindowFeatures) { WebContents* popup = RunCheckTest(browser(), "/popup_blocker/popup-window-open.html", ExpectPopup, DontCheckTitle); // Check that the new popup has (roughly) the requested size. gfx::Size window_size = popup->GetContainerBounds().size(); EXPECT_TRUE(349 <= window_size.width() && window_size.width() <= 351); EXPECT_TRUE(249 <= window_size.height() && window_size.height() <= 251); } IN_PROC_BROWSER_TEST_F(PopupBlockerBrowserTest, CorrectReferrer) { RunCheckTest(browser(), "/popup_blocker/popup-referrer.html", ExpectTab, CheckTitle); } IN_PROC_BROWSER_TEST_F(PopupBlockerBrowserTest, WindowFeaturesBarProps) { RunCheckTest(browser(), "/popup_blocker/popup-windowfeatures.html", ExpectPopup, CheckTitle); } IN_PROC_BROWSER_TEST_F(PopupBlockerBrowserTest, SessionStorage) { RunCheckTest(browser(), "/popup_blocker/popup-sessionstorage.html", ExpectTab, CheckTitle); } IN_PROC_BROWSER_TEST_F(PopupBlockerBrowserTest, Opener) { RunCheckTest(browser(), "/popup_blocker/popup-opener.html", ExpectTab, CheckTitle); } // Tests that the popup can still close itself after navigating. This tests that // the openedByDOM bit is preserved across blocked popups. IN_PROC_BROWSER_TEST_F(PopupBlockerBrowserTest, ClosableAfterNavigation) { // Open a popup. WebContents* popup = RunCheckTest(browser(), "/popup_blocker/popup-opener.html", ExpectTab, CheckTitle); // Navigate it elsewhere. content::TestNavigationObserver nav_observer(popup); popup->GetMainFrame()->ExecuteJavaScript( base::UTF8ToUTF16("location.href = '/empty.html'")); nav_observer.Wait(); // Have it close itself. CloseObserver close_observer(popup); popup->GetMainFrame()->ExecuteJavaScript( base::UTF8ToUTF16("window.close()")); close_observer.Wait(); } IN_PROC_BROWSER_TEST_F(PopupBlockerBrowserTest, OpenerSuppressed) { RunCheckTest(browser(), "/popup_blocker/popup-openersuppressed.html", ExpectTab, CheckTitle); } IN_PROC_BROWSER_TEST_F(PopupBlockerBrowserTest, ShiftClick) { RunCheckTest( browser(), "/popup_blocker/popup-fake-click-on-anchor3.html", ExpectPopup, CheckTitle); } IN_PROC_BROWSER_TEST_F(PopupBlockerBrowserTest, WebUI) { WebContents* popup = RunCheckTest(browser(), "/popup_blocker/popup-webui.html", ExpectTab, DontCheckTitle); // Check that the new popup displays about:blank. EXPECT_EQ(GURL(url::kAboutBlankURL), popup->GetURL()); } // Verify that the renderer can't DOS the browser by creating arbitrarily many // popups. IN_PROC_BROWSER_TEST_F(PopupBlockerBrowserTest, DenialOfService) { GURL url(embedded_test_server()->GetURL("/popup_blocker/popup-dos.html")); ui_test_utils::NavigateToURL(browser(), url); ASSERT_EQ(25, GetBlockedContentsCount()); } // Verify that an onunload popup does not show up for about:blank. IN_PROC_BROWSER_TEST_F(PopupBlockerBrowserTest, Regress427477) { ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUINewTabURL)); ui_test_utils::NavigateToURL(browser(), GURL(url::kAboutBlankURL)); GURL url( embedded_test_server()->GetURL("/popup_blocker/popup-on-unload.html")); ui_test_utils::NavigateToURL(browser(), url); WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents(); tab->GetController().GoBack(); content::WaitForLoadStop(tab); ASSERT_EQ(1u, chrome::GetBrowserCount(browser()->profile(), browser()->host_desktop_type())); ASSERT_EQ(1, browser()->tab_strip_model()->count()); // The popup from the unload event handler should not show up for about:blank. ASSERT_EQ(0, GetBlockedContentsCount()); } // Verify that app modal prompts can't be used to create pop unders. IN_PROC_BROWSER_TEST_F(PopupBlockerBrowserTest, ModalPopUnder) { WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents(); GURL url( embedded_test_server()->GetURL("/popup_blocker/popup-window-open.html")); browser()->profile()->GetHostContentSettingsMap()->SetContentSetting( ContentSettingsPattern::FromURL(url), ContentSettingsPattern::Wildcard(), CONTENT_SETTINGS_TYPE_POPUPS, std::string(), CONTENT_SETTING_ALLOW); NavigateAndCheckPopupShown(url, ExpectPopup); Browser* popup_browser = chrome::FindLastActiveWithHostDesktopType(browser()->host_desktop_type()); ASSERT_NE(popup_browser, browser()); // Showing an alert will raise the tab over the popup. tab->GetMainFrame()->ExecuteJavaScript(base::UTF8ToUTF16("alert()")); app_modal::AppModalDialog* dialog = ui_test_utils::WaitForAppModalDialog(); // Verify that after the dialog was closed, the popup is in front again. ASSERT_TRUE(dialog->IsJavaScriptModalDialog()); app_modal::JavaScriptAppModalDialog* js_dialog = static_cast<app_modal::JavaScriptAppModalDialog*>(dialog); BrowserActivationObserver activation_observer(browser()->host_desktop_type()); js_dialog->native_dialog()->AcceptAppModalDialog(); if (popup_browser != chrome::FindLastActiveWithHostDesktopType( popup_browser->host_desktop_type())) { activation_observer.WaitForActivation(); } ASSERT_EQ(popup_browser, chrome::FindLastActiveWithHostDesktopType( popup_browser->host_desktop_type())); } } // namespace
mohamed--abdel-maksoud/chromium.src
chrome/browser/ui/blocked_content/popup_blocker_browsertest.cc
C++
bsd-3-clause
21,913
////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2008-2009, Image Engine Design Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // * Neither the name of Image Engine Design nor the names of any // other contributors to this software may be used to endorse or // promote products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER 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. // ////////////////////////////////////////////////////////////////////////// #ifndef IE_CORE_SWEEPANDPRUNETEST_H #define IE_CORE_SWEEPANDPRUNETEST_H #include <math.h> #include <cassert> #include <iostream> #include <vector> #include <string> #include "boost/test/unit_test.hpp" #include "boost/test/floating_point_comparison.hpp" #include "boost/random.hpp" #include "OpenEXR/ImathVec.h" #include "OpenEXR/ImathBox.h" #include "IECore/SweepAndPrune.h" #include "IECore/BoxTraits.h" #include "IECore/VectorTraits.h" #include "IECore/VectorOps.h" using namespace Imath; namespace IECore { void addSweepAndPruneTest( boost::unit_test::test_suite* test ); struct SweepAndPruneTest { template<typename BoundIterator> struct TestCallback { typedef std::set< std::pair< unsigned int, unsigned int > > IntersectingBoundIndices; IntersectingBoundIndices m_indices; BoundIterator m_begin; unsigned int m_numBoxesPerTest; TestCallback( BoundIterator begin, unsigned int numBoxesPerTest ) : m_begin( begin ), m_numBoxesPerTest( numBoxesPerTest ) { } void operator()( BoundIterator b1, BoundIterator b2 ) { BOOST_CHECK( b1->intersects( *b2 ) ); unsigned int idx0 = std::distance( m_begin, b1 ); unsigned int idx1 = std::distance( m_begin, b2 ); BOOST_CHECK( idx0 < m_numBoxesPerTest ); BOOST_CHECK( idx1 < m_numBoxesPerTest ); BOOST_CHECK( idx0 != idx1 ); #ifndef NDEBUG unsigned oldSize = m_indices.size(); #endif m_indices.insert( IntersectingBoundIndices::value_type( idx0, idx1 ) ); m_indices.insert( IntersectingBoundIndices::value_type( idx1, idx0 ) ); assert( m_indices.size() == oldSize + 2); } }; template<typename T> void test() { unsigned seed = 42; boost::mt19937 generator( static_cast<boost::mt19937::result_type>( seed ) ); typedef typename BoxTraits<T>::BaseType VecType; typedef typename VectorTraits<VecType>::BaseType BaseType; boost::uniform_real<> uni_dist( 0.0f, 1.0f ); boost::variate_generator<boost::mt19937&, boost::uniform_real<> > uni( generator, uni_dist ); // Run 50 tests, each intersecting 1000 boxes within a random 5x5x5 world const unsigned numTests = 10u; const unsigned numBoxesPerTest = 1000u; const unsigned numPostChecksPerTest = numBoxesPerTest; for ( unsigned i = 0; i < numTests; i ++ ) { std::vector<T> input; for ( unsigned n = 0; n < numBoxesPerTest; n++ ) { T b; VecType corner( uni() * 5.0, uni() * 5.0, uni() * 5.0 ); VecType size( uni(), uni(), uni() ); b.extendBy( corner ); b.extendBy( corner + size ); input.push_back( b ); } typedef typename std::vector<T>::iterator BoundIterator; typedef SweepAndPrune<BoundIterator, TestCallback> SAP; SAP sap; typename SAP::Callback cb( input.begin(), numBoxesPerTest ); sap.intersectingBounds( input.begin(), input.end(), cb, SAP::XZY ); /// Pick some random box pairs for ( unsigned n = 0; n < numPostChecksPerTest; n++ ) { unsigned int idx0 = (unsigned int)( uni() * numBoxesPerTest ); unsigned int idx1 = 0; do { idx1 = (unsigned int)( uni() * numBoxesPerTest ); } while ( idx0 == idx1 ); assert( idx0 != idx1 ); assert( idx0 < numBoxesPerTest ); assert( idx1 < numBoxesPerTest ); /// If SweepAndPrune hasn't determined this pair is intersecting, verify it actually is not. if ( cb.m_indices.find( typename TestCallback<BoundIterator>::IntersectingBoundIndices::value_type( idx0, idx1 ) ) == cb.m_indices.end() ) { const T &bound0 = input[ idx0 ]; const T &bound1 = input[ idx1 ]; BOOST_CHECK( ! bound0.intersects( bound1 ) ); } } } } }; struct SweepAndPruneTestSuite : public boost::unit_test::test_suite { SweepAndPruneTestSuite() : boost::unit_test::test_suite( "SweepAndPruneTestSuite" ) { static boost::shared_ptr<SweepAndPruneTest> instance( new SweepAndPruneTest() ); add( BOOST_CLASS_TEST_CASE( &SweepAndPruneTest::test<Imath::Box3f>, instance ) ); add( BOOST_CLASS_TEST_CASE( &SweepAndPruneTest::test<Imath::Box3d>, instance ) ); } }; } #endif // IE_CORE_SWEEPANDPRUNETEST_H
DoubleNegativeVisualEffects/cortex
test/IECore/SweepAndPruneTest.h
C
bsd-3-clause
5,877
// Copyright 2017 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. #ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_GRAPHICS_VIDEO_FRAME_SUBMITTER_H_ #define THIRD_PARTY_BLINK_RENDERER_PLATFORM_GRAPHICS_VIDEO_FRAME_SUBMITTER_H_ #include <memory> #include "base/memory/read_only_shared_memory_region.h" #include "base/memory/weak_ptr.h" #include "base/threading/thread_checker.h" #include "base/timer/timer.h" #include "cc/metrics/frame_sequence_tracker_collection.h" #include "cc/metrics/video_playback_roughness_reporter.h" #include "components/power_scheduler/power_mode_voter.h" #include "components/viz/client/shared_bitmap_reporter.h" #include "components/viz/common/gpu/context_provider.h" #include "components/viz/common/resources/shared_bitmap.h" #include "components/viz/common/surfaces/child_local_surface_id_allocator.h" #include "mojo/public/cpp/bindings/receiver.h" #include "mojo/public/cpp/bindings/remote.h" #include "mojo/public/cpp/system/buffer.h" #include "services/viz/public/mojom/compositing/compositor_frame_sink.mojom-blink.h" #include "services/viz/public/mojom/compositing/frame_timing_details.mojom-blink.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "third_party/blink/public/mojom/frame_sinks/embedded_frame_sink.mojom-blink.h" #include "third_party/blink/public/platform/web_video_frame_submitter.h" #include "third_party/blink/renderer/platform/graphics/video_frame_resource_provider.h" #include "third_party/blink/renderer/platform/platform_export.h" #include "third_party/blink/renderer/platform/wtf/functional.h" namespace blink { // This single-threaded class facilitates the communication between the media // stack and browser renderer, providing compositor frames containing video // frames and corresponding resources to the |compositor_frame_sink_|. // // This class requires and uses a viz::ContextProvider, and thus, besides // construction, must be consistently accessed from the same thread. class PLATFORM_EXPORT VideoFrameSubmitter : public WebVideoFrameSubmitter, public viz::ContextLostObserver, public viz::SharedBitmapReporter, public viz::mojom::blink::CompositorFrameSinkClient { public: VideoFrameSubmitter(WebContextProviderCallback, cc::VideoPlaybackRoughnessReporter::ReportingCallback, std::unique_ptr<VideoFrameResourceProvider>); VideoFrameSubmitter(const VideoFrameSubmitter&) = delete; VideoFrameSubmitter& operator=(const VideoFrameSubmitter&) = delete; ~VideoFrameSubmitter() override; // cc::VideoFrameProvider::Client implementation. void StopUsingProvider() override; void StartRendering() override; void StopRendering() override; void DidReceiveFrame() override; bool IsDrivingFrameUpdates() const override; // WebVideoFrameSubmitter implementation. void Initialize(cc::VideoFrameProvider*, bool is_media_stream) override; void SetTransform(media::VideoTransformation) override; void EnableSubmission(viz::SurfaceId) override; void SetIsSurfaceVisible(bool is_visible) override; void SetIsPageVisible(bool is_visible) override; void SetForceBeginFrames(bool force_begin_frames) override; void SetForceSubmit(bool) override; // viz::ContextLostObserver implementation. void OnContextLost() override; // cc::mojom::CompositorFrameSinkClient implementation. void DidReceiveCompositorFrameAck( WTF::Vector<viz::ReturnedResource> resources) override; void OnBeginFrame( const viz::BeginFrameArgs&, const WTF::HashMap<uint32_t, viz::FrameTimingDetails>&) override; void OnBeginFramePausedChanged(bool paused) override {} void ReclaimResources(WTF::Vector<viz::ReturnedResource> resources) override; void OnCompositorFrameTransitionDirectiveProcessed( uint32_t sequence_id) override {} // viz::SharedBitmapReporter implementation. void DidAllocateSharedBitmap(base::ReadOnlySharedMemoryRegion, const viz::SharedBitmapId&) override; void DidDeleteSharedBitmap(const viz::SharedBitmapId&) override; private: friend class VideoFrameSubmitterTest; class FrameSinkBundleProxy; // Called during Initialize() and OnContextLost() after a new ContextGL is // requested. void OnReceivedContextProvider( bool use_gpu_compositing, scoped_refptr<viz::RasterContextProvider> context_provider); // Starts submission and calls UpdateSubmissionState(); which may submit. void StartSubmitting(); // Sets CompositorFrameSink::SetNeedsBeginFrame() state and submits a frame if // visible or an empty frame if not. void UpdateSubmissionState(); // Will submit an empty frame to clear resource usage if it's safe. void SubmitEmptyFrameIfNeeded(); // Returns whether a frame was submitted. bool SubmitFrame(const viz::BeginFrameAck&, scoped_refptr<media::VideoFrame>); // SubmitEmptyFrame() is used to force the remote CompositorFrameSink to // release resources for the last submission; saving a significant amount of // memory (~30%) when content goes off-screen. See https://crbug.com/829813. void SubmitEmptyFrame(); // Pulls frame and submits it to compositor. Used in cases like // DidReceiveFrame(), which occurs before video rendering has started to post // the first frame or to submit a final frame before ending rendering. void SubmitSingleFrame(); // Return whether the submitter should submit frames based on its current // state. It's important to only submit when this is true to save memory. See // comments above and in UpdateSubmissionState(). bool ShouldSubmit() const; // Generates a new surface ID using using |child_local_surface_id_allocator_|. // Called during context loss or during a frame size change. void GenerateNewSurfaceId(); // Helper method for creating viz::CompositorFrame. If |video_frame| is null // then the frame will be empty. viz::CompositorFrame CreateCompositorFrame( uint32_t frame_token, const viz::BeginFrameAck& begin_frame_ack, scoped_refptr<media::VideoFrame> video_frame, media::VideoTransformation transform); cc::VideoFrameProvider* video_frame_provider_ = nullptr; bool is_media_stream_ = false; scoped_refptr<viz::RasterContextProvider> context_provider_; mojo::Remote<viz::mojom::blink::CompositorFrameSink> remote_frame_sink_; mojo::Remote<mojom::blink::SurfaceEmbedder> surface_embedder_; mojo::Receiver<viz::mojom::blink::CompositorFrameSinkClient> receiver_{this}; WebContextProviderCallback context_provider_callback_; std::unique_ptr<VideoFrameResourceProvider> resource_provider_; bool waiting_for_compositor_ack_ = false; // When UseVideoFrameSinkBundle is enabled, this is initialized to a local // implementation which batches outgoing Viz requests with those from other // related VideoFrameSubmitters, rather than having each VideoFrameSubmitter // submit their ad hoc requests directly to Viz. std::unique_ptr<FrameSinkBundleProxy> bundle_proxy_; // Points to either `remote_frame_sink_` or `bundle_proxy_` depending // on whether UseVideoFrameSinkBundle is enabled. viz::mojom::blink::CompositorFrameSink* compositor_frame_sink_ = nullptr; // Current rendering state. Set by StartRendering() and StopRendering(). bool is_rendering_ = false; // If the surface is not visible within in the current view port, we should // not submit. Not submitting when off-screen saves significant memory. bool is_surface_visible_ = false; // Likewise, if the entire page is not visible, we should not submit. Not // submitting in the background causes the VideoFrameProvider to enter a // background rendering mode using lower frequency artificial BeginFrames. bool is_page_visible_ = true; // Whether BeginFrames should be generated regardless of visibility. Does not // submit unless submission is expected. bool force_begin_frames_ = false; // Whether frames should always be submitted, even if we're not visible. Used // by Picture-in-Picture mode to ensure submission occurs even off-screen. bool force_submit_ = false; // Needs to be initialized in implementation because media isn't a public_dep // of blink/platform. media::VideoTransformation transform_; viz::FrameSinkId frame_sink_id_; // Size of the video frame being submitted. It is set the first time a frame // is submitted. Every time there is a change in the video frame size, the // child component of the LocalSurfaceId will be updated. gfx::Size frame_size_; // Used to updated the LocalSurfaceId when detecting a change in video frame // size. viz::ChildLocalSurfaceIdAllocator child_local_surface_id_allocator_; viz::FrameTokenGenerator next_frame_token_; std::unique_ptr<cc::VideoPlaybackRoughnessReporter> roughness_reporter_; base::OneShotTimer empty_frame_timer_; absl::optional<int> last_frame_id_; cc::FrameSequenceTrackerCollection frame_trackers_; // The BeginFrameArgs passed to the most recent call of OnBeginFrame(). // Required for FrameSequenceTrackerCollection::NotifySubmitFrame viz::BeginFrameArgs last_begin_frame_args_; // The token of the frames that are submitted outside OnBeginFrame(). These // frames should be ignored by the video tracker even if they are reported as // presented. base::flat_set<uint32_t> ignorable_submitted_frames_; std::unique_ptr<power_scheduler::PowerModeVoter> power_mode_voter_; THREAD_CHECKER(thread_checker_); base::WeakPtrFactory<VideoFrameSubmitter> weak_ptr_factory_{this}; }; } // namespace blink #endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_GRAPHICS_VIDEO_FRAME_SUBMITTER_H_
scheib/chromium
third_party/blink/renderer/platform/graphics/video_frame_submitter.h
C
bsd-3-clause
9,756
// NOTE(vakh): The process.h file needs to be included first because "rar.hpp" // defines certain macros that cause symbol redefinition errors #if defined(UNRAR_NO_EXCEPTIONS) #include "base/process/memory.h" #endif // defined(UNRAR_NO_EXCEPTIONS) #include "rar.hpp" #include "coder.cpp" #include "suballoc.cpp" #include "model.cpp" #include "unpackinline.cpp" #ifdef RAR_SMP #include "unpack50mt.cpp" #endif #ifndef SFX_MODULE #include "unpack15.cpp" #include "unpack20.cpp" #endif #include "unpack30.cpp" #include "unpack50.cpp" #include "unpack50frag.cpp" Unpack::Unpack(ComprDataIO *DataIO) :Inp(true),VMCodeInp(true) { UnpIO=DataIO; Window=NULL; Fragmented=false; Suspended=false; UnpAllBuf=false; UnpSomeRead=false; #ifdef RAR_SMP MaxUserThreads=1; UnpThreadPool=NULL; ReadBufMT=NULL; UnpThreadData=NULL; #endif MaxWinSize=0; MaxWinMask=0; // Perform initialization, which should be done only once for all files. // It prevents crash if first DoUnpack call is later made with wrong // (true) 'Solid' value. UnpInitData(false); #ifndef SFX_MODULE // RAR 1.5 decompression initialization UnpInitData15(false); InitHuff(); #endif } Unpack::~Unpack() { InitFilters30(false); if (Window!=NULL) free(Window); #ifdef RAR_SMP delete UnpThreadPool; delete[] ReadBufMT; delete[] UnpThreadData; #endif } #ifdef RAR_SMP void Unpack::SetThreads(uint Threads) { // More than 8 threads are unlikely to provide noticeable gain // for unpacking, but would use the additional memory. MaxUserThreads=Min(Threads,8); UnpThreadPool=new ThreadPool(MaxUserThreads); } #endif void Unpack::Init(size_t WinSize,bool Solid) { // If 32-bit RAR unpacks an archive with 4 GB dictionary, the window size // will be 0 because of size_t overflow. Let's issue the memory error. if (WinSize==0) ErrHandler.MemoryError(); // Minimum window size must be at least twice more than maximum possible // size of filter block, which is 0x10000 in RAR now. If window size is // smaller, we can have a block with never cleared flt->NextWindow flag // in UnpWriteBuf(). Minimum window size 0x20000 would be enough, but let's // use 0x40000 for extra safety and possible filter area size expansion. const size_t MinAllocSize=0x40000; if (WinSize<MinAllocSize) WinSize=MinAllocSize; if (WinSize<=MaxWinSize) // Use the already allocated window. return; if ((WinSize>>16)>0x10000) // Window size must not exceed 4 GB. return; // Archiving code guarantees that window size does not grow in the same // solid stream. So if we are here, we are either creating a new window // or increasing the size of non-solid window. So we could safely reject // current window data without copying them to a new window, though being // extra cautious, we still handle the solid window grow case below. bool Grow=Solid && (Window!=NULL || Fragmented); // We do not handle growth for existing fragmented window. if (Grow && Fragmented) { #if defined(UNRAR_NO_EXCEPTIONS) base::TerminateBecauseOutOfMemory(0); #else throw std::bad_alloc(); #endif // defined(UNRAR_NO_EXCEPTIONS) } byte *NewWindow=Fragmented ? NULL : (byte *)malloc(WinSize); if (NewWindow==NULL) { if (Grow || WinSize<0x1000000) { // We do not support growth for new fragmented window. // Also exclude RAR4 and small dictionaries. #if defined(UNRAR_NO_EXCEPTIONS) base::TerminateBecauseOutOfMemory(WinSize); #else throw std::bad_alloc(); #endif // defined(UNRAR_NO_EXCEPTIONS) } else { if (Window!=NULL) // If allocated by preceding files. { free(Window); Window=NULL; } FragWindow.Init(WinSize); Fragmented=true; } } if (!Fragmented) { // Clean the window to generate the same output when unpacking corrupt // RAR files, which may access unused areas of sliding dictionary. memset(NewWindow,0,WinSize); // If Window is not NULL, it means that window size has grown. // In solid streams we need to copy data to a new window in such case. // RAR archiving code does not allow it in solid streams now, // but let's implement it anyway just in case we'll change it sometimes. if (Grow) for (size_t I=1;I<=MaxWinSize;I++) NewWindow[(UnpPtr-I)&(WinSize-1)]=Window[(UnpPtr-I)&(MaxWinSize-1)]; if (Window!=NULL) free(Window); Window=NewWindow; } MaxWinSize=WinSize; MaxWinMask=MaxWinSize-1; } void Unpack::DoUnpack(uint Method,bool Solid) { // Methods <50 will crash in Fragmented mode when accessing NULL Window. // They cannot be called in such mode now, but we check it below anyway // just for extra safety. switch(Method) { #ifndef SFX_MODULE case 15: // rar 1.5 compression if (!Fragmented) Unpack15(Solid); break; case 20: // rar 2.x compression case 26: // files larger than 2GB if (!Fragmented) Unpack20(Solid); break; #endif case 29: // rar 3.x compression if (!Fragmented) Unpack29(Solid); break; case 50: // RAR 5.0 compression algorithm. #ifdef RAR_SMP if (MaxUserThreads>1) { // We do not use the multithreaded unpack routine to repack RAR archives // in 'suspended' mode, because unlike the single threaded code it can // write more than one dictionary for same loop pass. So we would need // larger buffers of unknown size. Also we do not support multithreading // in fragmented window mode. if (!Fragmented) { Unpack5MT(Solid); break; } } #endif Unpack5(Solid); break; } } void Unpack::UnpInitData(bool Solid) { if (!Solid) { memset(OldDist,0,sizeof(OldDist)); OldDistPtr=0; LastDist=LastLength=0; // memset(Window,0,MaxWinSize); memset(&BlockTables,0,sizeof(BlockTables)); UnpPtr=WrPtr=0; WriteBorder=Min(MaxWinSize,UNPACK_MAX_WRITE)&MaxWinMask; } // Filters never share several solid files, so we can safely reset them // even in solid archive. InitFilters(); Inp.InitBitInput(); WrittenFileSize=0; ReadTop=0; ReadBorder=0; memset(&BlockHeader,0,sizeof(BlockHeader)); BlockHeader.BlockSize=-1; // '-1' means not defined yet. #ifndef SFX_MODULE UnpInitData20(Solid); #endif UnpInitData30(Solid); UnpInitData50(Solid); } // LengthTable contains the length in bits for every element of alphabet. // Dec is the structure to decode Huffman code/ // Size is size of length table and DecodeNum field in Dec structure, void Unpack::MakeDecodeTables(byte *LengthTable,DecodeTable *Dec,uint Size) { // Size of alphabet and DecodePos array. Dec->MaxNum=Size; // Calculate how many entries for every bit length in LengthTable we have. uint LengthCount[16]; memset(LengthCount,0,sizeof(LengthCount)); for (size_t I=0;I<Size;I++) LengthCount[LengthTable[I] & 0xf]++; // We must not calculate the number of zero length codes. LengthCount[0]=0; // Set the entire DecodeNum to zero. memset(Dec->DecodeNum,0,Size*sizeof(*Dec->DecodeNum)); // Initialize not really used entry for zero length code. Dec->DecodePos[0]=0; // Start code for bit length 1 is 0. Dec->DecodeLen[0]=0; // Right aligned upper limit code for current bit length. uint UpperLimit=0; for (size_t I=1;I<16;I++) { // Adjust the upper limit code. UpperLimit+=LengthCount[I]; // Left aligned upper limit code. uint LeftAligned=UpperLimit<<(16-I); // Prepare the upper limit code for next bit length. UpperLimit*=2; // Store the left aligned upper limit code. Dec->DecodeLen[I]=(uint)LeftAligned; // Every item of this array contains the sum of all preceding items. // So it contains the start position in code list for every bit length. Dec->DecodePos[I]=Dec->DecodePos[I-1]+LengthCount[I-1]; } // Prepare the copy of DecodePos. We'll modify this copy below, // so we cannot use the original DecodePos. uint CopyDecodePos[ASIZE(Dec->DecodePos)]; memcpy(CopyDecodePos,Dec->DecodePos,sizeof(CopyDecodePos)); // For every bit length in the bit length table and so for every item // of alphabet. for (uint I=0;I<Size;I++) { // Get the current bit length. byte CurBitLength=LengthTable[I] & 0xf; if (CurBitLength!=0) { // Last position in code list for current bit length. uint LastPos=CopyDecodePos[CurBitLength]; // Prepare the decode table, so this position in code list will be // decoded to current alphabet item number. Dec->DecodeNum[LastPos]=(ushort)I; // We'll use next position number for this bit length next time. // So we pass through the entire range of positions available // for every bit length. CopyDecodePos[CurBitLength]++; } } // Define the number of bits to process in quick mode. We use more bits // for larger alphabets. More bits means that more codes will be processed // in quick mode, but also that more time will be spent to preparation // of tables for quick decode. switch (Size) { case NC: case NC20: case NC30: Dec->QuickBits=MAX_QUICK_DECODE_BITS; break; default: Dec->QuickBits=MAX_QUICK_DECODE_BITS-3; break; } // Size of tables for quick mode. uint QuickDataSize=1<<Dec->QuickBits; // Bit length for current code, start from 1 bit codes. It is important // to use 1 bit instead of 0 for minimum code length, so we are moving // forward even when processing a corrupt archive. uint CurBitLength=1; // For every right aligned bit string which supports the quick decoding. for (uint Code=0;Code<QuickDataSize;Code++) { // Left align the current code, so it will be in usual bit field format. uint BitField=Code<<(16-Dec->QuickBits); // Prepare the table for quick decoding of bit lengths. // Find the upper limit for current bit field and adjust the bit length // accordingly if necessary. while (CurBitLength<ASIZE(Dec->DecodeLen) && BitField>=Dec->DecodeLen[CurBitLength]) CurBitLength++; // Translation of right aligned bit string to bit length. Dec->QuickLen[Code]=CurBitLength; // Prepare the table for quick translation of position in code list // to position in alphabet. // Calculate the distance from the start code for current bit length. uint Dist=BitField-Dec->DecodeLen[CurBitLength-1]; // Right align the distance. Dist>>=(16-CurBitLength); // Now we can calculate the position in the code list. It is the sum // of first position for current bit length and right aligned distance // between our bit field and start code for current bit length. uint Pos; if (CurBitLength<ASIZE(Dec->DecodePos) && (Pos=Dec->DecodePos[CurBitLength]+Dist)<Size) { // Define the code to alphabet number translation. Dec->QuickNum[Code]=Dec->DecodeNum[Pos]; } else { // Can be here for length table filled with zeroes only (empty). Dec->QuickNum[Code]=0; } } }
scheib/chromium
third_party/unrar/src/unpack.cpp
C++
bsd-3-clause
11,154
// Copyright 2016 the V8 project 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 "src/builtins/builtins-utils.h" #include "src/builtins/builtins.h" #include "src/execution/isolate.h" #include "src/handles/handles-inl.h" #include "src/objects/objects-inl.h" namespace v8 { namespace internal { Handle<Code> Builtins::CallFunction(ConvertReceiverMode mode) { switch (mode) { case ConvertReceiverMode::kNullOrUndefined: return builtin_handle(kCallFunction_ReceiverIsNullOrUndefined); case ConvertReceiverMode::kNotNullOrUndefined: return builtin_handle(kCallFunction_ReceiverIsNotNullOrUndefined); case ConvertReceiverMode::kAny: return builtin_handle(kCallFunction_ReceiverIsAny); } UNREACHABLE(); } Handle<Code> Builtins::Call(ConvertReceiverMode mode) { switch (mode) { case ConvertReceiverMode::kNullOrUndefined: return builtin_handle(kCall_ReceiverIsNullOrUndefined); case ConvertReceiverMode::kNotNullOrUndefined: return builtin_handle(kCall_ReceiverIsNotNullOrUndefined); case ConvertReceiverMode::kAny: return builtin_handle(kCall_ReceiverIsAny); } UNREACHABLE(); } } // namespace internal } // namespace v8
endlessm/chromium-browser
v8/src/builtins/builtins-call.cc
C++
bsd-3-clause
1,287
// Copyright 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. #ifndef IOS_CHROME_BROWSER_BROWSER_STATE_METRICS_BROWSER_STATE_METRICS_H_ #define IOS_CHROME_BROWSER_BROWSER_STATE_METRICS_BROWSER_STATE_METRICS_H_ namespace ios { class ChromeBrowserStateManager; } namespace profile_metrics { struct Counts; } // namespace profile_metrics // Counts and returns summary information about the browser states currently in // the |manager|. This information is returned in the output variable // |counts|. Assumes that all field of |counts| are set to zero before the call. bool CountBrowserStateInformation(ios::ChromeBrowserStateManager* manager, profile_metrics::Counts* counts); void LogNumberOfBrowserStates(ios::ChromeBrowserStateManager* manager); #endif // IOS_CHROME_BROWSER_BROWSER_STATE_METRICS_BROWSER_STATE_METRICS_H_
scheib/chromium
ios/chrome/browser/browser_state_metrics/browser_state_metrics.h
C
bsd-3-clause
968
<?php header("set-cookie: name=val\x09ue"); ?>
chromium/chromium
third_party/blink/web_tests/http/tests/inspector-protocol/network/resources/set-cookie-invalid-syntax.php
PHP
bsd-3-clause
47
/* GraphicsConfiguration.java -- describes characteristics of graphics Copyright (C) 2000, 2001, 2002 Free Software Foundation 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 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.awt; import gnu.classpath.NotImplementedException; import java.awt.geom.AffineTransform; import java.awt.image.BufferedImage; import java.awt.image.ColorModel; import java.awt.image.VolatileImage; /** * This class describes the configuration of various graphics devices, such * as a monitor or printer. Different configurations may exist for the same * device, according to the different native modes supported. * * <p>Virtual devices are supported (for example, in a multiple screen * environment, a virtual device covers all screens simultaneously); the * configuration will have a non-zero relative coordinate system in such * a case. * * @author Eric Blake ([email protected]) * @see Window * @see Frame * @see GraphicsEnvironment * @see GraphicsDevice * @since 1.0 * @status updated to 1.4 */ public abstract class GraphicsConfiguration { /** The cached image capabilities. */ private ImageCapabilities imageCapabilities; /** The cached buffer capabilities. */ private BufferCapabilities bufferCapabilities; /** * The default constructor. * * @see GraphicsDevice#getConfigurations() * @see GraphicsDevice#getDefaultConfiguration() * @see GraphicsDevice#getBestConfiguration(GraphicsConfigTemplate) * @see Graphics2D#getDeviceConfiguration() */ protected GraphicsConfiguration () { } /** * Gets the associated device that this configuration describes. * * @return the device */ public abstract GraphicsDevice getDevice(); /** * Returns a buffered image optimized to this device, so that blitting can * be supported in the buffered image. * * @param w the width of the buffer * @param h the height of the buffer * @return the buffered image, or null if none is supported */ public abstract BufferedImage createCompatibleImage(int w, int h); /** * Returns a buffered volatile image optimized to this device, so that * blitting can be supported in the buffered image. Because the buffer is * volatile, it can be optimized by native graphics accelerators. * * @param w the width of the buffer * @param h the height of the buffer * @return the buffered image, or null if none is supported * @see Component#createVolatileImage(int, int) * @since 1.4 */ public abstract VolatileImage createCompatibleVolatileImage(int w, int h); /** * Returns a buffered volatile image optimized to this device, and with the * given capabilities, so that blitting can be supported in the buffered * image. Because the buffer is volatile, it can be optimized by native * graphics accelerators. * * @param w the width of the buffer * @param h the height of the buffer * @param caps the desired capabilities of the image buffer * @return the buffered image, or null if none is supported * @throws AWTException if the capabilities cannot be met * @since 1.4 */ public VolatileImage createCompatibleVolatileImage(int w, int h, ImageCapabilities caps) throws AWTException { throw new AWTException("not implemented"); } /** * Returns a buffered volatile image optimized to this device, and * with the given transparency. Because the buffer is volatile, it * can be optimized by native graphics accelerators. * * @param width the width of the buffer * @param height the height of the buffer * @param transparency the transparency value for the buffer * @return the buffered image, or null if none is supported * @since 1.5 */ public abstract VolatileImage createCompatibleVolatileImage(int width, int height, int transparency); /** * Returns a buffered image optimized to this device, and with the specified * transparency, so that blitting can be supported in the buffered image. * * @param w the width of the buffer * @param h the height of the buffer * @param transparency the transparency of the buffer * @return the buffered image, or null if none is supported * @see Transparency#OPAQUE * @see Transparency#BITMASK * @see Transparency#TRANSLUCENT */ public abstract BufferedImage createCompatibleImage(int w, int h, int transparency); /** * Gets the color model of the corresponding device. * * @return the color model */ public abstract ColorModel getColorModel(); /** * Gets a color model for the corresponding device which supports the desired * transparency level. * * @param transparency the transparency of the model * @return the color model, with transparency * @see Transparency#OPAQUE * @see Transparency#BITMASK * @see Transparency#TRANSLUCENT */ public abstract ColorModel getColorModel(int transparency); /** * Returns a transform that maps user coordinates to device coordinates. The * preferred mapping is about 72 user units to 1 inch (2.54 cm) of physical * space. This is often the identity transform. The device coordinates have * the origin at the upper left, with increasing x to the right, and * increasing y to the bottom. * * @return the transformation from user space to device space * @see #getNormalizingTransform() */ public abstract AffineTransform getDefaultTransform(); /** * Returns a transform that maps user coordinates to device coordinates. The * exact mapping is 72 user units to 1 inch (2.54 cm) of physical space. * This is often the identity transform. The device coordinates have the * origin at the upper left, with increasing x to the right, and increasing * y to the bottom. Note that this is more accurate (and thus, sometimes more * costly) than the default transform. * * @return the normalized transformation from user space to device space * @see #getDefaultTransform() */ public abstract AffineTransform getNormalizingTransform(); /** * Returns the bounds of the configuration, in device coordinates. If this * is a virtual device (for example, encompassing several screens), the * bounds may have a non-zero origin. * * @return the device bounds * @since 1.3 */ public abstract Rectangle getBounds(); /** * Returns the buffering capabilities of this configuration. * * @return the buffer capabilities * @since 1.4 */ public BufferCapabilities getBufferCapabilities() { if (imageCapabilities == null) getImageCapabilities(); if (bufferCapabilities == null) bufferCapabilities = new BufferCapabilities(imageCapabilities, imageCapabilities, null); return bufferCapabilities; } /** * Returns the imaging capabilities of this configuration. * * @return the image capabilities * @since 1.4 */ public ImageCapabilities getImageCapabilities() { if (imageCapabilities == null) imageCapabilities = new ImageCapabilities(false); return imageCapabilities; } } // class GraphicsConfiguration
shaotuanchen/sunflower_exp
tools/source/gcc-4.2.4/libjava/classpath/java/awt/GraphicsConfiguration.java
Java
bsd-3-clause
8,994
<!-- -- Copyright 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. --> <link rel="import" href="chrome://resources/polymer/v1_0/polymer/polymer.html"> <link rel="import" href="track_info_panel.html"> <link rel="import" href="track_list.html"> <link rel="import" href="control_panel.html"> <dom-module id="audio-player"> <link rel="import" type="css" href="audio_player.css"> <template> <track-info-panel id="trackInfo" expanded="{{trackInfoExpanded}}"></track-info-panel> <track-list id="trackList" expanded$="[[playlistExpanded]]" shuffle="[[shuffle]]" current-track-index="{{currentTrackIndex}}" on-replay="onReplayCurrentTrack" on-play="onPlayCurrentTrack"></track-list> <control-panel id="audioController" playing="{{playing}}" time="{{time}}" duration="[[duration]]" shuffle="{{shuffle}}" repeat="{{repeat}}" volume="{{volume}}" playlist-expanded="{{playlistExpanded}}" aria-labels="[[ariaLabels]]" on-next-clicked="onControllerNextClicked" on-previous-clicked="onControllerPreviousClicked"></control-panel> <audio id="audio" volume="[[computeAudioVolume_(volume)]]"></audio> </template> </dom-module> <script src="audio_player.js"></script>
danakj/chromium
ui/file_manager/audio_player/elements/audio_player.html
HTML
bsd-3-clause
1,419
//===----------------------------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // <set> // class multiset // multiset(const multiset& m, const allocator_type& a); #include <set> #include <cassert> #include "test_macros.h" #include "../../../test_compare.h" #include "test_allocator.h" int main(int, char**) { typedef int V; V ar[] = { 1, 1, 1, 2, 2, 2, 3, 3, 3 }; typedef test_compare<std::less<int> > C; typedef test_allocator<V> A; std::multiset<int, C, A> mo(ar, ar+sizeof(ar)/sizeof(ar[0]), C(5), A(7)); std::multiset<int, C, A> m(mo, A(3)); assert(m.get_allocator() == A(3)); assert(m.key_comp() == C(5)); assert(m.size() == 9); assert(distance(m.begin(), m.end()) == 9); assert(*next(m.begin(), 0) == 1); assert(*next(m.begin(), 1) == 1); assert(*next(m.begin(), 2) == 1); assert(*next(m.begin(), 3) == 2); assert(*next(m.begin(), 4) == 2); assert(*next(m.begin(), 5) == 2); assert(*next(m.begin(), 6) == 3); assert(*next(m.begin(), 7) == 3); assert(*next(m.begin(), 8) == 3); assert(mo.get_allocator() == A(7)); assert(mo.key_comp() == C(5)); assert(mo.size() == 9); assert(distance(mo.begin(), mo.end()) == 9); assert(*next(mo.begin(), 0) == 1); assert(*next(mo.begin(), 1) == 1); assert(*next(mo.begin(), 2) == 1); assert(*next(mo.begin(), 3) == 2); assert(*next(mo.begin(), 4) == 2); assert(*next(mo.begin(), 5) == 2); assert(*next(mo.begin(), 6) == 3); assert(*next(mo.begin(), 7) == 3); assert(*next(mo.begin(), 8) == 3); return 0; }
endlessm/chromium-browser
third_party/llvm/libcxx/test/std/containers/associative/multiset/multiset.cons/copy_alloc.pass.cpp
C++
bsd-3-clause
1,954
//===----------------------------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // <string> // const_reference operator[](size_type pos) const; // reference operator[](size_type pos); #ifdef _LIBCPP_DEBUG #define _LIBCPP_ASSERT(x, m) ((x) ? (void)0 : std::exit(0)) #endif #include <string> #include <cassert> #include "test_macros.h" #include "min_allocator.h" int main(int, char**) { { typedef std::string S; S s("0123456789"); const S& cs = s; ASSERT_SAME_TYPE(decltype( s[0]), typename S::reference); ASSERT_SAME_TYPE(decltype(cs[0]), typename S::const_reference); LIBCPP_ASSERT_NOEXCEPT( s[0]); LIBCPP_ASSERT_NOEXCEPT( cs[0]); for (S::size_type i = 0; i < cs.size(); ++i) { assert(s[i] == static_cast<char>('0' + i)); assert(cs[i] == s[i]); } assert(cs[cs.size()] == '\0'); const S s2 = S(); assert(s2[0] == '\0'); } #if TEST_STD_VER >= 11 { typedef std::basic_string<char, std::char_traits<char>, min_allocator<char>> S; S s("0123456789"); const S& cs = s; ASSERT_SAME_TYPE(decltype( s[0]), typename S::reference); ASSERT_SAME_TYPE(decltype(cs[0]), typename S::const_reference); LIBCPP_ASSERT_NOEXCEPT( s[0]); LIBCPP_ASSERT_NOEXCEPT( cs[0]); for (S::size_type i = 0; i < cs.size(); ++i) { assert(s[i] == static_cast<char>('0' + i)); assert(cs[i] == s[i]); } assert(cs[cs.size()] == '\0'); const S s2 = S(); assert(s2[0] == '\0'); } #endif #ifdef _LIBCPP_DEBUG { std::string s; char c = s[0]; assert(c == '\0'); c = s[1]; assert(false); } #endif return 0; }
endlessm/chromium-browser
third_party/llvm/libcxx/test/std/strings/basic.string/string.access/index.pass.cpp
C++
bsd-3-clause
1,976
//============================================================================================================= /** * @file tmsiimpedanceview.h * @author Lorenz Esch <[email protected]>; * Christoph Dinh <[email protected]>; * Matti Hamalainen <[email protected]>; * @version 1.0 * @date June, 2014 * * @section LICENSE * * Copyright (C) 2014, Lorenz Esch, Christoph Dinh and Matti Hamalainen. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that * the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of conditions and the * following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and * the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of MNE-CPP authors nor the names of its contributors may be used * to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER 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. * * * @brief Contains the declaration of the TMSIImpedanceView class. * */ #ifndef TMSIIMPEDANCEVIEW_H #define TMSIIMPEDANCEVIEW_H //************************************************************************************************************* //============================================================================================================= // INCLUDES //============================================================================================================= #include <iostream> #include <tmsielectrodeitem.h> //************************************************************************************************************* //============================================================================================================= // QT INCLUDES //============================================================================================================= #include <QGraphicsView> #include <QWheelEvent> //************************************************************************************************************* //============================================================================================================= // DEFINE NAMESPACE TMSIPlugin //============================================================================================================= namespace TMSIPlugin { //============================================================================================================= /** * TMSIImpedanceView... * * @brief The TMSIImpedanceView class provides a reimplemented QGraphicsView. */ class TMSIImpedanceView : public QGraphicsView { Q_OBJECT public: //========================================================================================================= /** * Constructs a TMSIImpedanceView. */ explicit TMSIImpedanceView(QWidget *parent = 0); private: //========================================================================================================= /** * Reimplemented wheel event used for zoomin in and out of the scene. */ void wheelEvent(QWheelEvent* event); //========================================================================================================= /** * Reimplemented resize event used scaling fitting the scene into the view after a resize occured. */ void resizeEvent(QResizeEvent* event); //========================================================================================================= /** * Reimplemented mouse press event handler. */ void mouseDoubleClickEvent(QMouseEvent* event); }; } // NAMESPACE #endif // TMSIIMPEDANCEVIEW_H
CBoensel/mne-cpp
applications/mne_x/plugins/tmsi/tmsiimpedanceview.h
C
bsd-3-clause
4,593
// 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. var current = chrome.app.window.current(); var bg = null; var nextTestNumber = 1; function makeEventTest(eventName, startFunction) { var test = function() { bg.clearEventCounts(); var listener = function() { current[eventName].removeListener(listener); function waitForBackgroundPageToSeeEvent() { if (!bg.eventCounts[eventName] > 0) { bg.eventCallback = waitForBackgroundPageToSeeEvent; } else { bg.eventCallback = null; current.restore(); chrome.test.succeed(); } } waitForBackgroundPageToSeeEvent(); }; current[eventName].addListener(listener); startFunction(); }; // For anonymous functions, setting 'generatedName' controls what shows up in // the apitest framework's logging output. test.generatedName = "Test" + nextTestNumber++ + "_" + eventName; return test; } var tests = { minimized: [ makeEventTest( 'onMinimized', function() { current.minimize(); }), ], maximized: [ makeEventTest( 'onMaximized', function() { current.maximize(); }), ], restored: [ makeEventTest( 'onRestored', function() { var doRestore = function() { current.onMinimized.removeListener(doRestore); current.restore(); }; current.onMinimized.addListener(doRestore); current.minimize(); }), makeEventTest( 'onRestored', function() { var doRestore = function() { current.onMaximized.removeListener(doRestore); current.restore(); }; current.onMaximized.addListener(doRestore); current.maximize(); }) ], boundsChanged: [ makeEventTest( 'onBoundsChanged', function() { current.outerBounds.setPosition(5, 5); }), makeEventTest( 'onBoundsChanged', function() { current.outerBounds.setSize(150, 150); }), makeEventTest( 'onBoundsChanged', function() { current.innerBounds.setPosition(40, 40); }), makeEventTest( 'onBoundsChanged', function() { current.innerBounds.setSize(100, 100); }) ], }; chrome.runtime.getBackgroundPage(function(page) { bg = page; chrome.test.getConfig(function(config) { if (config.customArg in tests) chrome.test.runTests(tests[config.customArg]); else chrome.test.fail('Test "' + config.customArg + '"" doesnt exist!'); }); });
ric2b/Vivaldi-browser
chromium/chrome/test/data/extensions/platform_apps/windows_api_properties/main.js
JavaScript
bsd-3-clause
2,782
@charset "UTF-8"; [ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak, .ng-hide { display: none !important; } ng\:form { display: block; } .ng-animate-block-transitions { transition:0s all!important; -webkit-transition:0s all!important; }
southampton-code-dojo/battleships
server/bower_components/angular-latest/css/angular.css
CSS
mit
277
# !!!!!!! DO NOT EDIT THIS FILE !!!!!!! # This file is machine-generated by mktables from the Unicode # database, Version 6.1.0. Any changes made here will be lost! # !!!!!!! INTERNAL PERL USE ONLY !!!!!!! # This file is for internal use by core Perl only. The format and even the # name or existence of this file are subject to change without notice. Don't # use it directly. return <<'END'; 05D0 05EA 05F0 05F2 FB1D FB1F FB28 FB2A FB36 FB38 FB3C FB3E FB40 FB41 FB43 FB44 FB46 FB4F END
liuyangning/WX_web
xampp/perl/lib/unicore/lib/Lb/HL.pl
Perl
mit
505
/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const ConstDependency = require("./dependencies/ConstDependency"); const ProvidedDependency = require("./dependencies/ProvidedDependency"); const { approve } = require("./javascript/JavascriptParserHelpers"); /** @typedef {import("./Compiler")} Compiler */ class ProvidePlugin { /** * @param {Record<string, string | string[]>} definitions the provided identifiers */ constructor(definitions) { this.definitions = definitions; } /** * Apply the plugin * @param {Compiler} compiler the compiler instance * @returns {void} */ apply(compiler) { const definitions = this.definitions; compiler.hooks.compilation.tap( "ProvidePlugin", (compilation, { normalModuleFactory }) => { compilation.dependencyTemplates.set( ConstDependency, new ConstDependency.Template() ); compilation.dependencyFactories.set( ProvidedDependency, normalModuleFactory ); compilation.dependencyTemplates.set( ProvidedDependency, new ProvidedDependency.Template() ); const handler = (parser, parserOptions) => { Object.keys(definitions).forEach(name => { const request = [].concat(definitions[name]); const splittedName = name.split("."); if (splittedName.length > 0) { splittedName.slice(1).forEach((_, i) => { const name = splittedName.slice(0, i + 1).join("."); parser.hooks.canRename.for(name).tap("ProvidePlugin", approve); }); } parser.hooks.expression.for(name).tap("ProvidePlugin", expr => { const nameIdentifier = name.includes(".") ? `__webpack_provided_${name.replace(/\./g, "_dot_")}` : name; const dep = new ProvidedDependency( request[0], nameIdentifier, request.slice(1), expr.range ); dep.loc = expr.loc; parser.state.module.addDependency(dep); return true; }); parser.hooks.call.for(name).tap("ProvidePlugin", expr => { const nameIdentifier = name.includes(".") ? `__webpack_provided_${name.replace(/\./g, "_dot_")}` : name; const dep = new ProvidedDependency( request[0], nameIdentifier, request.slice(1), expr.callee.range ); dep.loc = expr.callee.loc; parser.state.module.addDependency(dep); parser.walkExpressions(expr.arguments); return true; }); }); }; normalModuleFactory.hooks.parser .for("javascript/auto") .tap("ProvidePlugin", handler); normalModuleFactory.hooks.parser .for("javascript/dynamic") .tap("ProvidePlugin", handler); normalModuleFactory.hooks.parser .for("javascript/esm") .tap("ProvidePlugin", handler); } ); } } module.exports = ProvidePlugin;
arvenil/resume
node_modules/webpack/lib/ProvidePlugin.js
JavaScript
mit
2,890
var combine = require('stream-combiner2'); var through = require('through2'); var split = require('split'); var zlib = require('zlib'); module.exports = function () { var grouper = through(write, end); var current; function write (line, _, next) { if (line.length === 0) return next(); var row = JSON.parse(line); if (row.type === 'genre') { if (current) { this.push(JSON.stringify(current) + '\n'); } current = { name: row.name, books: [] }; } else if (row.type === 'book') { current.books.push(row.name); } next(); } function end (next) { if (current) { this.push(JSON.stringify(current) + '\n'); } next(); } return combine(split(), grouper, zlib.createGzip()); };
Gtskk/stream-adventure
test/solutions/combiner.js
JavaScript
mit
871
import EmberObject from 'ember-runtime/system/object'; import { get } from 'ember-metal/property_get'; import { mixin, Mixin } from 'ember-metal/mixin'; QUnit.module('Mixin mergedProperties'); QUnit.test('defining mergedProperties should merge future version', function() { var MixinA = Mixin.create({ mergedProperties: ['foo'], foo: { a: true, b: true, c: true } }); var MixinB = Mixin.create({ foo: { d: true, e: true, f: true } }); var obj = mixin({}, MixinA, MixinB); deepEqual(get(obj, 'foo'), { a: true, b: true, c: true, d: true, e: true, f: true }); }); QUnit.test('defining mergedProperties on future mixin should merged into past', function() { var MixinA = Mixin.create({ foo: { a: true, b: true, c: true } }); var MixinB = Mixin.create({ mergedProperties: ['foo'], foo: { d: true, e: true, f: true } }); var obj = mixin({}, MixinA, MixinB); deepEqual(get(obj, 'foo'), { a: true, b: true, c: true, d: true, e: true, f: true }); }); QUnit.test('defining mergedProperties with null properties should keep properties null', function() { var MixinA = Mixin.create({ mergedProperties: ['foo'], foo: null }); var MixinB = Mixin.create({ foo: null }); var obj = mixin({}, MixinA, MixinB); equal(get(obj, 'foo'), null); }); QUnit.test('mergedProperties\' properties can get overwritten', function() { var MixinA = Mixin.create({ mergedProperties: ['foo'], foo: { a: 1 } }); var MixinB = Mixin.create({ foo: { a: 2 } }); var obj = mixin({}, MixinA, MixinB); deepEqual(get(obj, 'foo'), { a: 2 }); }); QUnit.test('mergedProperties should be concatenated', function() { var MixinA = Mixin.create({ mergedProperties: ['foo'], foo: { a: true, b: true, c: true } }); var MixinB = Mixin.create({ mergedProperties: 'bar', foo: { d: true, e: true, f: true }, bar: { a: true, l: true } }); var MixinC = Mixin.create({ bar: { e: true, x: true } }); var obj = mixin({}, MixinA, MixinB, MixinC); deepEqual(get(obj, 'mergedProperties'), ['foo', 'bar'], 'get mergedProperties'); deepEqual(get(obj, 'foo'), { a: true, b: true, c: true, d: true, e: true, f: true }, 'get foo'); deepEqual(get(obj, 'bar'), { a: true, l: true, e: true, x: true }, 'get bar'); }); QUnit.test('mergedProperties should exist even if not explicitly set on create', function() { var AnObj = EmberObject.extend({ mergedProperties: ['options'], options: { a: 'a', b: { c: 'ccc' } } }); var obj = AnObj.create({ options: { a: 'A' } }); equal(get(obj, 'options').a, 'A'); equal(get(obj, 'options').b.c, 'ccc'); }); QUnit.test('mergedProperties\' overwriting methods can call _super', function() { expect(4); var MixinA = Mixin.create({ mergedProperties: ['foo'], foo: { meth(a) { equal(a, 'WOOT', '_super successfully called MixinA\'s `foo.meth` method'); return 'WAT'; } } }); var MixinB = Mixin.create({ foo: { meth(a) { ok(true, 'MixinB\'s `foo.meth` method called'); return this._super(...arguments); } } }); var MixinC = Mixin.create({ foo: { meth(a) { ok(true, 'MixinC\'s `foo.meth` method called'); return this._super(a); } } }); var obj = mixin({}, MixinA, MixinB, MixinC); equal(obj.foo.meth('WOOT'), 'WAT'); }); QUnit.test('Merging an Array should raise an error', function() { expect(1); var MixinA = Mixin.create({ mergedProperties: ['foo'], foo: { a: true, b: true, c: true } }); var MixinB = Mixin.create({ foo: ['a'] }); expectAssertion(function() { mixin({}, MixinA, MixinB); }, 'You passed in `["a"]` as the value for `foo` but `foo` cannot be an Array'); });
mdehoog/ember.js
packages/ember-metal/tests/mixin/merged_properties_test.js
JavaScript
mit
3,835
declare module 'mime' { declare type MimeMap = { [mimeType: string]: string[] } declare module.exports: { define(map: MimeMap): void; load(file: string): void; lookup(path: string, fallback?: string): string; extension(mimeType: string): string; default_type: string; charsets: { lookup: (mimeType: string, fallback: string) => string } }; }
flowtype/flow-typed
definitions/npm/node-mime_v1.x.x/flow_v0.25.x-v0.103.x/node-mime_v1.x.x.js
JavaScript
mit
390
--- version: 0.17 category: "Installation Guide" title: "Install Repositories" next: url: "install-sensu" text: "Install Sensu" success: "<strong>NOTE:</strong> this is part 3 of 6 steps in the Sensu Installation Guide. For the best results, please make sure to follow the instructions carefully and complete all of the steps in each section before moving on." --- # Overview Sensu Core is installed via software installer packages which are made available via software repositories for various platforms (e.g. APT repositories for Ubuntu/Debian, YUM repositories for CentOS/RHEL; installer packages for Microsoft Windows are also available). Sensu packages contain all of the Sensu services and their dependencies, with the exception of RabbitMQ & Redis. This ensures the simplest installation process, promotes consistency across installs, and prevents interference with other services. Sensu Enterprise is also installed via software installer packages which are made available via software repositories for various platforms. Sensu Enterprise depends on a Java runtime for execution. The following instructions will help you to: - Install the Sensu Core repository - **[OPTIONAL]** Install the Sensu Enterprise repository # Install the Sensu Core Repository _NOTE: installation of the Sensu core repository is required for all Sensu users, including Sensu Enterprise customers._ ## Ubuntu/Debian Install the GPG public key, and create the APT repository configuration file for the Sensu Core repository: ~~~ shell wget -q http://repos.sensuapp.org/apt/pubkey.gpg -O- | sudo apt-key add - echo "deb http://repos.sensuapp.org/apt sensu main" | sudo tee /etc/apt/sources.list.d/sensu.list ~~~ ## CentOS/RHEL Create the YUM repository configuration file for the Sensu Core repository at `/etc/yum.repos.d/sensu.repo`: ~~~ shell echo '[sensu] name=sensu baseurl=http://repos.sensuapp.org/yum/el/$basearch/ gpgcheck=0 enabled=1' | sudo tee /etc/yum.repos.d/sensu.repo ~~~ # Install the Sensu Enterprise Repository {#enterprise-installation} _NOTE: access to the Sensu Enterprise repositories requires an active [Sensu Enterprise](http://sensuapp.org/enterprise#pricing) subscription, and valid access credentials._ ## Set Access Credentials Please set the following environment variables, replacing `USER` and `PASSWORD` with the access credentials provided with your Sensu Enterprise subscription: ~~~ shell export SE_USER=USER export SE_PASS=PASSWORD ~~~ ## Ubuntu/Debian Install the GPG public key, and create the APT repository configuration file for the Sensu Enterprise repository: ~~~ shell wget -q http://$SE_USER:[email protected]/apt/pubkey.gpg -O- | sudo apt-key add - echo "deb http://$SE_USER:[email protected]/apt sensu-enterprise main" | sudo tee /etc/apt/sources.list.d/sensu-enterprise.list ~~~ ## CentOS/RHEL Create the YUM repository configuration file for the Sensu Enterprise repository at `/etc/yum.repos.d/sensu-enterprise.repo`: ~~~ shell echo "[sensu-enterprise] name=sensu-enterprise baseurl=http://$SE_USER:[email protected]/yum/noarch/ gpgcheck=0 enabled=1" | sudo tee /etc/yum.repos.d/sensu-enterprise.repo ~~~ Create the YUM repository configuration file for the Sensu Enterprise Dashboard repository at `/etc/yum.repos.d/sensu-enterprise-dashboard.repo`: ~~~ shell echo "[sensu-enterprise-dashboard] name=sensu-enterprise-dashboard baseurl=http://$SE_USER:[email protected]/yum/\$basearch/ gpgcheck=0 enabled=1" | sudo tee /etc/yum.repos.d/sensu-enterprise-dashboard.repo ~~~
mahata/sensu-docs
source/docs/0.17/install-repositories.md
Markdown
mit
3,609
/* Simple DirectMedia Layer Copyright (C) 1997-2019 Sam Lantinga <[email protected]> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ // Modified by Lasse Oorni for Urho3D /** * \file SDL_video.h * * Header file for SDL video functions. */ #ifndef SDL_video_h_ #define SDL_video_h_ #include "SDL_stdinc.h" #include "SDL_pixels.h" #include "SDL_rect.h" #include "SDL_surface.h" #include "begin_code.h" /* Set up for C function definitions, even when using C++ */ #ifdef __cplusplus extern "C" { #endif /** * \brief The structure that defines a display mode * * \sa SDL_GetNumDisplayModes() * \sa SDL_GetDisplayMode() * \sa SDL_GetDesktopDisplayMode() * \sa SDL_GetCurrentDisplayMode() * \sa SDL_GetClosestDisplayMode() * \sa SDL_SetWindowDisplayMode() * \sa SDL_GetWindowDisplayMode() */ typedef struct { Uint32 format; /**< pixel format */ int w; /**< width, in screen coordinates */ int h; /**< height, in screen coordinates */ int refresh_rate; /**< refresh rate (or zero for unspecified) */ void *driverdata; /**< driver-specific data, initialize to 0 */ } SDL_DisplayMode; /** * \brief The type used to identify a window * * \sa SDL_CreateWindow() * \sa SDL_CreateWindowFrom() * \sa SDL_DestroyWindow() * \sa SDL_GetWindowData() * \sa SDL_GetWindowFlags() * \sa SDL_GetWindowGrab() * \sa SDL_GetWindowPosition() * \sa SDL_GetWindowSize() * \sa SDL_GetWindowTitle() * \sa SDL_HideWindow() * \sa SDL_MaximizeWindow() * \sa SDL_MinimizeWindow() * \sa SDL_RaiseWindow() * \sa SDL_RestoreWindow() * \sa SDL_SetWindowData() * \sa SDL_SetWindowFullscreen() * \sa SDL_SetWindowGrab() * \sa SDL_SetWindowIcon() * \sa SDL_SetWindowPosition() * \sa SDL_SetWindowSize() * \sa SDL_SetWindowBordered() * \sa SDL_SetWindowResizable() * \sa SDL_SetWindowTitle() * \sa SDL_ShowWindow() */ typedef struct SDL_Window SDL_Window; /** * \brief The flags on a window * * \sa SDL_GetWindowFlags() */ typedef enum { /* !!! FIXME: change this to name = (1<<x). */ SDL_WINDOW_FULLSCREEN = 0x00000001, /**< fullscreen window */ SDL_WINDOW_OPENGL = 0x00000002, /**< window usable with OpenGL context */ SDL_WINDOW_SHOWN = 0x00000004, /**< window is visible */ SDL_WINDOW_HIDDEN = 0x00000008, /**< window is not visible */ SDL_WINDOW_BORDERLESS = 0x00000010, /**< no window decoration */ SDL_WINDOW_RESIZABLE = 0x00000020, /**< window can be resized */ SDL_WINDOW_MINIMIZED = 0x00000040, /**< window is minimized */ SDL_WINDOW_MAXIMIZED = 0x00000080, /**< window is maximized */ SDL_WINDOW_INPUT_GRABBED = 0x00000100, /**< window has grabbed input focus */ SDL_WINDOW_INPUT_FOCUS = 0x00000200, /**< window has input focus */ SDL_WINDOW_MOUSE_FOCUS = 0x00000400, /**< window has mouse focus */ SDL_WINDOW_FULLSCREEN_DESKTOP = ( SDL_WINDOW_FULLSCREEN | 0x00001000 ), SDL_WINDOW_FOREIGN = 0x00000800, /**< window not created by SDL */ SDL_WINDOW_ALLOW_HIGHDPI = 0x00002000, /**< window should be created in high-DPI mode if supported. On macOS NSHighResolutionCapable must be set true in the application's Info.plist for this to have any effect. */ SDL_WINDOW_MOUSE_CAPTURE = 0x00004000, /**< window has mouse captured (unrelated to INPUT_GRABBED) */ SDL_WINDOW_ALWAYS_ON_TOP = 0x00008000, /**< window should always be above others */ SDL_WINDOW_SKIP_TASKBAR = 0x00010000, /**< window should not be added to the taskbar */ SDL_WINDOW_UTILITY = 0x00020000, /**< window should be treated as a utility window */ SDL_WINDOW_TOOLTIP = 0x00040000, /**< window should be treated as a tooltip */ SDL_WINDOW_POPUP_MENU = 0x00080000, /**< window should be treated as a popup menu */ SDL_WINDOW_VULKAN = 0x10000000 /**< window usable for Vulkan surface */ } SDL_WindowFlags; /** * \brief Used to indicate that you don't care what the window position is. */ #define SDL_WINDOWPOS_UNDEFINED_MASK 0x1FFF0000u #define SDL_WINDOWPOS_UNDEFINED_DISPLAY(X) (SDL_WINDOWPOS_UNDEFINED_MASK|(X)) #define SDL_WINDOWPOS_UNDEFINED SDL_WINDOWPOS_UNDEFINED_DISPLAY(0) #define SDL_WINDOWPOS_ISUNDEFINED(X) \ (((X)&0xFFFF0000) == SDL_WINDOWPOS_UNDEFINED_MASK) /** * \brief Used to indicate that the window position should be centered. */ #define SDL_WINDOWPOS_CENTERED_MASK 0x2FFF0000u #define SDL_WINDOWPOS_CENTERED_DISPLAY(X) (SDL_WINDOWPOS_CENTERED_MASK|(X)) #define SDL_WINDOWPOS_CENTERED SDL_WINDOWPOS_CENTERED_DISPLAY(0) #define SDL_WINDOWPOS_ISCENTERED(X) \ (((X)&0xFFFF0000) == SDL_WINDOWPOS_CENTERED_MASK) /** * \brief Event subtype for window events */ typedef enum { SDL_WINDOWEVENT_NONE, /**< Never used */ SDL_WINDOWEVENT_SHOWN, /**< Window has been shown */ SDL_WINDOWEVENT_HIDDEN, /**< Window has been hidden */ SDL_WINDOWEVENT_EXPOSED, /**< Window has been exposed and should be redrawn */ SDL_WINDOWEVENT_MOVED, /**< Window has been moved to data1, data2 */ SDL_WINDOWEVENT_RESIZED, /**< Window has been resized to data1xdata2 */ SDL_WINDOWEVENT_SIZE_CHANGED, /**< The window size has changed, either as a result of an API call or through the system or user changing the window size. */ SDL_WINDOWEVENT_MINIMIZED, /**< Window has been minimized */ SDL_WINDOWEVENT_MAXIMIZED, /**< Window has been maximized */ SDL_WINDOWEVENT_RESTORED, /**< Window has been restored to normal size and position */ SDL_WINDOWEVENT_ENTER, /**< Window has gained mouse focus */ SDL_WINDOWEVENT_LEAVE, /**< Window has lost mouse focus */ SDL_WINDOWEVENT_FOCUS_GAINED, /**< Window has gained keyboard focus */ SDL_WINDOWEVENT_FOCUS_LOST, /**< Window has lost keyboard focus */ SDL_WINDOWEVENT_CLOSE, /**< The window manager requests that the window be closed */ SDL_WINDOWEVENT_TAKE_FOCUS, /**< Window is being offered a focus (should SetWindowInputFocus() on itself or a subwindow, or ignore) */ SDL_WINDOWEVENT_HIT_TEST /**< Window had a hit test that wasn't SDL_HITTEST_NORMAL. */ } SDL_WindowEventID; /** * \brief Event subtype for display events */ typedef enum { SDL_DISPLAYEVENT_NONE, /**< Never used */ SDL_DISPLAYEVENT_ORIENTATION /**< Display orientation has changed to data1 */ } SDL_DisplayEventID; typedef enum { SDL_ORIENTATION_UNKNOWN, /**< The display orientation can't be determined */ SDL_ORIENTATION_LANDSCAPE, /**< The display is in landscape mode, with the right side up, relative to portrait mode */ SDL_ORIENTATION_LANDSCAPE_FLIPPED, /**< The display is in landscape mode, with the left side up, relative to portrait mode */ SDL_ORIENTATION_PORTRAIT, /**< The display is in portrait mode */ SDL_ORIENTATION_PORTRAIT_FLIPPED /**< The display is in portrait mode, upside down */ } SDL_DisplayOrientation; /** * \brief An opaque handle to an OpenGL context. */ typedef void *SDL_GLContext; /** * \brief OpenGL configuration attributes */ typedef enum { SDL_GL_RED_SIZE, SDL_GL_GREEN_SIZE, SDL_GL_BLUE_SIZE, SDL_GL_ALPHA_SIZE, SDL_GL_BUFFER_SIZE, SDL_GL_DOUBLEBUFFER, SDL_GL_DEPTH_SIZE, SDL_GL_STENCIL_SIZE, SDL_GL_ACCUM_RED_SIZE, SDL_GL_ACCUM_GREEN_SIZE, SDL_GL_ACCUM_BLUE_SIZE, SDL_GL_ACCUM_ALPHA_SIZE, SDL_GL_STEREO, SDL_GL_MULTISAMPLEBUFFERS, SDL_GL_MULTISAMPLESAMPLES, SDL_GL_ACCELERATED_VISUAL, SDL_GL_RETAINED_BACKING, SDL_GL_CONTEXT_MAJOR_VERSION, SDL_GL_CONTEXT_MINOR_VERSION, SDL_GL_CONTEXT_EGL, SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_SHARE_WITH_CURRENT_CONTEXT, SDL_GL_FRAMEBUFFER_SRGB_CAPABLE, SDL_GL_CONTEXT_RELEASE_BEHAVIOR, SDL_GL_CONTEXT_RESET_NOTIFICATION, SDL_GL_CONTEXT_NO_ERROR } SDL_GLattr; typedef enum { SDL_GL_CONTEXT_PROFILE_CORE = 0x0001, SDL_GL_CONTEXT_PROFILE_COMPATIBILITY = 0x0002, SDL_GL_CONTEXT_PROFILE_ES = 0x0004 /**< GLX_CONTEXT_ES2_PROFILE_BIT_EXT */ } SDL_GLprofile; typedef enum { SDL_GL_CONTEXT_DEBUG_FLAG = 0x0001, SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG = 0x0002, SDL_GL_CONTEXT_ROBUST_ACCESS_FLAG = 0x0004, SDL_GL_CONTEXT_RESET_ISOLATION_FLAG = 0x0008 } SDL_GLcontextFlag; typedef enum { SDL_GL_CONTEXT_RELEASE_BEHAVIOR_NONE = 0x0000, SDL_GL_CONTEXT_RELEASE_BEHAVIOR_FLUSH = 0x0001 } SDL_GLcontextReleaseFlag; typedef enum { SDL_GL_CONTEXT_RESET_NO_NOTIFICATION = 0x0000, SDL_GL_CONTEXT_RESET_LOSE_CONTEXT = 0x0001 } SDL_GLContextResetNotification; /* Function prototypes */ /** * \brief Get the number of video drivers compiled into SDL * * \sa SDL_GetVideoDriver() */ extern DECLSPEC int SDLCALL SDL_GetNumVideoDrivers(void); /** * \brief Get the name of a built in video driver. * * \note The video drivers are presented in the order in which they are * normally checked during initialization. * * \sa SDL_GetNumVideoDrivers() */ extern DECLSPEC const char *SDLCALL SDL_GetVideoDriver(int index); /** * \brief Initialize the video subsystem, optionally specifying a video driver. * * \param driver_name Initialize a specific driver by name, or NULL for the * default video driver. * * \return 0 on success, -1 on error * * This function initializes the video subsystem; setting up a connection * to the window manager, etc, and determines the available display modes * and pixel formats, but does not initialize a window or graphics mode. * * \sa SDL_VideoQuit() */ extern DECLSPEC int SDLCALL SDL_VideoInit(const char *driver_name); /** * \brief Shuts down the video subsystem. * * This function closes all windows, and restores the original video mode. * * \sa SDL_VideoInit() */ extern DECLSPEC void SDLCALL SDL_VideoQuit(void); /** * \brief Returns the name of the currently initialized video driver. * * \return The name of the current video driver or NULL if no driver * has been initialized * * \sa SDL_GetNumVideoDrivers() * \sa SDL_GetVideoDriver() */ extern DECLSPEC const char *SDLCALL SDL_GetCurrentVideoDriver(void); /** * \brief Returns the number of available video displays. * * \sa SDL_GetDisplayBounds() */ extern DECLSPEC int SDLCALL SDL_GetNumVideoDisplays(void); /** * \brief Get the name of a display in UTF-8 encoding * * \return The name of a display, or NULL for an invalid display index. * * \sa SDL_GetNumVideoDisplays() */ extern DECLSPEC const char * SDLCALL SDL_GetDisplayName(int displayIndex); /** * \brief Get the desktop area represented by a display, with the primary * display located at 0,0 * * \return 0 on success, or -1 if the index is out of range. * * \sa SDL_GetNumVideoDisplays() */ extern DECLSPEC int SDLCALL SDL_GetDisplayBounds(int displayIndex, SDL_Rect * rect); /** * \brief Get the usable desktop area represented by a display, with the * primary display located at 0,0 * * This is the same area as SDL_GetDisplayBounds() reports, but with portions * reserved by the system removed. For example, on Mac OS X, this subtracts * the area occupied by the menu bar and dock. * * Setting a window to be fullscreen generally bypasses these unusable areas, * so these are good guidelines for the maximum space available to a * non-fullscreen window. * * \return 0 on success, or -1 if the index is out of range. * * \sa SDL_GetDisplayBounds() * \sa SDL_GetNumVideoDisplays() */ extern DECLSPEC int SDLCALL SDL_GetDisplayUsableBounds(int displayIndex, SDL_Rect * rect); /** * \brief Get the dots/pixels-per-inch for a display * * \note Diagonal, horizontal and vertical DPI can all be optionally * returned if the parameter is non-NULL. * * \return 0 on success, or -1 if no DPI information is available or the index is out of range. * * \sa SDL_GetNumVideoDisplays() */ extern DECLSPEC int SDLCALL SDL_GetDisplayDPI(int displayIndex, float * ddpi, float * hdpi, float * vdpi); /** * \brief Get the orientation of a display * * \return The orientation of the display, or SDL_ORIENTATION_UNKNOWN if it isn't available. * * \sa SDL_GetNumVideoDisplays() */ extern DECLSPEC SDL_DisplayOrientation SDLCALL SDL_GetDisplayOrientation(int displayIndex); /** * \brief Returns the number of available display modes. * * \sa SDL_GetDisplayMode() */ extern DECLSPEC int SDLCALL SDL_GetNumDisplayModes(int displayIndex); /** * \brief Fill in information about a specific display mode. * * \note The display modes are sorted in this priority: * \li bits per pixel -> more colors to fewer colors * \li width -> largest to smallest * \li height -> largest to smallest * \li refresh rate -> highest to lowest * * \sa SDL_GetNumDisplayModes() */ extern DECLSPEC int SDLCALL SDL_GetDisplayMode(int displayIndex, int modeIndex, SDL_DisplayMode * mode); /** * \brief Fill in information about the desktop display mode. */ extern DECLSPEC int SDLCALL SDL_GetDesktopDisplayMode(int displayIndex, SDL_DisplayMode * mode); /** * \brief Fill in information about the current display mode. */ extern DECLSPEC int SDLCALL SDL_GetCurrentDisplayMode(int displayIndex, SDL_DisplayMode * mode); /** * \brief Get the closest match to the requested display mode. * * \param displayIndex The index of display from which mode should be queried. * \param mode The desired display mode * \param closest A pointer to a display mode to be filled in with the closest * match of the available display modes. * * \return The passed in value \c closest, or NULL if no matching video mode * was available. * * The available display modes are scanned, and \c closest is filled in with the * closest mode matching the requested mode and returned. The mode format and * refresh_rate default to the desktop mode if they are 0. The modes are * scanned with size being first priority, format being second priority, and * finally checking the refresh_rate. If all the available modes are too * small, then NULL is returned. * * \sa SDL_GetNumDisplayModes() * \sa SDL_GetDisplayMode() */ extern DECLSPEC SDL_DisplayMode * SDLCALL SDL_GetClosestDisplayMode(int displayIndex, const SDL_DisplayMode * mode, SDL_DisplayMode * closest); /** * \brief Get the display index associated with a window. * * \return the display index of the display containing the center of the * window, or -1 on error. */ extern DECLSPEC int SDLCALL SDL_GetWindowDisplayIndex(SDL_Window * window); /** * \brief Set the display mode used when a fullscreen window is visible. * * By default the window's dimensions and the desktop format and refresh rate * are used. * * \param window The window for which the display mode should be set. * \param mode The mode to use, or NULL for the default mode. * * \return 0 on success, or -1 if setting the display mode failed. * * \sa SDL_GetWindowDisplayMode() * \sa SDL_SetWindowFullscreen() */ extern DECLSPEC int SDLCALL SDL_SetWindowDisplayMode(SDL_Window * window, const SDL_DisplayMode * mode); /** * \brief Fill in information about the display mode used when a fullscreen * window is visible. * * \sa SDL_SetWindowDisplayMode() * \sa SDL_SetWindowFullscreen() */ extern DECLSPEC int SDLCALL SDL_GetWindowDisplayMode(SDL_Window * window, SDL_DisplayMode * mode); /** * \brief Get the pixel format associated with the window. */ extern DECLSPEC Uint32 SDLCALL SDL_GetWindowPixelFormat(SDL_Window * window); /** * \brief Create a window with the specified position, dimensions, and flags. * * \param title The title of the window, in UTF-8 encoding. * \param x The x position of the window, ::SDL_WINDOWPOS_CENTERED, or * ::SDL_WINDOWPOS_UNDEFINED. * \param y The y position of the window, ::SDL_WINDOWPOS_CENTERED, or * ::SDL_WINDOWPOS_UNDEFINED. * \param w The width of the window, in screen coordinates. * \param h The height of the window, in screen coordinates. * \param flags The flags for the window, a mask of any of the following: * ::SDL_WINDOW_FULLSCREEN, ::SDL_WINDOW_OPENGL, * ::SDL_WINDOW_HIDDEN, ::SDL_WINDOW_BORDERLESS, * ::SDL_WINDOW_RESIZABLE, ::SDL_WINDOW_MAXIMIZED, * ::SDL_WINDOW_MINIMIZED, ::SDL_WINDOW_INPUT_GRABBED, * ::SDL_WINDOW_ALLOW_HIGHDPI, ::SDL_WINDOW_VULKAN. * * \return The created window, or NULL if window creation failed. * * If the window is created with the SDL_WINDOW_ALLOW_HIGHDPI flag, its size * in pixels may differ from its size in screen coordinates on platforms with * high-DPI support (e.g. iOS and Mac OS X). Use SDL_GetWindowSize() to query * the client area's size in screen coordinates, and SDL_GL_GetDrawableSize(), * SDL_Vulkan_GetDrawableSize(), or SDL_GetRendererOutputSize() to query the * drawable size in pixels. * * If the window is created with any of the SDL_WINDOW_OPENGL or * SDL_WINDOW_VULKAN flags, then the corresponding LoadLibrary function * (SDL_GL_LoadLibrary or SDL_Vulkan_LoadLibrary) is called and the * corresponding UnloadLibrary function is called by SDL_DestroyWindow(). * * If SDL_WINDOW_VULKAN is specified and there isn't a working Vulkan driver, * SDL_CreateWindow() will fail because SDL_Vulkan_LoadLibrary() will fail. * * \note On non-Apple devices, SDL requires you to either not link to the * Vulkan loader or link to a dynamic library version. This limitation * may be removed in a future version of SDL. * * \sa SDL_DestroyWindow() * \sa SDL_GL_LoadLibrary() * \sa SDL_Vulkan_LoadLibrary() */ extern DECLSPEC SDL_Window * SDLCALL SDL_CreateWindow(const char *title, int x, int y, int w, int h, Uint32 flags); /** * \brief Create an SDL window from an existing native window. * * \param data A pointer to driver-dependent window creation data * * \return The created window, or NULL if window creation failed. * * \sa SDL_DestroyWindow() */ // Urho3D: added window flags parameter extern DECLSPEC SDL_Window * SDLCALL SDL_CreateWindowFrom(const void *data, Uint32 flags); /** * \brief Get the numeric ID of a window, for logging purposes. */ extern DECLSPEC Uint32 SDLCALL SDL_GetWindowID(SDL_Window * window); /** * \brief Get a window from a stored ID, or NULL if it doesn't exist. */ extern DECLSPEC SDL_Window * SDLCALL SDL_GetWindowFromID(Uint32 id); /** * \brief Get the window flags. */ extern DECLSPEC Uint32 SDLCALL SDL_GetWindowFlags(SDL_Window * window); /** * \brief Set the title of a window, in UTF-8 format. * * \sa SDL_GetWindowTitle() */ extern DECLSPEC void SDLCALL SDL_SetWindowTitle(SDL_Window * window, const char *title); /** * \brief Get the title of a window, in UTF-8 format. * * \sa SDL_SetWindowTitle() */ extern DECLSPEC const char *SDLCALL SDL_GetWindowTitle(SDL_Window * window); /** * \brief Set the icon for a window. * * \param window The window for which the icon should be set. * \param icon The icon for the window. */ extern DECLSPEC void SDLCALL SDL_SetWindowIcon(SDL_Window * window, SDL_Surface * icon); /** * \brief Associate an arbitrary named pointer with a window. * * \param window The window to associate with the pointer. * \param name The name of the pointer. * \param userdata The associated pointer. * * \return The previous value associated with 'name' * * \note The name is case-sensitive. * * \sa SDL_GetWindowData() */ extern DECLSPEC void* SDLCALL SDL_SetWindowData(SDL_Window * window, const char *name, void *userdata); /** * \brief Retrieve the data pointer associated with a window. * * \param window The window to query. * \param name The name of the pointer. * * \return The value associated with 'name' * * \sa SDL_SetWindowData() */ extern DECLSPEC void *SDLCALL SDL_GetWindowData(SDL_Window * window, const char *name); /** * \brief Set the position of a window. * * \param window The window to reposition. * \param x The x coordinate of the window in screen coordinates, or * ::SDL_WINDOWPOS_CENTERED or ::SDL_WINDOWPOS_UNDEFINED. * \param y The y coordinate of the window in screen coordinates, or * ::SDL_WINDOWPOS_CENTERED or ::SDL_WINDOWPOS_UNDEFINED. * * \note The window coordinate origin is the upper left of the display. * * \sa SDL_GetWindowPosition() */ extern DECLSPEC void SDLCALL SDL_SetWindowPosition(SDL_Window * window, int x, int y); /** * \brief Get the position of a window. * * \param window The window to query. * \param x Pointer to variable for storing the x position, in screen * coordinates. May be NULL. * \param y Pointer to variable for storing the y position, in screen * coordinates. May be NULL. * * \sa SDL_SetWindowPosition() */ extern DECLSPEC void SDLCALL SDL_GetWindowPosition(SDL_Window * window, int *x, int *y); /** * \brief Set the size of a window's client area. * * \param window The window to resize. * \param w The width of the window, in screen coordinates. Must be >0. * \param h The height of the window, in screen coordinates. Must be >0. * * \note Fullscreen windows automatically match the size of the display mode, * and you should use SDL_SetWindowDisplayMode() to change their size. * * The window size in screen coordinates may differ from the size in pixels, if * the window was created with SDL_WINDOW_ALLOW_HIGHDPI on a platform with * high-dpi support (e.g. iOS or OS X). Use SDL_GL_GetDrawableSize() or * SDL_GetRendererOutputSize() to get the real client area size in pixels. * * \sa SDL_GetWindowSize() * \sa SDL_SetWindowDisplayMode() */ extern DECLSPEC void SDLCALL SDL_SetWindowSize(SDL_Window * window, int w, int h); /** * \brief Get the size of a window's client area. * * \param window The window to query. * \param w Pointer to variable for storing the width, in screen * coordinates. May be NULL. * \param h Pointer to variable for storing the height, in screen * coordinates. May be NULL. * * The window size in screen coordinates may differ from the size in pixels, if * the window was created with SDL_WINDOW_ALLOW_HIGHDPI on a platform with * high-dpi support (e.g. iOS or OS X). Use SDL_GL_GetDrawableSize() or * SDL_GetRendererOutputSize() to get the real client area size in pixels. * * \sa SDL_SetWindowSize() */ extern DECLSPEC void SDLCALL SDL_GetWindowSize(SDL_Window * window, int *w, int *h); /** * \brief Get the size of a window's borders (decorations) around the client area. * * \param window The window to query. * \param top Pointer to variable for storing the size of the top border. NULL is permitted. * \param left Pointer to variable for storing the size of the left border. NULL is permitted. * \param bottom Pointer to variable for storing the size of the bottom border. NULL is permitted. * \param right Pointer to variable for storing the size of the right border. NULL is permitted. * * \return 0 on success, or -1 if getting this information is not supported. * * \note if this function fails (returns -1), the size values will be * initialized to 0, 0, 0, 0 (if a non-NULL pointer is provided), as * if the window in question was borderless. */ extern DECLSPEC int SDLCALL SDL_GetWindowBordersSize(SDL_Window * window, int *top, int *left, int *bottom, int *right); /** * \brief Set the minimum size of a window's client area. * * \param window The window to set a new minimum size. * \param min_w The minimum width of the window, must be >0 * \param min_h The minimum height of the window, must be >0 * * \note You can't change the minimum size of a fullscreen window, it * automatically matches the size of the display mode. * * \sa SDL_GetWindowMinimumSize() * \sa SDL_SetWindowMaximumSize() */ extern DECLSPEC void SDLCALL SDL_SetWindowMinimumSize(SDL_Window * window, int min_w, int min_h); /** * \brief Get the minimum size of a window's client area. * * \param window The window to query. * \param w Pointer to variable for storing the minimum width, may be NULL * \param h Pointer to variable for storing the minimum height, may be NULL * * \sa SDL_GetWindowMaximumSize() * \sa SDL_SetWindowMinimumSize() */ extern DECLSPEC void SDLCALL SDL_GetWindowMinimumSize(SDL_Window * window, int *w, int *h); /** * \brief Set the maximum size of a window's client area. * * \param window The window to set a new maximum size. * \param max_w The maximum width of the window, must be >0 * \param max_h The maximum height of the window, must be >0 * * \note You can't change the maximum size of a fullscreen window, it * automatically matches the size of the display mode. * * \sa SDL_GetWindowMaximumSize() * \sa SDL_SetWindowMinimumSize() */ extern DECLSPEC void SDLCALL SDL_SetWindowMaximumSize(SDL_Window * window, int max_w, int max_h); /** * \brief Get the maximum size of a window's client area. * * \param window The window to query. * \param w Pointer to variable for storing the maximum width, may be NULL * \param h Pointer to variable for storing the maximum height, may be NULL * * \sa SDL_GetWindowMinimumSize() * \sa SDL_SetWindowMaximumSize() */ extern DECLSPEC void SDLCALL SDL_GetWindowMaximumSize(SDL_Window * window, int *w, int *h); /** * \brief Set the border state of a window. * * This will add or remove the window's SDL_WINDOW_BORDERLESS flag and * add or remove the border from the actual window. This is a no-op if the * window's border already matches the requested state. * * \param window The window of which to change the border state. * \param bordered SDL_FALSE to remove border, SDL_TRUE to add border. * * \note You can't change the border state of a fullscreen window. * * \sa SDL_GetWindowFlags() */ extern DECLSPEC void SDLCALL SDL_SetWindowBordered(SDL_Window * window, SDL_bool bordered); /** * \brief Set the user-resizable state of a window. * * This will add or remove the window's SDL_WINDOW_RESIZABLE flag and * allow/disallow user resizing of the window. This is a no-op if the * window's resizable state already matches the requested state. * * \param window The window of which to change the resizable state. * \param resizable SDL_TRUE to allow resizing, SDL_FALSE to disallow. * * \note You can't change the resizable state of a fullscreen window. * * \sa SDL_GetWindowFlags() */ extern DECLSPEC void SDLCALL SDL_SetWindowResizable(SDL_Window * window, SDL_bool resizable); /** * \brief Show a window. * * \sa SDL_HideWindow() */ extern DECLSPEC void SDLCALL SDL_ShowWindow(SDL_Window * window); /** * \brief Hide a window. * * \sa SDL_ShowWindow() */ extern DECLSPEC void SDLCALL SDL_HideWindow(SDL_Window * window); /** * \brief Raise a window above other windows and set the input focus. */ extern DECLSPEC void SDLCALL SDL_RaiseWindow(SDL_Window * window); /** * \brief Make a window as large as possible. * * \sa SDL_RestoreWindow() */ extern DECLSPEC void SDLCALL SDL_MaximizeWindow(SDL_Window * window); /** * \brief Minimize a window to an iconic representation. * * \sa SDL_RestoreWindow() */ extern DECLSPEC void SDLCALL SDL_MinimizeWindow(SDL_Window * window); /** * \brief Restore the size and position of a minimized or maximized window. * * \sa SDL_MaximizeWindow() * \sa SDL_MinimizeWindow() */ extern DECLSPEC void SDLCALL SDL_RestoreWindow(SDL_Window * window); /** * \brief Set a window's fullscreen state. * * \return 0 on success, or -1 if setting the display mode failed. * * \sa SDL_SetWindowDisplayMode() * \sa SDL_GetWindowDisplayMode() */ extern DECLSPEC int SDLCALL SDL_SetWindowFullscreen(SDL_Window * window, Uint32 flags); /** * \brief Get the SDL surface associated with the window. * * \return The window's framebuffer surface, or NULL on error. * * A new surface will be created with the optimal format for the window, * if necessary. This surface will be freed when the window is destroyed. * * \note You may not combine this with 3D or the rendering API on this window. * * \sa SDL_UpdateWindowSurface() * \sa SDL_UpdateWindowSurfaceRects() */ extern DECLSPEC SDL_Surface * SDLCALL SDL_GetWindowSurface(SDL_Window * window); /** * \brief Copy the window surface to the screen. * * \return 0 on success, or -1 on error. * * \sa SDL_GetWindowSurface() * \sa SDL_UpdateWindowSurfaceRects() */ extern DECLSPEC int SDLCALL SDL_UpdateWindowSurface(SDL_Window * window); /** * \brief Copy a number of rectangles on the window surface to the screen. * * \return 0 on success, or -1 on error. * * \sa SDL_GetWindowSurface() * \sa SDL_UpdateWindowSurface() */ extern DECLSPEC int SDLCALL SDL_UpdateWindowSurfaceRects(SDL_Window * window, const SDL_Rect * rects, int numrects); /** * \brief Set a window's input grab mode. * * \param window The window for which the input grab mode should be set. * \param grabbed This is SDL_TRUE to grab input, and SDL_FALSE to release input. * * If the caller enables a grab while another window is currently grabbed, * the other window loses its grab in favor of the caller's window. * * \sa SDL_GetWindowGrab() */ extern DECLSPEC void SDLCALL SDL_SetWindowGrab(SDL_Window * window, SDL_bool grabbed); /** * \brief Get a window's input grab mode. * * \return This returns SDL_TRUE if input is grabbed, and SDL_FALSE otherwise. * * \sa SDL_SetWindowGrab() */ extern DECLSPEC SDL_bool SDLCALL SDL_GetWindowGrab(SDL_Window * window); /** * \brief Get the window that currently has an input grab enabled. * * \return This returns the window if input is grabbed, and NULL otherwise. * * \sa SDL_SetWindowGrab() */ extern DECLSPEC SDL_Window * SDLCALL SDL_GetGrabbedWindow(void); /** * \brief Set the brightness (gamma correction) for a window. * * \return 0 on success, or -1 if setting the brightness isn't supported. * * \sa SDL_GetWindowBrightness() * \sa SDL_SetWindowGammaRamp() */ extern DECLSPEC int SDLCALL SDL_SetWindowBrightness(SDL_Window * window, float brightness); /** * \brief Get the brightness (gamma correction) for a window. * * \return The last brightness value passed to SDL_SetWindowBrightness() * * \sa SDL_SetWindowBrightness() */ extern DECLSPEC float SDLCALL SDL_GetWindowBrightness(SDL_Window * window); /** * \brief Set the opacity for a window * * \param window The window which will be made transparent or opaque * \param opacity Opacity (0.0f - transparent, 1.0f - opaque) This will be * clamped internally between 0.0f and 1.0f. * * \return 0 on success, or -1 if setting the opacity isn't supported. * * \sa SDL_GetWindowOpacity() */ extern DECLSPEC int SDLCALL SDL_SetWindowOpacity(SDL_Window * window, float opacity); /** * \brief Get the opacity of a window. * * If transparency isn't supported on this platform, opacity will be reported * as 1.0f without error. * * \param window The window in question. * \param out_opacity Opacity (0.0f - transparent, 1.0f - opaque) * * \return 0 on success, or -1 on error (invalid window, etc). * * \sa SDL_SetWindowOpacity() */ extern DECLSPEC int SDLCALL SDL_GetWindowOpacity(SDL_Window * window, float * out_opacity); /** * \brief Sets the window as a modal for another window (TODO: reconsider this function and/or its name) * * \param modal_window The window that should be modal * \param parent_window The parent window * * \return 0 on success, or -1 otherwise. */ extern DECLSPEC int SDLCALL SDL_SetWindowModalFor(SDL_Window * modal_window, SDL_Window * parent_window); /** * \brief Explicitly sets input focus to the window. * * You almost certainly want SDL_RaiseWindow() instead of this function. Use * this with caution, as you might give focus to a window that's completely * obscured by other windows. * * \param window The window that should get the input focus * * \return 0 on success, or -1 otherwise. * \sa SDL_RaiseWindow() */ extern DECLSPEC int SDLCALL SDL_SetWindowInputFocus(SDL_Window * window); /** * \brief Set the gamma ramp for a window. * * \param window The window for which the gamma ramp should be set. * \param red The translation table for the red channel, or NULL. * \param green The translation table for the green channel, or NULL. * \param blue The translation table for the blue channel, or NULL. * * \return 0 on success, or -1 if gamma ramps are unsupported. * * Set the gamma translation table for the red, green, and blue channels * of the video hardware. Each table is an array of 256 16-bit quantities, * representing a mapping between the input and output for that channel. * The input is the index into the array, and the output is the 16-bit * gamma value at that index, scaled to the output color precision. * * \sa SDL_GetWindowGammaRamp() */ extern DECLSPEC int SDLCALL SDL_SetWindowGammaRamp(SDL_Window * window, const Uint16 * red, const Uint16 * green, const Uint16 * blue); /** * \brief Get the gamma ramp for a window. * * \param window The window from which the gamma ramp should be queried. * \param red A pointer to a 256 element array of 16-bit quantities to hold * the translation table for the red channel, or NULL. * \param green A pointer to a 256 element array of 16-bit quantities to hold * the translation table for the green channel, or NULL. * \param blue A pointer to a 256 element array of 16-bit quantities to hold * the translation table for the blue channel, or NULL. * * \return 0 on success, or -1 if gamma ramps are unsupported. * * \sa SDL_SetWindowGammaRamp() */ extern DECLSPEC int SDLCALL SDL_GetWindowGammaRamp(SDL_Window * window, Uint16 * red, Uint16 * green, Uint16 * blue); /** * \brief Possible return values from the SDL_HitTest callback. * * \sa SDL_HitTest */ typedef enum { SDL_HITTEST_NORMAL, /**< Region is normal. No special properties. */ SDL_HITTEST_DRAGGABLE, /**< Region can drag entire window. */ SDL_HITTEST_RESIZE_TOPLEFT, SDL_HITTEST_RESIZE_TOP, SDL_HITTEST_RESIZE_TOPRIGHT, SDL_HITTEST_RESIZE_RIGHT, SDL_HITTEST_RESIZE_BOTTOMRIGHT, SDL_HITTEST_RESIZE_BOTTOM, SDL_HITTEST_RESIZE_BOTTOMLEFT, SDL_HITTEST_RESIZE_LEFT } SDL_HitTestResult; /** * \brief Callback used for hit-testing. * * \sa SDL_SetWindowHitTest */ typedef SDL_HitTestResult (SDLCALL *SDL_HitTest)(SDL_Window *win, const SDL_Point *area, void *data); /** * \brief Provide a callback that decides if a window region has special properties. * * Normally windows are dragged and resized by decorations provided by the * system window manager (a title bar, borders, etc), but for some apps, it * makes sense to drag them from somewhere else inside the window itself; for * example, one might have a borderless window that wants to be draggable * from any part, or simulate its own title bar, etc. * * This function lets the app provide a callback that designates pieces of * a given window as special. This callback is run during event processing * if we need to tell the OS to treat a region of the window specially; the * use of this callback is known as "hit testing." * * Mouse input may not be delivered to your application if it is within * a special area; the OS will often apply that input to moving the window or * resizing the window and not deliver it to the application. * * Specifying NULL for a callback disables hit-testing. Hit-testing is * disabled by default. * * Platforms that don't support this functionality will return -1 * unconditionally, even if you're attempting to disable hit-testing. * * Your callback may fire at any time, and its firing does not indicate any * specific behavior (for example, on Windows, this certainly might fire * when the OS is deciding whether to drag your window, but it fires for lots * of other reasons, too, some unrelated to anything you probably care about * _and when the mouse isn't actually at the location it is testing_). * Since this can fire at any time, you should try to keep your callback * efficient, devoid of allocations, etc. * * \param window The window to set hit-testing on. * \param callback The callback to call when doing a hit-test. * \param callback_data An app-defined void pointer passed to the callback. * \return 0 on success, -1 on error (including unsupported). */ extern DECLSPEC int SDLCALL SDL_SetWindowHitTest(SDL_Window * window, SDL_HitTest callback, void *callback_data); /** * \brief Destroy a window. */ extern DECLSPEC void SDLCALL SDL_DestroyWindow(SDL_Window * window); /** * \brief Returns whether the screensaver is currently enabled (default off). * * \sa SDL_EnableScreenSaver() * \sa SDL_DisableScreenSaver() */ extern DECLSPEC SDL_bool SDLCALL SDL_IsScreenSaverEnabled(void); /** * \brief Allow the screen to be blanked by a screensaver * * \sa SDL_IsScreenSaverEnabled() * \sa SDL_DisableScreenSaver() */ extern DECLSPEC void SDLCALL SDL_EnableScreenSaver(void); /** * \brief Prevent the screen from being blanked by a screensaver * * \sa SDL_IsScreenSaverEnabled() * \sa SDL_EnableScreenSaver() */ extern DECLSPEC void SDLCALL SDL_DisableScreenSaver(void); /** * \name OpenGL support functions */ /* @{ */ /** * \brief Dynamically load an OpenGL library. * * \param path The platform dependent OpenGL library name, or NULL to open the * default OpenGL library. * * \return 0 on success, or -1 if the library couldn't be loaded. * * This should be done after initializing the video driver, but before * creating any OpenGL windows. If no OpenGL library is loaded, the default * library will be loaded upon creation of the first OpenGL window. * * \note If you do this, you need to retrieve all of the GL functions used in * your program from the dynamic library using SDL_GL_GetProcAddress(). * * \sa SDL_GL_GetProcAddress() * \sa SDL_GL_UnloadLibrary() */ extern DECLSPEC int SDLCALL SDL_GL_LoadLibrary(const char *path); /** * \brief Get the address of an OpenGL function. */ extern DECLSPEC void *SDLCALL SDL_GL_GetProcAddress(const char *proc); /** * \brief Unload the OpenGL library previously loaded by SDL_GL_LoadLibrary(). * * \sa SDL_GL_LoadLibrary() */ extern DECLSPEC void SDLCALL SDL_GL_UnloadLibrary(void); /** * \brief Return true if an OpenGL extension is supported for the current * context. */ extern DECLSPEC SDL_bool SDLCALL SDL_GL_ExtensionSupported(const char *extension); /** * \brief Reset all previously set OpenGL context attributes to their default values */ extern DECLSPEC void SDLCALL SDL_GL_ResetAttributes(void); /** * \brief Set an OpenGL window attribute before window creation. * * \return 0 on success, or -1 if the attribute could not be set. */ extern DECLSPEC int SDLCALL SDL_GL_SetAttribute(SDL_GLattr attr, int value); /** * \brief Get the actual value for an attribute from the current context. * * \return 0 on success, or -1 if the attribute could not be retrieved. * The integer at \c value will be modified in either case. */ extern DECLSPEC int SDLCALL SDL_GL_GetAttribute(SDL_GLattr attr, int *value); /** * \brief Create an OpenGL context for use with an OpenGL window, and make it * current. * * \sa SDL_GL_DeleteContext() */ extern DECLSPEC SDL_GLContext SDLCALL SDL_GL_CreateContext(SDL_Window * window); /** * \brief Set up an OpenGL context for rendering into an OpenGL window. * * \note The context must have been created with a compatible window. */ extern DECLSPEC int SDLCALL SDL_GL_MakeCurrent(SDL_Window * window, SDL_GLContext context); /** * \brief Get the currently active OpenGL window. */ extern DECLSPEC SDL_Window* SDLCALL SDL_GL_GetCurrentWindow(void); /** * \brief Get the currently active OpenGL context. */ extern DECLSPEC SDL_GLContext SDLCALL SDL_GL_GetCurrentContext(void); /** * \brief Get the size of a window's underlying drawable in pixels (for use * with glViewport). * * \param window Window from which the drawable size should be queried * \param w Pointer to variable for storing the width in pixels, may be NULL * \param h Pointer to variable for storing the height in pixels, may be NULL * * This may differ from SDL_GetWindowSize() if we're rendering to a high-DPI * drawable, i.e. the window was created with SDL_WINDOW_ALLOW_HIGHDPI on a * platform with high-DPI support (Apple calls this "Retina"), and not disabled * by the SDL_HINT_VIDEO_HIGHDPI_DISABLED hint. * * \sa SDL_GetWindowSize() * \sa SDL_CreateWindow() */ extern DECLSPEC void SDLCALL SDL_GL_GetDrawableSize(SDL_Window * window, int *w, int *h); /** * \brief Set the swap interval for the current OpenGL context. * * \param interval 0 for immediate updates, 1 for updates synchronized with the * vertical retrace. If the system supports it, you may * specify -1 to allow late swaps to happen immediately * instead of waiting for the next retrace. * * \return 0 on success, or -1 if setting the swap interval is not supported. * * \sa SDL_GL_GetSwapInterval() */ extern DECLSPEC int SDLCALL SDL_GL_SetSwapInterval(int interval); /** * \brief Get the swap interval for the current OpenGL context. * * \return 0 if there is no vertical retrace synchronization, 1 if the buffer * swap is synchronized with the vertical retrace, and -1 if late * swaps happen immediately instead of waiting for the next retrace. * If the system can't determine the swap interval, or there isn't a * valid current context, this will return 0 as a safe default. * * \sa SDL_GL_SetSwapInterval() */ extern DECLSPEC int SDLCALL SDL_GL_GetSwapInterval(void); /** * \brief Swap the OpenGL buffers for a window, if double-buffering is * supported. */ extern DECLSPEC void SDLCALL SDL_GL_SwapWindow(SDL_Window * window); /** * \brief Delete an OpenGL context. * * \sa SDL_GL_CreateContext() */ extern DECLSPEC void SDLCALL SDL_GL_DeleteContext(SDL_GLContext context); /* @} *//* OpenGL support functions */ /* Ends C function definitions when using C++ */ #ifdef __cplusplus } #endif #include "close_code.h" #endif /* SDL_video_h_ */ /* vi: set ts=4 sw=4 expandtab: */
bacsmar/Urho3D
Source/ThirdParty/SDL/include/SDL_video.h
C
mit
46,604
/* jshint node:true */ 'use strict'; // Expose `React` as a global, because the ReactIntlMixin assumes it's global. var oldReact = global.React; global.React = require('react'); // Require the lib and add all locale data to `ReactIntl`. This module will be // ignored when bundling for the browser with Browserify/Webpack. var ReactIntl = require('./lib/react-intl'); require('./lib/locales'); // Export the Mixin as the default export for back-compat with v1.0.0. This will // be changed to simply re-exporting `ReactIntl` as the default export in v2.0. exports = module.exports = ReactIntl.IntlMixin; // Define non-enumerable expandos for each named export on the default export -- // which is the Mixin for back-compat with v1.0.0. Object.keys(ReactIntl).forEach(function (namedExport) { Object.defineProperty(exports, namedExport, { enumerable: true, value : ReactIntl[namedExport] }); }); // Put back `global.React` to how it was. if (oldReact) { global.React = oldReact; } else { // IE < 9 will throw when trying to delete something off the global object, // `window`, so this does the next best thing as sets it to `undefined`. try { delete global.React; } catch (e) { global.React = undefined; } }
Rooiean/study
public/vendor/react-intl/index.js
JavaScript
mit
1,279
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {ɵgetDOM as getDOM} from '@angular/common'; import {beforeEach, describe, it} from '@angular/core/testing/src/testing_internal'; import {DomSharedStylesHost} from '@angular/platform-browser/src/dom/shared_styles_host'; import {expect} from '@angular/platform-browser/testing/src/matchers'; { describe('DomSharedStylesHost', () => { let doc: Document; let ssh: DomSharedStylesHost; let someHost: Element; beforeEach(() => { doc = getDOM().createHtmlDocument(); doc.title = ''; ssh = new DomSharedStylesHost(doc); someHost = getDOM().createElement('div'); }); it('should add existing styles to new hosts', () => { ssh.addStyles(['a {};']); ssh.addHost(someHost); expect(someHost.innerHTML).toEqual('<style>a {};</style>'); }); it('should add new styles to hosts', () => { ssh.addHost(someHost); ssh.addStyles(['a {};']); expect(someHost.innerHTML).toEqual('<style>a {};</style>'); }); it('should add styles only once to hosts', () => { ssh.addStyles(['a {};']); ssh.addHost(someHost); ssh.addStyles(['a {};']); expect(someHost.innerHTML).toEqual('<style>a {};</style>'); }); it('should use the document head as default host', () => { ssh.addStyles(['a {};', 'b {};']); expect(doc.head).toHaveText('a {};b {};'); }); it('should remove style nodes on destroy', () => { ssh.addStyles(['a {};']); ssh.addHost(someHost); expect(someHost.innerHTML).toEqual('<style>a {};</style>'); ssh.ngOnDestroy(); expect(someHost.innerHTML).toEqual(''); }); }); }
Toxicable/angular
packages/platform-browser/test/dom/shared_styles_host_spec.ts
TypeScript
mit
1,852
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2015, Daniel Stenberg, <[email protected]>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #if defined(USE_GSKIT) || defined(USE_NSS) || defined(USE_GNUTLS) || \ defined(USE_CYASSL) #include <curl/curl.h> #include "urldata.h" #include "strequal.h" #include "hostcheck.h" #include "vtls/vtls.h" #include "sendf.h" #include "inet_pton.h" #include "curl_base64.h" #include "x509asn1.h" #include "curl_printf.h" #include "curl_memory.h" /* The last #include file should be: */ #include "memdebug.h" /* ASN.1 OIDs. */ static const char cnOID[] = "2.5.4.3"; /* Common name. */ static const char sanOID[] = "2.5.29.17"; /* Subject alternative name. */ static const curl_OID OIDtable[] = { { "1.2.840.10040.4.1", "dsa" }, { "1.2.840.10040.4.3", "dsa-with-sha1" }, { "1.2.840.10045.2.1", "ecPublicKey" }, { "1.2.840.10045.3.0.1", "c2pnb163v1" }, { "1.2.840.10045.4.1", "ecdsa-with-SHA1" }, { "1.2.840.10046.2.1", "dhpublicnumber" }, { "1.2.840.113549.1.1.1", "rsaEncryption" }, { "1.2.840.113549.1.1.2", "md2WithRSAEncryption" }, { "1.2.840.113549.1.1.4", "md5WithRSAEncryption" }, { "1.2.840.113549.1.1.5", "sha1WithRSAEncryption" }, { "1.2.840.113549.1.1.10", "RSASSA-PSS" }, { "1.2.840.113549.1.1.14", "sha224WithRSAEncryption" }, { "1.2.840.113549.1.1.11", "sha256WithRSAEncryption" }, { "1.2.840.113549.1.1.12", "sha384WithRSAEncryption" }, { "1.2.840.113549.1.1.13", "sha512WithRSAEncryption" }, { "1.2.840.113549.2.2", "md2" }, { "1.2.840.113549.2.5", "md5" }, { "1.3.14.3.2.26", "sha1" }, { cnOID, "CN" }, { "2.5.4.4", "SN" }, { "2.5.4.5", "serialNumber" }, { "2.5.4.6", "C" }, { "2.5.4.7", "L" }, { "2.5.4.8", "ST" }, { "2.5.4.9", "streetAddress" }, { "2.5.4.10", "O" }, { "2.5.4.11", "OU" }, { "2.5.4.12", "title" }, { "2.5.4.13", "description" }, { "2.5.4.17", "postalCode" }, { "2.5.4.41", "name" }, { "2.5.4.42", "givenName" }, { "2.5.4.43", "initials" }, { "2.5.4.44", "generationQualifier" }, { "2.5.4.45", "X500UniqueIdentifier" }, { "2.5.4.46", "dnQualifier" }, { "2.5.4.65", "pseudonym" }, { "1.2.840.113549.1.9.1", "emailAddress" }, { "2.5.4.72", "role" }, { sanOID, "subjectAltName" }, { "2.5.29.18", "issuerAltName" }, { "2.5.29.19", "basicConstraints" }, { "2.16.840.1.101.3.4.2.4", "sha224" }, { "2.16.840.1.101.3.4.2.1", "sha256" }, { "2.16.840.1.101.3.4.2.2", "sha384" }, { "2.16.840.1.101.3.4.2.3", "sha512" }, { (const char *) NULL, (const char *) NULL } }; /* * Lightweight ASN.1 parser. * In particular, it does not check for syntactic/lexical errors. * It is intended to support certificate information gathering for SSL backends * that offer a mean to get certificates as a whole, but do not supply * entry points to get particular certificate sub-fields. * Please note there is no pretention here to rewrite a full SSL library. */ const char * Curl_getASN1Element(curl_asn1Element * elem, const char * beg, const char * end) { unsigned char b; unsigned long len; curl_asn1Element lelem; /* Get a single ASN.1 element into `elem', parse ASN.1 string at `beg' ending at `end'. Returns a pointer in source string after the parsed element, or NULL if an error occurs. */ if(beg >= end || !*beg) return (const char *) NULL; /* Process header byte. */ elem->header = beg; b = (unsigned char) *beg++; elem->constructed = (b & 0x20) != 0; elem->class = (b >> 6) & 3; b &= 0x1F; if(b == 0x1F) return (const char *) NULL; /* Long tag values not supported here. */ elem->tag = b; /* Process length. */ if(beg >= end) return (const char *) NULL; b = (unsigned char) *beg++; if(!(b & 0x80)) len = b; else if(!(b &= 0x7F)) { /* Unspecified length. Since we have all the data, we can determine the effective length by skipping element until an end element is found. */ if(!elem->constructed) return (const char *) NULL; elem->beg = beg; while(beg < end && *beg) { beg = Curl_getASN1Element(&lelem, beg, end); if(!beg) return (const char *) NULL; } if(beg >= end) return (const char *) NULL; elem->end = beg; return beg + 1; } else if(beg + b > end) return (const char *) NULL; /* Does not fit in source. */ else { /* Get long length. */ len = 0; do { if(len & 0xFF000000L) return (const char *) NULL; /* Lengths > 32 bits are not supported. */ len = (len << 8) | (unsigned char) *beg++; } while(--b); } if((unsigned long) (end - beg) < len) return (const char *) NULL; /* Element data does not fit in source. */ elem->beg = beg; elem->end = beg + len; return elem->end; } static const curl_OID * searchOID(const char * oid) { const curl_OID * op; /* Search the null terminated OID or OID identifier in local table. Return the table entry pointer or NULL if not found. */ for(op = OIDtable; op->numoid; op++) if(!strcmp(op->numoid, oid) || curl_strequal(op->textoid, oid)) return op; return (const curl_OID *) NULL; } static const char * bool2str(const char * beg, const char * end) { /* Convert an ASN.1 Boolean value into its string representation. Return the dynamically allocated string, or NULL if source is not an ASN.1 Boolean value. */ if(end - beg != 1) return (const char *) NULL; return strdup(*beg? "TRUE": "FALSE"); } static const char * octet2str(const char * beg, const char * end) { size_t n = end - beg; char * buf; /* Convert an ASN.1 octet string to a printable string. Return the dynamically allocated string, or NULL if an error occurs. */ buf = malloc(3 * n + 1); if(buf) for(n = 0; beg < end; n += 3) snprintf(buf + n, 4, "%02x:", *(const unsigned char *) beg++); return buf; } static const char * bit2str(const char * beg, const char * end) { /* Convert an ASN.1 bit string to a printable string. Return the dynamically allocated string, or NULL if an error occurs. */ if(++beg > end) return (const char *) NULL; return octet2str(beg, end); } static const char * int2str(const char * beg, const char * end) { long val = 0; size_t n = end - beg; /* Convert an ASN.1 integer value into its string representation. Return the dynamically allocated string, or NULL if source is not an ASN.1 integer value. */ if(!n) return (const char *) NULL; if(n > 4) return octet2str(beg, end); /* Represent integers <= 32-bit as a single value. */ if(*beg & 0x80) val = ~val; do val = (val << 8) | *(const unsigned char *) beg++; while(beg < end); return curl_maprintf("%s%lx", (val < 0 || val >= 10)? "0x": "", val); } static ssize_t utf8asn1str(char * * to, int type, const char * from, const char * end) { size_t inlength = end - from; int size = 1; size_t outlength; int charsize; unsigned int wc; char * buf; /* Perform a lazy conversion from an ASN.1 typed string to UTF8. Allocate the destination buffer dynamically. The allocation size will normally be too large: this is to avoid buffer overflows. Terminate the string with a nul byte and return the converted string length. */ *to = (char *) NULL; switch (type) { case CURL_ASN1_BMP_STRING: size = 2; break; case CURL_ASN1_UNIVERSAL_STRING: size = 4; break; case CURL_ASN1_NUMERIC_STRING: case CURL_ASN1_PRINTABLE_STRING: case CURL_ASN1_TELETEX_STRING: case CURL_ASN1_IA5_STRING: case CURL_ASN1_VISIBLE_STRING: case CURL_ASN1_UTF8_STRING: break; default: return -1; /* Conversion not supported. */ } if(inlength % size) return -1; /* Length inconsistent with character size. */ buf = malloc(4 * (inlength / size) + 1); if(!buf) return -1; /* Not enough memory. */ if(type == CURL_ASN1_UTF8_STRING) { /* Just copy. */ outlength = inlength; if(outlength) memcpy(buf, from, outlength); } else { for(outlength = 0; from < end;) { wc = 0; switch (size) { case 4: wc = (wc << 8) | *(const unsigned char *) from++; wc = (wc << 8) | *(const unsigned char *) from++; /* fallthrough */ case 2: wc = (wc << 8) | *(const unsigned char *) from++; /* fallthrough */ default: /* case 1: */ wc = (wc << 8) | *(const unsigned char *) from++; } charsize = 1; if(wc >= 0x00000080) { if(wc >= 0x00000800) { if(wc >= 0x00010000) { if(wc >= 0x00200000) { free(buf); return -1; /* Invalid char. size for target encoding. */ } buf[outlength + 3] = (char) (0x80 | (wc & 0x3F)); wc = (wc >> 6) | 0x00010000; charsize++; } buf[outlength + 2] = (char) (0x80 | (wc & 0x3F)); wc = (wc >> 6) | 0x00000800; charsize++; } buf[outlength + 1] = (char) (0x80 | (wc & 0x3F)); wc = (wc >> 6) | 0x000000C0; charsize++; } buf[outlength] = (char) wc; outlength += charsize; } } buf[outlength] = '\0'; *to = buf; return outlength; } static const char * string2str(int type, const char * beg, const char * end) { char * buf; /* Convert an ASN.1 String into its UTF-8 string representation. Return the dynamically allocated string, or NULL if an error occurs. */ if(utf8asn1str(&buf, type, beg, end) < 0) return (const char *) NULL; return buf; } static int encodeUint(char * buf, int n, unsigned int x) { int i = 0; unsigned int y = x / 10; /* Decimal ASCII encode unsigned integer `x' in the `n'-byte buffer at `buf'. Return the total number of encoded digits, even if larger than `n'. */ if(y) { i += encodeUint(buf, n, y); x -= y * 10; } if(i < n) buf[i] = (char) ('0' + x); i++; if(i < n) buf[i] = '\0'; /* Store a terminator if possible. */ return i; } static int encodeOID(char * buf, int n, const char * beg, const char * end) { int i = 0; unsigned int x; unsigned int y; /* Convert an ASN.1 OID into its dotted string representation. Store the result in th `n'-byte buffer at `buf'. Return the converted string length, or -1 if an error occurs. */ /* Process the first two numbers. */ y = *(const unsigned char *) beg++; x = y / 40; y -= x * 40; i += encodeUint(buf + i, n - i, x); if(i < n) buf[i] = '.'; i++; i += encodeUint(buf + i, n - i, y); /* Process the trailing numbers. */ while(beg < end) { if(i < n) buf[i] = '.'; i++; x = 0; do { if(x & 0xFF000000) return -1; y = *(const unsigned char *) beg++; x = (x << 7) | (y & 0x7F); } while(y & 0x80); i += encodeUint(buf + i, n - i, x); } if(i < n) buf[i] = '\0'; return i; } static const char * OID2str(const char * beg, const char * end, bool symbolic) { char * buf = (char *) NULL; const curl_OID * op; int n; /* Convert an ASN.1 OID into its dotted or symbolic string representation. Return the dynamically allocated string, or NULL if an error occurs. */ if(beg < end) { n = encodeOID((char *) NULL, -1, beg, end); if(n >= 0) { buf = malloc(n + 1); if(buf) { encodeOID(buf, n, beg, end); buf[n] = '\0'; if(symbolic) { op = searchOID(buf); if(op) { free(buf); buf = strdup(op->textoid); } } } } } return buf; } static const char * GTime2str(const char * beg, const char * end) { const char * tzp; const char * fracp; char sec1, sec2; size_t fracl; size_t tzl; const char * sep = ""; /* Convert an ASN.1 Generalized time to a printable string. Return the dynamically allocated string, or NULL if an error occurs. */ for(fracp = beg; fracp < end && *fracp >= '0' && *fracp <= '9'; fracp++) ; /* Get seconds digits. */ sec1 = '0'; switch (fracp - beg - 12) { case 0: sec2 = '0'; break; case 2: sec1 = fracp[-2]; case 1: sec2 = fracp[-1]; break; default: return (const char *) NULL; } /* Scan for timezone, measure fractional seconds. */ tzp = fracp; fracl = 0; if(fracp < end && (*fracp == '.' || *fracp == ',')) { fracp++; do tzp++; while(tzp < end && *tzp >= '0' && *tzp <= '9'); /* Strip leading zeroes in fractional seconds. */ for(fracl = tzp - fracp - 1; fracl && fracp[fracl - 1] == '0'; fracl--) ; } /* Process timezone. */ if(tzp >= end) ; /* Nothing to do. */ else if(*tzp == 'Z') { tzp = " GMT"; end = tzp + 4; } else { sep = " "; tzp++; } tzl = end - tzp; return curl_maprintf("%.4s-%.2s-%.2s %.2s:%.2s:%c%c%s%.*s%s%.*s", beg, beg + 4, beg + 6, beg + 8, beg + 10, sec1, sec2, fracl? ".": "", fracl, fracp, sep, tzl, tzp); } static const char * UTime2str(const char * beg, const char * end) { const char * tzp; size_t tzl; const char * sec; /* Convert an ASN.1 UTC time to a printable string. Return the dynamically allocated string, or NULL if an error occurs. */ for(tzp = beg; tzp < end && *tzp >= '0' && *tzp <= '9'; tzp++) ; /* Get the seconds. */ sec = beg + 10; switch (tzp - sec) { case 0: sec = "00"; case 2: break; default: return (const char *) NULL; } /* Process timezone. */ if(tzp >= end) return (const char *) NULL; if(*tzp == 'Z') { tzp = "GMT"; end = tzp + 3; } else tzp++; tzl = end - tzp; return curl_maprintf("%u%.2s-%.2s-%.2s %.2s:%.2s:%.2s %.*s", 20 - (*beg >= '5'), beg, beg + 2, beg + 4, beg + 6, beg + 8, sec, tzl, tzp); } const char * Curl_ASN1tostr(curl_asn1Element * elem, int type) { /* Convert an ASN.1 element to a printable string. Return the dynamically allocated string, or NULL if an error occurs. */ if(elem->constructed) return (const char *) NULL; /* No conversion of structured elements. */ if(!type) type = elem->tag; /* Type not forced: use element tag as type. */ switch (type) { case CURL_ASN1_BOOLEAN: return bool2str(elem->beg, elem->end); case CURL_ASN1_INTEGER: case CURL_ASN1_ENUMERATED: return int2str(elem->beg, elem->end); case CURL_ASN1_BIT_STRING: return bit2str(elem->beg, elem->end); case CURL_ASN1_OCTET_STRING: return octet2str(elem->beg, elem->end); case CURL_ASN1_NULL: return strdup(""); case CURL_ASN1_OBJECT_IDENTIFIER: return OID2str(elem->beg, elem->end, TRUE); case CURL_ASN1_UTC_TIME: return UTime2str(elem->beg, elem->end); case CURL_ASN1_GENERALIZED_TIME: return GTime2str(elem->beg, elem->end); case CURL_ASN1_UTF8_STRING: case CURL_ASN1_NUMERIC_STRING: case CURL_ASN1_PRINTABLE_STRING: case CURL_ASN1_TELETEX_STRING: case CURL_ASN1_IA5_STRING: case CURL_ASN1_VISIBLE_STRING: case CURL_ASN1_UNIVERSAL_STRING: case CURL_ASN1_BMP_STRING: return string2str(type, elem->beg, elem->end); } return (const char *) NULL; /* Unsupported. */ } static ssize_t encodeDN(char * buf, size_t n, curl_asn1Element * dn) { curl_asn1Element rdn; curl_asn1Element atv; curl_asn1Element oid; curl_asn1Element value; size_t l = 0; const char * p1; const char * p2; const char * p3; const char * str; /* ASCII encode distinguished name at `dn' into the `n'-byte buffer at `buf'. Return the total string length, even if larger than `n'. */ for(p1 = dn->beg; p1 < dn->end;) { p1 = Curl_getASN1Element(&rdn, p1, dn->end); for(p2 = rdn.beg; p2 < rdn.end;) { p2 = Curl_getASN1Element(&atv, p2, rdn.end); p3 = Curl_getASN1Element(&oid, atv.beg, atv.end); Curl_getASN1Element(&value, p3, atv.end); str = Curl_ASN1tostr(&oid, 0); if(!str) return -1; /* Encode delimiter. If attribute has a short uppercase name, delimiter is ", ". */ if(l) { for(p3 = str; isupper(*p3); p3++) ; for(p3 = (*p3 || p3 - str > 2)? "/": ", "; *p3; p3++) { if(l < n) buf[l] = *p3; l++; } } /* Encode attribute name. */ for(p3 = str; *p3; p3++) { if(l < n) buf[l] = *p3; l++; } free((char *) str); /* Generate equal sign. */ if(l < n) buf[l] = '='; l++; /* Generate value. */ str = Curl_ASN1tostr(&value, 0); if(!str) return -1; for(p3 = str; *p3; p3++) { if(l < n) buf[l] = *p3; l++; } free((char *) str); } } return l; } const char * Curl_DNtostr(curl_asn1Element * dn) { char * buf = (char *) NULL; ssize_t n = encodeDN(buf, 0, dn); /* Convert an ASN.1 distinguished name into a printable string. Return the dynamically allocated string, or NULL if an error occurs. */ if(n >= 0) { buf = malloc(n + 1); if(buf) { encodeDN(buf, n + 1, dn); buf[n] = '\0'; } } return (const char *) buf; } /* * X509 parser. */ void Curl_parseX509(curl_X509certificate * cert, const char * beg, const char * end) { curl_asn1Element elem; curl_asn1Element tbsCertificate; const char * ccp; static const char defaultVersion = 0; /* v1. */ /* ASN.1 parse an X509 certificate into structure subfields. Syntax is assumed to have already been checked by the SSL backend. See RFC 5280. */ cert->certificate.header = NULL; cert->certificate.beg = beg; cert->certificate.end = end; /* Get the sequence content. */ Curl_getASN1Element(&elem, beg, end); beg = elem.beg; end = elem.end; /* Get tbsCertificate. */ beg = Curl_getASN1Element(&tbsCertificate, beg, end); /* Skip the signatureAlgorithm. */ beg = Curl_getASN1Element(&cert->signatureAlgorithm, beg, end); /* Get the signatureValue. */ Curl_getASN1Element(&cert->signature, beg, end); /* Parse TBSCertificate. */ beg = tbsCertificate.beg; end = tbsCertificate.end; /* Get optional version, get serialNumber. */ cert->version.header = NULL; cert->version.beg = &defaultVersion; cert->version.end = &defaultVersion + sizeof defaultVersion;; beg = Curl_getASN1Element(&elem, beg, end); if(elem.tag == 0) { Curl_getASN1Element(&cert->version, elem.beg, elem.end); beg = Curl_getASN1Element(&elem, beg, end); } cert->serialNumber = elem; /* Get signature algorithm. */ beg = Curl_getASN1Element(&cert->signatureAlgorithm, beg, end); /* Get issuer. */ beg = Curl_getASN1Element(&cert->issuer, beg, end); /* Get notBefore and notAfter. */ beg = Curl_getASN1Element(&elem, beg, end); ccp = Curl_getASN1Element(&cert->notBefore, elem.beg, elem.end); Curl_getASN1Element(&cert->notAfter, ccp, elem.end); /* Get subject. */ beg = Curl_getASN1Element(&cert->subject, beg, end); /* Get subjectPublicKeyAlgorithm and subjectPublicKey. */ beg = Curl_getASN1Element(&cert->subjectPublicKeyInfo, beg, end); ccp = Curl_getASN1Element(&cert->subjectPublicKeyAlgorithm, cert->subjectPublicKeyInfo.beg, cert->subjectPublicKeyInfo.end); Curl_getASN1Element(&cert->subjectPublicKey, ccp, cert->subjectPublicKeyInfo.end); /* Get optional issuerUiqueID, subjectUniqueID and extensions. */ cert->issuerUniqueID.tag = cert->subjectUniqueID.tag = 0; cert->extensions.tag = elem.tag = 0; cert->issuerUniqueID.header = cert->subjectUniqueID.header = NULL; cert->issuerUniqueID.beg = cert->issuerUniqueID.end = ""; cert->subjectUniqueID.beg = cert->subjectUniqueID.end = ""; cert->extensions.header = NULL; cert->extensions.beg = cert->extensions.end = ""; if(beg < end) beg = Curl_getASN1Element(&elem, beg, end); if(elem.tag == 1) { cert->issuerUniqueID = elem; if(beg < end) beg = Curl_getASN1Element(&elem, beg, end); } if(elem.tag == 2) { cert->subjectUniqueID = elem; if(beg < end) beg = Curl_getASN1Element(&elem, beg, end); } if(elem.tag == 3) Curl_getASN1Element(&cert->extensions, elem.beg, elem.end); } static size_t copySubstring(char * to, const char * from) { size_t i; /* Copy at most 64-characters, terminate with a newline and returns the effective number of stored characters. */ for(i = 0; i < 64; i++) { to[i] = *from; if(!*from++) break; } to[i++] = '\n'; return i; } static const char * dumpAlgo(curl_asn1Element * param, const char * beg, const char * end) { curl_asn1Element oid; /* Get algorithm parameters and return algorithm name. */ beg = Curl_getASN1Element(&oid, beg, end); param->header = NULL; param->tag = 0; param->beg = param->end = end; if(beg < end) Curl_getASN1Element(param, beg, end); return OID2str(oid.beg, oid.end, TRUE); } static void do_pubkey_field(struct SessionHandle * data, int certnum, const char * label, curl_asn1Element * elem) { const char * output; /* Generate a certificate information record for the public key. */ output = Curl_ASN1tostr(elem, 0); if(output) { if(data->set.ssl.certinfo) Curl_ssl_push_certinfo(data, certnum, label, output); if(!certnum) infof(data, " %s: %s\n", label, output); free((char *) output); } } static void do_pubkey(struct SessionHandle * data, int certnum, const char * algo, curl_asn1Element * param, curl_asn1Element * pubkey) { curl_asn1Element elem; curl_asn1Element pk; const char * p; const char * q; unsigned long len; unsigned int i; /* Generate all information records for the public key. */ /* Get the public key (single element). */ Curl_getASN1Element(&pk, pubkey->beg + 1, pubkey->end); if(curl_strequal(algo, "rsaEncryption")) { p = Curl_getASN1Element(&elem, pk.beg, pk.end); /* Compute key length. */ for(q = elem.beg; !*q && q < elem.end; q++) ; len = (unsigned long)((elem.end - q) * 8); if(len) for(i = *(unsigned char *) q; !(i & 0x80); i <<= 1) len--; if(len > 32) elem.beg = q; /* Strip leading zero bytes. */ if(!certnum) infof(data, " RSA Public Key (%lu bits)\n", len); if(data->set.ssl.certinfo) { q = curl_maprintf("%lu", len); if(q) { Curl_ssl_push_certinfo(data, certnum, "RSA Public Key", q); free((char *) q); } } /* Generate coefficients. */ do_pubkey_field(data, certnum, "rsa(n)", &elem); Curl_getASN1Element(&elem, p, pk.end); do_pubkey_field(data, certnum, "rsa(e)", &elem); } else if(curl_strequal(algo, "dsa")) { p = Curl_getASN1Element(&elem, param->beg, param->end); do_pubkey_field(data, certnum, "dsa(p)", &elem); p = Curl_getASN1Element(&elem, p, param->end); do_pubkey_field(data, certnum, "dsa(q)", &elem); Curl_getASN1Element(&elem, p, param->end); do_pubkey_field(data, certnum, "dsa(g)", &elem); do_pubkey_field(data, certnum, "dsa(pub_key)", &pk); } else if(curl_strequal(algo, "dhpublicnumber")) { p = Curl_getASN1Element(&elem, param->beg, param->end); do_pubkey_field(data, certnum, "dh(p)", &elem); Curl_getASN1Element(&elem, param->beg, param->end); do_pubkey_field(data, certnum, "dh(g)", &elem); do_pubkey_field(data, certnum, "dh(pub_key)", &pk); } #if 0 /* Patent-encumbered. */ else if(curl_strequal(algo, "ecPublicKey")) { /* Left TODO. */ } #endif } CURLcode Curl_extract_certinfo(struct connectdata * conn, int certnum, const char * beg, const char * end) { curl_X509certificate cert; struct SessionHandle * data = conn->data; curl_asn1Element param; const char * ccp; char * cp1; size_t cl1; char * cp2; CURLcode result; unsigned long version; size_t i; size_t j; if(!data->set.ssl.certinfo) if(certnum) return CURLE_OK; /* Prepare the certificate information for curl_easy_getinfo(). */ /* Extract the certificate ASN.1 elements. */ Curl_parseX509(&cert, beg, end); /* Subject. */ ccp = Curl_DNtostr(&cert.subject); if(!ccp) return CURLE_OUT_OF_MEMORY; if(data->set.ssl.certinfo) Curl_ssl_push_certinfo(data, certnum, "Subject", ccp); if(!certnum) infof(data, "%2d Subject: %s\n", certnum, ccp); free((char *) ccp); /* Issuer. */ ccp = Curl_DNtostr(&cert.issuer); if(!ccp) return CURLE_OUT_OF_MEMORY; if(data->set.ssl.certinfo) Curl_ssl_push_certinfo(data, certnum, "Issuer", ccp); if(!certnum) infof(data, " Issuer: %s\n", ccp); free((char *) ccp); /* Version (always fits in less than 32 bits). */ version = 0; for(ccp = cert.version.beg; ccp < cert.version.end; ccp++) version = (version << 8) | *(const unsigned char *) ccp; if(data->set.ssl.certinfo) { ccp = curl_maprintf("%lx", version); if(!ccp) return CURLE_OUT_OF_MEMORY; Curl_ssl_push_certinfo(data, certnum, "Version", ccp); free((char *) ccp); } if(!certnum) infof(data, " Version: %lu (0x%lx)\n", version + 1, version); /* Serial number. */ ccp = Curl_ASN1tostr(&cert.serialNumber, 0); if(!ccp) return CURLE_OUT_OF_MEMORY; if(data->set.ssl.certinfo) Curl_ssl_push_certinfo(data, certnum, "Serial Number", ccp); if(!certnum) infof(data, " Serial Number: %s\n", ccp); free((char *) ccp); /* Signature algorithm .*/ ccp = dumpAlgo(&param, cert.signatureAlgorithm.beg, cert.signatureAlgorithm.end); if(!ccp) return CURLE_OUT_OF_MEMORY; if(data->set.ssl.certinfo) Curl_ssl_push_certinfo(data, certnum, "Signature Algorithm", ccp); if(!certnum) infof(data, " Signature Algorithm: %s\n", ccp); free((char *) ccp); /* Start Date. */ ccp = Curl_ASN1tostr(&cert.notBefore, 0); if(!ccp) return CURLE_OUT_OF_MEMORY; if(data->set.ssl.certinfo) Curl_ssl_push_certinfo(data, certnum, "Start Date", ccp); if(!certnum) infof(data, " Start Date: %s\n", ccp); free((char *) ccp); /* Expire Date. */ ccp = Curl_ASN1tostr(&cert.notAfter, 0); if(!ccp) return CURLE_OUT_OF_MEMORY; if(data->set.ssl.certinfo) Curl_ssl_push_certinfo(data, certnum, "Expire Date", ccp); if(!certnum) infof(data, " Expire Date: %s\n", ccp); free((char *) ccp); /* Public Key Algorithm. */ ccp = dumpAlgo(&param, cert.subjectPublicKeyAlgorithm.beg, cert.subjectPublicKeyAlgorithm.end); if(!ccp) return CURLE_OUT_OF_MEMORY; if(data->set.ssl.certinfo) Curl_ssl_push_certinfo(data, certnum, "Public Key Algorithm", ccp); if(!certnum) infof(data, " Public Key Algorithm: %s\n", ccp); do_pubkey(data, certnum, ccp, &param, &cert.subjectPublicKey); free((char *) ccp); /* TODO: extensions. */ /* Signature. */ ccp = Curl_ASN1tostr(&cert.signature, 0); if(!ccp) return CURLE_OUT_OF_MEMORY; if(data->set.ssl.certinfo) Curl_ssl_push_certinfo(data, certnum, "Signature", ccp); if(!certnum) infof(data, " Signature: %s\n", ccp); free((char *) ccp); /* Generate PEM certificate. */ result = Curl_base64_encode(data, cert.certificate.beg, cert.certificate.end - cert.certificate.beg, &cp1, &cl1); if(result) return result; /* Compute the number of characters in final certificate string. Format is: -----BEGIN CERTIFICATE-----\n <max 64 base64 characters>\n . . . -----END CERTIFICATE-----\n */ i = 28 + cl1 + (cl1 + 64 - 1) / 64 + 26; cp2 = malloc(i + 1); if(!cp2) { free(cp1); return CURLE_OUT_OF_MEMORY; } /* Build the certificate string. */ i = copySubstring(cp2, "-----BEGIN CERTIFICATE-----"); for(j = 0; j < cl1; j += 64) i += copySubstring(cp2 + i, cp1 + j); i += copySubstring(cp2 + i, "-----END CERTIFICATE-----"); cp2[i] = '\0'; free(cp1); if(data->set.ssl.certinfo) Curl_ssl_push_certinfo(data, certnum, "Cert", cp2); if(!certnum) infof(data, "%s\n", cp2); free(cp2); return CURLE_OK; } #endif /* USE_GSKIT or USE_NSS or USE_GNUTLS or USE_CYASSL */ #if defined(USE_GSKIT) static const char * checkOID(const char * beg, const char * end, const char * oid) { curl_asn1Element e; const char * ccp; const char * p; bool matched; /* Check if first ASN.1 element at `beg' is the given OID. Return a pointer in the source after the OID if found, else NULL. */ ccp = Curl_getASN1Element(&e, beg, end); if(!ccp || e.tag != CURL_ASN1_OBJECT_IDENTIFIER) return (const char *) NULL; p = OID2str(e.beg, e.end, FALSE); if(!p) return (const char *) NULL; matched = !strcmp(p, oid); free((char *) p); return matched? ccp: (const char *) NULL; } CURLcode Curl_verifyhost(struct connectdata * conn, const char * beg, const char * end) { struct SessionHandle * data = conn->data; curl_X509certificate cert; curl_asn1Element dn; curl_asn1Element elem; curl_asn1Element ext; curl_asn1Element name; const char * p; const char * q; char * dnsname; int matched = -1; size_t addrlen = (size_t) -1; ssize_t len; #ifdef ENABLE_IPV6 struct in6_addr addr; #else struct in_addr addr; #endif /* Verify that connection server matches info in X509 certificate at `beg'..`end'. */ if(!data->set.ssl.verifyhost) return CURLE_OK; if(!beg) return CURLE_PEER_FAILED_VERIFICATION; Curl_parseX509(&cert, beg, end); /* Get the server IP address. */ #ifdef ENABLE_IPV6 if(conn->bits.ipv6_ip && Curl_inet_pton(AF_INET6, conn->host.name, &addr)) addrlen = sizeof(struct in6_addr); else #endif if(Curl_inet_pton(AF_INET, conn->host.name, &addr)) addrlen = sizeof(struct in_addr); /* Process extensions. */ for(p = cert.extensions.beg; p < cert.extensions.end && matched != 1;) { p = Curl_getASN1Element(&ext, p, cert.extensions.end); /* Check if extension is a subjectAlternativeName. */ ext.beg = checkOID(ext.beg, ext.end, sanOID); if(ext.beg) { ext.beg = Curl_getASN1Element(&elem, ext.beg, ext.end); /* Skip critical if present. */ if(elem.tag == CURL_ASN1_BOOLEAN) ext.beg = Curl_getASN1Element(&elem, ext.beg, ext.end); /* Parse the octet string contents: is a single sequence. */ Curl_getASN1Element(&elem, elem.beg, elem.end); /* Check all GeneralNames. */ for(q = elem.beg; matched != 1 && q < elem.end;) { q = Curl_getASN1Element(&name, q, elem.end); switch (name.tag) { case 2: /* DNS name. */ len = utf8asn1str(&dnsname, CURL_ASN1_IA5_STRING, name.beg, name.end); if(len > 0 && (size_t)len == strlen(dnsname)) matched = Curl_cert_hostcheck(dnsname, conn->host.name); else matched = 0; free(dnsname); break; case 7: /* IP address. */ matched = (size_t) (name.end - q) == addrlen && !memcmp(&addr, q, addrlen); break; } } } } switch (matched) { case 1: /* an alternative name matched the server hostname */ infof(data, "\t subjectAltName: %s matched\n", conn->host.dispname); return CURLE_OK; case 0: /* an alternative name field existed, but didn't match and then we MUST fail */ infof(data, "\t subjectAltName does not match %s\n", conn->host.dispname); return CURLE_PEER_FAILED_VERIFICATION; } /* Process subject. */ name.header = NULL; name.beg = name.end = ""; q = cert.subject.beg; /* we have to look to the last occurrence of a commonName in the distinguished one to get the most significant one. */ while(q < cert.subject.end) { q = Curl_getASN1Element(&dn, q, cert.subject.end); for(p = dn.beg; p < dn.end;) { p = Curl_getASN1Element(&elem, p, dn.end); /* We have a DN's AttributeTypeAndValue: check it in case it's a CN. */ elem.beg = checkOID(elem.beg, elem.end, cnOID); if(elem.beg) name = elem; /* Latch CN. */ } } /* Check the CN if found. */ if(!Curl_getASN1Element(&elem, name.beg, name.end)) failf(data, "SSL: unable to obtain common name from peer certificate"); else { len = utf8asn1str(&dnsname, elem.tag, elem.beg, elem.end); if(len < 0) { free(dnsname); return CURLE_OUT_OF_MEMORY; } if(strlen(dnsname) != (size_t) len) /* Nul byte in string ? */ failf(data, "SSL: illegal cert name field"); else if(Curl_cert_hostcheck((const char *) dnsname, conn->host.name)) { infof(data, "\t common name: %s (matched)\n", dnsname); free(dnsname); return CURLE_OK; } else failf(data, "SSL: certificate subject name '%s' does not match " "target host name '%s'", dnsname, conn->host.dispname); free(dnsname); } return CURLE_PEER_FAILED_VERIFICATION; } #endif /* USE_GSKIT */
phr34k/serpent
thirdparty/curl/lib/x509asn1.c
C
mit
34,773
<?php /** * This code was generated by * \ / _ _ _| _ _ * | (_)\/(_)(_|\/| |(/_ v1.0.0 * / / */ namespace Twilio\Rest\Preview\Marketplace; use Twilio\ListResource; use Twilio\Options; use Twilio\Serialize; use Twilio\Values; use Twilio\Version; /** * PLEASE NOTE that this class contains preview products that are subject to change. Use them with caution. If you currently do not have developer preview access, please contact [email protected]. */ class InstalledAddOnList extends ListResource { /** * Construct the InstalledAddOnList * * @param Version $version Version that contains the resource * @return \Twilio\Rest\Preview\Marketplace\InstalledAddOnList */ public function __construct(Version $version) { parent::__construct($version); // Path Solution $this->solution = array(); $this->uri = '/InstalledAddOns'; } /** * Create a new InstalledAddOnInstance * * @param string $availableAddOnSid A string that uniquely identifies the * Add-on to install * @param boolean $acceptTermsOfService A boolean reflecting your acceptance of * the Terms of Service * @param array|Options $options Optional Arguments * @return InstalledAddOnInstance Newly created InstalledAddOnInstance * @throws TwilioException When an HTTP error occurs. */ public function create($availableAddOnSid, $acceptTermsOfService, $options = array()) { $options = new Values($options); $data = Values::of(array( 'AvailableAddOnSid' => $availableAddOnSid, 'AcceptTermsOfService' => Serialize::booleanToString($acceptTermsOfService), 'Configuration' => Serialize::jsonObject($options['configuration']), 'UniqueName' => $options['uniqueName'], )); $payload = $this->version->create( 'POST', $this->uri, array(), $data ); return new InstalledAddOnInstance($this->version, $payload); } /** * Streams InstalledAddOnInstance records from the API as a generator stream. * This operation lazily loads records as efficiently as possible until the * limit * is reached. * The results are returned as a generator, so this operation is memory * efficient. * * @param int $limit Upper limit for the number of records to return. stream() * guarantees to never return more than limit. Default is no * limit * @param mixed $pageSize Number of records to fetch per request, when not set * will use the default value of 50 records. If no * page_size is defined but a limit is defined, stream() * will attempt to read the limit with the most * efficient page size, i.e. min(limit, 1000) * @return \Twilio\Stream stream of results */ public function stream($limit = null, $pageSize = null) { $limits = $this->version->readLimits($limit, $pageSize); $page = $this->page($limits['pageSize']); return $this->version->stream($page, $limits['limit'], $limits['pageLimit']); } /** * Reads InstalledAddOnInstance records from the API as a list. * Unlike stream(), this operation is eager and will load `limit` records into * memory before returning. * * @param int $limit Upper limit for the number of records to return. read() * guarantees to never return more than limit. Default is no * limit * @param mixed $pageSize Number of records to fetch per request, when not set * will use the default value of 50 records. If no * page_size is defined but a limit is defined, read() * will attempt to read the limit with the most * efficient page size, i.e. min(limit, 1000) * @return InstalledAddOnInstance[] Array of results */ public function read($limit = null, $pageSize = null) { return iterator_to_array($this->stream($limit, $pageSize), false); } /** * Retrieve a single page of InstalledAddOnInstance records from the API. * Request is executed immediately * * @param mixed $pageSize Number of records to return, defaults to 50 * @param string $pageToken PageToken provided by the API * @param mixed $pageNumber Page Number, this value is simply for client state * @return \Twilio\Page Page of InstalledAddOnInstance */ public function page($pageSize = Values::NONE, $pageToken = Values::NONE, $pageNumber = Values::NONE) { $params = Values::of(array( 'PageToken' => $pageToken, 'Page' => $pageNumber, 'PageSize' => $pageSize, )); $response = $this->version->page( 'GET', $this->uri, $params ); return new InstalledAddOnPage($this->version, $response, $this->solution); } /** * Retrieve a specific page of InstalledAddOnInstance records from the API. * Request is executed immediately * * @param string $targetUrl API-generated URL for the requested results page * @return \Twilio\Page Page of InstalledAddOnInstance */ public function getPage($targetUrl) { $response = $this->version->getDomain()->getClient()->request( 'GET', $targetUrl ); return new InstalledAddOnPage($this->version, $response, $this->solution); } /** * Constructs a InstalledAddOnContext * * @param string $sid The unique Installed Add-on Sid * @return \Twilio\Rest\Preview\Marketplace\InstalledAddOnContext */ public function getContext($sid) { return new InstalledAddOnContext($this->version, $sid); } /** * Provide a friendly representation * * @return string Machine friendly representation */ public function __toString() { return '[Twilio.Preview.Marketplace.InstalledAddOnList]'; } }
camperjz/trident
upgrade/files/9.0.0.RC8-9.0.0.RC9/files/plugins/Twilio/Rest/Preview/Marketplace/InstalledAddOnList.php
PHP
mit
6,315
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="CandleStickAndVolumeSeries.cs" company="OxyPlot"> // Copyright (c) 2014 OxyPlot contributors // </copyright> // <summary> // Represents a dual view (candlestick + volume) series for OHLCV bars // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace OxyPlot.Series { using System; using System.Collections.Generic; using System.Linq; using OxyPlot.Axes; /// <summary> /// Represents a dual view (candlestick + volume) series for OHLCV bars /// <para/> /// Note that to use this series, one *must* define two y-axes, one named "Bars" and the other named /// "Volume". Typically would set up the volume on StartPosition =0, EndPosition = fraction and for /// the bar axis StartPosition = fraction + delta, EndPosition = 1.0. /// </summary> /// <remarks>See <a href="http://www.mathworks.com/help/toolbox/finance/highlowfts.html">link</a></remarks> public class CandleStickAndVolumeSeries : XYAxisSeries { /// <summary> /// The default tracker format string /// </summary> public new const string DefaultTrackerFormatString = "Time: {0}\nHigh: {1}\nLow: {2}\nOpen: {3}\nClose: {4}\nBuy Volume: {5}\nSell Volume: {6}"; /// <summary> /// The data series /// </summary> private List<OhlcvItem> data; /// <summary> /// The minimum X gap between successive data items /// </summary> private double minDx; /// <summary> /// The index of the data item at the start of visible window /// </summary> private int winIndex; /// <summary> /// Initializes a new instance of the <see cref = "CandleStickAndVolumeSeries" /> class. /// </summary> public CandleStickAndVolumeSeries() { this.PositiveColor = OxyColors.DarkGreen; this.NegativeColor = OxyColors.Red; this.SeparatorColor = OxyColors.Black; this.CandleWidth = 0; this.SeparatorStrokeThickness = 1; this.SeparatorLineStyle = LineStyle.Dash; this.StrokeThickness = 1; this.NegativeHollow = false; this.PositiveHollow = true; this.StrokeIntensity = 0.80; this.VolumeStyle = VolumeStyle.Combined; this.VolumeAxisKey = "Volume"; this.BarAxisKey = null; this.TrackerFormatString = DefaultTrackerFormatString; } /// <summary> /// Gets or sets the items of the series. /// </summary> /// <value>The items.</value> public List<OhlcvItem> Items { get { return this.data ?? (this.data = new List<OhlcvItem>()); } set { this.data = value; } } /// <summary> /// Gets the portion of the Y axis associated with bars /// </summary> public LinearAxis BarAxis { get { return (LinearAxis)this.YAxis; } } /// <summary> /// Gets the portion of the Y axis associated with volume /// </summary> public LinearAxis VolumeAxis { get; private set; } /// <summary> /// Gets or sets the volume axis key (defaults to "Volume") /// </summary> public string VolumeAxisKey { get; set; } /// <summary> /// Gets or sets the bar axis key (defaults to null, as is the primary axis). /// </summary> public string BarAxisKey { get; set; } /// <summary> /// Gets or sets the style of volume rendering (defaults to Combined) /// </summary> public VolumeStyle VolumeStyle { get; set; } /// <summary> /// Gets or sets the thickness of the bar lines /// </summary> /// <value>The stroke thickness.</value> public double StrokeThickness { get; set; } /// <summary> /// Gets or sets the stroke intensity scale (used to generate stroke color from positive or negative color). /// For example, 1.0 = same color and 0.5 is 1/2 of the intensity of the source fill color. /// </summary> public double StrokeIntensity { get; set; } /// <summary> /// Gets or sets the thickness of the volume / bar separator /// </summary> /// <value>The stroke thickness.</value> public double SeparatorStrokeThickness { get; set; } /// <summary> /// Gets or sets the line style for the volume / bar separator /// </summary> public LineStyle SeparatorLineStyle { get; set; } /// <summary> /// Gets or sets the color used when the closing value is greater than opening value or /// for buying volume. /// </summary> public OxyColor PositiveColor { get; set; } /// <summary> /// Gets or sets the fill color used when the closing value is less than opening value or /// for selling volume /// </summary> public OxyColor NegativeColor { get; set; } /// <summary> /// Gets or sets the color of the separator line /// </summary> public OxyColor SeparatorColor { get; set; } /// <summary> /// Gets or sets a value indicating whether positive bars are shown as filled (false) or hollow (true) candlesticks /// </summary> public bool PositiveHollow { get; set; } /// <summary> /// Gets or sets a value indicating whether negative bars are shown as filled (false) or hollow (true) candlesticks /// </summary> public bool NegativeHollow { get; set; } /// <summary> /// Gets or sets the bar width in data units (for example if the X axis is date-time based, then should /// use the difference of DateTimeAxis.ToDouble(date) to indicate the width). By default candlestick /// series will use 0.80 x the minimum difference in data points. /// </summary> public double CandleWidth { get; set; } /// <summary> /// Gets or sets the minimum volume seen in the data series. /// </summary> public double MinimumVolume { get; protected set; } /// <summary> /// Gets or sets the maximum volume seen in the data series. /// </summary> public double MaximumVolume { get; protected set; } /// <summary> /// Gets or sets the average volume seen in the data series. /// </summary> public double AverageVolume { get; protected set; } /// <summary> /// Append a bar to the series (must be in X order) /// </summary> /// <param name="bar">Bar object.</param> public void Append(OhlcvItem bar) { if (this.data == null) { this.data = new List<OhlcvItem>(); } if (this.data.Count > 0 && this.data[this.data.Count - 1].X > bar.X) { throw new ArgumentException("cannot append bar out of order, must be sequential in X"); } this.data.Add(bar); } /// <summary> /// Fast index of bar where max(bar[i].X) &lt;= x /// </summary> /// <returns>The index of the bar closest to X, where max(bar[i].X) &lt;= x.</returns> /// <param name="x">The x coordinate.</param> /// <param name="startingIndex">starting index</param> public int FindByX(double x, int startingIndex = -1) { if (startingIndex < 0) { startingIndex = this.winIndex; } return OhlcvItem.FindIndex(this.data, x, startingIndex); } /// <summary> /// Renders the series on the specified rendering context. /// </summary> /// <param name="rc">The rendering context.</param> // ReSharper disable once FunctionComplexityOverflow public override void Render(IRenderContext rc) { if (this.data == null || this.data.Count == 0) { return; } var items = this.data; var nitems = this.data.Count; this.VerifyAxes(); var clippingBar = this.GetClippingRect(this.BarAxis); var clippingSep = this.GetSeparationClippingRect(); var clippingVol = this.GetClippingRect(this.VolumeAxis); var datacandlewidth = (this.CandleWidth > 0) ? this.CandleWidth : this.minDx * 0.80; var candlewidth = this.XAxis.Transform(items[0].X + datacandlewidth) - this.XAxis.Transform(items[0].X) - this.StrokeThickness; // colors var fillUp = this.GetSelectableFillColor(this.PositiveColor); var fillDown = this.GetSelectableFillColor(this.NegativeColor); var barfillUp = this.PositiveHollow ? OxyColors.Transparent : fillUp; var barfillDown = this.NegativeHollow ? OxyColors.Transparent : fillDown; var lineUp = this.GetSelectableColor(this.PositiveColor.ChangeIntensity(this.StrokeIntensity)); var lineDown = this.GetSelectableColor(this.NegativeColor.ChangeIntensity(this.StrokeIntensity)); // determine render range var xmin = this.XAxis.ActualMinimum; var xmax = this.XAxis.ActualMaximum; this.winIndex = OhlcvItem.FindIndex(items, xmin, this.winIndex); for (int i = this.winIndex; i < nitems; i++) { var bar = items[i]; // if item beyond visible range, done if (bar.X > xmax) { break; } // check to see whether is valid if (!bar.IsValid()) { continue; } var fillColor = bar.Close > bar.Open ? barfillUp : barfillDown; var lineColor = bar.Close > bar.Open ? lineUp : lineDown; var high = this.Transform(bar.X, bar.High); var low = this.Transform(bar.X, bar.Low); var open = this.Transform(bar.X, bar.Open); var close = this.Transform(bar.X, bar.Close); var max = new ScreenPoint(open.X, Math.Max(open.Y, close.Y)); var min = new ScreenPoint(open.X, Math.Min(open.Y, close.Y)); // Bar part rc.DrawClippedLine( clippingBar, new[] { high, min }, 0, lineColor, this.StrokeThickness, null, LineJoin.Miter, true); // Lower extent rc.DrawClippedLine( clippingBar, new[] { max, low }, 0, lineColor, this.StrokeThickness, null, LineJoin.Miter, true); // Body var openLeft = open + new ScreenVector(-candlewidth * 0.5, 0); var rect = new OxyRect(openLeft.X, min.Y, candlewidth, max.Y - min.Y); rc.DrawClippedRectangleAsPolygon( clippingBar, rect, fillColor, lineColor, this.StrokeThickness); // Volume Part if (this.VolumeAxis == null || this.VolumeStyle == VolumeStyle.None) { continue; } var iY0 = this.VolumeAxis.Transform(0); switch (this.VolumeStyle) { case VolumeStyle.Combined: { var adj = this.VolumeAxis.Transform(Math.Abs(bar.BuyVolume - bar.SellVolume)); var fillcolor = (bar.BuyVolume > bar.SellVolume) ? barfillUp : barfillDown; var linecolor = (bar.BuyVolume > bar.SellVolume) ? lineUp : lineDown; var rect1 = new OxyRect(openLeft.X, adj, candlewidth, Math.Abs(adj - iY0)); rc.DrawClippedRectangleAsPolygon(clippingVol, rect1, fillcolor, linecolor, this.StrokeThickness); } break; case VolumeStyle.PositiveNegative: { var buyY = this.VolumeAxis.Transform(bar.BuyVolume); var sellY = this.VolumeAxis.Transform(-bar.SellVolume); var rect1 = new OxyRect(openLeft.X, buyY, candlewidth, Math.Abs(buyY - iY0)); rc.DrawClippedRectangleAsPolygon(clippingVol, rect1, fillUp, lineUp, this.StrokeThickness); var rect2 = new OxyRect(openLeft.X, iY0, candlewidth, Math.Abs(sellY - iY0)); rc.DrawClippedRectangleAsPolygon(clippingVol, rect2, fillDown, lineDown, this.StrokeThickness); } break; case VolumeStyle.Stacked: if (bar.BuyVolume > bar.SellVolume) { var buyY = this.VolumeAxis.Transform(bar.BuyVolume); var sellY = this.VolumeAxis.Transform(bar.SellVolume); var dyoffset = sellY - iY0; var rect2 = new OxyRect(openLeft.X, sellY, candlewidth, Math.Abs(sellY - iY0)); rc.DrawClippedRectangleAsPolygon(clippingVol, rect2, fillDown, lineDown, this.StrokeThickness); var rect1 = new OxyRect(openLeft.X, buyY + dyoffset, candlewidth, Math.Abs(buyY - iY0)); rc.DrawClippedRectangleAsPolygon(clippingVol, rect1, fillUp, lineUp, this.StrokeThickness); } else { var buyY = this.VolumeAxis.Transform(bar.BuyVolume); var sellY = this.VolumeAxis.Transform(bar.SellVolume); var dyoffset = buyY - iY0; var rect1 = new OxyRect(openLeft.X, buyY, candlewidth, Math.Abs(buyY - iY0)); rc.DrawClippedRectangleAsPolygon(clippingVol, rect1, fillUp, lineUp, this.StrokeThickness); var rect2 = new OxyRect(openLeft.X, sellY + dyoffset, candlewidth, Math.Abs(sellY - iY0)); rc.DrawClippedRectangleAsPolygon(clippingVol, rect2, fillDown, lineDown, this.StrokeThickness); } break; } } // draw volume & bar separation line if (this.VolumeStyle != VolumeStyle.None) { var ysep = (clippingSep.Bottom + clippingSep.Top) / 2.0; rc.DrawClippedLine( clippingSep, new[] { new ScreenPoint(clippingSep.Left, ysep), new ScreenPoint(clippingSep.Right, ysep) }, 0, this.SeparatorColor, this.SeparatorStrokeThickness, this.SeparatorLineStyle.GetDashArray(), LineJoin.Miter, true); } // draw volume y=0 line if (this.VolumeAxis != null && this.VolumeStyle == VolumeStyle.PositiveNegative) { var y0 = this.VolumeAxis.Transform(0); rc.DrawClippedLine( clippingVol, new[] { new ScreenPoint(clippingVol.Left, y0), new ScreenPoint(clippingVol.Right, y0) }, 0, OxyColors.Goldenrod, this.SeparatorStrokeThickness, this.SeparatorLineStyle.GetDashArray(), LineJoin.Miter, true); } } /// <summary> /// Renders the legend symbol for the series on the specified rendering context. /// </summary> /// <param name="rc">The rendering context.</param> /// <param name="legendBox">The bounding rectangle of the legend box.</param> public override void RenderLegend(IRenderContext rc, OxyRect legendBox) { double xmid = (legendBox.Left + legendBox.Right) / 2; double yopen = legendBox.Top + ((legendBox.Bottom - legendBox.Top) * 0.7); double yclose = legendBox.Top + ((legendBox.Bottom - legendBox.Top) * 0.3); double[] dashArray = LineStyle.Solid.GetDashArray(); var datacandlewidth = (this.CandleWidth > 0) ? this.CandleWidth : this.minDx * 0.80; var fillUp = this.GetSelectableFillColor(this.PositiveColor); var lineUp = this.GetSelectableColor(this.PositiveColor.ChangeIntensity(0.70)); var candlewidth = Math.Min( legendBox.Width, this.XAxis.Transform(this.data[0].X + datacandlewidth) - this.XAxis.Transform(this.data[0].X)); rc.DrawLine( new[] { new ScreenPoint(xmid, legendBox.Top), new ScreenPoint(xmid, legendBox.Bottom) }, lineUp, this.StrokeThickness, dashArray, LineJoin.Miter, true); rc.DrawRectangleAsPolygon( new OxyRect(xmid - (candlewidth * 0.5), yclose, candlewidth, yopen - yclose), fillUp, lineUp, this.StrokeThickness); } /// <summary> /// Gets the point on the series that is nearest the specified point. /// </summary> /// <param name="point">The point.</param> /// <param name="interpolate">Interpolate the series if this flag is set to <c>true</c>.</param> /// <returns>A TrackerHitResult for the current hit.</returns> public override TrackerHitResult GetNearestPoint(ScreenPoint point, bool interpolate) { if (this.XAxis == null || this.YAxis == null || interpolate || this.data.Count == 0) { return null; } var nbars = this.data.Count; var xy = this.InverseTransform(point); var targetX = xy.X; // punt if beyond start & end of series if (targetX > (this.data[nbars - 1].X + this.minDx)) { return null; } else if (targetX < (this.data[0].X - this.minDx)) { return null; } var pidx = OhlcvItem.FindIndex(this.data, targetX, this.winIndex); var nidx = ((pidx + 1) < this.data.Count) ? pidx + 1 : pidx; Func<OhlcvItem, double> distance = bar => { var dx = bar.X - xy.X; return dx * dx; }; // determine closest point var midx = distance(this.data[pidx]) <= distance(this.data[nidx]) ? pidx : nidx; var mbar = this.data[midx]; var hit = new DataPoint(mbar.X, mbar.Close); return new TrackerHitResult { Series = this, DataPoint = hit, Position = this.Transform(hit), Item = mbar, Index = midx, Text = StringHelper.Format( this.ActualCulture, this.TrackerFormatString, mbar, this.XAxis.GetValue(mbar.X), this.YAxis.GetValue(mbar.High), this.YAxis.GetValue(mbar.Low), this.YAxis.GetValue(mbar.Open), this.YAxis.GetValue(mbar.Close), this.YAxis.GetValue(mbar.BuyVolume), this.YAxis.GetValue(mbar.SellVolume)) }; } /// <summary> /// Updates the data. /// </summary> protected internal override void UpdateData() { base.UpdateData(); this.winIndex = 0; // determine minimum X gap between successive points var items = this.data; var nitems = items.Count; this.minDx = double.MaxValue; for (int i = 1; i < nitems; i++) { this.minDx = Math.Min(this.minDx, items[i].X - items[i - 1].X); if (this.minDx < 0) { throw new ArgumentException("bars are out of order, must be sequential in x"); } } if (nitems <= 1) { this.minDx = 1; } } /// <summary> /// Ensures that the axes of the series is defined. /// </summary> protected internal override void EnsureAxes() { // find volume axis this.VolumeAxis = (LinearAxis)this.PlotModel.Axes.FirstOrDefault(a => a.Key == this.VolumeAxisKey); // now setup XYSeries axes, where BarAxisKey indicates the primary Y axis this.YAxisKey = this.BarAxisKey; base.EnsureAxes(); } /// <summary> /// Updates the axes to include the max and min of this series. /// </summary> protected internal override void UpdateAxisMaxMin() { this.XAxis.Include(this.MinX); this.XAxis.Include(this.MaxX); this.YAxis.Include(this.MinY); this.YAxis.Include(this.MaxY); // we may not have a volume axis, if so, skip adjustments if (this.VolumeAxis == null) { return; } var ymin = this.MinimumVolume; var ymax = this.MaximumVolume; var yavg = this.AverageVolume; var yquartile = (ymax - ymin) / 4.0; switch (VolumeStyle) { case VolumeStyle.PositiveNegative: ymin = -(yavg + (yquartile / 2.0)); ymax = +(yavg + (yquartile / 2.0)); break; case VolumeStyle.Stacked: ymax = yavg + yquartile; ymin = 0; break; default: case VolumeStyle.Combined: ymax = yavg + (yquartile / 2.0); ymin = 0; break; } ymin = Math.Max(this.VolumeAxis.FilterMinValue, ymin); ymax = Math.Min(this.VolumeAxis.FilterMaxValue, ymax); this.VolumeAxis.Include(ymin); this.VolumeAxis.Include(ymax); } /// <summary> /// Updates the maximum and minimum values of the series. /// </summary> protected internal override void UpdateMaxMin() { base.UpdateMaxMin(); double xmin = double.MaxValue; double xmax = double.MinValue; double ymin_bar = double.MaxValue; double ymax_bar = double.MinValue; double ymin_vol = double.MaxValue; double ymax_vol = double.MinValue; var nvol = 0.0; var cumvol = 0.0; foreach (var bar in this.Items) { if (!bar.IsValid()) { continue; } if (bar.SellVolume > 0) { nvol++; } if (bar.BuyVolume > 0) { nvol++; } cumvol += bar.BuyVolume; cumvol += bar.SellVolume; xmin = Math.Min(xmin, bar.X); xmax = Math.Max(xmax, bar.X); ymin_bar = Math.Min(ymin_bar, bar.Low); ymax_bar = Math.Max(ymax_bar, bar.High); ymin_vol = Math.Min(ymin_vol, -bar.SellVolume); ymax_vol = Math.Max(ymax_vol, +bar.BuyVolume); } this.MinX = Math.Max(this.XAxis.FilterMinValue, xmin); this.MaxX = Math.Min(this.XAxis.FilterMaxValue, xmax); this.MinY = Math.Max(this.YAxis.FilterMinValue, ymin_bar); this.MaxY = Math.Min(this.YAxis.FilterMaxValue, ymax_bar); this.MinimumVolume = ymin_vol; this.MaximumVolume = ymax_vol; this.AverageVolume = cumvol / nvol; } /// <summary> /// Gets the clipping rectangle for the given combination of existing X-Axis and specific Y-Axis /// </summary> /// <returns>The clipping rectangle.</returns> /// <param name="yaxis">Y axis.</param> protected OxyRect GetClippingRect(Axis yaxis) { if (yaxis == null) { return default(OxyRect); } double minX = Math.Min(this.XAxis.ScreenMin.X, this.XAxis.ScreenMax.X); double minY = Math.Min(yaxis.ScreenMin.Y, yaxis.ScreenMax.Y); double maxX = Math.Max(this.XAxis.ScreenMin.X, this.XAxis.ScreenMax.X); double maxY = Math.Max(yaxis.ScreenMin.Y, yaxis.ScreenMax.Y); return new OxyRect(minX, minY, maxX - minX, maxY - minY); } /// <summary> /// Gets the clipping rectangle between plots /// </summary> /// <returns>The clipping rectangle.</returns> protected OxyRect GetSeparationClippingRect() { if (this.VolumeAxis == null) { return default(OxyRect); } double minX = Math.Min(this.XAxis.ScreenMin.X, this.XAxis.ScreenMax.X); double maxX = Math.Max(this.XAxis.ScreenMin.X, this.XAxis.ScreenMax.X); double minY; double maxY; if (this.VolumeAxis.ScreenMax.Y < this.BarAxis.ScreenMin.Y) { maxY = this.BarAxis.ScreenMin.Y; minY = this.VolumeAxis.ScreenMax.Y; } else { maxY = this.VolumeAxis.ScreenMin.Y; minY = this.BarAxis.ScreenMax.Y; } return new OxyRect(minX, minY, maxX - minX, maxY - minY); } } }
Mitch-Connor/oxyplot
Source/OxyPlot/Series/FinancialSeries/CandleStickAndVolumeSeries.cs
C#
mit
26,886
require 'spec_helper' module Grape module DSL module SettingsSpec class Dummy include Grape::DSL::Settings def reset_validations!; end end end describe Settings do subject { SettingsSpec::Dummy.new } describe '#unset' do it 'deletes a key from settings' do subject.namespace_setting :dummy, 1 expect(subject.inheritable_setting.namespace.keys).to include(:dummy) subject.unset :namespace, :dummy expect(subject.inheritable_setting.namespace.keys).not_to include(:dummy) end end describe '#get_or_set' do it 'sets a values' do subject.get_or_set :namespace, :dummy, 1 expect(subject.namespace_setting(:dummy)).to eq 1 end it 'returns a value when nil is new value is provided' do subject.get_or_set :namespace, :dummy, 1 expect(subject.get_or_set(:namespace, :dummy, nil)).to eq 1 end end describe '#global_setting' do it 'delegates to get_or_set' do expect(subject).to receive(:get_or_set).with(:global, :dummy, 1) subject.global_setting(:dummy, 1) end end describe '#unset_global_setting' do it 'delegates to unset' do expect(subject).to receive(:unset).with(:global, :dummy) subject.unset_global_setting(:dummy) end end describe '#route_setting' do it 'delegates to get_or_set' do expect(subject).to receive(:get_or_set).with(:route, :dummy, 1) subject.route_setting(:dummy, 1) end it 'sets a value until the next route' do subject.route_setting :some_thing, :foo_bar expect(subject.route_setting(:some_thing)).to eq :foo_bar subject.route_end expect(subject.route_setting(:some_thing)).to be_nil end end describe '#unset_route_setting' do it 'delegates to unset' do expect(subject).to receive(:unset).with(:route, :dummy) subject.unset_route_setting(:dummy) end end describe '#namespace_setting' do it 'delegates to get_or_set' do expect(subject).to receive(:get_or_set).with(:namespace, :dummy, 1) subject.namespace_setting(:dummy, 1) end it 'sets a value until the end of a namespace' do subject.namespace_start subject.namespace_setting :some_thing, :foo_bar expect(subject.namespace_setting(:some_thing)).to eq :foo_bar subject.namespace_end expect(subject.namespace_setting(:some_thing)).to be_nil end it 'resets values after leaving nested namespaces' do subject.namespace_start subject.namespace_setting :some_thing, :foo_bar expect(subject.namespace_setting(:some_thing)).to eq :foo_bar subject.namespace_start expect(subject.namespace_setting(:some_thing)).to be_nil subject.namespace_end expect(subject.namespace_setting(:some_thing)).to eq :foo_bar subject.namespace_end expect(subject.namespace_setting(:some_thing)).to be_nil end end describe '#unset_namespace_setting' do it 'delegates to unset' do expect(subject).to receive(:unset).with(:namespace, :dummy) subject.unset_namespace_setting(:dummy) end end describe '#namespace_inheritable' do it 'delegates to get_or_set' do expect(subject).to receive(:get_or_set).with(:namespace_inheritable, :dummy, 1) subject.namespace_inheritable(:dummy, 1) end it 'inherits values from surrounding namespace' do subject.namespace_start subject.namespace_inheritable(:some_thing, :foo_bar) expect(subject.namespace_inheritable(:some_thing)).to eq :foo_bar subject.namespace_start expect(subject.namespace_inheritable(:some_thing)).to eq :foo_bar subject.namespace_inheritable(:some_thing, :foo_bar_2) expect(subject.namespace_inheritable(:some_thing)).to eq :foo_bar_2 subject.namespace_end expect(subject.namespace_inheritable(:some_thing)).to eq :foo_bar subject.namespace_end end end describe '#unset_namespace_inheritable' do it 'delegates to unset' do expect(subject).to receive(:unset).with(:namespace_inheritable, :dummy) subject.unset_namespace_inheritable(:dummy) end end describe '#namespace_stackable' do it 'delegates to get_or_set' do expect(subject).to receive(:get_or_set).with(:namespace_stackable, :dummy, 1) subject.namespace_stackable(:dummy, 1) end it 'stacks values from surrounding namespace' do subject.namespace_start subject.namespace_stackable(:some_thing, :foo_bar) expect(subject.namespace_stackable(:some_thing)).to eq [:foo_bar] subject.namespace_start expect(subject.namespace_stackable(:some_thing)).to eq [:foo_bar] subject.namespace_stackable(:some_thing, :foo_bar_2) expect(subject.namespace_stackable(:some_thing)).to eq [:foo_bar, :foo_bar_2] subject.namespace_end expect(subject.namespace_stackable(:some_thing)).to eq [:foo_bar] subject.namespace_end end end describe '#unset_namespace_stackable' do it 'delegates to unset' do expect(subject).to receive(:unset).with(:namespace_stackable, :dummy) subject.unset_namespace_stackable(:dummy) end end describe '#api_class_setting' do it 'delegates to get_or_set' do expect(subject).to receive(:get_or_set).with(:api_class, :dummy, 1) subject.api_class_setting(:dummy, 1) end end describe '#unset_api_class_setting' do it 'delegates to unset' do expect(subject).to receive(:unset).with(:api_class, :dummy) subject.unset_api_class_setting(:dummy) end end describe '#within_namespace' do it 'calls start and end for a namespace' do expect(subject).to receive :namespace_start expect(subject).to receive :namespace_end subject.within_namespace do end end it 'returns the last result' do result = subject.within_namespace do 1 end expect(result).to eq 1 end end describe 'complex scenario' do it 'plays well' do obj1 = SettingsSpec::Dummy.new obj2 = SettingsSpec::Dummy.new obj3 = SettingsSpec::Dummy.new obj1_copy = nil obj2_copy = nil obj3_copy = nil obj1.within_namespace do obj1.namespace_stackable(:some_thing, :obj1) expect(obj1.namespace_stackable(:some_thing)).to eq [:obj1] obj1_copy = obj1.inheritable_setting.point_in_time_copy end expect(obj1.namespace_stackable(:some_thing)).to eq [] expect(obj1_copy.namespace_stackable[:some_thing]).to eq [:obj1] obj2.within_namespace do obj2.namespace_stackable(:some_thing, :obj2) expect(obj2.namespace_stackable(:some_thing)).to eq [:obj2] obj2_copy = obj2.inheritable_setting.point_in_time_copy end expect(obj2.namespace_stackable(:some_thing)).to eq [] expect(obj2_copy.namespace_stackable[:some_thing]).to eq [:obj2] obj3.within_namespace do obj3.namespace_stackable(:some_thing, :obj3) expect(obj3.namespace_stackable(:some_thing)).to eq [:obj3] obj3_copy = obj3.inheritable_setting.point_in_time_copy end expect(obj3.namespace_stackable(:some_thing)).to eq [] expect(obj3_copy.namespace_stackable[:some_thing]).to eq [:obj3] obj1.top_level_setting.inherit_from obj2_copy.point_in_time_copy obj2.top_level_setting.inherit_from obj3_copy.point_in_time_copy expect(obj1_copy.namespace_stackable[:some_thing]).to eq [:obj3, :obj2, :obj1] end end end end end
thogg4/grape
spec/grape/dsl/settings_spec.rb
Ruby
mit
8,323
# encoding: utf-8 module RuboCop module Cop module Style # This cop checks for usage of the %x() syntax when `` would do. class UnneededPercentX < Cop MSG = 'Do not use `%x` unless the command string contains backquotes.' def on_xstr(node) add_offense(node, :expression) if node.loc.expression.source !~ /`/ end private def autocorrect(node) @corrections << lambda do |corrector| corrector.replace(node.loc.begin, '`') corrector.replace(node.loc.end, '`') end end end end end end
eprislac/guard-yard
vendor/ruby/2.3.0/gems/rubocop-0.25.0/lib/rubocop/cop/style/unneeded_percent_x.rb
Ruby
mit
616
html.swal2-shown:not(.swal2-no-backdrop):not(.swal2-toast-shown), body.swal2-shown:not(.swal2-no-backdrop):not(.swal2-toast-shown) { overflow-y: hidden; height: auto; } body.swal2-toast-shown.swal2-has-input > .swal2-container > .swal2-toast { -webkit-box-orient: vertical; -webkit-box-direction: normal; -ms-flex-direction: column; flex-direction: column; } body.swal2-toast-shown.swal2-has-input > .swal2-container > .swal2-toast .swal2-icon { margin: 0 0 15px; } body.swal2-toast-shown.swal2-has-input > .swal2-container > .swal2-toast .swal2-actions { -webkit-box-flex: 1; -ms-flex: 1; flex: 1; -ms-flex-item-align: stretch; align-self: stretch; -webkit-box-pack: end; -ms-flex-pack: end; justify-content: flex-end; } body.swal2-toast-shown.swal2-has-input > .swal2-container > .swal2-toast .swal2-loading { -webkit-box-pack: center; -ms-flex-pack: center; justify-content: center; } body.swal2-toast-shown.swal2-has-input > .swal2-container > .swal2-toast .swal2-input { height: 32px; font-size: 14px; margin: 5px auto; } body.swal2-toast-shown > .swal2-container { position: fixed; background-color: transparent; } body.swal2-toast-shown > .swal2-container.swal2-shown { background-color: transparent; } body.swal2-toast-shown > .swal2-container.swal2-top { top: 0; left: 50%; bottom: auto; right: auto; -webkit-transform: translateX(-50%); transform: translateX(-50%); } body.swal2-toast-shown > .swal2-container.swal2-top-end, body.swal2-toast-shown > .swal2-container.swal2-top-right { top: 0; left: auto; bottom: auto; right: 0; } body.swal2-toast-shown > .swal2-container.swal2-top-start, body.swal2-toast-shown > .swal2-container.swal2-top-left { top: 0; left: 0; bottom: auto; right: auto; } body.swal2-toast-shown > .swal2-container.swal2-center-start, body.swal2-toast-shown > .swal2-container.swal2-center-left { top: 50%; left: 0; bottom: auto; right: auto; -webkit-transform: translateY(-50%); transform: translateY(-50%); } body.swal2-toast-shown > .swal2-container.swal2-center { top: 50%; left: 50%; bottom: auto; right: auto; -webkit-transform: translate(-50%, -50%); transform: translate(-50%, -50%); } body.swal2-toast-shown > .swal2-container.swal2-center-end, body.swal2-toast-shown > .swal2-container.swal2-center-right { top: 50%; left: auto; bottom: auto; right: 0; -webkit-transform: translateY(-50%); transform: translateY(-50%); } body.swal2-toast-shown > .swal2-container.swal2-bottom-start, body.swal2-toast-shown > .swal2-container.swal2-bottom-left { top: auto; left: 0; bottom: 0; right: auto; } body.swal2-toast-shown > .swal2-container.swal2-bottom { top: auto; left: 50%; bottom: 0; right: auto; -webkit-transform: translateX(-50%); transform: translateX(-50%); } body.swal2-toast-shown > .swal2-container.swal2-bottom-end, body.swal2-toast-shown > .swal2-container.swal2-bottom-right { top: auto; left: auto; bottom: 0; right: 0; } body.swal2-iosfix { position: fixed; left: 0; right: 0; } body.swal2-no-backdrop .swal2-shown { top: auto; bottom: auto; left: auto; right: auto; background-color: transparent; } body.swal2-no-backdrop .swal2-shown > .swal2-modal { -webkit-box-shadow: 0 0 10px rgba(0, 0, 0, 0.4); box-shadow: 0 0 10px rgba(0, 0, 0, 0.4); } body.swal2-no-backdrop .swal2-shown.swal2-top { top: 0; left: 50%; -webkit-transform: translateX(-50%); transform: translateX(-50%); } body.swal2-no-backdrop .swal2-shown.swal2-top-start, body.swal2-no-backdrop .swal2-shown.swal2-top-left { top: 0; left: 0; } body.swal2-no-backdrop .swal2-shown.swal2-top-end, body.swal2-no-backdrop .swal2-shown.swal2-top-right { top: 0; right: 0; } body.swal2-no-backdrop .swal2-shown.swal2-center { top: 50%; left: 50%; -webkit-transform: translate(-50%, -50%); transform: translate(-50%, -50%); } body.swal2-no-backdrop .swal2-shown.swal2-center-start, body.swal2-no-backdrop .swal2-shown.swal2-center-left { top: 50%; left: 0; -webkit-transform: translateY(-50%); transform: translateY(-50%); } body.swal2-no-backdrop .swal2-shown.swal2-center-end, body.swal2-no-backdrop .swal2-shown.swal2-center-right { top: 50%; right: 0; -webkit-transform: translateY(-50%); transform: translateY(-50%); } body.swal2-no-backdrop .swal2-shown.swal2-bottom { bottom: 0; left: 50%; -webkit-transform: translateX(-50%); transform: translateX(-50%); } body.swal2-no-backdrop .swal2-shown.swal2-bottom-start, body.swal2-no-backdrop .swal2-shown.swal2-bottom-left { bottom: 0; left: 0; } body.swal2-no-backdrop .swal2-shown.swal2-bottom-end, body.swal2-no-backdrop .swal2-shown.swal2-bottom-right { bottom: 0; right: 0; } .swal2-container { display: -webkit-box; display: -ms-flexbox; display: flex; -webkit-box-orient: horizontal; -webkit-box-direction: normal; -ms-flex-direction: row; flex-direction: row; -webkit-box-align: center; -ms-flex-align: center; align-items: center; -webkit-box-pack: center; -ms-flex-pack: center; justify-content: center; position: fixed; padding: 10px; top: 0; left: 0; right: 0; bottom: 0; background-color: transparent; z-index: 1060; } .swal2-container.swal2-top { -webkit-box-align: start; -ms-flex-align: start; align-items: flex-start; } .swal2-container.swal2-top-start, .swal2-container.swal2-top-left { -webkit-box-align: start; -ms-flex-align: start; align-items: flex-start; -webkit-box-pack: start; -ms-flex-pack: start; justify-content: flex-start; } .swal2-container.swal2-top-end, .swal2-container.swal2-top-right { -webkit-box-align: start; -ms-flex-align: start; align-items: flex-start; -webkit-box-pack: end; -ms-flex-pack: end; justify-content: flex-end; } .swal2-container.swal2-center { -webkit-box-align: center; -ms-flex-align: center; align-items: center; } .swal2-container.swal2-center-start, .swal2-container.swal2-center-left { -webkit-box-align: center; -ms-flex-align: center; align-items: center; -webkit-box-pack: start; -ms-flex-pack: start; justify-content: flex-start; } .swal2-container.swal2-center-end, .swal2-container.swal2-center-right { -webkit-box-align: center; -ms-flex-align: center; align-items: center; -webkit-box-pack: end; -ms-flex-pack: end; justify-content: flex-end; } .swal2-container.swal2-bottom { -webkit-box-align: end; -ms-flex-align: end; align-items: flex-end; } .swal2-container.swal2-bottom-start, .swal2-container.swal2-bottom-left { -webkit-box-align: end; -ms-flex-align: end; align-items: flex-end; -webkit-box-pack: start; -ms-flex-pack: start; justify-content: flex-start; } .swal2-container.swal2-bottom-end, .swal2-container.swal2-bottom-right { -webkit-box-align: end; -ms-flex-align: end; align-items: flex-end; -webkit-box-pack: end; -ms-flex-pack: end; justify-content: flex-end; } .swal2-container.swal2-grow-fullscreen > .swal2-modal { display: -webkit-box !important; display: -ms-flexbox !important; display: flex !important; -webkit-box-flex: 1; -ms-flex: 1; flex: 1; -ms-flex-item-align: stretch; align-self: stretch; -webkit-box-pack: center; -ms-flex-pack: center; justify-content: center; } .swal2-container.swal2-grow-row > .swal2-modal { display: -webkit-box !important; display: -ms-flexbox !important; display: flex !important; -webkit-box-flex: 1; -ms-flex: 1; flex: 1; -ms-flex-line-pack: center; align-content: center; -webkit-box-pack: center; -ms-flex-pack: center; justify-content: center; } .swal2-container.swal2-grow-column { -webkit-box-flex: 1; -ms-flex: 1; flex: 1; -webkit-box-orient: vertical; -webkit-box-direction: normal; -ms-flex-direction: column; flex-direction: column; } .swal2-container.swal2-grow-column.swal2-top, .swal2-container.swal2-grow-column.swal2-center, .swal2-container.swal2-grow-column.swal2-bottom { -webkit-box-align: center; -ms-flex-align: center; align-items: center; } .swal2-container.swal2-grow-column.swal2-top-start, .swal2-container.swal2-grow-column.swal2-center-start, .swal2-container.swal2-grow-column.swal2-bottom-start, .swal2-container.swal2-grow-column.swal2-top-left, .swal2-container.swal2-grow-column.swal2-center-left, .swal2-container.swal2-grow-column.swal2-bottom-left { -webkit-box-align: start; -ms-flex-align: start; align-items: flex-start; } .swal2-container.swal2-grow-column.swal2-top-end, .swal2-container.swal2-grow-column.swal2-center-end, .swal2-container.swal2-grow-column.swal2-bottom-end, .swal2-container.swal2-grow-column.swal2-top-right, .swal2-container.swal2-grow-column.swal2-center-right, .swal2-container.swal2-grow-column.swal2-bottom-right { -webkit-box-align: end; -ms-flex-align: end; align-items: flex-end; } .swal2-container.swal2-grow-column > .swal2-modal { display: -webkit-box !important; display: -ms-flexbox !important; display: flex !important; -webkit-box-flex: 1; -ms-flex: 1; flex: 1; -ms-flex-line-pack: center; align-content: center; -webkit-box-pack: center; -ms-flex-pack: center; justify-content: center; } .swal2-container:not(.swal2-top):not(.swal2-top-start):not(.swal2-top-end):not(.swal2-top-left):not(.swal2-top-right):not(.swal2-center-start):not(.swal2-center-end):not(.swal2-center-left):not(.swal2-center-right):not(.swal2-bottom):not(.swal2-bottom-start):not(.swal2-bottom-end):not(.swal2-bottom-left):not(.swal2-bottom-right) > .swal2-modal { margin: auto; } @media all and (-ms-high-contrast: none), (-ms-high-contrast: active) { .swal2-container .swal2-modal { margin: 0 !important; } } .swal2-container.swal2-fade { -webkit-transition: background-color .1s; transition: background-color .1s; } .swal2-container.swal2-shown { background-color: rgba(0, 0, 0, 0.4); } .swal2-popup { -webkit-box-orient: vertical; -webkit-box-direction: normal; -ms-flex-direction: column; flex-direction: column; background-color: #fff; font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; border-radius: 5px; -webkit-box-sizing: border-box; box-sizing: border-box; text-align: center; overflow-x: hidden; overflow-y: auto; display: none; position: relative; max-width: 100%; } .swal2-popup.swal2-toast { width: 300px; padding: 0 15px; -webkit-box-orient: horizontal; -webkit-box-direction: normal; -ms-flex-direction: row; flex-direction: row; -webkit-box-align: center; -ms-flex-align: center; align-items: center; overflow-y: hidden; -webkit-box-shadow: 0 0 10px #d9d9d9; box-shadow: 0 0 10px #d9d9d9; } .swal2-popup.swal2-toast .swal2-header { -webkit-box-orient: horizontal; -webkit-box-direction: normal; -ms-flex-direction: row; flex-direction: row; } .swal2-popup.swal2-toast .swal2-title { max-width: 300px; font-size: 16px; text-align: left; } .swal2-popup.swal2-toast .swal2-content { font-size: 14px; text-align: left; } .swal2-popup.swal2-toast .swal2-icon { width: 32px; min-width: 32px; height: 32px; margin: 0 15px 0 0; } .swal2-popup.swal2-toast .swal2-icon.swal2-success .swal2-success-ring { width: 32px; height: 32px; } .swal2-popup.swal2-toast .swal2-icon.swal2-info, .swal2-popup.swal2-toast .swal2-icon.swal2-warning, .swal2-popup.swal2-toast .swal2-icon.swal2-question { font-size: 26px; line-height: 32px; } .swal2-popup.swal2-toast .swal2-icon.swal2-error [class^='swal2-x-mark-line'] { top: 14px; width: 22px; } .swal2-popup.swal2-toast .swal2-icon.swal2-error [class^='swal2-x-mark-line'][class$='left'] { left: 5px; } .swal2-popup.swal2-toast .swal2-icon.swal2-error [class^='swal2-x-mark-line'][class$='right'] { right: 5px; } .swal2-popup.swal2-toast .swal2-actions { margin: 0 0 0 5px; } .swal2-popup.swal2-toast .swal2-styled { margin: 0 0 0 5px; padding: 5px 10px; } .swal2-popup.swal2-toast .swal2-styled:focus { -webkit-box-shadow: 0 0 0 1px #fff, 0 0 0 2px rgba(50, 100, 150, 0.4); box-shadow: 0 0 0 1px #fff, 0 0 0 2px rgba(50, 100, 150, 0.4); } .swal2-popup.swal2-toast .swal2-validationerror { width: 100%; margin: 5px -20px; } .swal2-popup.swal2-toast .swal2-success { border-color: #a5dc86; } .swal2-popup.swal2-toast .swal2-success [class^='swal2-success-circular-line'] { border-radius: 50%; position: absolute; width: 32px; height: 64px; -webkit-transform: rotate(45deg); transform: rotate(45deg); } .swal2-popup.swal2-toast .swal2-success [class^='swal2-success-circular-line'][class$='left'] { border-radius: 64px 0 0 64px; top: -4px; left: -15px; -webkit-transform: rotate(-45deg); transform: rotate(-45deg); -webkit-transform-origin: 32px 32px; transform-origin: 32px 32px; } .swal2-popup.swal2-toast .swal2-success [class^='swal2-success-circular-line'][class$='right'] { border-radius: 0 64px 64px 0; top: -5px; left: 14px; -webkit-transform-origin: 0 32px; transform-origin: 0 32px; } .swal2-popup.swal2-toast .swal2-success .swal2-success-ring { width: 32px; height: 32px; } .swal2-popup.swal2-toast .swal2-success .swal2-success-fix { width: 7px; height: 43px; left: 7px; top: 0; } .swal2-popup.swal2-toast .swal2-success [class^='swal2-success-line'] { height: 5px; } .swal2-popup.swal2-toast .swal2-success [class^='swal2-success-line'][class$='tip'] { width: 12px; left: 3px; top: 18px; } .swal2-popup.swal2-toast .swal2-success [class^='swal2-success-line'][class$='long'] { width: 22px; right: 3px; top: 15px; } .swal2-popup.swal2-toast .swal2-animate-success-line-tip { -webkit-animation: animate-toast-success-tip .75s; animation: animate-toast-success-tip .75s; } .swal2-popup.swal2-toast .swal2-animate-success-line-long { -webkit-animation: animate-toast-success-long .75s; animation: animate-toast-success-long .75s; } .swal2-popup:focus { outline: none; } .swal2-popup.swal2-loading { overflow-y: hidden; } .swal2-popup .swal2-header { display: -webkit-box; display: -ms-flexbox; display: flex; -webkit-box-orient: vertical; -webkit-box-direction: normal; -ms-flex-direction: column; flex-direction: column; -webkit-box-align: center; -ms-flex-align: center; align-items: center; } .swal2-popup .swal2-title { color: #595959; font-size: 30px; text-align: center; font-weight: 600; text-transform: none; position: relative; margin: 0 0 .4em; padding: 0; display: block; word-wrap: break-word; } .swal2-popup .swal2-actions { -webkit-box-align: center; -ms-flex-align: center; align-items: center; -webkit-box-pack: center; -ms-flex-pack: center; justify-content: center; margin-top: 15px; } .swal2-popup .swal2-actions:not(.swal2-loading) .swal2-styled[disabled] { opacity: .4; cursor: no-drop; } .swal2-popup .swal2-actions.swal2-loading .swal2-styled.swal2-confirm { -webkit-box-sizing: border-box; box-sizing: border-box; border: 4px solid transparent; border-color: transparent; width: 40px; height: 40px; padding: 0; margin: 7.5px; vertical-align: top; background-color: transparent !important; color: transparent; cursor: default; border-radius: 100%; -webkit-animation: rotate-loading 1.5s linear 0s infinite normal; animation: rotate-loading 1.5s linear 0s infinite normal; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; } .swal2-popup .swal2-actions.swal2-loading .swal2-styled.swal2-cancel { margin-left: 30px; margin-right: 30px; } .swal2-popup .swal2-actions.swal2-loading :not(.swal2-styled).swal2-confirm::after { display: inline-block; content: ''; margin-left: 5px; vertical-align: -1px; height: 15px; width: 15px; border: 3px solid #999999; -webkit-box-shadow: 1px 1px 1px #fff; box-shadow: 1px 1px 1px #fff; border-right-color: transparent; border-radius: 50%; -webkit-animation: rotate-loading 1.5s linear 0s infinite normal; animation: rotate-loading 1.5s linear 0s infinite normal; } .swal2-popup .swal2-styled { border: 0; border-radius: 3px; -webkit-box-shadow: none; box-shadow: none; color: #fff; cursor: pointer; font-size: 17px; font-weight: 500; margin: 15px 5px 0; padding: 10px 32px; } .swal2-popup .swal2-styled:focus { outline: none; -webkit-box-shadow: 0 0 0 2px #fff, 0 0 0 4px rgba(50, 100, 150, 0.4); box-shadow: 0 0 0 2px #fff, 0 0 0 4px rgba(50, 100, 150, 0.4); } .swal2-popup .swal2-image { margin: 20px auto; max-width: 100%; } .swal2-popup .swal2-close { background: transparent; border: 0; margin: 0; padding: 0; width: 38px; height: 40px; font-size: 36px; line-height: 40px; font-family: serif; position: absolute; top: 5px; right: 8px; cursor: pointer; color: #cccccc; -webkit-transition: color .1s ease; transition: color .1s ease; } .swal2-popup .swal2-close:hover { color: #d55; } .swal2-popup > .swal2-input, .swal2-popup > .swal2-file, .swal2-popup > .swal2-textarea, .swal2-popup > .swal2-select, .swal2-popup > .swal2-radio, .swal2-popup > .swal2-checkbox { display: none; } .swal2-popup .swal2-content { font-size: 18px; text-align: center; font-weight: 300; position: relative; float: none; margin: 0; padding: 0; line-height: normal; color: #545454; word-wrap: break-word; } .swal2-popup .swal2-input, .swal2-popup .swal2-file, .swal2-popup .swal2-textarea, .swal2-popup .swal2-select, .swal2-popup .swal2-radio, .swal2-popup .swal2-checkbox { margin: 20px auto; } .swal2-popup .swal2-input, .swal2-popup .swal2-file, .swal2-popup .swal2-textarea { width: 100%; -webkit-box-sizing: border-box; box-sizing: border-box; font-size: 18px; border-radius: 3px; border: 1px solid #d9d9d9; -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.06); box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.06); -webkit-transition: border-color .3s, -webkit-box-shadow .3s; transition: border-color .3s, -webkit-box-shadow .3s; transition: border-color .3s, box-shadow .3s; transition: border-color .3s, box-shadow .3s, -webkit-box-shadow .3s; } .swal2-popup .swal2-input.swal2-inputerror, .swal2-popup .swal2-file.swal2-inputerror, .swal2-popup .swal2-textarea.swal2-inputerror { border-color: #f27474 !important; -webkit-box-shadow: 0 0 2px #f27474 !important; box-shadow: 0 0 2px #f27474 !important; } .swal2-popup .swal2-input:focus, .swal2-popup .swal2-file:focus, .swal2-popup .swal2-textarea:focus { outline: none; border: 1px solid #b4dbed; -webkit-box-shadow: 0 0 3px #c4e6f5; box-shadow: 0 0 3px #c4e6f5; } .swal2-popup .swal2-input::-webkit-input-placeholder, .swal2-popup .swal2-file::-webkit-input-placeholder, .swal2-popup .swal2-textarea::-webkit-input-placeholder { color: #cccccc; } .swal2-popup .swal2-input:-ms-input-placeholder, .swal2-popup .swal2-file:-ms-input-placeholder, .swal2-popup .swal2-textarea:-ms-input-placeholder { color: #cccccc; } .swal2-popup .swal2-input::-ms-input-placeholder, .swal2-popup .swal2-file::-ms-input-placeholder, .swal2-popup .swal2-textarea::-ms-input-placeholder { color: #cccccc; } .swal2-popup .swal2-input::placeholder, .swal2-popup .swal2-file::placeholder, .swal2-popup .swal2-textarea::placeholder { color: #cccccc; } .swal2-popup .swal2-range input { float: left; width: 80%; } .swal2-popup .swal2-range output { float: right; width: 20%; font-size: 20px; font-weight: 600; text-align: center; } .swal2-popup .swal2-range input, .swal2-popup .swal2-range output { height: 43px; line-height: 43px; vertical-align: middle; margin: 20px auto; padding: 0; } .swal2-popup .swal2-input { height: 43px; padding: 0 12px; } .swal2-popup .swal2-input[type='number'] { max-width: 150px; } .swal2-popup .swal2-file { font-size: 20px; } .swal2-popup .swal2-textarea { height: 108px; padding: 12px; } .swal2-popup .swal2-select { color: #545454; font-size: inherit; padding: 5px 10px; min-width: 40%; max-width: 100%; } .swal2-popup .swal2-radio { border: 0; } .swal2-popup .swal2-radio label:not(:first-child) { margin-left: 20px; } .swal2-popup .swal2-radio input, .swal2-popup .swal2-radio span { vertical-align: middle; } .swal2-popup .swal2-radio input { margin: 0 3px 0 0; } .swal2-popup .swal2-checkbox { color: #545454; } .swal2-popup .swal2-checkbox input, .swal2-popup .swal2-checkbox span { vertical-align: middle; } .swal2-popup .swal2-validationerror { background-color: #f0f0f0; margin: 0 -20px; overflow: hidden; padding: 10px; color: gray; font-size: 16px; font-weight: 300; display: none; } .swal2-popup .swal2-validationerror::before { content: '!'; display: inline-block; width: 24px; height: 24px; border-radius: 50%; background-color: #ea7d7d; color: #fff; line-height: 24px; text-align: center; margin-right: 10px; } @supports (-ms-accelerator: true) { .swal2-range input { width: 100% !important; } .swal2-range output { display: none; } } @media all and (-ms-high-contrast: none), (-ms-high-contrast: active) { .swal2-range input { width: 100% !important; } .swal2-range output { display: none; } } .swal2-icon { width: 80px; height: 80px; border: 4px solid transparent; border-radius: 50%; margin: 20px auto 30px; padding: 0; position: relative; -webkit-box-sizing: content-box; box-sizing: content-box; cursor: default; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; } .swal2-icon.swal2-error { border-color: #f27474; } .swal2-icon.swal2-error .swal2-x-mark { position: relative; display: block; } .swal2-icon.swal2-error [class^='swal2-x-mark-line'] { position: absolute; height: 5px; width: 47px; background-color: #f27474; display: block; top: 37px; border-radius: 2px; } .swal2-icon.swal2-error [class^='swal2-x-mark-line'][class$='left'] { -webkit-transform: rotate(45deg); transform: rotate(45deg); left: 17px; } .swal2-icon.swal2-error [class^='swal2-x-mark-line'][class$='right'] { -webkit-transform: rotate(-45deg); transform: rotate(-45deg); right: 16px; } .swal2-icon.swal2-warning { font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; color: #f8bb86; border-color: #facea8; font-size: 60px; line-height: 80px; text-align: center; } .swal2-icon.swal2-info { font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; color: #3fc3ee; border-color: #9de0f6; font-size: 60px; line-height: 80px; text-align: center; } .swal2-icon.swal2-question { font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; color: #87adbd; border-color: #c9dae1; font-size: 60px; line-height: 80px; text-align: center; } .swal2-icon.swal2-success { border-color: #a5dc86; } .swal2-icon.swal2-success [class^='swal2-success-circular-line'] { border-radius: 50%; position: absolute; width: 60px; height: 120px; -webkit-transform: rotate(45deg); transform: rotate(45deg); } .swal2-icon.swal2-success [class^='swal2-success-circular-line'][class$='left'] { border-radius: 120px 0 0 120px; top: -7px; left: -33px; -webkit-transform: rotate(-45deg); transform: rotate(-45deg); -webkit-transform-origin: 60px 60px; transform-origin: 60px 60px; } .swal2-icon.swal2-success [class^='swal2-success-circular-line'][class$='right'] { border-radius: 0 120px 120px 0; top: -11px; left: 30px; -webkit-transform: rotate(-45deg); transform: rotate(-45deg); -webkit-transform-origin: 0 60px; transform-origin: 0 60px; } .swal2-icon.swal2-success .swal2-success-ring { width: 80px; height: 80px; border: 4px solid rgba(165, 220, 134, 0.2); border-radius: 50%; -webkit-box-sizing: content-box; box-sizing: content-box; position: absolute; left: -4px; top: -4px; z-index: 2; } .swal2-icon.swal2-success .swal2-success-fix { width: 7px; height: 90px; position: absolute; left: 26px; top: 8px; z-index: 1; -webkit-transform: rotate(-45deg); transform: rotate(-45deg); } .swal2-icon.swal2-success [class^='swal2-success-line'] { height: 5px; background-color: #a5dc86; display: block; border-radius: 2px; position: absolute; z-index: 2; } .swal2-icon.swal2-success [class^='swal2-success-line'][class$='tip'] { width: 25px; left: 14px; top: 46px; -webkit-transform: rotate(45deg); transform: rotate(45deg); } .swal2-icon.swal2-success [class^='swal2-success-line'][class$='long'] { width: 47px; right: 8px; top: 38px; -webkit-transform: rotate(-45deg); transform: rotate(-45deg); } .swal2-progresssteps { font-weight: 600; margin: 0 0 20px; padding: 0; } .swal2-progresssteps li { display: inline-block; position: relative; } .swal2-progresssteps .swal2-progresscircle { background: #3085d6; border-radius: 2em; color: #fff; height: 2em; line-height: 2em; text-align: center; width: 2em; z-index: 20; } .swal2-progresssteps .swal2-progresscircle:first-child { margin-left: 0; } .swal2-progresssteps .swal2-progresscircle:last-child { margin-right: 0; } .swal2-progresssteps .swal2-progresscircle.swal2-activeprogressstep { background: #3085d6; } .swal2-progresssteps .swal2-progresscircle.swal2-activeprogressstep ~ .swal2-progresscircle { background: #add8e6; } .swal2-progresssteps .swal2-progresscircle.swal2-activeprogressstep ~ .swal2-progressline { background: #add8e6; } .swal2-progresssteps .swal2-progressline { background: #3085d6; height: .4em; margin: 0 -1px; z-index: 10; } [class^='swal2'] { -webkit-tap-highlight-color: transparent; } @-webkit-keyframes showSweetToast { 0% { -webkit-transform: translateY(-10px) rotateZ(2deg); transform: translateY(-10px) rotateZ(2deg); opacity: 0; } 33% { -webkit-transform: translateY(0) rotateZ(-2deg); transform: translateY(0) rotateZ(-2deg); opacity: .5; } 66% { -webkit-transform: translateY(5px) rotateZ(2deg); transform: translateY(5px) rotateZ(2deg); opacity: .7; } 100% { -webkit-transform: translateY(0) rotateZ(0); transform: translateY(0) rotateZ(0); opacity: 1; } } @keyframes showSweetToast { 0% { -webkit-transform: translateY(-10px) rotateZ(2deg); transform: translateY(-10px) rotateZ(2deg); opacity: 0; } 33% { -webkit-transform: translateY(0) rotateZ(-2deg); transform: translateY(0) rotateZ(-2deg); opacity: .5; } 66% { -webkit-transform: translateY(5px) rotateZ(2deg); transform: translateY(5px) rotateZ(2deg); opacity: .7; } 100% { -webkit-transform: translateY(0) rotateZ(0); transform: translateY(0) rotateZ(0); opacity: 1; } } @-webkit-keyframes hideSweetToast { 0% { opacity: 1; } 33% { opacity: .5; } 100% { -webkit-transform: rotateZ(1deg); transform: rotateZ(1deg); opacity: 0; } } @keyframes hideSweetToast { 0% { opacity: 1; } 33% { opacity: .5; } 100% { -webkit-transform: rotateZ(1deg); transform: rotateZ(1deg); opacity: 0; } } @-webkit-keyframes showSweetAlert { 0% { -webkit-transform: scale(0.7); transform: scale(0.7); } 45% { -webkit-transform: scale(1.05); transform: scale(1.05); } 80% { -webkit-transform: scale(0.95); transform: scale(0.95); } 100% { -webkit-transform: scale(1); transform: scale(1); } } @keyframes showSweetAlert { 0% { -webkit-transform: scale(0.7); transform: scale(0.7); } 45% { -webkit-transform: scale(1.05); transform: scale(1.05); } 80% { -webkit-transform: scale(0.95); transform: scale(0.95); } 100% { -webkit-transform: scale(1); transform: scale(1); } } @-webkit-keyframes hideSweetAlert { 0% { -webkit-transform: scale(1); transform: scale(1); opacity: 1; } 100% { -webkit-transform: scale(0.5); transform: scale(0.5); opacity: 0; } } @keyframes hideSweetAlert { 0% { -webkit-transform: scale(1); transform: scale(1); opacity: 1; } 100% { -webkit-transform: scale(0.5); transform: scale(0.5); opacity: 0; } } .swal2-show { -webkit-animation: showSweetAlert .3s; animation: showSweetAlert .3s; } .swal2-show.swal2-toast { -webkit-animation: showSweetToast .5s; animation: showSweetToast .5s; } .swal2-show.swal2-noanimation { -webkit-animation: none; animation: none; } .swal2-hide { -webkit-animation: hideSweetAlert .15s forwards; animation: hideSweetAlert .15s forwards; } .swal2-hide.swal2-toast { -webkit-animation: hideSweetToast .2s forwards; animation: hideSweetToast .2s forwards; } .swal2-hide.swal2-noanimation { -webkit-animation: none; animation: none; } [dir='rtl'] .swal2-close { left: 8px; right: auto; } @-webkit-keyframes animate-success-tip { 0% { width: 0; left: 1px; top: 19px; } 54% { width: 0; left: 2px; top: 17px; } 70% { width: 50px; left: -6px; top: 35px; } 84% { width: 17px; left: 21px; top: 48px; } 100% { width: 25px; left: 14px; top: 45px; } } @keyframes animate-success-tip { 0% { width: 0; left: 1px; top: 19px; } 54% { width: 0; left: 2px; top: 17px; } 70% { width: 50px; left: -6px; top: 35px; } 84% { width: 17px; left: 21px; top: 48px; } 100% { width: 25px; left: 14px; top: 45px; } } @-webkit-keyframes animate-success-long { 0% { width: 0; right: 46px; top: 54px; } 65% { width: 0; right: 46px; top: 54px; } 84% { width: 55px; right: 0; top: 35px; } 100% { width: 47px; right: 8px; top: 38px; } } @keyframes animate-success-long { 0% { width: 0; right: 46px; top: 54px; } 65% { width: 0; right: 46px; top: 54px; } 84% { width: 55px; right: 0; top: 35px; } 100% { width: 47px; right: 8px; top: 38px; } } @-webkit-keyframes animate-toast-success-tip { 0% { width: 0; left: 1px; top: 9px; } 54% { width: 0; left: 2px; top: 2px; } 70% { width: 26px; left: -4px; top: 10px; } 84% { width: 8px; left: 12px; top: 17px; } 100% { width: 12px; left: 3px; top: 18px; } } @keyframes animate-toast-success-tip { 0% { width: 0; left: 1px; top: 9px; } 54% { width: 0; left: 2px; top: 2px; } 70% { width: 26px; left: -4px; top: 10px; } 84% { width: 8px; left: 12px; top: 17px; } 100% { width: 12px; left: 3px; top: 18px; } } @-webkit-keyframes animate-toast-success-long { 0% { width: 0; right: 22px; top: 26px; } 65% { width: 0; right: 15px; top: 20px; } 84% { width: 18px; right: 0; top: 15px; } 100% { width: 22px; right: 3px; top: 15px; } } @keyframes animate-toast-success-long { 0% { width: 0; right: 22px; top: 26px; } 65% { width: 0; right: 15px; top: 20px; } 84% { width: 18px; right: 0; top: 15px; } 100% { width: 22px; right: 3px; top: 15px; } } @-webkit-keyframes rotatePlaceholder { 0% { -webkit-transform: rotate(-45deg); transform: rotate(-45deg); } 5% { -webkit-transform: rotate(-45deg); transform: rotate(-45deg); } 12% { -webkit-transform: rotate(-405deg); transform: rotate(-405deg); } 100% { -webkit-transform: rotate(-405deg); transform: rotate(-405deg); } } @keyframes rotatePlaceholder { 0% { -webkit-transform: rotate(-45deg); transform: rotate(-45deg); } 5% { -webkit-transform: rotate(-45deg); transform: rotate(-45deg); } 12% { -webkit-transform: rotate(-405deg); transform: rotate(-405deg); } 100% { -webkit-transform: rotate(-405deg); transform: rotate(-405deg); } } .swal2-animate-success-line-tip { -webkit-animation: animate-success-tip .75s; animation: animate-success-tip .75s; } .swal2-animate-success-line-long { -webkit-animation: animate-success-long .75s; animation: animate-success-long .75s; } .swal2-success.swal2-animate-success-icon .swal2-success-circular-line-right { -webkit-animation: rotatePlaceholder 4.25s ease-in; animation: rotatePlaceholder 4.25s ease-in; } @-webkit-keyframes animate-error-icon { 0% { -webkit-transform: rotateX(100deg); transform: rotateX(100deg); opacity: 0; } 100% { -webkit-transform: rotateX(0deg); transform: rotateX(0deg); opacity: 1; } } @keyframes animate-error-icon { 0% { -webkit-transform: rotateX(100deg); transform: rotateX(100deg); opacity: 0; } 100% { -webkit-transform: rotateX(0deg); transform: rotateX(0deg); opacity: 1; } } .swal2-animate-error-icon { -webkit-animation: animate-error-icon .5s; animation: animate-error-icon .5s; } @-webkit-keyframes animate-x-mark { 0% { -webkit-transform: scale(0.4); transform: scale(0.4); margin-top: 26px; opacity: 0; } 50% { -webkit-transform: scale(0.4); transform: scale(0.4); margin-top: 26px; opacity: 0; } 80% { -webkit-transform: scale(1.15); transform: scale(1.15); margin-top: -6px; } 100% { -webkit-transform: scale(1); transform: scale(1); margin-top: 0; opacity: 1; } } @keyframes animate-x-mark { 0% { -webkit-transform: scale(0.4); transform: scale(0.4); margin-top: 26px; opacity: 0; } 50% { -webkit-transform: scale(0.4); transform: scale(0.4); margin-top: 26px; opacity: 0; } 80% { -webkit-transform: scale(1.15); transform: scale(1.15); margin-top: -6px; } 100% { -webkit-transform: scale(1); transform: scale(1); margin-top: 0; opacity: 1; } } .swal2-animate-x-mark { -webkit-animation: animate-x-mark .5s; animation: animate-x-mark .5s; } @-webkit-keyframes rotate-loading { 0% { -webkit-transform: rotate(0deg); transform: rotate(0deg); } 100% { -webkit-transform: rotate(360deg); transform: rotate(360deg); } } @keyframes rotate-loading { 0% { -webkit-transform: rotate(0deg); transform: rotate(0deg); } 100% { -webkit-transform: rotate(360deg); transform: rotate(360deg); } }
ahocevar/cdnjs
ajax/libs/limonte-sweetalert2/7.4.1/sweetalert2.css
CSS
mit
37,880
/* Copyright (c) 2009 Christopher J. W. Lloyd 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. */ #import <Onyx2D/O2Surface.h> #import <cairo.h> @class O2Context_cairo; @interface O2Surface_cairo : O2Surface { cairo_surface_t *_cairo_surface; } - initWithWidth:(size_t)width height:(size_t)height compatibleWithContext:(O2Context_cairo *)compatible; - (cairo_surface_t *)cairo_surface; @end
cjwl/cocotron
AppKit/X11.subproj/O2Surface_cairo.h
C
mit
1,375
"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=isNextMonth;var _moment=_interopRequireDefault(require("moment")),_isSameMonth=_interopRequireDefault(require("./isSameMonth"));function isNextMonth(e,t){return!(!_moment.default.isMoment(e)||!_moment.default.isMoment(t))&&(0,_isSameMonth.default)(e.clone().add(1,"month"),t)}
cdnjs/cdnjs
ajax/libs/react-dates/21.8.0/utils/isNextMonth.min.js
JavaScript
mit
443
/* ** $Id: lapi.c,v 2.259 2016/02/29 14:27:14 roberto Exp $ ** Lua API ** See Copyright Notice in lua.h */ #define lapi_c #define LUA_CORE #include "lprefix.h" #include <stdarg.h> #include <string.h> #include "lua.h" #include "lapi.h" #include "ldebug.h" #include "ldo.h" #include "lfunc.h" #include "lgc.h" #include "lmem.h" #include "lobject.h" #include "lstate.h" #include "lstring.h" #include "ltable.h" #include "ltm.h" #include "lundump.h" #include "lvm.h" #include "lfunc.h" const char lua_ident[] = "$LuaVersion: " LUA_COPYRIGHT " $" "$LuaAuthors: " LUA_AUTHORS " $"; /* value at a non-valid index */ #define NONVALIDVALUE cast(TValue *, luaO_nilobject) /* corresponding test */ #define isvalid(o) ((o) != luaO_nilobject) /* test for pseudo index */ #define ispseudo(i) ((i) <= LUA_REGISTRYINDEX) /* test for upvalue */ #define isupvalue(i) ((i) < LUA_REGISTRYINDEX) /* test for valid but not pseudo index */ #define isstackindex(i, o) (isvalid(o) && !ispseudo(i)) #define api_checkvalidindex(l,o) api_check(l, isvalid(o), "invalid index") #define api_checkstackindex(l, i, o) \ api_check(l, isstackindex(i, o), "index not in the stack") static TValue *index2addr (lua_State *L, int idx) { CallInfo *ci = L->ci; if (idx > 0) { TValue *o = ci->func + idx; api_check(L, idx <= ci->top - (ci->func + 1), "unacceptable index"); if (o >= L->top) return NONVALIDVALUE; else return o; } else if (!ispseudo(idx)) { /* negative index */ api_check(L, idx != 0 && -idx <= L->top - (ci->func + 1), "invalid index"); return L->top + idx; } else if (idx == LUA_REGISTRYINDEX) return &G(L)->l_registry; else { /* upvalues */ idx = LUA_REGISTRYINDEX - idx; api_check(L, idx <= MAXUPVAL + 1, "upvalue index too large"); if (ttislcf(ci->func)) /* light C function? */ return NONVALIDVALUE; /* it has no upvalues */ else { CClosure *func = clCvalue(ci->func); return (idx <= func->nupvalues) ? &func->upvalue[idx-1] : NONVALIDVALUE; } } } /* ** to be called by 'lua_checkstack' in protected mode, to grow stack ** capturing memory errors */ static void growstack (lua_State *L, void *ud) { int size = *(int *)ud; luaD_growstack(L, size); } LUA_API int lua_checkstack (lua_State *L, int n) { int res; CallInfo *ci = L->ci; lua_lock(L); api_check(L, n >= 0, "negative 'n'"); if (L->stack_last - L->top > n) /* stack large enough? */ res = 1; /* yes; check is OK */ else { /* no; need to grow stack */ int inuse = cast_int(L->top - L->stack) + EXTRA_STACK; if (inuse > LUAI_MAXSTACK - n) /* can grow without overflow? */ res = 0; /* no */ else /* try to grow stack */ res = (luaD_rawrunprotected(L, &growstack, &n) == LUA_OK); } if (res && ci->top < L->top + n) ci->top = L->top + n; /* adjust frame top */ lua_unlock(L); return res; } LUA_API void lua_xmove (lua_State *from, lua_State *to, int n) { int i; if (from == to) return; lua_lock(to); api_checknelems(from, n); api_check(from, G(from) == G(to), "moving among independent states"); api_check(from, to->ci->top - to->top >= n, "stack overflow"); from->top -= n; for (i = 0; i < n; i++) { setobj2s(to, to->top, from->top + i); to->top++; /* stack already checked by previous 'api_check' */ } lua_unlock(to); } LUA_API lua_CFunction lua_atpanic (lua_State *L, lua_CFunction panicf) { lua_CFunction old; lua_lock(L); old = G(L)->panic; G(L)->panic = panicf; lua_unlock(L); return old; } LUA_API const lua_Number *lua_version (lua_State *L) { static const lua_Number version = LUA_VERSION_NUM; if (L == NULL) return &version; else return G(L)->version; } /* ** basic stack manipulation */ /* ** convert an acceptable stack index into an absolute index */ LUA_API int lua_absindex (lua_State *L, int idx) { return (idx > 0 || ispseudo(idx)) ? idx : cast_int(L->top - L->ci->func) + idx; } LUA_API int lua_gettop (lua_State *L) { return cast_int(L->top - (L->ci->func + 1)); } LUA_API void lua_settop (lua_State *L, int idx) { StkId func = L->ci->func; lua_lock(L); if (idx >= 0) { api_check(L, idx <= L->stack_last - (func + 1), "new top too large"); while (L->top < (func + 1) + idx) setnilvalue(L->top++); L->top = (func + 1) + idx; } else { api_check(L, -(idx+1) <= (L->top - (func + 1)), "invalid new top"); L->top += idx+1; /* 'subtract' index (index is negative) */ } lua_unlock(L); } /* ** Reverse the stack segment from 'from' to 'to' ** (auxiliary to 'lua_rotate') */ static void reverse (lua_State *L, StkId from, StkId to) { for (; from < to; from++, to--) { TValue temp; setobj(L, &temp, from); setobjs2s(L, from, to); setobj2s(L, to, &temp); } } /* ** Let x = AB, where A is a prefix of length 'n'. Then, ** rotate x n == BA. But BA == (A^r . B^r)^r. */ LUA_API void lua_rotate (lua_State *L, int idx, int n) { StkId p, t, m; lua_lock(L); t = L->top - 1; /* end of stack segment being rotated */ p = index2addr(L, idx); /* start of segment */ api_checkstackindex(L, idx, p); api_check(L, (n >= 0 ? n : -n) <= (t - p + 1), "invalid 'n'"); m = (n >= 0 ? t - n : p - n - 1); /* end of prefix */ reverse(L, p, m); /* reverse the prefix with length 'n' */ reverse(L, m + 1, t); /* reverse the suffix */ reverse(L, p, t); /* reverse the entire segment */ lua_unlock(L); } LUA_API void lua_copy (lua_State *L, int fromidx, int toidx) { TValue *fr, *to; lua_lock(L); fr = index2addr(L, fromidx); to = index2addr(L, toidx); api_checkvalidindex(L, to); setobj(L, to, fr); if (isupvalue(toidx)) /* function upvalue? */ luaC_barrier(L, clCvalue(L->ci->func), fr); /* LUA_REGISTRYINDEX does not need gc barrier (collector revisits it before finishing collection) */ lua_unlock(L); } LUA_API void lua_pushvalue (lua_State *L, int idx) { lua_lock(L); setobj2s(L, L->top, index2addr(L, idx)); api_incr_top(L); lua_unlock(L); } /* ** access functions (stack -> C) */ LUA_API int lua_type (lua_State *L, int idx) { StkId o = index2addr(L, idx); return (isvalid(o) ? ttnov(o) : LUA_TNONE); } LUA_API const char *lua_typename (lua_State *L, int t) { UNUSED(L); api_check(L, LUA_TNONE <= t && t < LUA_NUMTAGS, "invalid tag"); return ttypename(t); } LUA_API int lua_iscfunction (lua_State *L, int idx) { StkId o = index2addr(L, idx); return (ttislcf(o) || (ttisCclosure(o))); } LUA_API int lua_isinteger (lua_State *L, int idx) { StkId o = index2addr(L, idx); return ttisinteger(o); } LUA_API int lua_isnumber (lua_State *L, int idx) { lua_Number n; const TValue *o = index2addr(L, idx); return tonumber(o, &n); } LUA_API int lua_isstring (lua_State *L, int idx) { const TValue *o = index2addr(L, idx); return (ttisstring(o) || cvt2str(o)); } LUA_API int lua_isuserdata (lua_State *L, int idx) { const TValue *o = index2addr(L, idx); return (ttisfulluserdata(o) || ttislightuserdata(o)); } LUA_API int lua_rawequal (lua_State *L, int index1, int index2) { StkId o1 = index2addr(L, index1); StkId o2 = index2addr(L, index2); return (isvalid(o1) && isvalid(o2)) ? luaV_rawequalobj(o1, o2) : 0; } LUA_API void lua_arith (lua_State *L, int op) { lua_lock(L); if (op != LUA_OPUNM && op != LUA_OPBNOT) api_checknelems(L, 2); /* all other operations expect two operands */ else { /* for unary operations, add fake 2nd operand */ api_checknelems(L, 1); setobjs2s(L, L->top, L->top - 1); api_incr_top(L); } /* first operand at top - 2, second at top - 1; result go to top - 2 */ luaO_arith(L, op, L->top - 2, L->top - 1, L->top - 2); L->top--; /* remove second operand */ lua_unlock(L); } LUA_API int lua_compare (lua_State *L, int index1, int index2, int op) { StkId o1, o2; int i = 0; lua_lock(L); /* may call tag method */ o1 = index2addr(L, index1); o2 = index2addr(L, index2); if (isvalid(o1) && isvalid(o2)) { switch (op) { case LUA_OPEQ: i = luaV_equalobj(L, o1, o2); break; case LUA_OPLT: i = luaV_lessthan(L, o1, o2); break; case LUA_OPLE: i = luaV_lessequal(L, o1, o2); break; default: api_check(L, 0, "invalid option"); } } lua_unlock(L); return i; } LUA_API size_t lua_stringtonumber (lua_State *L, const char *s) { size_t sz = luaO_str2num(s, L->top); if (sz != 0) api_incr_top(L); return sz; } LUA_API lua_Number lua_tonumberx (lua_State *L, int idx, int *pisnum) { lua_Number n; const TValue *o = index2addr(L, idx); int isnum = tonumber(o, &n); if (!isnum) n = 0; /* call to 'tonumber' may change 'n' even if it fails */ if (pisnum) *pisnum = isnum; return n; } LUA_API lua_Integer lua_tointegerx (lua_State *L, int idx, int *pisnum) { lua_Integer res; const TValue *o = index2addr(L, idx); int isnum = tointeger(o, &res); if (!isnum) res = 0; /* call to 'tointeger' may change 'n' even if it fails */ if (pisnum) *pisnum = isnum; return res; } LUA_API int lua_toboolean (lua_State *L, int idx) { const TValue *o = index2addr(L, idx); return !l_isfalse(o); } LUA_API const char *lua_tolstring (lua_State *L, int idx, size_t *len) { StkId o = index2addr(L, idx); if (!ttisstring(o)) { if (!cvt2str(o)) { /* not convertible? */ if (len != NULL) *len = 0; return NULL; } lua_lock(L); /* 'luaO_tostring' may create a new string */ luaO_tostring(L, o); luaC_checkGC(L); o = index2addr(L, idx); /* previous call may reallocate the stack */ lua_unlock(L); } if (len != NULL) *len = vslen(o); return svalue(o); } LUA_API size_t lua_rawlen (lua_State *L, int idx) { StkId o = index2addr(L, idx); switch (ttype(o)) { case LUA_TSHRSTR: return tsvalue(o)->shrlen; case LUA_TLNGSTR: return tsvalue(o)->u.lnglen; case LUA_TUSERDATA: return uvalue(o)->len; case LUA_TTABLE: return luaH_getn(hvalue(o)); default: return 0; } } LUA_API lua_CFunction lua_tocfunction (lua_State *L, int idx) { StkId o = index2addr(L, idx); if (ttislcf(o)) return fvalue(o); else if (ttisCclosure(o)) return clCvalue(o)->f; else return NULL; /* not a C function */ } LUA_API void *lua_touserdata (lua_State *L, int idx) { StkId o = index2addr(L, idx); switch (ttnov(o)) { case LUA_TUSERDATA: return getudatamem(uvalue(o)); case LUA_TLIGHTUSERDATA: return pvalue(o); default: return NULL; } } LUA_API lua_State *lua_tothread (lua_State *L, int idx) { StkId o = index2addr(L, idx); return (!ttisthread(o)) ? NULL : thvalue(o); } LUA_API const void *lua_topointer (lua_State *L, int idx) { StkId o = index2addr(L, idx); switch (ttype(o)) { case LUA_TTABLE: return hvalue(o); case LUA_TLCL: return clLvalue(o); case LUA_TCCL: return clCvalue(o); case LUA_TLCF: return cast(void *, cast(size_t, fvalue(o))); case LUA_TTHREAD: return thvalue(o); case LUA_TUSERDATA: return getudatamem(uvalue(o)); case LUA_TLIGHTUSERDATA: return pvalue(o); default: return NULL; } } /* ** push functions (C -> stack) */ LUA_API void lua_pushnil (lua_State *L) { lua_lock(L); setnilvalue(L->top); api_incr_top(L); lua_unlock(L); } LUA_API void lua_pushnumber (lua_State *L, lua_Number n) { lua_lock(L); setfltvalue(L->top, n); api_incr_top(L); lua_unlock(L); } LUA_API void lua_pushinteger (lua_State *L, lua_Integer n) { lua_lock(L); setivalue(L->top, n); api_incr_top(L); lua_unlock(L); } /* ** Pushes on the stack a string with given length. Avoid using 's' when ** 'len' == 0 (as 's' can be NULL in that case), due to later use of ** 'memcmp' and 'memcpy'. */ LUA_API const char *lua_pushlstring (lua_State *L, const char *s, size_t len) { TString *ts; lua_lock(L); ts = (len == 0) ? luaS_new(L, "") : luaS_newlstr(L, s, len); setsvalue2s(L, L->top, ts); api_incr_top(L); luaC_checkGC(L); lua_unlock(L); return getstr(ts); } LUA_API const char *lua_pushstring (lua_State *L, const char *s) { lua_lock(L); if (s == NULL) setnilvalue(L->top); else { TString *ts; ts = luaS_new(L, s); setsvalue2s(L, L->top, ts); s = getstr(ts); /* internal copy's address */ } api_incr_top(L); luaC_checkGC(L); lua_unlock(L); return s; } LUA_API const char *lua_pushvfstring (lua_State *L, const char *fmt, va_list argp) { const char *ret; lua_lock(L); ret = luaO_pushvfstring(L, fmt, argp); luaC_checkGC(L); lua_unlock(L); return ret; } LUA_API const char *lua_pushfstring (lua_State *L, const char *fmt, ...) { const char *ret; va_list argp; lua_lock(L); va_start(argp, fmt); ret = luaO_pushvfstring(L, fmt, argp); va_end(argp); luaC_checkGC(L); lua_unlock(L); return ret; } LUA_API void lua_pushcclosure (lua_State *L, lua_CFunction fn, int n) { lua_lock(L); if (n == 0) { setfvalue(L->top, fn); } else { CClosure *cl; api_checknelems(L, n); api_check(L, n <= MAXUPVAL, "upvalue index too large"); cl = luaF_newCclosure(L, n); cl->f = fn; L->top -= n; while (n--) { setobj2n(L, &cl->upvalue[n], L->top + n); /* does not need barrier because closure is white */ } setclCvalue(L, L->top, cl); } api_incr_top(L); luaC_checkGC(L); lua_unlock(L); } LUA_API void lua_pushboolean (lua_State *L, int b) { lua_lock(L); setbvalue(L->top, (b != 0)); /* ensure that true is 1 */ api_incr_top(L); lua_unlock(L); } LUA_API void lua_pushlightuserdata (lua_State *L, void *p) { lua_lock(L); setpvalue(L->top, p); api_incr_top(L); lua_unlock(L); } LUA_API int lua_pushthread (lua_State *L) { lua_lock(L); setthvalue(L, L->top, L); api_incr_top(L); lua_unlock(L); return (G(L)->mainthread == L); } /* ** get functions (Lua -> stack) */ static int auxgetstr (lua_State *L, const TValue *t, const char *k) { const TValue *slot; TString *str = luaS_new(L, k); if (luaV_fastget(L, t, str, slot, luaH_getstr)) { setobj2s(L, L->top, slot); api_incr_top(L); } else { setsvalue2s(L, L->top, str); api_incr_top(L); luaV_finishget(L, t, L->top - 1, L->top - 1, slot); } lua_unlock(L); return ttnov(L->top - 1); } LUA_API int lua_getglobal (lua_State *L, const char *name) { Table *reg = hvalue(&G(L)->l_registry); lua_lock(L); return auxgetstr(L, luaH_getint(reg, LUA_RIDX_GLOBALS), name); } LUA_API int lua_gettable (lua_State *L, int idx) { StkId t; lua_lock(L); t = index2addr(L, idx); luaV_gettable(L, t, L->top - 1, L->top - 1); lua_unlock(L); return ttnov(L->top - 1); } LUA_API int lua_getfield (lua_State *L, int idx, const char *k) { lua_lock(L); return auxgetstr(L, index2addr(L, idx), k); } LUA_API int lua_geti (lua_State *L, int idx, lua_Integer n) { StkId t; const TValue *slot; lua_lock(L); t = index2addr(L, idx); if (luaV_fastget(L, t, n, slot, luaH_getint)) { setobj2s(L, L->top, slot); api_incr_top(L); } else { setivalue(L->top, n); api_incr_top(L); luaV_finishget(L, t, L->top - 1, L->top - 1, slot); } lua_unlock(L); return ttnov(L->top - 1); } LUA_API int lua_rawget (lua_State *L, int idx) { StkId t; lua_lock(L); t = index2addr(L, idx); api_check(L, ttistable(t), "table expected"); setobj2s(L, L->top - 1, luaH_get(hvalue(t), L->top - 1)); lua_unlock(L); return ttnov(L->top - 1); } LUA_API int lua_rawgeti (lua_State *L, int idx, lua_Integer n) { StkId t; lua_lock(L); t = index2addr(L, idx); api_check(L, ttistable(t), "table expected"); setobj2s(L, L->top, luaH_getint(hvalue(t), n)); api_incr_top(L); lua_unlock(L); return ttnov(L->top - 1); } LUA_API int lua_rawgetp (lua_State *L, int idx, const void *p) { StkId t; TValue k; lua_lock(L); t = index2addr(L, idx); api_check(L, ttistable(t), "table expected"); setpvalue(&k, cast(void *, p)); setobj2s(L, L->top, luaH_get(hvalue(t), &k)); api_incr_top(L); lua_unlock(L); return ttnov(L->top - 1); } LUA_API void lua_createtable (lua_State *L, int narray, int nrec) { Table *t; lua_lock(L); t = luaH_new(L); sethvalue(L, L->top, t); api_incr_top(L); if (narray > 0 || nrec > 0) luaH_resize(L, t, narray, nrec); luaC_checkGC(L); lua_unlock(L); } LUA_API int lua_getmetatable (lua_State *L, int objindex) { const TValue *obj; Table *mt; int res = 0; lua_lock(L); obj = index2addr(L, objindex); switch (ttnov(obj)) { case LUA_TTABLE: mt = hvalue(obj)->metatable; break; case LUA_TUSERDATA: mt = uvalue(obj)->metatable; break; default: mt = G(L)->mt[ttnov(obj)]; break; } if (mt != NULL) { sethvalue(L, L->top, mt); api_incr_top(L); res = 1; } lua_unlock(L); return res; } LUA_API int lua_getuservalue (lua_State *L, int idx) { StkId o; lua_lock(L); o = index2addr(L, idx); api_check(L, ttisfulluserdata(o), "full userdata expected"); getuservalue(L, uvalue(o), L->top); api_incr_top(L); lua_unlock(L); return ttnov(L->top - 1); } /* ** set functions (stack -> Lua) */ /* ** t[k] = value at the top of the stack (where 'k' is a string) */ static void auxsetstr (lua_State *L, const TValue *t, const char *k) { const TValue *slot; TString *str = luaS_new(L, k); api_checknelems(L, 1); if (luaV_fastset(L, t, str, slot, luaH_getstr, L->top - 1)) L->top--; /* pop value */ else { setsvalue2s(L, L->top, str); /* push 'str' (to make it a TValue) */ api_incr_top(L); luaV_finishset(L, t, L->top - 1, L->top - 2, slot); L->top -= 2; /* pop value and key */ } lua_unlock(L); /* lock done by caller */ } LUA_API void lua_setglobal (lua_State *L, const char *name) { Table *reg = hvalue(&G(L)->l_registry); lua_lock(L); /* unlock done in 'auxsetstr' */ auxsetstr(L, luaH_getint(reg, LUA_RIDX_GLOBALS), name); } LUA_API void lua_settable (lua_State *L, int idx) { StkId t; lua_lock(L); api_checknelems(L, 2); t = index2addr(L, idx); luaV_settable(L, t, L->top - 2, L->top - 1); L->top -= 2; /* pop index and value */ lua_unlock(L); } LUA_API void lua_setfield (lua_State *L, int idx, const char *k) { lua_lock(L); /* unlock done in 'auxsetstr' */ auxsetstr(L, index2addr(L, idx), k); } LUA_API void lua_seti (lua_State *L, int idx, lua_Integer n) { StkId t; const TValue *slot; lua_lock(L); api_checknelems(L, 1); t = index2addr(L, idx); if (luaV_fastset(L, t, n, slot, luaH_getint, L->top - 1)) L->top--; /* pop value */ else { setivalue(L->top, n); api_incr_top(L); luaV_finishset(L, t, L->top - 1, L->top - 2, slot); L->top -= 2; /* pop value and key */ } lua_unlock(L); } LUA_API void lua_rawset (lua_State *L, int idx) { StkId o; TValue *slot; lua_lock(L); api_checknelems(L, 2); o = index2addr(L, idx); api_check(L, ttistable(o), "table expected"); slot = luaH_set(L, hvalue(o), L->top - 2); setobj2t(L, slot, L->top - 1); invalidateTMcache(hvalue(o)); luaC_barrierback(L, hvalue(o), L->top-1); L->top -= 2; lua_unlock(L); } LUA_API void lua_rawseti (lua_State *L, int idx, lua_Integer n) { StkId o; lua_lock(L); api_checknelems(L, 1); o = index2addr(L, idx); api_check(L, ttistable(o), "table expected"); luaH_setint(L, hvalue(o), n, L->top - 1); luaC_barrierback(L, hvalue(o), L->top-1); L->top--; lua_unlock(L); } LUA_API void lua_rawsetp (lua_State *L, int idx, const void *p) { StkId o; TValue k, *slot; lua_lock(L); api_checknelems(L, 1); o = index2addr(L, idx); api_check(L, ttistable(o), "table expected"); setpvalue(&k, cast(void *, p)); slot = luaH_set(L, hvalue(o), &k); setobj2t(L, slot, L->top - 1); luaC_barrierback(L, hvalue(o), L->top - 1); L->top--; lua_unlock(L); } LUA_API int lua_setmetatable (lua_State *L, int objindex) { TValue *obj; Table *mt; lua_lock(L); api_checknelems(L, 1); obj = index2addr(L, objindex); if (ttisnil(L->top - 1)) mt = NULL; else { api_check(L, ttistable(L->top - 1), "table expected"); mt = hvalue(L->top - 1); } switch (ttnov(obj)) { case LUA_TTABLE: { hvalue(obj)->metatable = mt; if (mt) { luaC_objbarrier(L, gcvalue(obj), mt); luaC_checkfinalizer(L, gcvalue(obj), mt); } break; } case LUA_TUSERDATA: { uvalue(obj)->metatable = mt; if (mt) { luaC_objbarrier(L, uvalue(obj), mt); luaC_checkfinalizer(L, gcvalue(obj), mt); } break; } default: { G(L)->mt[ttnov(obj)] = mt; break; } } L->top--; lua_unlock(L); return 1; } LUA_API void lua_setuservalue (lua_State *L, int idx) { StkId o; lua_lock(L); api_checknelems(L, 1); o = index2addr(L, idx); api_check(L, ttisfulluserdata(o), "full userdata expected"); setuservalue(L, uvalue(o), L->top - 1); luaC_barrier(L, gcvalue(o), L->top - 1); L->top--; lua_unlock(L); } /* ** 'load' and 'call' functions (run Lua code) */ #define checkresults(L,na,nr) \ api_check(L, (nr) == LUA_MULTRET || (L->ci->top - L->top >= (nr) - (na)), \ "results from function overflow current stack size") LUA_API void lua_callk (lua_State *L, int nargs, int nresults, lua_KContext ctx, lua_KFunction k) { StkId func; lua_lock(L); api_check(L, k == NULL || !isLua(L->ci), "cannot use continuations inside hooks"); api_checknelems(L, nargs+1); api_check(L, L->status == LUA_OK, "cannot do calls on non-normal thread"); checkresults(L, nargs, nresults); func = L->top - (nargs+1); if (k != NULL && L->nny == 0) { /* need to prepare continuation? */ L->ci->u.c.k = k; /* save continuation */ L->ci->u.c.ctx = ctx; /* save context */ luaD_call(L, func, nresults); /* do the call */ } else /* no continuation or no yieldable */ luaD_callnoyield(L, func, nresults); /* just do the call */ adjustresults(L, nresults); lua_unlock(L); } /* ** Execute a protected call. */ struct CallS { /* data to 'f_call' */ StkId func; int nresults; }; static void f_call (lua_State *L, void *ud) { struct CallS *c = cast(struct CallS *, ud); luaD_callnoyield(L, c->func, c->nresults); } LUA_API int lua_pcallk (lua_State *L, int nargs, int nresults, int errfunc, lua_KContext ctx, lua_KFunction k) { struct CallS c; int status; ptrdiff_t func; lua_lock(L); api_check(L, k == NULL || !isLua(L->ci), "cannot use continuations inside hooks"); api_checknelems(L, nargs+1); api_check(L, L->status == LUA_OK, "cannot do calls on non-normal thread"); checkresults(L, nargs, nresults); if (errfunc == 0) func = 0; else { StkId o = index2addr(L, errfunc); api_checkstackindex(L, errfunc, o); func = savestack(L, o); } c.func = L->top - (nargs+1); /* function to be called */ if (k == NULL || L->nny > 0) { /* no continuation or no yieldable? */ c.nresults = nresults; /* do a 'conventional' protected call */ status = luaD_pcall(L, f_call, &c, savestack(L, c.func), func); } else { /* prepare continuation (call is already protected by 'resume') */ CallInfo *ci = L->ci; ci->u.c.k = k; /* save continuation */ ci->u.c.ctx = ctx; /* save context */ /* save information for error recovery */ ci->extra = savestack(L, c.func); ci->u.c.old_errfunc = L->errfunc; L->errfunc = func; setoah(ci->callstatus, L->allowhook); /* save value of 'allowhook' */ ci->callstatus |= CIST_YPCALL; /* function can do error recovery */ luaD_call(L, c.func, nresults); /* do the call */ ci->callstatus &= ~CIST_YPCALL; L->errfunc = ci->u.c.old_errfunc; status = LUA_OK; /* if it is here, there were no errors */ } adjustresults(L, nresults); lua_unlock(L); return status; } LUA_API int lua_load (lua_State *L, lua_Reader reader, void *data, const char *chunkname, const char *mode) { ZIO z; int status; lua_lock(L); if (!chunkname) chunkname = "?"; luaZ_init(L, &z, reader, data); status = luaD_protectedparser(L, &z, chunkname, mode); if (status == LUA_OK) { /* no errors? */ LClosure *f = clLvalue(L->top - 1); /* get newly created function */ if (f->nupvalues >= 1) { /* does it have an upvalue? */ /* get global table from registry */ Table *reg = hvalue(&G(L)->l_registry); const TValue *gt = luaH_getint(reg, LUA_RIDX_GLOBALS); /* set global table as 1st upvalue of 'f' (may be LUA_ENV) */ setobj(L, f->upvals[0]->v, gt); luaC_upvalbarrier(L, f->upvals[0]); } } lua_unlock(L); return status; } void cloneproto (lua_State *L, Proto *f, const Proto *src) { /* copy constants and nested proto */ int i,n; n = src->sp->sizek; f->k=luaM_newvector(L,n,TValue); for (i=0; i<n; i++) setnilvalue(&f->k[i]); for (i=0; i<n; i++) { const TValue *s=&src->k[i]; TValue *o=&f->k[i]; if (ttisstring(s)) { TString * str = luaS_clonestring(L,tsvalue(s)); setsvalue2n(L,o,str); } else { setobj(L,o,s); } } n = src->sp->sizep; f->p=luaM_newvector(L,n,struct Proto *); for (i=0; i<n; i++) f->p[i]=NULL; for (i=0; i<n; i++) { f->p[i]= luaF_newproto(L, src->p[i]->sp); cloneproto(L, f->p[i], src->p[i]); } } LUA_API void lua_clonefunction (lua_State *L, const void * fp) { LClosure *cl; LClosure *f = cast(LClosure *, fp); lua_lock(L); if (f->p->sp->l_G == G(L)) { setclLvalue(L,L->top,f); api_incr_top(L); lua_unlock(L); return; } cl = luaF_newLclosure(L,f->nupvalues); setclLvalue(L,L->top,cl); api_incr_top(L); cl->p = luaF_newproto(L, f->p->sp); cloneproto(L, cl->p, f->p); luaF_initupvals(L, cl); if (cl->nupvalues >= 1) { /* does it have an upvalue? */ /* get global table from registry */ Table *reg = hvalue(&G(L)->l_registry); const TValue *gt = luaH_getint(reg, LUA_RIDX_GLOBALS); /* set global table as 1st upvalue of 'f' (may be LUA_ENV) */ setobj(L, cl->upvals[0]->v, gt); luaC_upvalbarrier(L, cl->upvals[0]); } lua_unlock(L); } LUA_API int lua_dump (lua_State *L, lua_Writer writer, void *data, int strip) { int status; TValue *o; lua_lock(L); api_checknelems(L, 1); o = L->top - 1; if (isLfunction(o)) status = luaU_dump(L, getproto(o), writer, data, strip); else status = 1; lua_unlock(L); return status; } LUA_API int lua_status (lua_State *L) { return L->status; } /* ** Garbage-collection function */ LUA_API int lua_gc (lua_State *L, int what, int data) { int res = 0; global_State *g; lua_lock(L); g = G(L); switch (what) { case LUA_GCSTOP: { g->gcrunning = 0; break; } case LUA_GCRESTART: { luaE_setdebt(g, 0); g->gcrunning = 1; break; } case LUA_GCCOLLECT: { luaC_fullgc(L, 0); break; } case LUA_GCCOUNT: { /* GC values are expressed in Kbytes: #bytes/2^10 */ res = cast_int(gettotalbytes(g) >> 10); break; } case LUA_GCCOUNTB: { res = cast_int(gettotalbytes(g) & 0x3ff); break; } case LUA_GCSTEP: { l_mem debt = 1; /* =1 to signal that it did an actual step */ lu_byte oldrunning = g->gcrunning; g->gcrunning = 1; /* allow GC to run */ if (data == 0) { luaE_setdebt(g, -GCSTEPSIZE); /* to do a "small" step */ luaC_step(L); } else { /* add 'data' to total debt */ debt = cast(l_mem, data) * 1024 + g->GCdebt; luaE_setdebt(g, debt); luaC_checkGC(L); } g->gcrunning = oldrunning; /* restore previous state */ if (debt > 0 && g->gcstate == GCSpause) /* end of cycle? */ res = 1; /* signal it */ break; } case LUA_GCSETPAUSE: { res = g->gcpause; g->gcpause = data; break; } case LUA_GCSETSTEPMUL: { res = g->gcstepmul; if (data < 40) data = 40; /* avoid ridiculous low values (and 0) */ g->gcstepmul = data; break; } case LUA_GCISRUNNING: { res = g->gcrunning; break; } default: res = -1; /* invalid option */ } lua_unlock(L); return res; } /* ** miscellaneous functions */ LUA_API int lua_error (lua_State *L) { lua_lock(L); api_checknelems(L, 1); luaG_errormsg(L); /* code unreachable; will unlock when control actually leaves the kernel */ return 0; /* to avoid warnings */ } LUA_API int lua_next (lua_State *L, int idx) { StkId t; int more; lua_lock(L); t = index2addr(L, idx); api_check(L, ttistable(t), "table expected"); more = luaH_next(L, hvalue(t), L->top - 1); if (more) { api_incr_top(L); } else /* no more elements */ L->top -= 1; /* remove key */ lua_unlock(L); return more; } LUA_API void lua_concat (lua_State *L, int n) { lua_lock(L); api_checknelems(L, n); if (n >= 2) { luaV_concat(L, n); } else if (n == 0) { /* push empty string */ setsvalue2s(L, L->top, luaS_newlstr(L, "", 0)); api_incr_top(L); } /* else n == 1; nothing to do */ luaC_checkGC(L); lua_unlock(L); } LUA_API void lua_len (lua_State *L, int idx) { StkId t; lua_lock(L); t = index2addr(L, idx); luaV_objlen(L, L->top, t); api_incr_top(L); lua_unlock(L); } LUA_API lua_Alloc lua_getallocf (lua_State *L, void **ud) { lua_Alloc f; lua_lock(L); if (ud) *ud = G(L)->ud; f = G(L)->frealloc; lua_unlock(L); return f; } LUA_API void lua_setallocf (lua_State *L, lua_Alloc f, void *ud) { lua_lock(L); G(L)->ud = ud; G(L)->frealloc = f; lua_unlock(L); } LUA_API void *lua_newuserdata (lua_State *L, size_t size) { Udata *u; lua_lock(L); u = luaS_newudata(L, size); setuvalue(L, L->top, u); api_incr_top(L); luaC_checkGC(L); lua_unlock(L); return getudatamem(u); } static const char *aux_upvalue (StkId fi, int n, TValue **val, CClosure **owner, UpVal **uv) { switch (ttype(fi)) { case LUA_TCCL: { /* C closure */ CClosure *f = clCvalue(fi); if (!(1 <= n && n <= f->nupvalues)) return NULL; *val = &f->upvalue[n-1]; if (owner) *owner = f; return ""; } case LUA_TLCL: { /* Lua closure */ LClosure *f = clLvalue(fi); TString *name; SharedProto *p = f->p->sp; if (!(1 <= n && n <= p->sizeupvalues)) return NULL; *val = f->upvals[n-1]->v; if (uv) *uv = f->upvals[n - 1]; name = p->upvalues[n-1].name; return (name == NULL) ? "(*no name)" : getstr(name); } default: return NULL; /* not a closure */ } } LUA_API const char *lua_getupvalue (lua_State *L, int funcindex, int n) { const char *name; TValue *val = NULL; /* to avoid warnings */ lua_lock(L); name = aux_upvalue(index2addr(L, funcindex), n, &val, NULL, NULL); if (name) { setobj2s(L, L->top, val); api_incr_top(L); } lua_unlock(L); return name; } LUA_API const char *lua_setupvalue (lua_State *L, int funcindex, int n) { const char *name; TValue *val = NULL; /* to avoid warnings */ CClosure *owner = NULL; UpVal *uv = NULL; StkId fi; lua_lock(L); fi = index2addr(L, funcindex); api_checknelems(L, 1); name = aux_upvalue(fi, n, &val, &owner, &uv); if (name) { L->top--; setobj(L, val, L->top); if (owner) { luaC_barrier(L, owner, L->top); } else if (uv) { luaC_upvalbarrier(L, uv); } } lua_unlock(L); return name; } static UpVal **getupvalref (lua_State *L, int fidx, int n, LClosure **pf) { LClosure *f; StkId fi = index2addr(L, fidx); api_check(L, ttisLclosure(fi), "Lua function expected"); f = clLvalue(fi); api_check(L, (1 <= n && n <= f->p->sp->sizeupvalues), "invalid upvalue index"); if (pf) *pf = f; return &f->upvals[n - 1]; /* get its upvalue pointer */ } LUA_API void *lua_upvalueid (lua_State *L, int fidx, int n) { StkId fi = index2addr(L, fidx); switch (ttype(fi)) { case LUA_TLCL: { /* lua closure */ return *getupvalref(L, fidx, n, NULL); } case LUA_TCCL: { /* C closure */ CClosure *f = clCvalue(fi); api_check(L, 1 <= n && n <= f->nupvalues, "invalid upvalue index"); return &f->upvalue[n - 1]; } default: { api_check(L, 0, "closure expected"); return NULL; } } } LUA_API void lua_upvaluejoin (lua_State *L, int fidx1, int n1, int fidx2, int n2) { LClosure *f1; UpVal **up1 = getupvalref(L, fidx1, n1, &f1); UpVal **up2 = getupvalref(L, fidx2, n2, NULL); luaC_upvdeccount(L, *up1); *up1 = *up2; (*up1)->refcount++; if (upisopen(*up1)) (*up1)->u.open.touched = 1; luaC_upvalbarrier(L, *up1); }
suzuren/some-mmorpg
3rd/skynet/3rd/lua/lapi.c
C
mit
32,819
<!doctype html> <title>CodeMirror: Properties files mode</title> <meta charset="utf-8"/> <link rel=stylesheet href="../../doc/docs.css"> <link rel="stylesheet" href="../../lib/codemirror.css"> <script src="../../lib/codemirror.js"></script> <script src="properties.js"></script> <style>.CodeMirror {border-top: 1px solid #ddd; border-bottom: 1px solid #ddd;}</style> <div id=nav> <a href="http://codemirror.net"><img id=logo src="../../doc/logo.png"></a> <ul> <li><a href="../../index.html">Home</a> <li><a href="../../doc/manual.html">Manual</a> <li><a href="https://github.com/codemirror/codemirror">Code</a> </ul> <ul> <li><a href="../index.html">Language modes</a> <li><a class=active href="#">Properties files</a> </ul> </div> <article> <h2>Properties files mode</h2> <form><textarea id="code" name="code"> # This is a properties file a.key = A value another.key = http://example.com ! Exclamation mark as comment but.not=Within ! A value # indeed # Spaces at the beginning of a line spaces.before.key=value backslash=Used for multi\ line entries,\ that's convenient. # Unicode sequences unicode.key=This is \u0020 Unicode no.multiline=here # Colons colons : can be used too # Spaces spaces\ in\ keys=Not very common... </textarea></form> <script> var editor = CodeMirror.fromTextArea(document.getElementById("code"), {}); </script> <p><strong>MIME types defined:</strong> <code>text/x-properties</code>, <code>text/x-ini</code>.</p> </article>
forevernull/chromeSSE
src/core/lib/CodeMirror/mode/properties/index.html
HTML
mit
1,536
/* eslint-disable */ ;(function(root, factory) { if (typeof define === 'function' && define.amd) { // AMD define(['../core'], factory); } else if (typeof exports === 'object') { // Node.js module.exports = factory(require('../core')); } else { // Browser root.Blockly.Msg = factory(root.Blockly); } }(this, function(Blockly) { var Blockly = {};Blockly.Msg={};// This file was automatically generated. Do not modify. 'use strict'; Blockly.Msg["ADD_COMMENT"] = "ಟಿಪ್ಪಣಿ ಸೇರ್ಸಲೆ"; Blockly.Msg["CANNOT_DELETE_VARIABLE_PROCEDURE"] = "Can't delete the variable '%1' because it's part of the definition of the function '%2'"; // untranslated Blockly.Msg["CHANGE_VALUE_TITLE"] = "ಮೌಲ್ಯೊನು ಬದಲ್ ಮಲ್ಪು"; Blockly.Msg["CLEAN_UP"] = "ಬ್ಲಾಕ್‍ಲೆನ್ ಸ್ವೊಚ್ಚೊ ಮಲ್ಪುಲೆ"; Blockly.Msg["COLLAPSED_WARNINGS_WARNING"] = "Collapsed blocks contain warnings."; // untranslated Blockly.Msg["COLLAPSE_ALL"] = "ಮಾತಾ ತಡೆಕ್ಲೆನ ಮಾಹಿತಿನ್ ಎಲ್ಯ ಮಲ್ಪು"; Blockly.Msg["COLLAPSE_BLOCK"] = "ಎಲ್ಯೆ ಮಲ್ತ್‌ದ್ ತಡೆಲೆ"; Blockly.Msg["COLOUR_BLEND_COLOUR1"] = "ಬಣ್ಣೊ ೧(ಒಂಜಿ)"; Blockly.Msg["COLOUR_BLEND_COLOUR2"] = "ಬಣ್ಣೊ ೨(ರಡ್ಡ್)"; Blockly.Msg["COLOUR_BLEND_HELPURL"] = "https://meyerweb.com/eric/tools/color-blend/#:::rgbp"; // untranslated Blockly.Msg["COLOUR_BLEND_RATIO"] = "ಅನುಪಾತೊ"; Blockly.Msg["COLOUR_BLEND_TITLE"] = "ಬೆರಕ್ಕೆ ಮಲ್ಪು"; Blockly.Msg["COLOUR_BLEND_TOOLTIP"] = "ಕೊರಿನ ಅನುಪಾತೊಡು (0.0- 1.0) ರಡ್ಡ್ ಬಣ್ಣೊಲೆನ್ ಬೆರಕೆ ಮಲ್ಪುಂಡು."; Blockly.Msg["COLOUR_PICKER_HELPURL"] = "https://en.wikipedia.org/wiki/ಬಣ್ಣೊ"; Blockly.Msg["COLOUR_PICKER_TOOLTIP"] = "ಬಣ್ಣೊ ಪಟೊಡ್ದು ಒಂಜಿ ಬಣ್ಣೊನು ಆಯ್ಕೆ ಮಲ್ಪುಲೆ."; Blockly.Msg["COLOUR_RANDOM_HELPURL"] = "http://randomcolour.com"; // untranslated Blockly.Msg["COLOUR_RANDOM_TITLE"] = "ಒವ್ವೇ ಒಂಜಿ ಬಣ್ಣೊ"; Blockly.Msg["COLOUR_RANDOM_TOOLTIP"] = "ಒವ್ವಾಂಡಲ ಒಂಜಿ ಬಣ್ಣೊನು ಆಯ್ಕೆ ಮಲ್ಪುಲೆ"; Blockly.Msg["COLOUR_RGB_BLUE"] = "ನೀಲಿ"; Blockly.Msg["COLOUR_RGB_GREEN"] = "ಪಚ್ಚೆ"; Blockly.Msg["COLOUR_RGB_HELPURL"] = "https://www.december.com/html/spec/colorpercompact.html"; // untranslated Blockly.Msg["COLOUR_RGB_RED"] = "ಕೆಂಪು"; Blockly.Msg["COLOUR_RGB_TITLE"] = "ಬಣ್ಣೊದ"; Blockly.Msg["COLOUR_RGB_TOOLTIP"] = "ತೊಜಪಾಯಿನ ಪ್ರಮಾಣೊದ ಕೆಂಪು, ಪಚ್ಚೆ ಬೊಕ್ಕ ನೀಲಿ ಬಣ್ಣೊಡ್ದು ಒಂಜಿ ಬಣ್ಣೊನು ಉಂಡು ಮಲ್ಪುಲೆ. ಮಾತಾ ಮೌಲ್ಯೊಲು 0 ಬುಕ್ಕೊ 100 ತ ನಡುಟೆ ಇಪ್ಪೊಡು."; Blockly.Msg["CONTROLS_FLOW_STATEMENTS_HELPURL"] = "https://github.com/google/blockly/wiki/Loops#loop-termination-blocks"; // untranslated Blockly.Msg["CONTROLS_FLOW_STATEMENTS_OPERATOR_BREAK"] = "ಲೂಪ್ ಕಡಿಯುನಿ"; Blockly.Msg["CONTROLS_FLOW_STATEMENTS_OPERATOR_CONTINUE"] = "ಬೊಕ್ಕದ ಲೂಪ್ ಪುನರಾವರ್ತನೆದೊಟ್ಟುಗು ದುಂಬರಿಲೆ"; Blockly.Msg["CONTROLS_FLOW_STATEMENTS_TOOLTIP_BREAK"] = "ಇತ್ತಿನ ಲೂಪ್‍ಡ್ದ್ ಪದಿಯಿ ಬಲೆ"; Blockly.Msg["CONTROLS_FLOW_STATEMENTS_TOOLTIP_CONTINUE"] = "ಈ ಲೂಪುನು ಅರ್ದೊಡೆ ಬುಡುದ್ ಬೊಕ್ಕ ನನತ್ತ ಪುನರಾವರ್ತನೆಗ್ ದುಂಬರಿಲೆ"; Blockly.Msg["CONTROLS_FLOW_STATEMENTS_WARNING"] = "ಎಚ್ಚರೊ: ಈ ತಡೆನ್ ಕಾಲಿ ಒಂಜಿ ಲೂಪುದುಲಯಿ ಮಾತ್ರ ಗಳಸೊಲಿ."; Blockly.Msg["CONTROLS_FOREACH_HELPURL"] = "https://github.com/google/blockly/wiki/Loops#for-each"; // untranslated Blockly.Msg["CONTROLS_FOREACH_TITLE"] = "%2 ಪಟ್ಟಿಡ್ ಪ್ರತಿ ಒಂಜಿ ವಿಸಯ %1 ಗ್"; Blockly.Msg["CONTROLS_FOREACH_TOOLTIP"] = "ಒಂಜಿ ಪಟ್ಟಿಡ್ ಪ್ರತಿ ವಿಸಯೊಗು, '%1' ವ್ಯತ್ಯಾಯೊನು ವಿಸಯೊಗು ಜೋಡಾಲೆ, ಬೊಕ್ಕ ಕೆಲವು ಪಾತೆರೊಲೆನ್ ಮಲ್ಪುಲೆ."; Blockly.Msg["CONTROLS_FOR_HELPURL"] = "https://github.com/google/blockly/wiki/Loops#count-with"; // untranslated Blockly.Msg["CONTROLS_FOR_TITLE"] = "%2 ಡ್ದ್ %3 ಮುಟ %4 ಸರ್ತಿ %1 ದ ಒಟ್ಟುಗು ಗೆನ್ಪು"; Blockly.Msg["CONTROLS_FOR_TOOLTIP"] = "ನಿರ್ದಿಸ್ಟೊ ಮದ್ಯಂತರೊದ ಮೂಲಕೊ ದೆತೊಂದು '%1' ವ್ಯತ್ಯಯೊಡ್ ಸುರುತ್ತ ಅಂಕೆಡ್ದ್ ಕಡೆತ್ತ ಅಂಕೆ ಮುಟ್ಟದ ಮೌಲ್ಯೊನು ದೆತ್ತೊನಾವ್ ಬೊಕ್ಕ ನಿಗಂಟ್ ಮಲ್ತಿನ ತಡೆಕ್ಲೆನ್ ಮಲ್ಪು"; Blockly.Msg["CONTROLS_IF_ELSEIF_TOOLTIP"] = "'ಒಂಜಿ ವೇಲೆ' ತಡೆಕ್ಕ್ ಒಂಜಿ ಶರ್ತನ್ ಸೇರಾವ್"; Blockly.Msg["CONTROLS_IF_ELSE_TOOLTIP"] = "'ಒಂಜಿ ವೇಲೆ' ತಡೆಕ್ಕ್ ಒಂಜಿ ಕಡೆತ್ತ ಮಾತೆನ್ಲಾ-ಪತ್ತ್ (catch-all) ಶರ್ತನ್ ಸೇರಾವ್"; Blockly.Msg["CONTROLS_IF_HELPURL"] = "https://github.com/google/blockly/wiki/IfElse"; // untranslated Blockly.Msg["CONTROLS_IF_IF_TOOLTIP"] = "ಸೇರಾವ್, ದೆತ್ತ್‌ ಬುಡು, ಅತ್ತಂಡ ಈ 'ಒಂಜಿ ವೇಲೆ' ತಡೆನ್ ಕುಡ ಸಂರಚಣೆ ಮಲ್ಪೆರೆ ವಿಭಾಗೊಲೆನ್ ಕುಡ ಒತ್ತರೆ ಮಲ್ಪುಲೆ."; Blockly.Msg["CONTROLS_IF_MSG_ELSE"] = "ಅತ್ತಂಡ"; Blockly.Msg["CONTROLS_IF_MSG_ELSEIF"] = "ಅತ್ತಂಡ"; Blockly.Msg["CONTROLS_IF_MSG_IF"] = "ಒಂಜಿ ವೇಲೆ"; Blockly.Msg["CONTROLS_IF_TOOLTIP_1"] = "ಮೌಲ್ಯ ನಿಜ ಆದಿತ್ತ್ಂಡ ಕೆಲವು ಪಾತೆರೊಲೆನ್ ಮಲ್ಪು"; Blockly.Msg["CONTROLS_IF_TOOLTIP_2"] = "ಮೌಲ್ಯ ನಿಜವಾದಿತ್ತ್‌ಂಡ, ಪಾತೆರೊಲೆನ ಸುರುತ್ತ ತಡೆ ಮಲ್ಪು. ಇಜ್ಜಿಂಡ ಪಾತೆರೊಲೆನ ರಡ್ಡನೆ ತಡೆ ಮಲ್ಪು."; Blockly.Msg["CONTROLS_IF_TOOLTIP_3"] = "ಸುರುತ್ತ ಮೌಲ್ಯ ನಿಜವಾದಿತ್ತ್‌ಂಡ, ಪಾತೆರೊಲೆನ ಸುರುತ್ತ ತಡೆ ಮಲ್ಪು. ಇಜ್ಜಿಂಡ, ರಡ್ಡನೆ ಮೌಲ್ಯ ನಿಜವಾದಿತ್ತ್ಂಡ, ಪಾತೆರೊಲೆನ ರಡ್ಡನೆ ತಡೆ ಮಲ್ಪು."; Blockly.Msg["CONTROLS_IF_TOOLTIP_4"] = "ಸುರುತ್ತ ಮೌಲ್ಯೊ ನಿಜವಾದಿತ್ತ್‌ಂಡ, ಪಾತೆರೊಲೆನ ಸುರುತ್ತ ತಡೆ ಮಲ್ಪು. ಇಜ್ಜಿಂಡ, ರಡ್ಡನೆದ ಮೌಲ್ಯ ನಿಜವಾದಿತ್ತ್ಂಡ, ಪಾತೆರೊಲೆನ ರಡ್ಡನೆ ತಡೆ ಮಲ್ಪು. ಒಂಜೇಲೆ ಒವ್ವೇ ಮೌಲ್ಯ ನಿಜವಾದಿತ್ತಿಜಿಂಡ, ಪಾತೆರೊಲೆನ ಕಡೆತ್ತ ತಡೆ ಮಲ್ಪು."; Blockly.Msg["CONTROLS_REPEAT_HELPURL"] = "https://en.wikipedia.org/wiki/For_loop"; Blockly.Msg["CONTROLS_REPEAT_INPUT_DO"] = "ಮಲ್ಪುಲೆ"; Blockly.Msg["CONTROLS_REPEAT_TITLE"] = " %1 ಸರ್ತಿ ಕೂಡೊರ ಮಲ್ಪು"; Blockly.Msg["CONTROLS_REPEAT_TOOLTIP"] = "ಕೆಲವು ಪಾತೆರೊಲೆನ್ ಮಸ್ತ್ ಸರ್ತಿ ಮಲ್ಪು"; Blockly.Msg["CONTROLS_WHILEUNTIL_HELPURL"] = "https://github.com/google/blockly/wiki/Loops#repeat"; // untranslated Blockly.Msg["CONTROLS_WHILEUNTIL_OPERATOR_UNTIL"] = "ಉಂದು ನಿಜ ಆಪಿಲೆಕೊ ಕುಡೊರ ಮಲ್ಪು:"; Blockly.Msg["CONTROLS_WHILEUNTIL_OPERATOR_WHILE"] = "ಉಂದು ನಿಜ ಆಂಡ ಕುಡೊರ ಮಲ್ಪು:"; Blockly.Msg["CONTROLS_WHILEUNTIL_TOOLTIP_UNTIL"] = "ಮೌಲ್ಯ ತಪ್ಪು ಆದಿತ್ತ್ಂಡ ಕೆಲವು ಪಾತೆರೊಲೆನ್ ಮಲ್ಪು"; Blockly.Msg["CONTROLS_WHILEUNTIL_TOOLTIP_WHILE"] = "ಮೌಲ್ಯ ನಿಜ ಆದಿತ್ತ್ಂಡ ಕೆಲವು ಪಾತೆರೊಲೆನ್ ಮಲ್ಪು"; Blockly.Msg["DELETE_ALL_BLOCKS"] = "ಮಾತ %1 ಬ್ಲಾಕ್‍ಲೆನ್ ದೆತ್ತ್‌ದ್ ಬುಡೊಡೆ?"; Blockly.Msg["DELETE_BLOCK"] = "ಬ್ಲಾಕ್‍ನ್ ಮಾಜಾವು"; Blockly.Msg["DELETE_VARIABLE"] = "'%1' ವ್ಯತ್ಯಯೊನು ಮಾಜಾಲೆ"; Blockly.Msg["DELETE_VARIABLE_CONFIRMATION"] = "'%2' ವ್ಯತ್ಯಯೊದ %1 ಉಪಯೋಗೊಲೆನ್ ಮಾಜಾವೊಡೆ?"; Blockly.Msg["DELETE_X_BLOCKS"] = "%1 ಬ್ಲಾಕ್‍ಲೆನ್ ಮಾಜಾವು"; Blockly.Msg["DIALOG_CANCEL"] = "ಉಂತಾಲೆ"; Blockly.Msg["DIALOG_OK"] = "ಅವು"; Blockly.Msg["DISABLE_BLOCK"] = "ಬ್ಲಾಕ್‍ನ್ ದೆತ್ತ್‌ಪಾಡ್"; Blockly.Msg["DUPLICATE_BLOCK"] = "ನಕಲ್"; Blockly.Msg["DUPLICATE_COMMENT"] = "Duplicate Comment"; // untranslated Blockly.Msg["ENABLE_BLOCK"] = "ತಡೆನ್ ಸಕ್ರಿಯೊ ಮಲ್ಪು"; Blockly.Msg["EXPAND_ALL"] = "ಮಾತಾ ತಡೆಕ್ಲೆನ ಮಾಹಿತಿನ್ ಪರಡಾವು"; Blockly.Msg["EXPAND_BLOCK"] = "ಬ್ಲಾಕ್‍ದ ಮಾಹಿತಿನ್ ಪರಡಾವು"; Blockly.Msg["EXTERNAL_INPUTS"] = "ಪಿದಯಿದ ಪರಿಪು"; Blockly.Msg["HELP"] = "ಸಹಾಯೊ"; Blockly.Msg["INLINE_INPUTS"] = "ಉಳಸಾಲ್‍ದ ಉಳಪರಿಪು"; Blockly.Msg["LISTS_CREATE_EMPTY_HELPURL"] = "https://github.com/google/blockly/wiki/Lists#create-empty-list"; // untranslated Blockly.Msg["LISTS_CREATE_EMPTY_TITLE"] = "ಕಾಲಿ ಪಟ್ಟಿನ್ ಉಂಡುಮಲ್ಪುಲೆ"; Blockly.Msg["LISTS_CREATE_EMPTY_TOOLTIP"] = "ಒಂಜಿ ಪಟ್ಟಿ, ೦ ಉದ್ದೊದ, ಒವ್ವೇ ಮಾಹಿತಿ ದಾಂತಿನ ದಾಖಲೆ ಪಿರಕೊರು."; Blockly.Msg["LISTS_CREATE_WITH_CONTAINER_TITLE_ADD"] = "ಪಟ್ಟಿ"; Blockly.Msg["LISTS_CREATE_WITH_CONTAINER_TOOLTIP"] = "ಈ ಪಟ್ಟಿ ತಡೆನ್ ಕುಡ ಸಂರಚನೆ ಮಲ್ಪೆರೆ ಸೇರಾಲೆ, ದೆತ್ತ್ ಬುಡುಲೆ, ಅತ್ತಂಡ ವಿಬಾಗೊಲೆನ್ ಕುಡ ಒತ್ತರೆ ಮಲ್ಪುಲೆ."; Blockly.Msg["LISTS_CREATE_WITH_HELPURL"] = "https://github.com/google/blockly/wiki/Lists#create-list-with"; // untranslated Blockly.Msg["LISTS_CREATE_WITH_INPUT_WITH"] = "ಒಟ್ಟುಗು ಪಟ್ಟಿನ್ ಉಂಡುಮಲ್ಪುಲೆ"; Blockly.Msg["LISTS_CREATE_WITH_ITEM_TOOLTIP"] = "ಪಟ್ಟಿಗ್ ಒಂಜಿ ವಿಸಯೊನು ಸೇರಾಲೆ."; Blockly.Msg["LISTS_CREATE_WITH_TOOLTIP"] = "ಏತೇ ವಿಸಯೊಲುಪ್ಪುನ ಒಂಜಿ ಪಟ್ಟಿನ್ ಉಂಡುಮಲ್ಪುಲೆ"; Blockly.Msg["LISTS_GET_INDEX_FIRST"] = "ಸುರುತ"; Blockly.Msg["LISTS_GET_INDEX_FROM_END"] = "ಅಕೇರಿಡ್ದ್ #"; Blockly.Msg["LISTS_GET_INDEX_FROM_START"] = "#"; // untranslated Blockly.Msg["LISTS_GET_INDEX_GET"] = "ದೆತೊನು"; Blockly.Msg["LISTS_GET_INDEX_GET_REMOVE"] = "ದೆತ್ತೊನು ಬೊಕ್ಕ ದೆತ್ತ್ ಬುಡು"; Blockly.Msg["LISTS_GET_INDEX_LAST"] = "ಕಡೆತ"; Blockly.Msg["LISTS_GET_INDEX_RANDOM"] = "ಒವ್ವಾಂಡಲ"; Blockly.Msg["LISTS_GET_INDEX_REMOVE"] = "ದೆಪ್ಪುಲೆ"; Blockly.Msg["LISTS_GET_INDEX_TAIL"] = ""; // untranslated Blockly.Msg["LISTS_GET_INDEX_TOOLTIP_GET_FIRST"] = "ಒಂಜಿ ಪಟ್ಟಿಡ್ ಸುರುತ್ತ ವಿಸಯೊನು ಪಿರಕೊರ್ಪುಂಡು."; Blockly.Msg["LISTS_GET_INDEX_TOOLTIP_GET_FROM"] = "ಒಂಜಿ ಪಟ್ಟಿಡ್ ನಿರ್ದಿಷ್ಟ ಸ್ಥಿತಿಡ್ ವಿಸಯೊನು ಪಿರಕೊರ್ಪುಂಡು."; Blockly.Msg["LISTS_GET_INDEX_TOOLTIP_GET_LAST"] = "ಒಂಜಿ ಪಟ್ಟಿಡ್ ಅಕೇರಿದ ವಿಸಯೊನು ಪಿರಕೊರ್ಪುಂಡು."; Blockly.Msg["LISTS_GET_INDEX_TOOLTIP_GET_RANDOM"] = "ಒಂಜಿ ಪಟ್ಟಿಡ್ ಒವ್ವಾಂಡಲ ಒಂಜಿ ವಿಸಯೊನು ಪಿರಕೊರ್ಪುಂಡು."; Blockly.Msg["LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_FIRST"] = "ಒಂಜಿ ಪಟ್ಟಿಡ್ ಸುರುತ್ತ ವಿಸಯೊನು ಪಿರಕೊರ್ಪುಂಡು ಬೊಕ್ಕ ದೆತ್ತ್ ಬುಡ್ಪುಂಡು."; Blockly.Msg["LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_FROM"] = "ಒಂಜಿ ಪಟ್ಟಿಡ್ ನಿರ್ದಿಷ್ಟ ಸ್ಥಿತಿಡ್ ವಿಸಯೊನು ಪಿರಕೊರ್ಪುಂಡು ಬೊಕ್ಕ ದೆತ್ತ್ ಬುಡ್ಪುಂಡು."; Blockly.Msg["LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_LAST"] = "ಒಂಜಿ ಪಟ್ಟಿಡ್ ಅಕೇರಿದ ವಿಸಯೊನು ಪಿರಕೊರ್ಪುಂಡು ಬೊಕ್ಕ ದೆತ್ತ್ ಬುಡ್ಪುಂಡು."; Blockly.Msg["LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_RANDOM"] = "ಒಂಜಿ ಪಟ್ಟಿಡ್ ಒವ್ವಾಂಡಲ ಒಂಜಿ ವಿಸಯೊನು ಪಿರಕೊರ್ಪುಂಡು ಬೊಕ್ಕ ದೆತ್ತ್ ಬುಡ್ಪುಂಡು."; Blockly.Msg["LISTS_GET_INDEX_TOOLTIP_REMOVE_FIRST"] = "ಒಂಜಿ ಪಟ್ಟಿಡ್ ಸುರುತ್ತ ವಿಸಯೊನು ದೆತ್ತ್ ಬುಡ್ಪುಂಡು."; Blockly.Msg["LISTS_GET_INDEX_TOOLTIP_REMOVE_FROM"] = "ಒಂಜಿ ಪಟ್ಟಿಡ್ ನಿರ್ದಿಷ್ಟ ಸ್ಥಿತಿಡ್ ವಿಸಯೊನು ದೆತ್ತ್ ಬುಡ್ಪುಂಡು."; Blockly.Msg["LISTS_GET_INDEX_TOOLTIP_REMOVE_LAST"] = "ಒಂಜಿ ಪಟ್ಟಿಡ್ ಅಕೇರಿದ ವಿಸಯೊನು ದೆತ್ತ್ ಬುಡ್ಪುಂಡು."; Blockly.Msg["LISTS_GET_INDEX_TOOLTIP_REMOVE_RANDOM"] = "ಒಂಜಿ ಪಟ್ಟಿಡ್ ಒವ್ವಾಂಡಲ ಒಂಜಿ ವಿಸಯೊನು ದೆತ್ತ್ ಬುಡ್ಪುಂಡು."; Blockly.Msg["LISTS_GET_SUBLIST_END_FROM_END"] = "ಅಕೇರಿಡ್ದ್ # ಗ್"; Blockly.Msg["LISTS_GET_SUBLIST_END_FROM_START"] = "# ಗ್"; Blockly.Msg["LISTS_GET_SUBLIST_END_LAST"] = "ಅಕೇರಿಗ್"; Blockly.Msg["LISTS_GET_SUBLIST_HELPURL"] = "https://github.com/google/blockly/wiki/Lists#getting-a-sublist"; // untranslated Blockly.Msg["LISTS_GET_SUBLIST_START_FIRST"] = "ಸುರುಡ್ದು ಉಪ-ಪಟ್ಟಿನ್ ದೆತ್ತೊನು"; Blockly.Msg["LISTS_GET_SUBLIST_START_FROM_END"] = "ಅಕೇರಿಡ್ದ್ # ಡ್ದ್ ಉಪ-ಪಟ್ಟಿನ್ ದೆತ್ತೊನು"; Blockly.Msg["LISTS_GET_SUBLIST_START_FROM_START"] = "# ಡ್ದ್ ಉಪ-ಪಟ್ಟಿನ್ ದೆತ್ತೊನು"; Blockly.Msg["LISTS_GET_SUBLIST_TAIL"] = ""; // untranslated Blockly.Msg["LISTS_GET_SUBLIST_TOOLTIP"] = "ಪಟ್ಯೊದ ನಿರ್ದಿಷ್ಟ ಬಾಗೊದ ಪ್ರತಿನ್ ಉಂಡುಮಲ್ಪುಂಡು."; Blockly.Msg["LISTS_INDEX_FROM_END_TOOLTIP"] = "%1 ಅಕೇರಿತ ವಿಸಯೊ"; Blockly.Msg["LISTS_INDEX_FROM_START_TOOLTIP"] = "%1 ಸುರುತ ವಿಸಯೊ"; Blockly.Msg["LISTS_INDEX_OF_FIRST"] = "ವಿಸಯೊ ಸುರುಕ್ಕು ಬತ್ತಿನೇನ್ ನಾಡ್"; Blockly.Msg["LISTS_INDEX_OF_HELPURL"] = "https://github.com/google/blockly/wiki/Lists#getting-items-from-a-list"; // untranslated Blockly.Msg["LISTS_INDEX_OF_LAST"] = "ವಿಸಯೊ ಅಕೇರಿಗ್ ಬತ್ತಿನೇನ್ ನಾಡ್"; Blockly.Msg["LISTS_INDEX_OF_TOOLTIP"] = "ಪಟ್ಟಿಡುಪ್ಪುನ ವಿಸಯೊ ಸುರುಕ್ಕು/ಅಕೇರಿಗ್ ಬತ್ತಿನೆತ್ತ ಸೂಚಿನ್ ಪಿರಕೊರ್ಪುಂಡು. ವಿಸಯೊ ತಿಕ್ಕಿಜ್ಜಾಂಡ %1 ನ್ ಪಿರಕೊರ್ಪುಂಡು."; Blockly.Msg["LISTS_INLIST"] = "ಪಟ್ಟಿಡ್"; Blockly.Msg["LISTS_ISEMPTY_HELPURL"] = "https://github.com/google/blockly/wiki/Lists#is-empty"; // untranslated Blockly.Msg["LISTS_ISEMPTY_TITLE"] = "%1 ಕಾಲಿ"; Blockly.Msg["LISTS_ISEMPTY_TOOLTIP"] = "ಪಟ್ಯೊ ಖಾಲಿ ಇತ್ತ್ಂಡ 'ನಿಜ'ನ್ ಪಿರಕೊರು."; Blockly.Msg["LISTS_LENGTH_HELPURL"] = "https://github.com/google/blockly/wiki/Lists#length-of"; // untranslated Blockly.Msg["LISTS_LENGTH_TITLE"] = "%1 ಉದ್ದೊ"; Blockly.Msg["LISTS_LENGTH_TOOLTIP"] = "ಪಟ್ಟಿದ ಉದ್ದೊನು ಪಿರಕೊರು."; Blockly.Msg["LISTS_REPEAT_HELPURL"] = "https://github.com/google/blockly/wiki/Lists#create-list-with"; // untranslated Blockly.Msg["LISTS_REPEAT_TITLE"] = "%1 ವಿಸಯೊ %2 ಸರ್ತಿ ಪುನರಾವರ್ತನೆ ಆದುಪ್ಪುನ ಪಟ್ಟಿನ್ ಉಂಡುಮಲ್ಪುಲೆ."; Blockly.Msg["LISTS_REPEAT_TOOLTIP"] = "ಕೊರಿನ ಮೌಲ್ಯೊ ಒಂಜಿ ನಿರ್ದಿಷ್ಟ ಸಂಕ್ಯೆದಾತ್ ಸರ್ತಿ ಪುನರಾವರ್ತನೆ ಆದುಪ್ಪುನ ಒಂಜಿ ಪಟ್ಟಿನ್ ಉಂಡುಮಲ್ಪುಲೆ."; Blockly.Msg["LISTS_REVERSE_HELPURL"] = "https://github.com/google/blockly/wiki/Lists#reversing-a-list"; // untranslated Blockly.Msg["LISTS_REVERSE_MESSAGE0"] = "reverse %1"; // untranslated Blockly.Msg["LISTS_REVERSE_TOOLTIP"] = "Reverse a copy of a list."; // untranslated Blockly.Msg["LISTS_SET_INDEX_HELPURL"] = "https://github.com/google/blockly/wiki/Lists#in-list--set"; // untranslated Blockly.Msg["LISTS_SET_INDEX_INPUT_TO"] = "ಲೆಕ"; Blockly.Msg["LISTS_SET_INDEX_INSERT"] = "ಸೇರಾವ್"; Blockly.Msg["LISTS_SET_INDEX_SET"] = "ಸೆಟ್ ಮಲ್ಪು"; Blockly.Msg["LISTS_SET_INDEX_TOOLTIP_INSERT_FIRST"] = "ಒಂಜಿ ಪಟ್ಟಿದ ಸುರುಕ್ಕು ವಿಸಯೊನು ಸೇರಾವುಂಡು."; Blockly.Msg["LISTS_SET_INDEX_TOOLTIP_INSERT_FROM"] = "ಒಂಜಿ ಪಟ್ಟಿಡ್ ನಿರ್ದಿಷ್ಟ ಸ್ಥಿತಿಡ್ ವಿಸಯೊನು ಸೇರಾವುಂಡು."; Blockly.Msg["LISTS_SET_INDEX_TOOLTIP_INSERT_LAST"] = "ಒಂಜಿ ಪಟ್ಟಿದ ಅಕೇರಿಗ್ ವಿಸಯೊನು ಸೇರಾವುಂಡು."; Blockly.Msg["LISTS_SET_INDEX_TOOLTIP_INSERT_RANDOM"] = "ಒಂಜಿ ಪಟ್ಟಿಡ್ ಓಲಾಂಡಲ ವಿಸಯೊನು ಸೇರಾವುಂಡು."; Blockly.Msg["LISTS_SET_INDEX_TOOLTIP_SET_FIRST"] = "ಒಂಜಿ ಪಟ್ಟಿಡ್ ಸುರುತ್ತ ವಿಸಯೊನು ಸೆಟ್ ಮಲ್ಪುಂಡು."; Blockly.Msg["LISTS_SET_INDEX_TOOLTIP_SET_FROM"] = "ಒಂಜಿ ಪಟ್ಟಿಡ್ ನಿರ್ದಿಷ್ಟ ಸ್ಥಿತಿಡ್ ವಿಸಯೊನು ಸೆಟ್ ಮಲ್ಪುಂಡು."; Blockly.Msg["LISTS_SET_INDEX_TOOLTIP_SET_LAST"] = "ಒಂಜಿ ಪಟ್ಟಿಡ್ ಅಕೇರಿದ ವಿಸಯೊನು ಸೆಟ್ ಮಲ್ಪುಂಡು."; Blockly.Msg["LISTS_SET_INDEX_TOOLTIP_SET_RANDOM"] = "ಒಂಜಿ ಪಟ್ಟಿಡ್ ಒವ್ವಾಂಡಲ ಒಂಜಿ ವಿಸಯೊನು ಸೆಟ್ ಮಲ್ಪುಂಡು."; Blockly.Msg["LISTS_SORT_HELPURL"] = "https://github.com/google/blockly/wiki/Lists#sorting-a-list"; Blockly.Msg["LISTS_SORT_ORDER_ASCENDING"] = "ಏರುನು"; Blockly.Msg["LISTS_SORT_ORDER_DESCENDING"] = "ಜಪ್ಪುನು"; Blockly.Msg["LISTS_SORT_TITLE"] = "%1 %2 %3 ಇಂಗಡಿಪು"; Blockly.Msg["LISTS_SORT_TOOLTIP"] = "ಒಂಜಿ ಪಟ್ಟಿದ ಒಂಜಿ ಪ್ರತಿನ್ ಇಂಗಡಿಪು"; Blockly.Msg["LISTS_SORT_TYPE_IGNORECASE"] = "ಅಕ್ಷರೊ, ನಮೂನೆ (case) ಅಲಕ್ಷ್ಯೊ ಮಲ್ಪುಲೆ"; Blockly.Msg["LISTS_SORT_TYPE_NUMERIC"] = "ಸಂಖ್ಯೆ"; Blockly.Msg["LISTS_SORT_TYPE_TEXT"] = "ಅಕ್ಷರೊ"; Blockly.Msg["LISTS_SPLIT_HELPURL"] = "https://github.com/google/blockly/wiki/Lists#splitting-strings-and-joining-lists"; // untranslated Blockly.Msg["LISTS_SPLIT_LIST_FROM_TEXT"] = "ಪಟ್ಯೊಲೆ ಪಟ್ಟಿನ್ ತಯಾರ್ ಮಲ್ಪುಲೆ"; Blockly.Msg["LISTS_SPLIT_TEXT_FROM_LIST"] = "ಪಟ್ಟಿದ ಪಟ್ಯೊನು ತಯಾರ್ ಮಲ್ಪುಲೆ"; Blockly.Msg["LISTS_SPLIT_TOOLTIP_JOIN"] = "ಪಟ್ಯೊಲೆನ ಒಂಜಿ ಪಟ್ಟಿನ್ ಮಿತಿಸೂಚಕೊದ ಮೂಲಕೊ ಬೇತೆ ಮಲ್ತ್‌ದ್ ಒಂಜಿ ಪಟ್ಯೊಗು ಸೇರಾಲೆ."; Blockly.Msg["LISTS_SPLIT_TOOLTIP_SPLIT"] = "ಪಟ್ಯೊಲೆನ್ ಪ್ರತಿ ಮಿತಿಸೂಚಕೊಡು ತುಂಡು ಮಲ್ತ್‌ದ್ ಪಟ್ಯೊಲೆನ ಒಂಜಿ ಪಟ್ಟಿಗ್ ಬಾಗೊ ಮಲ್ಪುಲೆ."; Blockly.Msg["LISTS_SPLIT_WITH_DELIMITER"] = "ಮಿತಿಸೂಚಕೊದ ಒಟ್ಟುಗು"; Blockly.Msg["LOGIC_BOOLEAN_FALSE"] = "ಸುಲ್ಲು"; Blockly.Msg["LOGIC_BOOLEAN_HELPURL"] = "https://github.com/google/blockly/wiki/Logic#values"; // untranslated Blockly.Msg["LOGIC_BOOLEAN_TOOLTIP"] = "ಒಂಜೆ ನಿಜ ಅತ್ತಂಡ ಸುಲ್ಲುನ್ ಪಿರಕೊರು"; Blockly.Msg["LOGIC_BOOLEAN_TRUE"] = "ಸತ್ಯೊ"; Blockly.Msg["LOGIC_COMPARE_HELPURL"] = "https://en.wikipedia.org/wiki/Inequality_(mathematics)"; Blockly.Msg["LOGIC_COMPARE_TOOLTIP_EQ"] = "ರಡ್ದ್ ಇನ್‌ಪುಟ್‌ಲಾ ಸಮ ಇತ್ತ್ಂಡ 'ನಿಜ'ನ್ ಪಿರಕೊರು"; Blockly.Msg["LOGIC_COMPARE_TOOLTIP_GT"] = "ಸುರುತ್ತ ಇನ್‌ಪುಟ್ ರಡ್ಡನೆ ಇನ್‌ಪುಟ್‌ಡ್ದ್ ಮಲ್ಲ ಆದಿತ್ತ್ಂಡ, 'ನಿಜ'ನ್ ಪಿರಕೊರು"; Blockly.Msg["LOGIC_COMPARE_TOOLTIP_GTE"] = "ಸುರುತ್ತ ಇನ್‌ಪುಟ್ ರಡ್ಡನೆ ಇನ್‌ಪುಟ್‌ಡ್ದ್ ಮಲ್ಲ ಅತ್ತಂಡ ಅಯಿಕ್ಕ್ ಸಮ ಆದಿತ್ತ್ಂಡ, 'ನಿಜ'ನ್ ಪಿರಕೊರು"; Blockly.Msg["LOGIC_COMPARE_TOOLTIP_LT"] = "ಸುರುತ್ತ ಇನ್‌ಪುಟ್ ರಡ್ಡನೆ ಇನ್‌ಪುಟ್‌ಡ್ದ್ ಎಲ್ಯ ಆದಿತ್ತ್ಂಡ, 'ನಿಜ'ನ್ ಪಿರಕೊರು"; Blockly.Msg["LOGIC_COMPARE_TOOLTIP_LTE"] = "ಸುರುತ್ತ ಇನ್‌ಪುಟ್ ರಡ್ಡನೆ ಇನ್‌ಪುಟ್‌ಡ್ದ್ ಎಲ್ಯ ಅತ್ತಂಡ ಅಯಿಕ್ಕ್ ಸಮ ಆದಿತ್ತ್ಂಡ, 'ನಿಜ'ನ್ ಪಿರಕೊರು"; Blockly.Msg["LOGIC_COMPARE_TOOLTIP_NEQ"] = "ರಡ್ದ್ ಇನ್‌ಪುಟ್‌ಲಾ ಸಮ ಅತ್ತಾಂಡ 'ನಿಜ'ನ್ ಪಿರಕೊರು"; Blockly.Msg["LOGIC_NEGATE_HELPURL"] = "https://github.com/google/blockly/wiki/Logic#not"; // untranslated Blockly.Msg["LOGIC_NEGATE_TITLE"] = "%1 ಅತ್ತ್"; Blockly.Msg["LOGIC_NEGATE_TOOLTIP"] = "ಇನ್‌ಪುಟ್ ಸುಲ್ಲಾದಿತ್ತ್ಂಡ, 'ನಿಜ'ನ್ ಪಿರಕೊರು. ಇನ್‌ಪುಟ್ ನಿಜ ಆದಿತ್ತ್ಂಡ, 'ಸುಲ್ಲು'ನ್ ಪಿರಕೊರು."; Blockly.Msg["LOGIC_NULL"] = "ಸೊನ್ನೆ"; Blockly.Msg["LOGIC_NULL_HELPURL"] = "https://en.wikipedia.org/wiki/Nullable_type"; // untranslated Blockly.Msg["LOGIC_NULL_TOOLTIP"] = "ಸೊನ್ನೆನ್ ಪಿರಕೊರ್ಪುಂಡು"; Blockly.Msg["LOGIC_OPERATION_AND"] = "ಬುಕ್ಕೊ"; Blockly.Msg["LOGIC_OPERATION_HELPURL"] = "https://github.com/google/blockly/wiki/Logic#logical-operations"; // untranslated Blockly.Msg["LOGIC_OPERATION_OR"] = "ಅತ್ತಂಡ"; Blockly.Msg["LOGIC_OPERATION_TOOLTIP_AND"] = "ರಡ್ಡ್‌ಲಾ ಇನ್‌ಪುಟ್ ನಿಜ ಆದಿತ್ತ್ಂಡ, 'ನಿಜ'ನ್ ಪಿರಕೊರು"; Blockly.Msg["LOGIC_OPERATION_TOOLTIP_OR"] = "ಒವ್ವಾಂಡಲ ಒಂಜಿ ಇನ್‌ಪುಟ್ ನಿಜ ಆಂಡಲಾ, 'ನಿಜ'ನ್ ಪಿರಕೊರು."; Blockly.Msg["LOGIC_TERNARY_CONDITION"] = "ಪರೀಕ್ಷೆ"; Blockly.Msg["LOGIC_TERNARY_HELPURL"] = "https://en.wikipedia.org/wiki/%3F:"; // untranslated Blockly.Msg["LOGIC_TERNARY_IF_FALSE"] = "ಒಂಜಿ ವೇಲೆ ಸುಲ್ಲಾಂಡ"; Blockly.Msg["LOGIC_TERNARY_IF_TRUE"] = "ಒಂಜಿ ವೇಲೆ ನಿಜ ಆಂಡ"; Blockly.Msg["LOGIC_TERNARY_TOOLTIP"] = "'ಪರೀಕ್ಷೆ'ಡ್ ಶರ್ತನ್ ಸರಿತೂಲೆ. ಶರ್ತ ನಿಜವಾದಿತ್ತ್ಂಡ, 'ಒಂಜಿ ವೇಲೆ ನಿಜ ಆಂಡ' ಮೌಲ್ಯೊನು ಪಿರಕೊರ್ಪುಂಡು; ಇಜ್ಜಿಂಡ 'ಒಂಜಿ ವೇಲೆ ಸುಲ್ಲಾಂಡ' ಮೌಲ್ಯೊನು ಪಿರಕೊರ್ಪುಂಡು."; Blockly.Msg["MATH_ADDITION_SYMBOL"] = "+"; // untranslated Blockly.Msg["MATH_ARITHMETIC_HELPURL"] = "https://en.wikipedia.org/wiki/ಅಂಕಗಣಿತ"; Blockly.Msg["MATH_ARITHMETIC_TOOLTIP_ADD"] = "ರಡ್ಡ್ ಸಂಖ್ಯೆದ ಮೊತ್ತನ್ ಪಿರಕೊರು."; Blockly.Msg["MATH_ARITHMETIC_TOOLTIP_DIVIDE"] = "ಸಂಖ್ಯೆದ ಭಾಗಲಬ್ದೊನು ಪಿರಕೊರು."; Blockly.Msg["MATH_ARITHMETIC_TOOLTIP_MINUS"] = "ರಡ್ಡ ಸ್ಂಖ್ಯೆದ ವ್ಯತ್ಯಾಸೊನು ಪಿರಕೊರು."; Blockly.Msg["MATH_ARITHMETIC_TOOLTIP_MULTIPLY"] = "ಸಂಖ್ಯೆದ ಗುಣಲಬ್ಧೊನು ಪಿರಕೊರು."; Blockly.Msg["MATH_ARITHMETIC_TOOLTIP_POWER"] = "ಸುರುತ್ತ ಸಂಖ್ಯೆದ ಘಾತೊನು ರಡ್ಡನೆ ಸಂಖ್ಯೆಗ್ ಏರ್ಪಾದ್ ಪಿರಕೊರು."; Blockly.Msg["MATH_ATAN2_HELPURL"] = "https://en.wikipedia.org/wiki/Atan2"; Blockly.Msg["MATH_ATAN2_TITLE"] = "atan2 of X:%1 Y:%2"; // untranslated Blockly.Msg["MATH_ATAN2_TOOLTIP"] = "Return the arctangent of point (X, Y) in degrees from -180 to 180."; // untranslated Blockly.Msg["MATH_CHANGE_HELPURL"] = "https://en.wikipedia.org/wiki/Programming_idiom#Incrementing_a_counter"; Blockly.Msg["MATH_CHANGE_TITLE"] = "%1 ನ್ %2 ಟ್ ಬದಲ್ ಮಲ್ಪು"; Blockly.Msg["MATH_CHANGE_TOOLTIP"] = "'%1' ವ್ಯತ್ಯಯೊಗು ಒಂಜಿ ಸಂಖ್ಯೆನ್ ಸೇರಾವ್"; Blockly.Msg["MATH_CONSTANT_HELPURL"] = "https://en.wikipedia.org/wiki/ಗಣಿತ_ನಿರಂತರ"; Blockly.Msg["MATH_CONSTANT_TOOLTIP"] = "ಒಂಜಿ ಸಾಮಾನ್ಯ ಸ್ಥಿರಾಂಕೊನು ಪಿರಕೊರು: π (3.141…), e (2.718…), φ (1.618…), sqrt(2) (1.414…), sqrt(½) (0.707…), or ∞ (infinity)."; Blockly.Msg["MATH_CONSTRAIN_HELPURL"] = "https://en.wikipedia.org/wiki/Clamping_(graphics)"; // untranslated Blockly.Msg["MATH_CONSTRAIN_TITLE"] = "%2 ಕಮ್ಮಿ %3 ಜಾಸ್ತಿ %1 ನಿರ್ಬಂಧ ಮಲ್ಪು"; Blockly.Msg["MATH_CONSTRAIN_TOOLTIP"] = "ನಿಗದಿತ ಮಿತಿತ ನಡುಟು ಒಂಜಿ ಸಂಖ್ಯೆನ್ ನಿರ್ಬಂಧ ಮಲ್ಪು"; Blockly.Msg["MATH_DIVISION_SYMBOL"] = "÷"; // untranslated Blockly.Msg["MATH_IS_DIVISIBLE_BY"] = "ಭಾಗಿಪೊಲಿ"; Blockly.Msg["MATH_IS_EVEN"] = "ಸಮ ಸಂಖ್ಯೆ"; Blockly.Msg["MATH_IS_NEGATIVE"] = "ಋಣ ಸಂಖ್ಯೆ"; Blockly.Msg["MATH_IS_ODD"] = "ಬೆಸ ಸಂಖ್ಯೆ"; Blockly.Msg["MATH_IS_POSITIVE"] = "ಧನ ಸಂಖ್ಯೆ"; Blockly.Msg["MATH_IS_PRIME"] = "ಅವಿಭಾಜ್ಯ ಸಂಖ್ಯೆ"; Blockly.Msg["MATH_IS_TOOLTIP"] = "ಒಂಜಿ ಸಂಖ್ಯೆ ಸಮನಾ, ಬೆಸನಾ, ಅವಿಭಾಜ್ಯನಾ, ಪೂರ್ಣನಾ, ಧನನಾ, ಋಣನಾ, ಅತ್ತಂಡ ಅವೆನ್ ಬೇತೆ ಒಂಜಿ ನಿರ್ದಿಷ್ಟ ಸಂಖ್ಯೆಡ್ದ್ ಭಾಗಿಪೊಲಿಯಾ ಪಂದ್ ಪರೀಕ್ಷೆ ಮಲ್ಪು. ನಿಜ ಅತ್ತಂಡ ಸುಲ್ಲುನು ಪಿರಕೊರ್ಪುಂಡು."; Blockly.Msg["MATH_IS_WHOLE"] = "ಪೂರ್ಣ ಸಂಖ್ಯೆ"; Blockly.Msg["MATH_MODULO_HELPURL"] = "https://en.wikipedia.org/wiki/ಮೋಡ್ಯುಲೊ_ಒಪರೇಶನ್"; Blockly.Msg["MATH_MODULO_TITLE"] = " %1 ÷ %2 ತ ಶೇಷ"; Blockly.Msg["MATH_MODULO_TOOLTIP"] = "ರಡ್ಡ್ ಸಂಖ್ಯೆಲೆನ್ ಭಾಗ ಮಲ್ತ್‌ದ್ ಶೇಷೊನು ಪಿರಕೊರು."; Blockly.Msg["MATH_MULTIPLICATION_SYMBOL"] = "×"; // untranslated Blockly.Msg["MATH_NUMBER_HELPURL"] = "https://en.wikipedia.org/wiki/ಸಂಖ್ಯೆ"; Blockly.Msg["MATH_NUMBER_TOOLTIP"] = "ಅ ನಂಬ್ರೊ."; Blockly.Msg["MATH_ONLIST_HELPURL"] = ""; // untranslated Blockly.Msg["MATH_ONLIST_OPERATOR_AVERAGE"] = "ಪಟ್ಟಿದ ಸರಾಸರಿ"; Blockly.Msg["MATH_ONLIST_OPERATOR_MAX"] = "ಪಟ್ಟಿಡ್ ಮಲ್ಲವ್"; Blockly.Msg["MATH_ONLIST_OPERATOR_MEDIAN"] = "ಪಟ್ಟಿದ ನಡುತ್ತವ್"; Blockly.Msg["MATH_ONLIST_OPERATOR_MIN"] = "ಪಟ್ಟಿಡ್ ಕಿಞ್ಞವ್"; Blockly.Msg["MATH_ONLIST_OPERATOR_MODE"] = "ಪಟ್ಟಿದ ಮಸ್ತ್ ಸಾಮಾನ್ಯ ಮೌಲ್ಯ"; Blockly.Msg["MATH_ONLIST_OPERATOR_RANDOM"] = "ಪಟ್ಟಿದ ಒವ್ವಾಂಡಲ ಒಂಜಿ ವಿಷಯ"; Blockly.Msg["MATH_ONLIST_OPERATOR_STD_DEV"] = "ಪಟ್ಟಿದ ಪ್ರಮಾಣಿತ ವಿಚಲನ"; Blockly.Msg["MATH_ONLIST_OPERATOR_SUM"] = "ಪಟ್ಟಿದ ಮೊತ್ತ"; Blockly.Msg["MATH_ONLIST_TOOLTIP_AVERAGE"] = "ಪಟ್ಟಿಡುಪ್ಪುನ ಮಾತಾ ಸಂಖ್ಯೆಲೆನ ಸರಾಸರಿನ್ ಪಿರಕೊರು"; Blockly.Msg["MATH_ONLIST_TOOLTIP_MAX"] = "ಪಟ್ಟಿಡುಪ್ಪುನ ಮಲ್ಲ ಸಂಖ್ಯೆನ್ ಪಿರಕೊರು"; Blockly.Msg["MATH_ONLIST_TOOLTIP_MEDIAN"] = "ಪಟ್ಟಿಡುಪ್ಪುನ ನಡುತ್ತ ಸಂಖ್ಯೆನ್ ಪಿರಕೊರು"; Blockly.Msg["MATH_ONLIST_TOOLTIP_MIN"] = "ಪಟ್ಟಿಡುಪ್ಪುನ ಕಿಞ್ಞ ಸಂಕ್ಯೆನ್ ಪಿರಕೊರು"; Blockly.Msg["MATH_ONLIST_TOOLTIP_MODE"] = "ಪಟ್ಟಿಡುಪ್ಪುನ ಮಸ್ತ್ ಸಾಮಾನ್ಯ ವಿಷಯೊನು ಪಿರಕೊರು"; Blockly.Msg["MATH_ONLIST_TOOLTIP_RANDOM"] = "ಪಟ್ಟಿದ ಒವ್ವಾಂಡಲ ಒಂಜಿ ಅಂಶೊನು ಪಿರಕೊರು."; Blockly.Msg["MATH_ONLIST_TOOLTIP_STD_DEV"] = "ಪಟ್ಟಿದ ಪ್ರಮಾಣಿತ ವಿಚಲನೊನು ಪಿರಕೊರು"; Blockly.Msg["MATH_ONLIST_TOOLTIP_SUM"] = "ಪಟ್ಟಿಡುಪ್ಪುನ ಮಾತಾ ಸಂಖ್ಯೆಲೆನ ಮೊತ್ತನ್ ಪಿರಕೊರು"; Blockly.Msg["MATH_POWER_SYMBOL"] = "^"; // untranslated Blockly.Msg["MATH_RANDOM_FLOAT_HELPURL"] = "https://en.wikipedia.org/wiki/ರಾಂಡಮ್_ನಂಬರ್_ಜನರೇಶನ್"; Blockly.Msg["MATH_RANDOM_FLOAT_TITLE_RANDOM"] = "ಒವ್ವಾಂಡಲ ಒಂಜಿ ಭಿನ್ನರಾಶಿ"; Blockly.Msg["MATH_RANDOM_FLOAT_TOOLTIP"] = "0.0 (ಸೇರ್‌ದ್) ಬೊಕ್ಕ 1.0 (ಸೇರಂದೆ) ನಡುತ ಒವ್ವಾಂಡಲ ಒಂಜಿ ಭಿನ್ನರಾಶಿನ್ ಪಿರಕೊರು."; Blockly.Msg["MATH_RANDOM_INT_HELPURL"] = "https://en.wikipedia.org/wiki/ರಾಂಡಮ್_ನಂಬರ್_ಜನರೇಶನ್"; Blockly.Msg["MATH_RANDOM_INT_TITLE"] = " %1 ಡ್ದ್ %2 ಯಾದೃಚ್ಛಿಕ ಪೂರ್ಣಾಂಕೊ"; Blockly.Msg["MATH_RANDOM_INT_TOOLTIP"] = "ರಡ್ಡ್ ನಿಗದಿತ ಮಿತಿತ ನಡುತ್ತ ಯಾದೃಚ್ಛಿಕ ಪೂರ್ಣಾಂಕೊನು ಪಿರಕೊರು"; Blockly.Msg["MATH_ROUND_HELPURL"] = "https://en.wikipedia.org/wiki/ಪೂರ್ಣಾಂಕೊ"; Blockly.Msg["MATH_ROUND_OPERATOR_ROUND"] = "ರೌಂಡ್"; Blockly.Msg["MATH_ROUND_OPERATOR_ROUNDDOWN"] = "ತಿರ್ತ್‌ಗ್ ರೌಂಡ್"; Blockly.Msg["MATH_ROUND_OPERATOR_ROUNDUP"] = "ಮಿತ್ತ್‌ಗ್ ರೌಂಡ್"; Blockly.Msg["MATH_ROUND_TOOLTIP"] = "ಒಂಜಿ ಸಂಖ್ಯೆನ್ ಮಿತ್ತ್‌ಗ್ ಅತ್ತಂಡ ತಿರ್ತ್‌ಗ್ ರೌಂಡ್ ಮಲ್ಪು"; Blockly.Msg["MATH_SINGLE_HELPURL"] = "https://en.wikipedia.org/wiki/ವರ್ಗಮೂಲೊ"; Blockly.Msg["MATH_SINGLE_OP_ABSOLUTE"] = "ಸಂಪೂರ್ನೊ"; Blockly.Msg["MATH_SINGLE_OP_ROOT"] = "ವರ್ಗಮೂಲೊ"; Blockly.Msg["MATH_SINGLE_TOOLTIP_ABS"] = "ಸಂಖ್ಯೆದ ಸರಿಯಾಯಿನ ಮೌಲ್ಯೊನು ಕೊರು"; Blockly.Msg["MATH_SINGLE_TOOLTIP_EXP"] = "ಒಂಜಿ ಸಂಖ್ಯೆದ ಘಾತೊಗು 'e'ನ್ ಪಿರಕೊರು."; Blockly.Msg["MATH_SINGLE_TOOLTIP_LN"] = "ಸಂಖ್ಯೆದ ಪ್ರಾಕೃತಿಕ ಲಘುಗಣಕನ್ ಪಿರಕೊರು"; Blockly.Msg["MATH_SINGLE_TOOLTIP_LOG10"] = "ಸಂಖ್ಯೆದ ದಶಮಾನ ಲಘುಗಣಕನ್ ಪಿರಕೊರು"; Blockly.Msg["MATH_SINGLE_TOOLTIP_NEG"] = "ಸಂಖ್ಯೆದ ನಿಷೇಧೊನು ಪಿರಕೊರು"; Blockly.Msg["MATH_SINGLE_TOOLTIP_POW10"] = "ಒಂಜಿ ಸಂಖ್ಯೆದ ಘಾತೊಗು ೧೦ನ್ ಪಿರಕೊರು"; Blockly.Msg["MATH_SINGLE_TOOLTIP_ROOT"] = "ಸಂಖ್ಯೆದ ವರ್ಗಮೂಲೊನು ಪಿರಕೊರು."; Blockly.Msg["MATH_SUBTRACTION_SYMBOL"] = "-"; // untranslated Blockly.Msg["MATH_TRIG_ACOS"] = "acos"; // untranslated Blockly.Msg["MATH_TRIG_ASIN"] = "asin"; // untranslated Blockly.Msg["MATH_TRIG_ATAN"] = "atan"; // untranslated Blockly.Msg["MATH_TRIG_COS"] = "cos"; // untranslated Blockly.Msg["MATH_TRIG_HELPURL"] = "https://en.wikipedia.org/wiki/ತ್ರಿಕೋನಮಿತಿದ_ಕಾರ್ಯೊಲು"; Blockly.Msg["MATH_TRIG_SIN"] = "sin"; // untranslated Blockly.Msg["MATH_TRIG_TAN"] = "tan"; // untranslated Blockly.Msg["MATH_TRIG_TOOLTIP_ACOS"] = "ಒಂಜಿ ಸಂಖ್ಯೆದ ಆರ್ಕ್‌‌ಕೊಸೈನ್ ಪಿರಕೊರು."; Blockly.Msg["MATH_TRIG_TOOLTIP_ASIN"] = "ಒಂಜಿ ಸಂಖ್ಯೆದ ಆರ್ಕ್‌ಸೈನ್ ಪಿರಕೊರು."; Blockly.Msg["MATH_TRIG_TOOLTIP_ATAN"] = "ಒಂಜಿ ಸಂಖ್ಯೆದ ಆರ್ಕ್‌ಟ್ಯಾನ್‌ಜ್ಂಟ್ ಪಿರಕೊರು."; Blockly.Msg["MATH_TRIG_TOOLTIP_COS"] = "ಒಂಜಿ ಡಿಗ್ರಿದ ಕೊಸೈನ್ (cosine) ಪಿರಕೊರು (ರೇಡಿಯನ್ ಅತ್ತ್)."; Blockly.Msg["MATH_TRIG_TOOLTIP_SIN"] = "ಒಂಜಿ ಡಿಗ್ರಿದ ಸೈನ್ (sine) ಪಿರಕೊರು (ರೇಡಿಯನ್ ಅತ್ತ್)."; Blockly.Msg["MATH_TRIG_TOOLTIP_TAN"] = "ಒಂಜಿ ಡಿಗ್ರಿದ ಟ್ಯಾನ್‌ಜೆಂಟ್ (tangent) ಪಿರಕೊರು (ರೇಡಿಯನ್ ಅತ್ತ್)."; Blockly.Msg["NEW_COLOUR_VARIABLE"] = "Create colour variable..."; // untranslated Blockly.Msg["NEW_NUMBER_VARIABLE"] = "Create number variable..."; // untranslated Blockly.Msg["NEW_STRING_VARIABLE"] = "Create string variable..."; // untranslated Blockly.Msg["NEW_VARIABLE"] = "ವ್ಯತ್ಯಯೊನು ಉಂಡು ಮಲ್ಪುಲೆ"; Blockly.Msg["NEW_VARIABLE_TITLE"] = "ಪೊಸ ವ್ಯತ್ಯಯೊದ ಪುದರ್:"; Blockly.Msg["NEW_VARIABLE_TYPE_TITLE"] = "New variable type:"; // untranslated Blockly.Msg["ORDINAL_NUMBER_SUFFIX"] = ""; // untranslated Blockly.Msg["PROCEDURES_ALLOW_STATEMENTS"] = "ಹೇಳಿಕೆಗ್ ಅವಕಾಸೊ"; Blockly.Msg["PROCEDURES_BEFORE_PARAMS"] = "ಒಟ್ಟುಗು:"; Blockly.Msg["PROCEDURES_CALLNORETURN_HELPURL"] = "https://en.wikipedia.org/wiki/ವರ್ಗಮೂಲೊ"; Blockly.Msg["PROCEDURES_CALLNORETURN_TOOLTIP"] = "'%1' ಬಳಕೆದಾರೆರೆ ಕಾರ್ಯೊನು ನಡಪಾಲೆ."; Blockly.Msg["PROCEDURES_CALLRETURN_HELPURL"] = "https://en.wikipedia.org/wiki/ವರ್ಗಮೂಲೊ"; Blockly.Msg["PROCEDURES_CALLRETURN_TOOLTIP"] = " ಬಳಕೆದಾರೆರೆ ಕಾರ್ಯೊ '%1' ನು ನಡಪಾಲೆ ಬುಕ್ಕೊ ಅಯಿತ ಉತ್ಪಾದನೆನ್ ಗಲಸ್‌ಲೆ."; Blockly.Msg["PROCEDURES_CALL_BEFORE_PARAMS"] = "ಒಟ್ಟುಗು:"; Blockly.Msg["PROCEDURES_CREATE_DO"] = " '%1'ನ್ ಉಂಡುಮಲ್ಪುಲೆ"; Blockly.Msg["PROCEDURES_DEFNORETURN_COMMENT"] = "ಈ ಕಾರ್ಯೊನು ಇವರಿಪುಲೆ..."; Blockly.Msg["PROCEDURES_DEFNORETURN_DO"] = ""; // untranslated Blockly.Msg["PROCEDURES_DEFNORETURN_HELPURL"] = "https://en.wikipedia.org/wiki/Subroutine"; // untranslated Blockly.Msg["PROCEDURES_DEFNORETURN_PROCEDURE"] = "ಎಂಚಿನಾಂಡಲ ಮಲ್ಪುಲೆ"; Blockly.Msg["PROCEDURES_DEFNORETURN_TITLE"] = "ಇಂದೆಕ್"; Blockly.Msg["PROCEDURES_DEFNORETURN_TOOLTIP"] = "ಔಟ್‌ಪುಟ್ ದಾಂತಿನ ಕಾರ್ಯೊನು ಉಂಡುಮಲ್ಪುಂಡು."; Blockly.Msg["PROCEDURES_DEFRETURN_HELPURL"] = "https://en.wikipedia.org/wiki/Subroutine"; // untranslated Blockly.Msg["PROCEDURES_DEFRETURN_RETURN"] = "ಪಿರಕೊರು"; Blockly.Msg["PROCEDURES_DEFRETURN_TOOLTIP"] = "ಔಟ್‌ಪುಟ್ ಇತ್ತಿನ ಕಾರ್ಯೊನು ಉಂಡುಮಲ್ಪುಂಡು."; Blockly.Msg["PROCEDURES_DEF_DUPLICATE_WARNING"] = "ಎಚ್ಚರಿಕೆ: ಈ ಕಾರ್ಯೊಡು ನಕಲಿ ಮಾನದಂಡೊ ಉಂಡು."; Blockly.Msg["PROCEDURES_HIGHLIGHT_DEF"] = "ದೆರ್ತ್ ತೋಜುನ ಕಾರ್ಯೊದ ವ್ಯಾಕ್ಯಾನೊ"; Blockly.Msg["PROCEDURES_IFRETURN_HELPURL"] = "http://c2.com/cgi/wiki?GuardClause"; // untranslated Blockly.Msg["PROCEDURES_IFRETURN_TOOLTIP"] = "ಮೌಲ್ಯೊ ಸತ್ಯೊ ಆಂಡ, ರಡ್ಡನೆ ಮೌಲ್ಯೊನು ಪಿರಕೊರು."; Blockly.Msg["PROCEDURES_IFRETURN_WARNING"] = "ಎಚ್ಚರಿಕೆ: ಒಂಜಿ ಕಾರ್ಯ ವ್ಯಾಕ್ಯಾನೊದುಲಯಿ ಮಾತ್ರ ಈ ತಡೆನ್ ಗಲಸೊಲಿ."; Blockly.Msg["PROCEDURES_MUTATORARG_TITLE"] = "ಉಲಪರಿಪುದ ಪುದರ್:"; Blockly.Msg["PROCEDURES_MUTATORARG_TOOLTIP"] = "ಕಾರ್ಯೊಗು ಒಂಜಿ ಉಲಪರಿಪುನು ಸೇರಲೆ."; Blockly.Msg["PROCEDURES_MUTATORCONTAINER_TITLE"] = "ಉಲಪರಿಪು"; Blockly.Msg["PROCEDURES_MUTATORCONTAINER_TOOLTIP"] = "ಸೇರಾಲೆ, ದೆತ್ತ್‌ ಬುಡುಲೆ, ಅತ್ತಂಡ ಈ ಕಾರ್ಯೊಗು ಉಲಪರಿಪುಲೆನ್ ಕುಡ ಒತ್ತರೆ ಮಲ್ಪುಲೆ."; Blockly.Msg["REDO"] = "ಕುಡ ಮಲ್ಪು"; Blockly.Msg["REMOVE_COMMENT"] = "ಟಿಪ್ಪಣಿನ್ ದೆತ್ತ್‌ದ್ ಬುಡ್ಲೆ"; Blockly.Msg["RENAME_VARIABLE"] = "ವ್ಯತ್ಯಯೊಗು ಕುಡೊರ ಪುದರ್ ದೀಲೆ"; Blockly.Msg["RENAME_VARIABLE_TITLE"] = "ಮಾತಾ '%1' ವ್ಯತ್ಯಯೊಲೆನ ಪುದರ್‌ನ್ ನೆಕ್ಕ್ ಬದಲ್ ಮಲ್ಪುಲೆ:"; Blockly.Msg["TEXT_APPEND_HELPURL"] = "https://github.com/google/blockly/wiki/Text#text-modification"; // untranslated Blockly.Msg["TEXT_APPEND_TITLE"] = "ಇಂದೆಕ್ %1 ಪಟ್ಯೊನು ಸೇರವೆ %2"; Blockly.Msg["TEXT_APPEND_TOOLTIP"] = "%1 ವ್ಯತ್ಯಯೊಗು ಕೆಲವು ಪಟ್ಯೊಲೆನ್ ಸೇರಾವ್"; Blockly.Msg["TEXT_CHANGECASE_HELPURL"] = "https://github.com/google/blockly/wiki/Text#adjusting-text-case"; // untranslated Blockly.Msg["TEXT_CHANGECASE_OPERATOR_LOWERCASE"] = "ಎಲ್ಯ ಅಕ್ಷರೊಗು"; Blockly.Msg["TEXT_CHANGECASE_OPERATOR_TITLECASE"] = "ತರೆಬರವುದ ಅಕ್ಷರೊಗು"; Blockly.Msg["TEXT_CHANGECASE_OPERATOR_UPPERCASE"] = "ಮಲ್ಲ ಅಕ್ಷರೊಗು"; Blockly.Msg["TEXT_CHANGECASE_TOOLTIP"] = "ಪಟ್ಯೊದ ಒಂಜಿ ನಕಲ್‍ನ್ ಬೇತೆ ನಮೂನೆಡ್ (case) ಪಿರಕೊರು."; Blockly.Msg["TEXT_CHARAT_FIRST"] = "ಸುರುತ್ತ ಅಕ್ಷರೊನು ದೆತ್ತೊನು"; Blockly.Msg["TEXT_CHARAT_FROM_END"] = "ಅಕೇರಿಡ್ದ್ ಅಕ್ಷರೊ #ನ್ ದೆತ್ತೊನು"; Blockly.Msg["TEXT_CHARAT_FROM_START"] = "ಅಕ್ಸರೊ #ನ್ ದೆತ್ತೊನು"; Blockly.Msg["TEXT_CHARAT_HELPURL"] = "https://github.com/google/blockly/wiki/Text#extracting-text"; // untranslated Blockly.Msg["TEXT_CHARAT_LAST"] = "ಅಕೇರಿದ ಅಕ್ಷರೊನು ದೆತ್ತೊನು"; Blockly.Msg["TEXT_CHARAT_RANDOM"] = "ಒವ್ವಾಂಡಲ ಒಂಜಿ ಅಕ್ಷರೊನು ದೆತ್ತೊನು"; Blockly.Msg["TEXT_CHARAT_TAIL"] = ""; // untranslated Blockly.Msg["TEXT_CHARAT_TITLE"] = "%1 %2 ಪದೊಟ್ಟು"; Blockly.Msg["TEXT_CHARAT_TOOLTIP"] = "ಅಕ್ಷರೊನು ನಿರ್ದಿಷ್ಟ ಸ್ಥಿತಿಡ್ ಪಿರಕೊರ್ಪುಂಡು."; Blockly.Msg["TEXT_COUNT_HELPURL"] = "https://github.com/google/blockly/wiki/Text#counting-substrings"; // untranslated Blockly.Msg["TEXT_COUNT_MESSAGE0"] = "count %1 in %2"; // untranslated Blockly.Msg["TEXT_COUNT_TOOLTIP"] = "Count how many times some text occurs within some other text."; // untranslated Blockly.Msg["TEXT_CREATE_JOIN_ITEM_TOOLTIP"] = "ಪಟ್ಯೊಗು ಒಂಜಿ ವಿಷಯೊನು ಸೇರಾವ್"; Blockly.Msg["TEXT_CREATE_JOIN_TITLE_JOIN"] = "ಸೇರಾವ್"; Blockly.Msg["TEXT_CREATE_JOIN_TOOLTIP"] = "ಈ ಪಠ್ಯ ತಡೆನ್ ಕುಡ ಸಂರಚಣೆ ಮಲ್ಪೆರೆ, ಸೇರಾವ್, ದೆತ್ತ್ ಬುಡು, ಅತ್ತಂಡ ವಿಭಾಗೊಲೆನ್ ಕುಡ ಒತ್ತರೆ ಮಲ್ಪು."; Blockly.Msg["TEXT_GET_SUBSTRING_END_FROM_END"] = "ಅಕೇರಿಡ್ದ್ ಅಕ್ಷರೊ #ಗು"; Blockly.Msg["TEXT_GET_SUBSTRING_END_FROM_START"] = "ಅಕ್ಷರೊ #ಗು"; Blockly.Msg["TEXT_GET_SUBSTRING_END_LAST"] = "ಅಕೇರಿದ ಅಕ್ಷರೊಗು"; Blockly.Msg["TEXT_GET_SUBSTRING_HELPURL"] = "https://github.com/google/blockly/wiki/Text#extracting-a-region-of-text"; // untranslated Blockly.Msg["TEXT_GET_SUBSTRING_INPUT_IN_TEXT"] = "ಪಟ್ಯೊಡು"; Blockly.Msg["TEXT_GET_SUBSTRING_START_FIRST"] = "ಸುರುತ್ತ ಅಕ್ಷರೊ #ಡ್ದು ಉಪವಾಕ್ಯೊನು ದೆತ್ತೊನು"; Blockly.Msg["TEXT_GET_SUBSTRING_START_FROM_END"] = "ಅಕೇರಿಡ್ದ್ ಅಕ್ಷರೊ #ಡ್ದು ಉಪವಾಕ್ಯೊನು ದೆತ್ತೊನು"; Blockly.Msg["TEXT_GET_SUBSTRING_START_FROM_START"] = "ಅಕ್ಷರೊ #ಡ್ದು ಉಪವಾಕ್ಯೊ ದೆತ್ತೊನು"; Blockly.Msg["TEXT_GET_SUBSTRING_TAIL"] = ""; // untranslated Blockly.Msg["TEXT_GET_SUBSTRING_TOOLTIP"] = "ಪಟ್ಯೊದ ಒಂಜಿ ನಿರ್ದಿಷ್ಟ ಬಾಗೊನು ಪಿರಕೊರ್ಪುಂಡು."; Blockly.Msg["TEXT_INDEXOF_HELPURL"] = "https://github.com/google/blockly/wiki/Text#finding-text"; // untranslated Blockly.Msg["TEXT_INDEXOF_OPERATOR_FIRST"] = "ಪಟ್ಯೊ ಸುರುಕ್ಕು ಬತ್ತಿನೇನ್ ನಾಡ್"; Blockly.Msg["TEXT_INDEXOF_OPERATOR_LAST"] = "ಪಟ್ಯೊ ಅಕೇರಿಗ್ ಬತ್ತಿನೇನ್ ನಾಡ್"; Blockly.Msg["TEXT_INDEXOF_TITLE"] = "ಪಟ್ಯೊಡು %1 %2 %3"; Blockly.Msg["TEXT_INDEXOF_TOOLTIP"] = "ರಡ್ಡನೆ ಪಟ್ಯೊಡು ಉಪ್ಪುನ ಸುರುತ ಪಟ್ಯೊ ಸುರುಕ್ಕು/ಅಕೇರಿಗ್ ಬತ್ತಿನೆತ್ತ ಸೂಚಿನ್ ಪಿರಕೊರು. ಪಟ್ಯೊ ತಿಕ್ಕಿಜ್ಜಾಂಡ %1 ನ್ ಪಿರಕೊರು."; Blockly.Msg["TEXT_ISEMPTY_HELPURL"] = "https://github.com/google/blockly/wiki/Text#checking-for-empty-text"; // untranslated Blockly.Msg["TEXT_ISEMPTY_TITLE"] = "%1 ಖಾಲಿ"; Blockly.Msg["TEXT_ISEMPTY_TOOLTIP"] = "ಕೊರಿನ ಪಟ್ಯೊ ಖಾಲಿ ಇತ್ತ್ಂಡ 'ನಿಜ'ನ್ ಪಿರಕೊರು."; Blockly.Msg["TEXT_JOIN_HELPURL"] = "https://github.com/google/blockly/wiki/Text#text-creation"; // untranslated Blockly.Msg["TEXT_JOIN_TITLE_CREATEWITH"] = "ನೆಡ್ದ್ ಪಟ್ಯೊನು ಉಂಡು ಮಲ್ಪು"; Blockly.Msg["TEXT_JOIN_TOOLTIP"] = "ಏತಾಂಡಲ ವಿಷಯಲೆನ್ ಒಟ್ಟುಗು ಸೇರಾದ್ ಒಂಜಿ ಪಟ್ಯೊದ ತುಂಡುನು ಉಂಡುಮಲ್ಪು."; Blockly.Msg["TEXT_LENGTH_HELPURL"] = "https://github.com/google/blockly/wiki/Text#text-modification"; // untranslated Blockly.Msg["TEXT_LENGTH_TITLE"] = "%1 ಉದ್ದೊ"; Blockly.Msg["TEXT_LENGTH_TOOLTIP"] = "ಕೊರಿನ ಪಟ್ಯೊದ ಅಕ್ಷರೊಲೆನ (ಅಂತರೊಲು ಸೇರ್‌ದ್) ಸಂಖ್ಯೆನ್ ಪಿರಕೊರು."; Blockly.Msg["TEXT_PRINT_HELPURL"] = "https://github.com/google/blockly/wiki/Text#printing-text"; // untranslated Blockly.Msg["TEXT_PRINT_TITLE"] = "%1 ಮುದ್ರಣ"; Blockly.Msg["TEXT_PRINT_TOOLTIP"] = "ನಿರ್ದಿಷ್ಟ ಪಟ್ಯೊ, ಸಂಖ್ಯೆ ಅತ್ತಂಡ ಬೇತೆ ಮೌಲ್ಯೊನು ಮುದ್ರಿಪುಲೆ."; Blockly.Msg["TEXT_PROMPT_HELPURL"] = "https://github.com/google/blockly/wiki/Text#getting-input-from-the-user"; // untranslated Blockly.Msg["TEXT_PROMPT_TOOLTIP_NUMBER"] = "ಒಂಜಿ ಸಂಖ್ಯೆಗ್ ಸದಸ್ಯೆರೆನ್ ಕೇನ್"; Blockly.Msg["TEXT_PROMPT_TOOLTIP_TEXT"] = "ಕೆಲವು ಪಟ್ಯೊಗು ಸದಸ್ಯೆರೆನ್ ಕೇನ್."; Blockly.Msg["TEXT_PROMPT_TYPE_NUMBER"] = "ಸಂದೇಶೊದೊಟ್ಟುಗು ಸಂಕ್ಯೆನ್ ಕೇನ್"; Blockly.Msg["TEXT_PROMPT_TYPE_TEXT"] = "ಸಂದೇಶೊದೊಟ್ಟುಗು ಪಟ್ಯೊಗು ಕೇನ್."; Blockly.Msg["TEXT_REPLACE_HELPURL"] = "https://github.com/google/blockly/wiki/Text#replacing-substrings"; // untranslated Blockly.Msg["TEXT_REPLACE_MESSAGE0"] = "replace %1 with %2 in %3"; // untranslated Blockly.Msg["TEXT_REPLACE_TOOLTIP"] = "Replace all occurances of some text within some other text."; // untranslated Blockly.Msg["TEXT_REVERSE_HELPURL"] = "https://github.com/google/blockly/wiki/Text#reversing-text"; // untranslated Blockly.Msg["TEXT_REVERSE_MESSAGE0"] = "reverse %1"; // untranslated Blockly.Msg["TEXT_REVERSE_TOOLTIP"] = "Reverses the order of the characters in the text."; // untranslated Blockly.Msg["TEXT_TEXT_HELPURL"] = "https://en.wikipedia.org/wiki/ಸ್ಟ್ರಿಂಗ್_(ಕಂಪ್ಯೂಟರ್_ಸೈನ್ಸ್)"; Blockly.Msg["TEXT_TEXT_TOOLTIP"] = "ಒಂಜಿ ಅಕ್ಷರೊ, ಪದೊ ಅತ್ತಂಡ ಪಾಟೊದ ಒಂಜಿ ಸಾಲ್"; Blockly.Msg["TEXT_TRIM_HELPURL"] = "https://github.com/google/blockly/wiki/Text#trimming-removing-spaces"; // untranslated Blockly.Msg["TEXT_TRIM_OPERATOR_BOTH"] = "ರಡ್ಡ್ ಮೆಯಿತ್ತಲ ಅಂತರೊಲೆನ್ (space) ಕತ್ತೆರ್."; Blockly.Msg["TEXT_TRIM_OPERATOR_LEFT"] = "ಎಡತ್ತ ಮೆಯಿತ್ತ ಅಂತರೊಲೆನ್ (space) ಕತ್ತೆರ್."; Blockly.Msg["TEXT_TRIM_OPERATOR_RIGHT"] = "ಬಲತ್ತ ಮೆಯಿತ್ತ ಅಂತರೊಲೆನ್ (space) ಕತ್ತೆರ್."; Blockly.Msg["TEXT_TRIM_TOOLTIP"] = "ಒಂಜಿ ಅತ್ತಂಡ ರಡ್ಡ್ ಕೊಡಿಡ್ದ್ ಅಂತರೊಲೆನ್ (space) ದೆತ್ತ್‌ದ್ ಪಟ್ಯೊದ ಪ್ರತಿನ್ ಪಿರಕೊರು."; Blockly.Msg["TODAY"] = "ಇನಿ"; Blockly.Msg["UNDO"] = "ದುಂಬುದಲೆಕೊ"; Blockly.Msg["UNNAMED_KEY"] = "ಪುದರ್ ಇಜ್ಜಂತಿನವು"; Blockly.Msg["VARIABLES_DEFAULT_NAME"] = "ವಸ್ತು"; Blockly.Msg["VARIABLES_GET_CREATE_SET"] = "'ಸೆಟ್ %1' ಉಂಡುಮಲ್ಪುಲೆ"; Blockly.Msg["VARIABLES_GET_HELPURL"] = "https://github.com/google/blockly/wiki/Variables#get"; // untranslated Blockly.Msg["VARIABLES_GET_TOOLTIP"] = "ಈ ವ್ಯತ್ಯಯೊದ ಮೌಲ್ಯೊನು ಪಿರಕೊರು."; Blockly.Msg["VARIABLES_SET"] = "%1 ನ್ %2 ಕ್ಕ್ ಸೆಟ್ ಮಲ್ಪುಲೆ"; Blockly.Msg["VARIABLES_SET_CREATE_GET"] = "'ದೆತ್ತೊನು %1' ಉಂಡುಮಲ್ಪುಲೆ"; Blockly.Msg["VARIABLES_SET_HELPURL"] = "https://github.com/google/blockly/wiki/Variables#set"; // untranslated Blockly.Msg["VARIABLES_SET_TOOLTIP"] = "ಈ ವ್ಯತ್ಯಯೊನು ಇನ್‌ಪುಟ್‌ಗ್ ಸಮ ಆಪಿಲೆಕ ಸೆಟ್ ಮಲ್ಪುಂಡು."; Blockly.Msg["VARIABLE_ALREADY_EXISTS"] = "'%1' ಪನ್ಪಿ ಪುದರ್‌ದ ವ್ಯತ್ಯಯೊ ದುಂಬೆ ಅಸ್ತಿತ್ವೊಡು ಉಂಡು."; Blockly.Msg["VARIABLE_ALREADY_EXISTS_FOR_ANOTHER_TYPE"] = "A variable named '%1' already exists for another type: '%2'."; // untranslated Blockly.Msg["WORKSPACE_ARIA_LABEL"] = "Blockly Workspace"; // untranslated Blockly.Msg["WORKSPACE_COMMENT_DEFAULT_TEXT"] = "ದಾದಾಂಡಲ ಪನ್ಲೇ..."; Blockly.Msg["CONTROLS_FOREACH_INPUT_DO"] = Blockly.Msg["CONTROLS_REPEAT_INPUT_DO"]; Blockly.Msg["CONTROLS_FOR_INPUT_DO"] = Blockly.Msg["CONTROLS_REPEAT_INPUT_DO"]; Blockly.Msg["CONTROLS_IF_ELSEIF_TITLE_ELSEIF"] = Blockly.Msg["CONTROLS_IF_MSG_ELSEIF"]; Blockly.Msg["CONTROLS_IF_ELSE_TITLE_ELSE"] = Blockly.Msg["CONTROLS_IF_MSG_ELSE"]; Blockly.Msg["CONTROLS_IF_IF_TITLE_IF"] = Blockly.Msg["CONTROLS_IF_MSG_IF"]; Blockly.Msg["CONTROLS_IF_MSG_THEN"] = Blockly.Msg["CONTROLS_REPEAT_INPUT_DO"]; Blockly.Msg["CONTROLS_WHILEUNTIL_INPUT_DO"] = Blockly.Msg["CONTROLS_REPEAT_INPUT_DO"]; Blockly.Msg["LISTS_CREATE_WITH_ITEM_TITLE"] = Blockly.Msg["VARIABLES_DEFAULT_NAME"]; Blockly.Msg["LISTS_GET_INDEX_HELPURL"] = Blockly.Msg["LISTS_INDEX_OF_HELPURL"]; Blockly.Msg["LISTS_GET_INDEX_INPUT_IN_LIST"] = Blockly.Msg["LISTS_INLIST"]; Blockly.Msg["LISTS_GET_SUBLIST_INPUT_IN_LIST"] = Blockly.Msg["LISTS_INLIST"]; Blockly.Msg["LISTS_INDEX_OF_INPUT_IN_LIST"] = Blockly.Msg["LISTS_INLIST"]; Blockly.Msg["LISTS_SET_INDEX_INPUT_IN_LIST"] = Blockly.Msg["LISTS_INLIST"]; Blockly.Msg["MATH_CHANGE_TITLE_ITEM"] = Blockly.Msg["VARIABLES_DEFAULT_NAME"]; Blockly.Msg["PROCEDURES_DEFRETURN_COMMENT"] = Blockly.Msg["PROCEDURES_DEFNORETURN_COMMENT"]; Blockly.Msg["PROCEDURES_DEFRETURN_DO"] = Blockly.Msg["PROCEDURES_DEFNORETURN_DO"]; Blockly.Msg["PROCEDURES_DEFRETURN_PROCEDURE"] = Blockly.Msg["PROCEDURES_DEFNORETURN_PROCEDURE"]; Blockly.Msg["PROCEDURES_DEFRETURN_TITLE"] = Blockly.Msg["PROCEDURES_DEFNORETURN_TITLE"]; Blockly.Msg["TEXT_APPEND_VARIABLE"] = Blockly.Msg["VARIABLES_DEFAULT_NAME"]; Blockly.Msg["TEXT_CREATE_JOIN_ITEM_TITLE_ITEM"] = Blockly.Msg["VARIABLES_DEFAULT_NAME"]; Blockly.Msg["MATH_HUE"] = "230"; Blockly.Msg["LOOPS_HUE"] = "120"; Blockly.Msg["LISTS_HUE"] = "260"; Blockly.Msg["LOGIC_HUE"] = "210"; Blockly.Msg["VARIABLES_HUE"] = "330"; Blockly.Msg["TEXTS_HUE"] = "160"; Blockly.Msg["PROCEDURES_HUE"] = "290"; Blockly.Msg["COLOUR_HUE"] = "20"; Blockly.Msg["VARIABLES_DYNAMIC_HUE"] = "310"; return Blockly.Msg; }));
cdnjs/cdnjs
ajax/libs/blockly/7.20211209.4/msg/tcy.js
JavaScript
mit
51,200
@charset "UTF-8"; /*! Ionicons, v4.0.0-13 Created by Ben Sperry for the Ionic Framework, http://ionicons.com/ https://twitter.com/benjsperry https://twitter.com/ionicframework MIT License: https://github.com/driftyco/ionicons Android-style icons originally built by Google’s Material Design Icons: https://github.com/google/material-design-icons used under CC BY http://creativecommons.org/licenses/by/4.0/ Modified icons to fit ionicon’s grid from original. */ .ion-ios-add:before { content: "\f102"; } .ion-ios-add-circle:before { content: "\f101"; } .ion-ios-add-circle-outline:before { content: "\f100"; } .ion-ios-airplane:before { content: "\f137"; } .ion-ios-alarm:before { content: "\f3c8"; } .ion-ios-albums:before { content: "\f3ca"; } .ion-ios-alert:before { content: "\f104"; } .ion-ios-american-football:before { content: "\f106"; } .ion-ios-analytics:before { content: "\f3ce"; } .ion-ios-aperture:before { content: "\f108"; } .ion-ios-apps:before { content: "\f10a"; } .ion-ios-appstore:before { content: "\f10c"; } .ion-ios-archive:before { content: "\f10e"; } .ion-ios-arrow-back:before { content: "\f3cf"; } .ion-ios-arrow-down:before { content: "\f3d0"; } .ion-ios-arrow-dropdown:before { content: "\f110"; } .ion-ios-arrow-dropdown-circle:before { content: "\f125"; } .ion-ios-arrow-dropleft:before { content: "\f112"; } .ion-ios-arrow-dropleft-circle:before { content: "\f129"; } .ion-ios-arrow-dropright:before { content: "\f114"; } .ion-ios-arrow-dropright-circle:before { content: "\f12b"; } .ion-ios-arrow-dropup:before { content: "\f116"; } .ion-ios-arrow-dropup-circle:before { content: "\f12d"; } .ion-ios-arrow-forward:before { content: "\f3d1"; } .ion-ios-arrow-round-back:before { content: "\f117"; } .ion-ios-arrow-round-down:before { content: "\f118"; } .ion-ios-arrow-round-forward:before { content: "\f119"; } .ion-ios-arrow-round-up:before { content: "\f11a"; } .ion-ios-arrow-up:before { content: "\f3d8"; } .ion-ios-at:before { content: "\f3da"; } .ion-ios-attach:before { content: "\f11b"; } .ion-ios-backspace:before { content: "\f11d"; } .ion-ios-barcode:before { content: "\f3dc"; } .ion-ios-baseball:before { content: "\f3de"; } .ion-ios-basket:before { content: "\f11f"; } .ion-ios-basketball:before { content: "\f3e0"; } .ion-ios-battery-charging:before { content: "\f120"; } .ion-ios-battery-dead:before { content: "\f121"; } .ion-ios-battery-full:before { content: "\f122"; } .ion-ios-beaker:before { content: "\f124"; } .ion-ios-bed:before { content: "\f139"; } .ion-ios-beer:before { content: "\f126"; } .ion-ios-bicycle:before { content: "\f127"; } .ion-ios-bluetooth:before { content: "\f128"; } .ion-ios-boat:before { content: "\f12a"; } .ion-ios-body:before { content: "\f3e4"; } .ion-ios-bonfire:before { content: "\f12c"; } .ion-ios-book:before { content: "\f3e8"; } .ion-ios-bookmark:before { content: "\f12e"; } .ion-ios-bookmarks:before { content: "\f3ea"; } .ion-ios-bowtie:before { content: "\f130"; } .ion-ios-briefcase:before { content: "\f3ee"; } .ion-ios-browsers:before { content: "\f3f0"; } .ion-ios-brush:before { content: "\f132"; } .ion-ios-bug:before { content: "\f134"; } .ion-ios-build:before { content: "\f136"; } .ion-ios-bulb:before { content: "\f138"; } .ion-ios-bus:before { content: "\f13a"; } .ion-ios-business:before { content: "\f1a3"; } .ion-ios-cafe:before { content: "\f13c"; } .ion-ios-calculator:before { content: "\f3f2"; } .ion-ios-calendar:before { content: "\f3f4"; } .ion-ios-call:before { content: "\f13e"; } .ion-ios-camera:before { content: "\f3f6"; } .ion-ios-car:before { content: "\f140"; } .ion-ios-card:before { content: "\f142"; } .ion-ios-cart:before { content: "\f3f8"; } .ion-ios-cash:before { content: "\f144"; } .ion-ios-cellular:before { content: "\f13d"; } .ion-ios-chatboxes:before { content: "\f3fa"; } .ion-ios-chatbubbles:before { content: "\f146"; } .ion-ios-checkbox:before { content: "\f148"; } .ion-ios-checkbox-outline:before { content: "\f147"; } .ion-ios-checkmark:before { content: "\f3ff"; } .ion-ios-checkmark-circle:before { content: "\f14a"; } .ion-ios-checkmark-circle-outline:before { content: "\f149"; } .ion-ios-clipboard:before { content: "\f14c"; } .ion-ios-clock:before { content: "\f403"; } .ion-ios-close:before { content: "\f406"; } .ion-ios-close-circle:before { content: "\f14e"; } .ion-ios-close-circle-outline:before { content: "\f14d"; } .ion-ios-cloud:before { content: "\f40c"; } .ion-ios-cloud-circle:before { content: "\f152"; } .ion-ios-cloud-done:before { content: "\f154"; } .ion-ios-cloud-download:before { content: "\f408"; } .ion-ios-cloud-outline:before { content: "\f409"; } .ion-ios-cloud-upload:before { content: "\f40b"; } .ion-ios-cloudy:before { content: "\f410"; } .ion-ios-cloudy-night:before { content: "\f40e"; } .ion-ios-code:before { content: "\f157"; } .ion-ios-code-download:before { content: "\f155"; } .ion-ios-code-working:before { content: "\f156"; } .ion-ios-cog:before { content: "\f412"; } .ion-ios-color-fill:before { content: "\f159"; } .ion-ios-color-filter:before { content: "\f414"; } .ion-ios-color-palette:before { content: "\f15b"; } .ion-ios-color-wand:before { content: "\f416"; } .ion-ios-compass:before { content: "\f15d"; } .ion-ios-construct:before { content: "\f15f"; } .ion-ios-contact:before { content: "\f41a"; } .ion-ios-contacts:before { content: "\f161"; } .ion-ios-contract:before { content: "\f162"; } .ion-ios-contrast:before { content: "\f163"; } .ion-ios-copy:before { content: "\f41c"; } .ion-ios-create:before { content: "\f165"; } .ion-ios-crop:before { content: "\f41e"; } .ion-ios-cube:before { content: "\f168"; } .ion-ios-cut:before { content: "\f16a"; } .ion-ios-desktop:before { content: "\f16c"; } .ion-ios-disc:before { content: "\f16e"; } .ion-ios-document:before { content: "\f170"; } .ion-ios-done-all:before { content: "\f171"; } .ion-ios-download:before { content: "\f420"; } .ion-ios-easel:before { content: "\f173"; } .ion-ios-egg:before { content: "\f175"; } .ion-ios-exit:before { content: "\f177"; } .ion-ios-expand:before { content: "\f178"; } .ion-ios-eye:before { content: "\f425"; } .ion-ios-eye-off:before { content: "\f17a"; } .ion-ios-fastforward:before { content: "\f427"; } .ion-ios-female:before { content: "\f17b"; } .ion-ios-filing:before { content: "\f429"; } .ion-ios-film:before { content: "\f42b"; } .ion-ios-finger-print:before { content: "\f17c"; } .ion-ios-fitness:before { content: "\f1ab"; } .ion-ios-flag:before { content: "\f42d"; } .ion-ios-flame:before { content: "\f42f"; } .ion-ios-flash:before { content: "\f17e"; } .ion-ios-flash-off:before { content: "\f12f"; } .ion-ios-flashlight:before { content: "\f141"; } .ion-ios-flask:before { content: "\f431"; } .ion-ios-flower:before { content: "\f433"; } .ion-ios-folder:before { content: "\f435"; } .ion-ios-folder-open:before { content: "\f180"; } .ion-ios-football:before { content: "\f437"; } .ion-ios-funnel:before { content: "\f182"; } .ion-ios-gift:before { content: "\f191"; } .ion-ios-git-branch:before { content: "\f183"; } .ion-ios-git-commit:before { content: "\f184"; } .ion-ios-git-compare:before { content: "\f185"; } .ion-ios-git-merge:before { content: "\f186"; } .ion-ios-git-network:before { content: "\f187"; } .ion-ios-git-pull-request:before { content: "\f188"; } .ion-ios-glasses:before { content: "\f43f"; } .ion-ios-globe:before { content: "\f18a"; } .ion-ios-grid:before { content: "\f18c"; } .ion-ios-hammer:before { content: "\f18e"; } .ion-ios-hand:before { content: "\f190"; } .ion-ios-happy:before { content: "\f192"; } .ion-ios-headset:before { content: "\f194"; } .ion-ios-heart:before { content: "\f443"; } .ion-ios-heart-dislike:before { content: "\f13f"; } .ion-ios-heart-empty:before { content: "\f19b"; } .ion-ios-heart-half:before { content: "\f19d"; } .ion-ios-help:before { content: "\f446"; } .ion-ios-help-buoy:before { content: "\f196"; } .ion-ios-help-circle:before { content: "\f198"; } .ion-ios-help-circle-outline:before { content: "\f197"; } .ion-ios-home:before { content: "\f448"; } .ion-ios-hourglass:before { content: "\f103"; } .ion-ios-ice-cream:before { content: "\f19a"; } .ion-ios-image:before { content: "\f19c"; } .ion-ios-images:before { content: "\f19e"; } .ion-ios-infinite:before { content: "\f44a"; } .ion-ios-information:before { content: "\f44d"; } .ion-ios-information-circle:before { content: "\f1a0"; } .ion-ios-information-circle-outline:before { content: "\f19f"; } .ion-ios-jet:before { content: "\f1a5"; } .ion-ios-journal:before { content: "\f189"; } .ion-ios-key:before { content: "\f1a7"; } .ion-ios-keypad:before { content: "\f450"; } .ion-ios-laptop:before { content: "\f1a8"; } .ion-ios-leaf:before { content: "\f1aa"; } .ion-ios-link:before { content: "\f22a"; } .ion-ios-list:before { content: "\f454"; } .ion-ios-list-box:before { content: "\f143"; } .ion-ios-locate:before { content: "\f1ae"; } .ion-ios-lock:before { content: "\f1b0"; } .ion-ios-log-in:before { content: "\f1b1"; } .ion-ios-log-out:before { content: "\f1b2"; } .ion-ios-magnet:before { content: "\f1b4"; } .ion-ios-mail:before { content: "\f1b8"; } .ion-ios-mail-open:before { content: "\f1b6"; } .ion-ios-mail-unread:before { content: "\f145"; } .ion-ios-male:before { content: "\f1b9"; } .ion-ios-man:before { content: "\f1bb"; } .ion-ios-map:before { content: "\f1bd"; } .ion-ios-medal:before { content: "\f1bf"; } .ion-ios-medical:before { content: "\f45c"; } .ion-ios-medkit:before { content: "\f45e"; } .ion-ios-megaphone:before { content: "\f1c1"; } .ion-ios-menu:before { content: "\f1c3"; } .ion-ios-mic:before { content: "\f461"; } .ion-ios-mic-off:before { content: "\f45f"; } .ion-ios-microphone:before { content: "\f1c6"; } .ion-ios-moon:before { content: "\f468"; } .ion-ios-more:before { content: "\f1c8"; } .ion-ios-move:before { content: "\f1cb"; } .ion-ios-musical-note:before { content: "\f46b"; } .ion-ios-musical-notes:before { content: "\f46c"; } .ion-ios-navigate:before { content: "\f46e"; } .ion-ios-notifications:before { content: "\f1d3"; } .ion-ios-notifications-off:before { content: "\f1d1"; } .ion-ios-notifications-outline:before { content: "\f133"; } .ion-ios-nuclear:before { content: "\f1d5"; } .ion-ios-nutrition:before { content: "\f470"; } .ion-ios-open:before { content: "\f1d7"; } .ion-ios-options:before { content: "\f1d9"; } .ion-ios-outlet:before { content: "\f1db"; } .ion-ios-paper:before { content: "\f472"; } .ion-ios-paper-plane:before { content: "\f1dd"; } .ion-ios-partly-sunny:before { content: "\f1df"; } .ion-ios-pause:before { content: "\f478"; } .ion-ios-paw:before { content: "\f47a"; } .ion-ios-people:before { content: "\f47c"; } .ion-ios-person:before { content: "\f47e"; } .ion-ios-person-add:before { content: "\f1e1"; } .ion-ios-phone-landscape:before { content: "\f1e2"; } .ion-ios-phone-portrait:before { content: "\f1e3"; } .ion-ios-photos:before { content: "\f482"; } .ion-ios-pie:before { content: "\f484"; } .ion-ios-pin:before { content: "\f1e5"; } .ion-ios-pint:before { content: "\f486"; } .ion-ios-pizza:before { content: "\f1e7"; } .ion-ios-plane:before { content: "\f1e9"; } .ion-ios-planet:before { content: "\f1eb"; } .ion-ios-play:before { content: "\f488"; } .ion-ios-play-circle:before { content: "\f113"; } .ion-ios-podium:before { content: "\f1ed"; } .ion-ios-power:before { content: "\f1ef"; } .ion-ios-pricetag:before { content: "\f48d"; } .ion-ios-pricetags:before { content: "\f48f"; } .ion-ios-print:before { content: "\f1f1"; } .ion-ios-pulse:before { content: "\f493"; } .ion-ios-qr-scanner:before { content: "\f1f3"; } .ion-ios-quote:before { content: "\f1f5"; } .ion-ios-radio:before { content: "\f1f9"; } .ion-ios-radio-button-off:before { content: "\f1f6"; } .ion-ios-radio-button-on:before { content: "\f1f7"; } .ion-ios-rainy:before { content: "\f495"; } .ion-ios-recording:before { content: "\f497"; } .ion-ios-redo:before { content: "\f499"; } .ion-ios-refresh:before { content: "\f49c"; } .ion-ios-refresh-circle:before { content: "\f135"; } .ion-ios-remove:before { content: "\f1fc"; } .ion-ios-remove-circle:before { content: "\f1fb"; } .ion-ios-remove-circle-outline:before { content: "\f1fa"; } .ion-ios-reorder:before { content: "\f1fd"; } .ion-ios-repeat:before { content: "\f1fe"; } .ion-ios-resize:before { content: "\f1ff"; } .ion-ios-restaurant:before { content: "\f201"; } .ion-ios-return-left:before { content: "\f202"; } .ion-ios-return-right:before { content: "\f203"; } .ion-ios-reverse-camera:before { content: "\f49f"; } .ion-ios-rewind:before { content: "\f4a1"; } .ion-ios-ribbon:before { content: "\f205"; } .ion-ios-rocket:before { content: "\f14b"; } .ion-ios-rose:before { content: "\f4a3"; } .ion-ios-sad:before { content: "\f207"; } .ion-ios-save:before { content: "\f1a6"; } .ion-ios-school:before { content: "\f209"; } .ion-ios-search:before { content: "\f4a5"; } .ion-ios-send:before { content: "\f20c"; } .ion-ios-settings:before { content: "\f4a7"; } .ion-ios-share:before { content: "\f211"; } .ion-ios-share-alt:before { content: "\f20f"; } .ion-ios-shirt:before { content: "\f213"; } .ion-ios-shuffle:before { content: "\f4a9"; } .ion-ios-skip-backward:before { content: "\f215"; } .ion-ios-skip-forward:before { content: "\f217"; } .ion-ios-snow:before { content: "\f218"; } .ion-ios-speedometer:before { content: "\f4b0"; } .ion-ios-square:before { content: "\f21a"; } .ion-ios-square-outline:before { content: "\f15c"; } .ion-ios-star:before { content: "\f4b3"; } .ion-ios-star-half:before { content: "\f4b1"; } .ion-ios-star-outline:before { content: "\f4b2"; } .ion-ios-stats:before { content: "\f21c"; } .ion-ios-stopwatch:before { content: "\f4b5"; } .ion-ios-subway:before { content: "\f21e"; } .ion-ios-sunny:before { content: "\f4b7"; } .ion-ios-swap:before { content: "\f21f"; } .ion-ios-switch:before { content: "\f221"; } .ion-ios-sync:before { content: "\f222"; } .ion-ios-tablet-landscape:before { content: "\f223"; } .ion-ios-tablet-portrait:before { content: "\f24e"; } .ion-ios-tennisball:before { content: "\f4bb"; } .ion-ios-text:before { content: "\f250"; } .ion-ios-thermometer:before { content: "\f252"; } .ion-ios-thumbs-down:before { content: "\f254"; } .ion-ios-thumbs-up:before { content: "\f256"; } .ion-ios-thunderstorm:before { content: "\f4bd"; } .ion-ios-time:before { content: "\f4bf"; } .ion-ios-timer:before { content: "\f4c1"; } .ion-ios-today:before { content: "\f14f"; } .ion-ios-train:before { content: "\f258"; } .ion-ios-transgender:before { content: "\f259"; } .ion-ios-trash:before { content: "\f4c5"; } .ion-ios-trending-down:before { content: "\f25a"; } .ion-ios-trending-up:before { content: "\f25b"; } .ion-ios-trophy:before { content: "\f25d"; } .ion-ios-tv:before { content: "\f115"; } .ion-ios-umbrella:before { content: "\f25f"; } .ion-ios-undo:before { content: "\f4c7"; } .ion-ios-unlock:before { content: "\f261"; } .ion-ios-videocam:before { content: "\f4cd"; } .ion-ios-volume-high:before { content: "\f11c"; } .ion-ios-volume-low:before { content: "\f11e"; } .ion-ios-volume-mute:before { content: "\f263"; } .ion-ios-volume-off:before { content: "\f264"; } .ion-ios-walk:before { content: "\f266"; } .ion-ios-wallet:before { content: "\f18b"; } .ion-ios-warning:before { content: "\f268"; } .ion-ios-watch:before { content: "\f269"; } .ion-ios-water:before { content: "\f26b"; } .ion-ios-wifi:before { content: "\f26d"; } .ion-ios-wine:before { content: "\f26f"; } .ion-ios-woman:before { content: "\f271"; } .ion-logo-android:before { content: "\f225"; } .ion-logo-angular:before { content: "\f227"; } .ion-logo-apple:before { content: "\f229"; } .ion-logo-bitbucket:before { content: "\f193"; } .ion-logo-bitcoin:before { content: "\f22b"; } .ion-logo-buffer:before { content: "\f22d"; } .ion-logo-chrome:before { content: "\f22f"; } .ion-logo-closed-captioning:before { content: "\f105"; } .ion-logo-codepen:before { content: "\f230"; } .ion-logo-css3:before { content: "\f231"; } .ion-logo-designernews:before { content: "\f232"; } .ion-logo-dribbble:before { content: "\f233"; } .ion-logo-dropbox:before { content: "\f234"; } .ion-logo-euro:before { content: "\f235"; } .ion-logo-facebook:before { content: "\f236"; } .ion-logo-flickr:before { content: "\f107"; } .ion-logo-foursquare:before { content: "\f237"; } .ion-logo-freebsd-devil:before { content: "\f238"; } .ion-logo-game-controller-a:before { content: "\f13b"; } .ion-logo-game-controller-b:before { content: "\f181"; } .ion-logo-github:before { content: "\f239"; } .ion-logo-google:before { content: "\f23a"; } .ion-logo-googleplus:before { content: "\f23b"; } .ion-logo-hackernews:before { content: "\f23c"; } .ion-logo-html5:before { content: "\f23d"; } .ion-logo-instagram:before { content: "\f23e"; } .ion-logo-ionic:before { content: "\f150"; } .ion-logo-ionitron:before { content: "\f151"; } .ion-logo-javascript:before { content: "\f23f"; } .ion-logo-linkedin:before { content: "\f240"; } .ion-logo-markdown:before { content: "\f241"; } .ion-logo-model-s:before { content: "\f153"; } .ion-logo-no-smoking:before { content: "\f109"; } .ion-logo-nodejs:before { content: "\f242"; } .ion-logo-npm:before { content: "\f195"; } .ion-logo-octocat:before { content: "\f243"; } .ion-logo-pinterest:before { content: "\f244"; } .ion-logo-playstation:before { content: "\f245"; } .ion-logo-polymer:before { content: "\f15e"; } .ion-logo-python:before { content: "\f246"; } .ion-logo-reddit:before { content: "\f247"; } .ion-logo-rss:before { content: "\f248"; } .ion-logo-sass:before { content: "\f249"; } .ion-logo-skype:before { content: "\f24a"; } .ion-logo-slack:before { content: "\f10b"; } .ion-logo-snapchat:before { content: "\f24b"; } .ion-logo-steam:before { content: "\f24c"; } .ion-logo-tumblr:before { content: "\f24d"; } .ion-logo-tux:before { content: "\f2ae"; } .ion-logo-twitch:before { content: "\f2af"; } .ion-logo-twitter:before { content: "\f2b0"; } .ion-logo-usd:before { content: "\f2b1"; } .ion-logo-vimeo:before { content: "\f2c4"; } .ion-logo-vk:before { content: "\f10d"; } .ion-logo-whatsapp:before { content: "\f2c5"; } .ion-logo-windows:before { content: "\f32f"; } .ion-logo-wordpress:before { content: "\f330"; } .ion-logo-xbox:before { content: "\f34c"; } .ion-logo-xing:before { content: "\f10f"; } .ion-logo-yahoo:before { content: "\f34d"; } .ion-logo-yen:before { content: "\f34e"; } .ion-logo-youtube:before { content: "\f34f"; } .ion-md-add:before { content: "\f273"; } .ion-md-add-circle:before { content: "\f272"; } .ion-md-add-circle-outline:before { content: "\f158"; } .ion-md-airplane:before { content: "\f15a"; } .ion-md-alarm:before { content: "\f274"; } .ion-md-albums:before { content: "\f275"; } .ion-md-alert:before { content: "\f276"; } .ion-md-american-football:before { content: "\f277"; } .ion-md-analytics:before { content: "\f278"; } .ion-md-aperture:before { content: "\f279"; } .ion-md-apps:before { content: "\f27a"; } .ion-md-appstore:before { content: "\f27b"; } .ion-md-archive:before { content: "\f27c"; } .ion-md-arrow-back:before { content: "\f27d"; } .ion-md-arrow-down:before { content: "\f27e"; } .ion-md-arrow-dropdown:before { content: "\f280"; } .ion-md-arrow-dropdown-circle:before { content: "\f27f"; } .ion-md-arrow-dropleft:before { content: "\f282"; } .ion-md-arrow-dropleft-circle:before { content: "\f281"; } .ion-md-arrow-dropright:before { content: "\f284"; } .ion-md-arrow-dropright-circle:before { content: "\f283"; } .ion-md-arrow-dropup:before { content: "\f286"; } .ion-md-arrow-dropup-circle:before { content: "\f285"; } .ion-md-arrow-forward:before { content: "\f287"; } .ion-md-arrow-round-back:before { content: "\f288"; } .ion-md-arrow-round-down:before { content: "\f289"; } .ion-md-arrow-round-forward:before { content: "\f28a"; } .ion-md-arrow-round-up:before { content: "\f28b"; } .ion-md-arrow-up:before { content: "\f28c"; } .ion-md-at:before { content: "\f28d"; } .ion-md-attach:before { content: "\f28e"; } .ion-md-backspace:before { content: "\f28f"; } .ion-md-barcode:before { content: "\f290"; } .ion-md-baseball:before { content: "\f291"; } .ion-md-basket:before { content: "\f292"; } .ion-md-basketball:before { content: "\f293"; } .ion-md-battery-charging:before { content: "\f294"; } .ion-md-battery-dead:before { content: "\f295"; } .ion-md-battery-full:before { content: "\f296"; } .ion-md-beaker:before { content: "\f297"; } .ion-md-bed:before { content: "\f160"; } .ion-md-beer:before { content: "\f298"; } .ion-md-bicycle:before { content: "\f299"; } .ion-md-bluetooth:before { content: "\f29a"; } .ion-md-boat:before { content: "\f29b"; } .ion-md-body:before { content: "\f29c"; } .ion-md-bonfire:before { content: "\f29d"; } .ion-md-book:before { content: "\f29e"; } .ion-md-bookmark:before { content: "\f29f"; } .ion-md-bookmarks:before { content: "\f2a0"; } .ion-md-bowtie:before { content: "\f2a1"; } .ion-md-briefcase:before { content: "\f2a2"; } .ion-md-browsers:before { content: "\f2a3"; } .ion-md-brush:before { content: "\f2a4"; } .ion-md-bug:before { content: "\f2a5"; } .ion-md-build:before { content: "\f2a6"; } .ion-md-bulb:before { content: "\f2a7"; } .ion-md-bus:before { content: "\f2a8"; } .ion-md-business:before { content: "\f1a4"; } .ion-md-cafe:before { content: "\f2a9"; } .ion-md-calculator:before { content: "\f2aa"; } .ion-md-calendar:before { content: "\f2ab"; } .ion-md-call:before { content: "\f2ac"; } .ion-md-camera:before { content: "\f2ad"; } .ion-md-car:before { content: "\f2b2"; } .ion-md-card:before { content: "\f2b3"; } .ion-md-cart:before { content: "\f2b4"; } .ion-md-cash:before { content: "\f2b5"; } .ion-md-cellular:before { content: "\f164"; } .ion-md-chatboxes:before { content: "\f2b6"; } .ion-md-chatbubbles:before { content: "\f2b7"; } .ion-md-checkbox:before { content: "\f2b9"; } .ion-md-checkbox-outline:before { content: "\f2b8"; } .ion-md-checkmark:before { content: "\f2bc"; } .ion-md-checkmark-circle:before { content: "\f2bb"; } .ion-md-checkmark-circle-outline:before { content: "\f2ba"; } .ion-md-clipboard:before { content: "\f2bd"; } .ion-md-clock:before { content: "\f2be"; } .ion-md-close:before { content: "\f2c0"; } .ion-md-close-circle:before { content: "\f2bf"; } .ion-md-close-circle-outline:before { content: "\f166"; } .ion-md-cloud:before { content: "\f2c9"; } .ion-md-cloud-circle:before { content: "\f2c2"; } .ion-md-cloud-done:before { content: "\f2c3"; } .ion-md-cloud-download:before { content: "\f2c6"; } .ion-md-cloud-outline:before { content: "\f2c7"; } .ion-md-cloud-upload:before { content: "\f2c8"; } .ion-md-cloudy:before { content: "\f2cb"; } .ion-md-cloudy-night:before { content: "\f2ca"; } .ion-md-code:before { content: "\f2ce"; } .ion-md-code-download:before { content: "\f2cc"; } .ion-md-code-working:before { content: "\f2cd"; } .ion-md-cog:before { content: "\f2cf"; } .ion-md-color-fill:before { content: "\f2d0"; } .ion-md-color-filter:before { content: "\f2d1"; } .ion-md-color-palette:before { content: "\f2d2"; } .ion-md-color-wand:before { content: "\f2d3"; } .ion-md-compass:before { content: "\f2d4"; } .ion-md-construct:before { content: "\f2d5"; } .ion-md-contact:before { content: "\f2d6"; } .ion-md-contacts:before { content: "\f2d7"; } .ion-md-contract:before { content: "\f2d8"; } .ion-md-contrast:before { content: "\f2d9"; } .ion-md-copy:before { content: "\f2da"; } .ion-md-create:before { content: "\f2db"; } .ion-md-crop:before { content: "\f2dc"; } .ion-md-cube:before { content: "\f2dd"; } .ion-md-cut:before { content: "\f2de"; } .ion-md-desktop:before { content: "\f2df"; } .ion-md-disc:before { content: "\f2e0"; } .ion-md-document:before { content: "\f2e1"; } .ion-md-done-all:before { content: "\f2e2"; } .ion-md-download:before { content: "\f2e3"; } .ion-md-easel:before { content: "\f2e4"; } .ion-md-egg:before { content: "\f2e5"; } .ion-md-exit:before { content: "\f2e6"; } .ion-md-expand:before { content: "\f2e7"; } .ion-md-eye:before { content: "\f2e9"; } .ion-md-eye-off:before { content: "\f2e8"; } .ion-md-fastforward:before { content: "\f2ea"; } .ion-md-female:before { content: "\f2eb"; } .ion-md-filing:before { content: "\f2ec"; } .ion-md-film:before { content: "\f2ed"; } .ion-md-finger-print:before { content: "\f2ee"; } .ion-md-fitness:before { content: "\f1ac"; } .ion-md-flag:before { content: "\f2ef"; } .ion-md-flame:before { content: "\f2f0"; } .ion-md-flash:before { content: "\f2f1"; } .ion-md-flash-off:before { content: "\f169"; } .ion-md-flashlight:before { content: "\f16b"; } .ion-md-flask:before { content: "\f2f2"; } .ion-md-flower:before { content: "\f2f3"; } .ion-md-folder:before { content: "\f2f5"; } .ion-md-folder-open:before { content: "\f2f4"; } .ion-md-football:before { content: "\f2f6"; } .ion-md-funnel:before { content: "\f2f7"; } .ion-md-gift:before { content: "\f199"; } .ion-md-git-branch:before { content: "\f2fa"; } .ion-md-git-commit:before { content: "\f2fb"; } .ion-md-git-compare:before { content: "\f2fc"; } .ion-md-git-merge:before { content: "\f2fd"; } .ion-md-git-network:before { content: "\f2fe"; } .ion-md-git-pull-request:before { content: "\f2ff"; } .ion-md-glasses:before { content: "\f300"; } .ion-md-globe:before { content: "\f301"; } .ion-md-grid:before { content: "\f302"; } .ion-md-hammer:before { content: "\f303"; } .ion-md-hand:before { content: "\f304"; } .ion-md-happy:before { content: "\f305"; } .ion-md-headset:before { content: "\f306"; } .ion-md-heart:before { content: "\f308"; } .ion-md-heart-dislike:before { content: "\f167"; } .ion-md-heart-empty:before { content: "\f1a1"; } .ion-md-heart-half:before { content: "\f1a2"; } .ion-md-help:before { content: "\f30b"; } .ion-md-help-buoy:before { content: "\f309"; } .ion-md-help-circle:before { content: "\f30a"; } .ion-md-help-circle-outline:before { content: "\f16d"; } .ion-md-home:before { content: "\f30c"; } .ion-md-hourglass:before { content: "\f111"; } .ion-md-ice-cream:before { content: "\f30d"; } .ion-md-image:before { content: "\f30e"; } .ion-md-images:before { content: "\f30f"; } .ion-md-infinite:before { content: "\f310"; } .ion-md-information:before { content: "\f312"; } .ion-md-information-circle:before { content: "\f311"; } .ion-md-information-circle-outline:before { content: "\f16f"; } .ion-md-jet:before { content: "\f315"; } .ion-md-journal:before { content: "\f18d"; } .ion-md-key:before { content: "\f316"; } .ion-md-keypad:before { content: "\f317"; } .ion-md-laptop:before { content: "\f318"; } .ion-md-leaf:before { content: "\f319"; } .ion-md-link:before { content: "\f22e"; } .ion-md-list:before { content: "\f31b"; } .ion-md-list-box:before { content: "\f31a"; } .ion-md-locate:before { content: "\f31c"; } .ion-md-lock:before { content: "\f31d"; } .ion-md-log-in:before { content: "\f31e"; } .ion-md-log-out:before { content: "\f31f"; } .ion-md-magnet:before { content: "\f320"; } .ion-md-mail:before { content: "\f322"; } .ion-md-mail-open:before { content: "\f321"; } .ion-md-mail-unread:before { content: "\f172"; } .ion-md-male:before { content: "\f323"; } .ion-md-man:before { content: "\f324"; } .ion-md-map:before { content: "\f325"; } .ion-md-medal:before { content: "\f326"; } .ion-md-medical:before { content: "\f327"; } .ion-md-medkit:before { content: "\f328"; } .ion-md-megaphone:before { content: "\f329"; } .ion-md-menu:before { content: "\f32a"; } .ion-md-mic:before { content: "\f32c"; } .ion-md-mic-off:before { content: "\f32b"; } .ion-md-microphone:before { content: "\f32d"; } .ion-md-moon:before { content: "\f32e"; } .ion-md-more:before { content: "\f1c9"; } .ion-md-move:before { content: "\f331"; } .ion-md-musical-note:before { content: "\f332"; } .ion-md-musical-notes:before { content: "\f333"; } .ion-md-navigate:before { content: "\f334"; } .ion-md-notifications:before { content: "\f338"; } .ion-md-notifications-off:before { content: "\f336"; } .ion-md-notifications-outline:before { content: "\f337"; } .ion-md-nuclear:before { content: "\f339"; } .ion-md-nutrition:before { content: "\f33a"; } .ion-md-open:before { content: "\f33b"; } .ion-md-options:before { content: "\f33c"; } .ion-md-outlet:before { content: "\f33d"; } .ion-md-paper:before { content: "\f33f"; } .ion-md-paper-plane:before { content: "\f33e"; } .ion-md-partly-sunny:before { content: "\f340"; } .ion-md-pause:before { content: "\f341"; } .ion-md-paw:before { content: "\f342"; } .ion-md-people:before { content: "\f343"; } .ion-md-person:before { content: "\f345"; } .ion-md-person-add:before { content: "\f344"; } .ion-md-phone-landscape:before { content: "\f346"; } .ion-md-phone-portrait:before { content: "\f347"; } .ion-md-photos:before { content: "\f348"; } .ion-md-pie:before { content: "\f349"; } .ion-md-pin:before { content: "\f34a"; } .ion-md-pint:before { content: "\f34b"; } .ion-md-pizza:before { content: "\f354"; } .ion-md-plane:before { content: "\f355"; } .ion-md-planet:before { content: "\f356"; } .ion-md-play:before { content: "\f357"; } .ion-md-play-circle:before { content: "\f174"; } .ion-md-podium:before { content: "\f358"; } .ion-md-power:before { content: "\f359"; } .ion-md-pricetag:before { content: "\f35a"; } .ion-md-pricetags:before { content: "\f35b"; } .ion-md-print:before { content: "\f35c"; } .ion-md-pulse:before { content: "\f35d"; } .ion-md-qr-scanner:before { content: "\f35e"; } .ion-md-quote:before { content: "\f35f"; } .ion-md-radio:before { content: "\f362"; } .ion-md-radio-button-off:before { content: "\f360"; } .ion-md-radio-button-on:before { content: "\f361"; } .ion-md-rainy:before { content: "\f363"; } .ion-md-recording:before { content: "\f364"; } .ion-md-redo:before { content: "\f365"; } .ion-md-refresh:before { content: "\f366"; } .ion-md-refresh-circle:before { content: "\f228"; } .ion-md-remove:before { content: "\f368"; } .ion-md-remove-circle:before { content: "\f367"; } .ion-md-remove-circle-outline:before { content: "\f176"; } .ion-md-reorder:before { content: "\f369"; } .ion-md-repeat:before { content: "\f36a"; } .ion-md-resize:before { content: "\f36b"; } .ion-md-restaurant:before { content: "\f36c"; } .ion-md-return-left:before { content: "\f36d"; } .ion-md-return-right:before { content: "\f36e"; } .ion-md-reverse-camera:before { content: "\f36f"; } .ion-md-rewind:before { content: "\f370"; } .ion-md-ribbon:before { content: "\f371"; } .ion-md-rocket:before { content: "\f179"; } .ion-md-rose:before { content: "\f372"; } .ion-md-sad:before { content: "\f373"; } .ion-md-save:before { content: "\f1a9"; } .ion-md-school:before { content: "\f374"; } .ion-md-search:before { content: "\f375"; } .ion-md-send:before { content: "\f376"; } .ion-md-settings:before { content: "\f377"; } .ion-md-share:before { content: "\f379"; } .ion-md-share-alt:before { content: "\f378"; } .ion-md-shirt:before { content: "\f37a"; } .ion-md-shuffle:before { content: "\f37b"; } .ion-md-skip-backward:before { content: "\f37c"; } .ion-md-skip-forward:before { content: "\f37d"; } .ion-md-snow:before { content: "\f37e"; } .ion-md-speedometer:before { content: "\f37f"; } .ion-md-square:before { content: "\f381"; } .ion-md-square-outline:before { content: "\f380"; } .ion-md-star:before { content: "\f384"; } .ion-md-star-half:before { content: "\f382"; } .ion-md-star-outline:before { content: "\f383"; } .ion-md-stats:before { content: "\f385"; } .ion-md-stopwatch:before { content: "\f386"; } .ion-md-subway:before { content: "\f387"; } .ion-md-sunny:before { content: "\f388"; } .ion-md-swap:before { content: "\f389"; } .ion-md-switch:before { content: "\f38a"; } .ion-md-sync:before { content: "\f38b"; } .ion-md-tablet-landscape:before { content: "\f38c"; } .ion-md-tablet-portrait:before { content: "\f38d"; } .ion-md-tennisball:before { content: "\f38e"; } .ion-md-text:before { content: "\f38f"; } .ion-md-thermometer:before { content: "\f390"; } .ion-md-thumbs-down:before { content: "\f391"; } .ion-md-thumbs-up:before { content: "\f392"; } .ion-md-thunderstorm:before { content: "\f393"; } .ion-md-time:before { content: "\f394"; } .ion-md-timer:before { content: "\f395"; } .ion-md-today:before { content: "\f17d"; } .ion-md-train:before { content: "\f396"; } .ion-md-transgender:before { content: "\f397"; } .ion-md-trash:before { content: "\f398"; } .ion-md-trending-down:before { content: "\f399"; } .ion-md-trending-up:before { content: "\f39a"; } .ion-md-trophy:before { content: "\f39b"; } .ion-md-tv:before { content: "\f17f"; } .ion-md-umbrella:before { content: "\f39c"; } .ion-md-undo:before { content: "\f39d"; } .ion-md-unlock:before { content: "\f39e"; } .ion-md-videocam:before { content: "\f39f"; } .ion-md-volume-high:before { content: "\f123"; } .ion-md-volume-low:before { content: "\f131"; } .ion-md-volume-mute:before { content: "\f3a1"; } .ion-md-volume-off:before { content: "\f3a2"; } .ion-md-walk:before { content: "\f3a4"; } .ion-md-wallet:before { content: "\f18f"; } .ion-md-warning:before { content: "\f3a5"; } .ion-md-watch:before { content: "\f3a6"; } .ion-md-water:before { content: "\f3a7"; } .ion-md-wifi:before { content: "\f3a8"; } .ion-md-wine:before { content: "\f3a9"; } .ion-md-woman:before { content: "\f3aa"; }
cdnjs/cdnjs
ajax/libs/ionicons/4.0.0-14/css/ionicons-core.css
CSS
mit
35,140
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_13) on Tue Feb 23 19:04:37 CET 2010 --> <TITLE> Uses of Class org.mt4j.util.opengl.shader.ShaderGLSL </TITLE> <META NAME="date" CONTENT="2010-02-23"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.mt4j.util.opengl.shader.ShaderGLSL"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../org/mt4j/util/opengl/shader/ShaderGLSL.html" title="class in org.mt4j.util.opengl.shader"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../index.html?org/mt4j/util/opengl/shader/\class-useShaderGLSL.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="ShaderGLSL.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <CENTER> <H2> <B>Uses of Class<br>org.mt4j.util.opengl.shader.ShaderGLSL</B></H2> </CENTER> No usage of org.mt4j.util.opengl.shader.ShaderGLSL <P> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../org/mt4j/util/opengl/shader/ShaderGLSL.html" title="class in org.mt4j.util.opengl.shader"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../index.html?org/mt4j/util/opengl/shader/\class-useShaderGLSL.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="ShaderGLSL.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> </BODY> </HTML>
AdalbertoJoseToledoEscalona/catalogo_productos_old_version
pantallaMT v0.95/MT4j/doc/org/mt4j/util/opengl/shader/class-use/ShaderGLSL.html
HTML
gpl-2.0
6,119
// { dg-do run } // Check that we can use multiple co_awaits as a call parm. #include "../coro.h" // boiler-plate for tests of codegen #define USE_AWAIT_TRANSFORM #include "../coro1-ret-int-yield-int.h" int gX = 1; __attribute__((__noinline__)) static int bar (int x, int y) { return x + y; } /* Function with a multiple awaits. */ coro1 g () { gX = bar (co_await 9, co_await 2); co_return gX + 31; } int main () { PRINT ("main: create coro1"); struct coro1 g_coro = g (); PRINT ("main: got coro1 - checking gX"); if (gX != 1) { PRINTF ("main: gX is wrong : %d, should be 1\n", gX); abort (); } if (g_coro.handle.done()) { PRINT ("main: we should not be 'done' [1]"); abort (); } PRINT ("main: resuming [1] (initial suspend)"); g_coro.handle.resume(); PRINT ("main: resuming [2] (parm 1)"); g_coro.handle.resume(); PRINT ("main: resuming [2] (parm 2)"); g_coro.handle.resume(); if (gX != 11) { PRINTF ("main: gX is wrong : %d, should be 11\n", gX); abort (); } /* we should now have returned with the co_return 11 + 31) */ if (!g_coro.handle.done()) { PRINT ("main: we should be 'done'"); abort (); } int y = g_coro.handle.promise().get_value(); if (y != 42) { PRINTF ("main: y is wrong : %d, should be 42\n", y); abort (); } puts ("main: done"); return 0; }
Gurgel100/gcc
gcc/testsuite/g++.dg/coroutines/torture/call-01-multiple-co-aw.C
C++
gpl-2.0
1,413
// ========================================================================== // This software is subject to the provisions of the Zope Public License, // Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution. // THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED // WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS // FOR A PARTICULAR PURPOSE. // ========================================================================== using System; using System.Collections; using System.Runtime.InteropServices; namespace Python.Runtime { //======================================================================== // Implements the "import hook" used to integrate Python with the CLR. //======================================================================== internal class ImportHook { static IntPtr py_import; static CLRModule root; static MethodWrapper hook; //=================================================================== // Initialization performed on startup of the Python runtime. //=================================================================== internal static void Initialize() { // Initialize the Python <--> CLR module hook. We replace the // built-in Python __import__ with our own. This isn't ideal, // but it provides the most "Pythonic" way of dealing with CLR // modules (Python doesn't provide a way to emulate packages). IntPtr dict = Runtime.PyImport_GetModuleDict(); IntPtr mod = Runtime.PyDict_GetItemString(dict, "__builtin__"); py_import = Runtime.PyObject_GetAttrString(mod, "__import__"); hook = new MethodWrapper(typeof(ImportHook), "__import__"); Runtime.PyObject_SetAttrString(mod, "__import__", hook.ptr); Runtime.Decref(hook.ptr); root = new CLRModule(); Runtime.Incref(root.pyHandle); // we are using the module two times Runtime.PyDict_SetItemString(dict, "CLR", root.pyHandle); Runtime.PyDict_SetItemString(dict, "clr", root.pyHandle); } //=================================================================== // Cleanup resources upon shutdown of the Python runtime. //=================================================================== internal static void Shutdown() { Runtime.Decref(root.pyHandle); Runtime.Decref(root.pyHandle); Runtime.Decref(py_import); } //=================================================================== // The actual import hook that ties Python to the managed world. //=================================================================== public static IntPtr __import__(IntPtr self, IntPtr args, IntPtr kw) { // Replacement for the builtin __import__. The original import // hook is saved as this.py_import. This version handles CLR // import and defers to the normal builtin for everything else. int num_args = Runtime.PyTuple_Size(args); if (num_args < 1) { return Exceptions.RaiseTypeError( "__import__() takes at least 1 argument (0 given)" ); } // borrowed reference IntPtr py_mod_name = Runtime.PyTuple_GetItem(args, 0); if ((py_mod_name == IntPtr.Zero) || (!Runtime.IsStringType(py_mod_name))) { return Exceptions.RaiseTypeError("string expected"); } // Check whether the import is of the form 'from x import y'. // This determines whether we return the head or tail module. IntPtr fromList = IntPtr.Zero; bool fromlist = false; if (num_args >= 4) { fromList = Runtime.PyTuple_GetItem(args, 3); if ((fromList != IntPtr.Zero) && (Runtime.PyObject_IsTrue(fromList) == 1)) { fromlist = true; } } string mod_name = Runtime.GetManagedString(py_mod_name); if (mod_name == "CLR") { Exceptions.deprecation("The CLR module is deprecated. " + "Please use 'clr'."); root.InitializePreload(); Runtime.Incref(root.pyHandle); return root.pyHandle; } if (mod_name == "clr") { root.InitializePreload(); Runtime.Incref(root.pyHandle); return root.pyHandle; } string realname = mod_name; if (mod_name.StartsWith("CLR.")) { realname = mod_name.Substring(4); string msg = String.Format("Importing from the CLR.* namespace "+ "is deprecated. Please import '{0}' directly.", realname); Exceptions.deprecation(msg); } string[] names = realname.Split('.'); // Now we need to decide if the name refers to a CLR module, // and may have to do an implicit load (for b/w compatibility) // using the AssemblyManager. The assembly manager tries // really hard not to use Python objects or APIs, because // parts of it can run recursively and on strange threads. // // It does need an opportunity from time to time to check to // see if sys.path has changed, in a context that is safe. Here // we know we have the GIL, so we'll let it update if needed. AssemblyManager.UpdatePath(); AssemblyManager.LoadImplicit(realname); if (!AssemblyManager.IsValidNamespace(realname)) { return Runtime.PyObject_Call(py_import, args, kw); } // See if sys.modules for this interpreter already has the // requested module. If so, just return the exising module. IntPtr modules = Runtime.PyImport_GetModuleDict(); IntPtr module = Runtime.PyDict_GetItem(modules, py_mod_name); if (module != IntPtr.Zero) { if (fromlist) { Runtime.Incref(module); return module; } module = Runtime.PyDict_GetItemString(modules, names[0]); Runtime.Incref(module); return module; } Exceptions.Clear(); // Traverse the qualified module name to get the named module // and place references in sys.modules as we go. Note that if // we are running in interactive mode we pre-load the names in // each module, which is often useful for introspection. If we // are not interactive, we stick to just-in-time creation of // objects at lookup time, which is much more efficient. // NEW: The clr got a new module variable preload. You can // enable preloading in a non-interactive python processing by // setting clr.preload = True ModuleObject head = (mod_name == realname) ? null : root; ModuleObject tail = root; root.InitializePreload(); for (int i = 0; i < names.Length; i++) { string name = names[i]; ManagedType mt = tail.GetAttribute(name, true); if (!(mt is ModuleObject)) { string error = String.Format("No module named {0}", name); Exceptions.SetError(Exceptions.ImportError, error); return IntPtr.Zero; } if (head == null) { head = (ModuleObject)mt; } tail = (ModuleObject) mt; if (CLRModule.preload) { tail.LoadNames(); } Runtime.PyDict_SetItemString(modules, tail.moduleName, tail.pyHandle ); } ModuleObject mod = fromlist ? tail : head; if (fromlist && Runtime.PySequence_Size(fromList) == 1) { IntPtr fp = Runtime.PySequence_GetItem(fromList, 0); if ((!CLRModule.preload) && Runtime.GetManagedString(fp) == "*") { mod.LoadNames(); } Runtime.Decref(fp); } Runtime.Incref(mod.pyHandle); return mod.pyHandle; } } }
lordtangent/arsenalsuite
python/pythondotnet/pythonnet/src/runtime/importhook.cs
C#
gpl-2.0
9,001