text
stringlengths
2
99.9k
meta
dict
:10FC000001C0DDC0112484B790E890936100109288 :10FC10006100882361F0982F9A70923041F081FF43 :10FC200002C097EF94BF282E80E0ECD0E9C185E0B8 :10FC30008093810082E08093C00088E18093C100BE :10FC400087E18093C40086E08093C2008EE0DAD022 :10FC5000209A84E02EE33EEF91E0309385002093DC :10FC6000840096BBB09BFECF189AA8954091C00027 :10FC700047FD02C0815089F7B9D0813479F4B6D0FC :10FC8000C82FC6D0C23811F480E004C088E0C13863 :10FC900009F083E0A4D080E1A2D0EECF823419F441 :10FCA00084E1BED0F8CF853411F485E0FACF8535F4 :10FCB00041F49CD0E82E9AD0F82EEE0CFF1CA8D070 :10FCC000EACF863519F484E0ABD0DECF843609F074 :10FCD00045C08CD0C82FD0E0DC2FCC2787D0C82BD4 :10FCE00085D0D82E5E01B39400E011E04801EFEF1B :10FCF0008E1A9E0A7BD0F801808384018A149B04AB :10FD0000A9F786D0F5E410E000E0DF1609F150E035 :10FD100040E063E0C70153D08701C12CDD24D394B8 :10FD2000F601419151916F0161E0C80148D00E5F29 :10FD30001F4F2297A9F750E040E065E0C7013FD090 :10FD4000AACF6081C8018E0D9F1D79D00F5F1F4F14 :10FD5000F801F395C017D107A1F79DCF843701F5BE :10FD600045D0C82FD0E0DC2FCC2740D0C82B3ED0C8 :10FD7000D82E4ED08701F5E4DF120BC0CE0DDF1D6B :10FD8000C80155D02CD00F5F1F4FC017D107C1F746 :10FD900082CFF80185918F0122D02197D1F77BCFB7 :10FDA000853739F435D08EE11AD086E918D089E04C :10FDB00071CF813509F083CF88E024D080CFFC015A :10FDC0000A0167BFE895112407B600FCFDCF6670F5 :10FDD00029F0452B19F481E187BFE89508959091AA :10FDE000C00095FFFCCF8093C60008958091C000AD :10FDF00087FFFCCF8091C00084FD01C0A895809151 :10FE0000C6000895E0E6F0E098E1908380830895CD :10FE1000EDDF803219F088E0F5DFFFCF84E1DFCF3E :10FE2000CF93C82FE3DFC150E9F7CF91F1CFF99914 :10FE3000FECF92BD81BDF89A992780B50895262FEF :10FE4000F999FECF1FBA92BD81BD20BD0FB6F894BF :0AFE5000FA9AF99A0FBE0196089580 :02FFFE000008F9 :040000030000FC00FD :00000001FF
{ "pile_set_name": "Github" }
<HTML><HEAD></HEAD><BODY><P> the resolver framework for retrieval of certificates and public keys from elements. </P></BODY></HTML>
{ "pile_set_name": "Github" }
<?xml version="1.0"?> <root> <movie> <title category="SF">STAR WARS</title> </movie> <movie> <title category="Children">tom &amp; jerry</title> </movie> </root>
{ "pile_set_name": "Github" }
<?xml version="1.0" ?> <annotation> <folder>widerface</folder> <filename>6--Funeral_6_Funeral_Funeral_6_170.jpg</filename> <source> <database>wider face Database</database> <annotation>PASCAL VOC2007</annotation> <image>flickr</image> <flickrid>-1</flickrid> </source> <owner> <flickrid>yanyu</flickrid> <name>yanyu</name> </owner> <size> <width>1024</width> <height>1122</height> <depth>3</depth> </size> <segmented>0</segmented> <object> <name>face</name> <pose>Unspecified</pose> <truncated>1</truncated> <difficult>0</difficult> <bndbox> <xmin>64</xmin> <ymin>202</ymin> <xmax>126</xmax> <ymax>275</ymax> </bndbox> <lm> <x1>71.0</x1> <y1>226.0</y1> <x2>91.0</x2> <y2>228.0</y2> <x3>70.0</x3> <y3>242.0</y3> <x4>70.0</x4> <y4>255.0</y4> <x5>86.0</x5> <y5>258.0</y5> <visible>0</visible> <blur>0.7</blur> </lm> <has_lm>1</has_lm> </object> <object> <name>face</name> <pose>Unspecified</pose> <truncated>1</truncated> <difficult>0</difficult> <bndbox> <xmin>227</xmin> <ymin>196</ymin> <xmax>295</xmax> <ymax>283</ymax> </bndbox> <lm> <x1>232.996</x1> <y1>225.772</y1> <x2>254.411</x2> <y2>226.871</y2> <x3>234.094</x3> <y3>246.089</y3> <x4>236.839</x4> <y4>263.112</y4> <x5>253.312</x5> <y5>263.112</y5> <visible>0</visible> <blur>0.7</blur> </lm> <has_lm>1</has_lm> </object> <object> <name>face</name> <pose>Unspecified</pose> <truncated>1</truncated> <difficult>0</difficult> <bndbox> <xmin>532</xmin> <ymin>229</ymin> <xmax>603</xmax> <ymax>320</ymax> </bndbox> <lm> <x1>539.357</x1> <y1>268.317</y1> <x2>567.576</x2> <y2>268.893</y2> <x3>546.268</x3> <y3>287.897</y3> <x4>544.54</x4> <y4>299.415</y4> <x5>565.848</x5> <y5>299.415</y5> <visible>0</visible> <blur>0.72</blur> </lm> <has_lm>1</has_lm> </object> <object> <name>face</name> <pose>Unspecified</pose> <truncated>1</truncated> <difficult>0</difficult> <bndbox> <xmin>597</xmin> <ymin>257</ymin> <xmax>637</xmax> <ymax>308</ymax> </bndbox> <lm> <x1>606.246</x1> <y1>275.33</y1> <x2>623.192</x2> <y2>275.33</y2> <x3>611.46</x3> <y3>287.388</y3> <x4>610.482</x4> <y4>297.165</y4> <x5>620.911</x5> <y5>296.839</y5> <visible>0</visible> <blur>0.64</blur> </lm> <has_lm>1</has_lm> </object> <object> <name>face</name> <pose>Unspecified</pose> <truncated>1</truncated> <difficult>0</difficult> <bndbox> <xmin>776</xmin> <ymin>257</ymin> <xmax>825</xmax> <ymax>328</ymax> </bndbox> <lm> <x1>784.321</x1> <y1>290.661</y1> <x2>804.857</x2> <y2>293.339</y2> <x3>791.018</x3> <y3>305.393</y3> <x4>783.875</x4> <y4>311.196</y4> <x5>803.071</x5> <y5>313.875</y5> <visible>0</visible> <blur>0.64</blur> </lm> <has_lm>1</has_lm> </object> <object> <name>face</name> <pose>Unspecified</pose> <truncated>1</truncated> <difficult>0</difficult> <bndbox> <xmin>862</xmin> <ymin>258</ymin> <xmax>908</xmax> <ymax>316</ymax> </bndbox> <lm> <x1>870.179</x1> <y1>278.719</y1> <x2>887.594</x2> <y2>280.201</y2> <x3>871.661</x3> <y3>288.723</y3> <x4>867.585</x4> <y4>302.804</y4> <x5>882.036</x5> <y5>303.915</y5> <visible>1</visible> <blur>0.68</blur> </lm> <has_lm>1</has_lm> </object> </annotation>
{ "pile_set_name": "Github" }
{ "extends": "../../tsconfig.json", "compilerOptions": { "outDir": "dist/esm", "module": "esnext", "target": "es2019", "moduleResolution": "node" }, "include": [ "./src" ] }
{ "pile_set_name": "Github" }
import { createSelector } from 'reselect'; function createTagDetailsSelector() { return createSelector( (state, { id }) => id, (state) => state.tags.details.items, (id, tagDetails) => { return tagDetails.find((t) => t.id === id); } ); } export default createTagDetailsSelector;
{ "pile_set_name": "Github" }
package com.werb.moretype import android.graphics.BitmapFactory import com.werb.library.MoreViewHolder import com.werb.moretype.multi.ImageSize import java.io.File import java.text.SimpleDateFormat import java.util.* /** * Created by wanbo on 2017/7/14. */ object Utils { fun sendTime(ms: Long): String { val calendar = Calendar.getInstance() calendar.timeInMillis = ms val format = SimpleDateFormat("MM/dd HH:mm") return format.format(Date(ms)) } fun dp2px(dpValue: Float): Int { val scale = MyApp.myApp.resources.displayMetrics.density return (dpValue * scale + 0.5f).toInt() } fun getIMImageSize(width: Double, height: Double): ImageSize { val fixWidth: Int val fixHeight: Int var ratio = width.toFloat() / height.toFloat() if (ratio > 1) { if (ratio > 3) { ratio = 3f } fixWidth = dp2px(200f) fixHeight = (fixWidth / ratio).toInt() } else { if (ratio < 0.3) { ratio = 0.3f } fixHeight = dp2px(200f) fixWidth = (ratio * fixHeight).toInt() } return ImageSize(fixWidth, fixHeight) } fun readImageSize(path: String): ImageSize? { val orFile = File(path) if (!orFile.exists()) { return null } val options = BitmapFactory.Options() options.inJustDecodeBounds = true BitmapFactory.decodeFile(orFile.absolutePath, options) return ImageSize(options.outWidth, options.outHeight) } }
{ "pile_set_name": "Github" }
Chainsaw ======== Build chainable fluent interfaces the easy way in node.js. With this meta-module you can write modules with chainable interfaces. Chainsaw takes care of all of the boring details and makes nested flow control super simple too. Just call `Chainsaw` with a constructor function like in the examples below. In your methods, just do `saw.next()` to move along to the next event and `saw.nest()` to create a nested chain. Examples ======== add_do.js --------- This silly example adds values with a chainsaw. var Chainsaw = require('chainsaw'); function AddDo (sum) { return Chainsaw(function (saw) { this.add = function (n) { sum += n; saw.next(); }; this.do = function (cb) { saw.nest(cb, sum); }; }); } AddDo(0) .add(5) .add(10) .do(function (sum) { if (sum > 12) this.add(-10); }) .do(function (sum) { console.log('Sum: ' + sum); }) ; Output: Sum: 5 prompt.js --------- This example provides a wrapper on top of stdin with the help of [node-lazy](https://github.com/pkrumins/node-lazy) for line-processing. var Chainsaw = require('chainsaw'); var Lazy = require('lazy'); module.exports = Prompt; function Prompt (stream) { var waiting = []; var lines = []; var lazy = Lazy(stream).lines.map(String) .forEach(function (line) { if (waiting.length) { var w = waiting.shift(); w(line); } else lines.push(line); }) ; var vars = {}; return Chainsaw(function (saw) { this.getline = function (f) { var g = function (line) { saw.nest(f, line, vars); }; if (lines.length) g(lines.shift()); else waiting.push(g); }; this.do = function (cb) { saw.nest(cb, vars); }; }); } And now for the new Prompt() module in action: var util = require('util'); var stdin = process.openStdin(); Prompt(stdin) .do(function () { util.print('x = '); }) .getline(function (line, vars) { vars.x = parseInt(line, 10); }) .do(function () { util.print('y = '); }) .getline(function (line, vars) { vars.y = parseInt(line, 10); }) .do(function (vars) { if (vars.x + vars.y < 10) { util.print('z = '); this.getline(function (line) { vars.z = parseInt(line, 10); }) } else { vars.z = 0; } }) .do(function (vars) { console.log('x + y + z = ' + (vars.x + vars.y + vars.z)); process.exit(); }) ; Installation ============ With [npm](http://github.com/isaacs/npm), just do: npm install chainsaw or clone this project on github: git clone http://github.com/substack/node-chainsaw.git To run the tests with [expresso](http://github.com/visionmedia/expresso), just do: expresso Light Mode vs Full Mode ======================= `node-chainsaw` supports two different modes. In full mode, every action is recorded, which allows you to replay actions using the `jump()`, `trap()` and `down()` methods. However, if your chainsaws are long-lived, recording every action can consume a tremendous amount of memory, so we also offer a "light" mode where actions are not recorded and the aforementioned methods are disabled. To enable light mode simply use `Chainsaw.light()` to construct your saw, instead of `Chainsaw()`.
{ "pile_set_name": "Github" }
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to [email protected] so we can send you a copy immediately. * * @category Zend * @package Zend_Media * @subpackage ID3 * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id: Tmcl.php 177 2010-03-09 13:13:34Z svollbehr $ * @since ID3v2.4.0 */ /**#@+ @ignore */ require_once 'Zend/Media/Id3/TextFrame.php'; /**#@-*/ /** * The <i>Musician credits list</i> is intended as a mapping between instruments * and the musician that played it. Every odd field is an instrument and every * even is an artist or a comma delimited list of artists. * * @todo Implement better support * @category Zend * @package Zend_Media * @subpackage ID3 * @author Sven Vollbehr <[email protected]> * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id: Tmcl.php 177 2010-03-09 13:13:34Z svollbehr $ * @since ID3v2.4.0 */ final class Zend_Media_Id3_Frame_Tmcl extends Zend_Media_Id3_TextFrame {}
{ "pile_set_name": "Github" }
#!/usr/bin/perl ## ## Copyright (C) 2002-2008, Marcelo E. Magallon <mmagallo[]debian org> ## Copyright (C) 2002-2008, Milan Ikits <milan ikits[]ieee org> ## ## This program is distributed under the terms and conditions of the GNU ## General Public License Version 2 as published by the Free Software ## Foundation or, at your option, any later version. use strict; use warnings; do 'bin/make.pl'; my @extlist = (); my %extensions = (); if (@ARGV) { @extlist = @ARGV; my $curexttype = ""; foreach my $ext (sort @extlist) { my ($extname, $exturl, $extstring, $types, $tokens, $functions, $exacts) = parse_ext($ext); my $exttype = $extname; $exttype =~ s/(W*?)GL(X*?)_(.*?_)(.*)/$3/; my $extrem = $extname; $extrem =~ s/(W*?)GL(X*?)_(.*?_)(.*)/$4/; my $extvar = $extname; $extvar =~ s/(W*)GL(X*)_/$1GL$2EW_/; if(!($exttype =~ $curexttype)) { if(length($curexttype) > 0) { print " }\n"; } print " if (_glewStrSame2(&pos, &len, (const GLubyte*)\"$exttype\", " . length($exttype) . "))\n"; print " {\n"; $curexttype = $exttype; } print "#ifdef $extname\n"; print " if (_glewStrSame3(&pos, &len, (const GLubyte*)\"$extrem\", ". length($extrem) . "))\n"; #print " return $extvar;\n"; print " {\n"; print " ret = $extvar;\n"; print " continue;\n"; print " }\n"; print "#endif\n"; } print " }\n"; }
{ "pile_set_name": "Github" }
// Copyright 2019 The Bazel Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // package com.google.devtools.build.lib.bazel.rules.ninja.parser; import static com.google.common.base.Strings.nullToEmpty; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSortedMap; import com.google.common.collect.Interner; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.devtools.build.lib.util.Pair; import java.util.ArrayDeque; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.NavigableMap; import java.util.function.Consumer; import java.util.function.Function; import javax.annotation.Nullable; /** * Ninja file scope to keep all defined variables and rules according to the order of their * definition (and redefinition). */ public class NinjaScope { /** Parent scope for the case of subninja/include command */ @Nullable private final NinjaScope parentScope; /** If include command was used for the current scope, the offset of that include command */ @Nullable private final Long includePoint; private final NavigableMap<Long, NinjaScope> includedScopes; private final NavigableMap<Long, NinjaScope> subNinjaScopes; private Map<String, List<Pair<Long, String>>> expandedVariables; private final Map<String, List<Pair<Long, NinjaRule>>> rules; private final Map<String, List<Pair<Long, NinjaPool>>> pools; public NinjaScope() { this(null, null); } private NinjaScope(@Nullable NinjaScope parentScope, @Nullable Long includePoint) { this.parentScope = parentScope; this.includePoint = includePoint; this.rules = Maps.newTreeMap(); this.pools = Maps.newTreeMap(); this.includedScopes = Maps.newTreeMap(); this.subNinjaScopes = Maps.newTreeMap(); this.expandedVariables = Maps.newHashMap(); } public void setRules(Map<String, List<Pair<Long, NinjaRule>>> rules) { this.rules.putAll(rules); } public void setPools(Map<String, List<Pair<Long, NinjaPool>>> pools) { this.pools.putAll(pools); } @VisibleForTesting public Map<String, List<Pair<Long, NinjaRule>>> getRules() { return rules; } @VisibleForTesting public Map<String, List<Pair<Long, NinjaPool>>> getPools() { return pools; } public Collection<NinjaScope> getIncludedScopes() { return includedScopes.values(); } public Collection<NinjaScope> getSubNinjaScopes() { return subNinjaScopes.values(); } /** * Expands variable value at the given offset. If some of the variable references, used in the * value, can not be found, uses an empty string as their value. */ public String getExpandedValue(long offset, NinjaVariableValue value) { // Cache expanded variables values to save time replacing several references to the same // variable. // This cache is local to the offset, it depends on the offset of the variable we are expanding. Map<String, String> cache = Maps.newHashMap(); // We are using the start offset of the value holding the reference to the variable. // Do the same as Ninja implementation: if the variable is not found, use empty string. Function<String, String> expander = ref -> cache.computeIfAbsent(ref, (key) -> nullToEmpty(findExpandedVariable(offset, key))); return value.getExpandedValue(expander); } /** * Partially expands variable value at the given offset. If some of the variable references, used * in the value, can not be found, they are left unexpanded. */ public NinjaVariableValue getReducedValue( long offset, NinjaVariableValue value, ImmutableSet<String> variablesToNotExpand, Interner<String> interner) { // Cache expanded variables values to save time replacing several references to the same // variable. // This cache is local to the offset, it depends on the offset of the variable we are expanding. Map<String, String> cache = Maps.newHashMap(); // We are using the start offset of the value holding the reference to the variable. // Do the same as Ninja implementation: if the variable is not found, use empty string. Function<String, String> expander = ref -> computeExpandedString(offset, ref, cache, variablesToNotExpand, interner); return value.reduce(expander); } private String computeExpandedString( long offset, String key, Map<String, String> cache, ImmutableSet<String> variablesToNotExpand, Interner<String> interner) { String cachedValue = cache.get(key); if (cachedValue != null) { return cachedValue; } if (variablesToNotExpand.contains(key)) { return null; } String expandedValue = findExpandedVariable(offset, key); // It's very important an interner is used here, as there is considerable duplication of // string literals in expanded rule-variable-parts over the course of a large build. return expandedValue == null ? null : interner.intern(expandedValue); } public void addExpandedVariable(Long offset, String name, String value) { expandedVariables.computeIfAbsent(name, k -> Lists.newArrayList()).add(Pair.of(offset, value)); } public NinjaScope addIncluded(Long offset) { NinjaScope scope = new NinjaScope(this, offset); includedScopes.put(offset, scope); return scope; } public NinjaScope addSubNinja(Long offset) { NinjaScope scope = new NinjaScope(this, offset); subNinjaScopes.put(offset, scope); return scope; } /** * Finds expanded variable with the name <code>name</code> to be used in the reference to it at * <code>offset</code>. Returns null if nothing was found. */ @Nullable public String findExpandedVariable(long offset, String name) { return findByNameAndOffsetRecursively(offset, name, scope -> scope.expandedVariables); } /** * Finds a rule with the name <code>name</code> to be used in the reference to it at <code>offset * </code>. Returns null if nothing was found. */ @Nullable public NinjaRule findRule(long offset, String name) { return findByNameAndOffsetRecursively(offset, name, scope -> scope.rules); } /** * Finds a variable or rule with the name <code>name</code> to be used in the reference to it at * <code>offset</code>. * * <p>The following checks are made: - the last definition of variable/rule before the offset in * the current scope is looked up. - the last definition of variable/rule inside the relevant * included scopes (i.e. in the files from include statements before offset) * * <p>If any of the definitions are found in the current or included scopes, the value with the * largest offset is returned. * * <p>If nothing is found, we make an attempt to find the definition in the parent scope at offset * before the offset at which the current scope was introduced to parent. * * <p>If no definition was found, we return null. */ @Nullable private <T> T findByNameAndOffsetRecursively( long offset, String name, Function<NinjaScope, Map<String, List<Pair<Long, T>>>> mapSupplier) { Pair<Long, T> currentScopeValue = findByNameAndOffset(offset, name, this, mapSupplier); Long currentScopeOffset = currentScopeValue != null ? Preconditions.checkNotNull(currentScopeValue.getFirst()) : -1L; // Search in included scopes, which were included after the current scope, so they could // override the value, but before the reference offset. NavigableMap<Long, NinjaScope> subMap = includedScopes.subMap(currentScopeOffset, false, offset, false); // Search in descending order, so that the first found value is the result. for (NinjaScope includedScope : subMap.descendingMap().values()) { T includedValue = includedScope.findByNameAndOffsetRecursively(Long.MAX_VALUE, name, mapSupplier); if (includedValue != null) { return includedValue; } } if (currentScopeValue != null) { return currentScopeValue.getSecond(); } if (parentScope != null) { Preconditions.checkNotNull(includePoint); // -1 is used in order not to conflict with the current scope. return parentScope.findByNameAndOffsetRecursively(includePoint - 1, name, mapSupplier); } return null; } /** * Finds the variable or rule with the name <code>name</code>, defined in the current scope before * the <code>offset</code>. (Ninja allows to re-define the values of rules and variables.) */ @Nullable private static <T> Pair<Long, T> findByNameAndOffset( long offset, String name, NinjaScope scope, Function<NinjaScope, Map<String, List<Pair<Long, T>>>> mapFunction) { List<Pair<Long, T>> pairs = Preconditions.checkNotNull(mapFunction.apply(scope)).get(name); if (pairs == null) { // We may want to search in the parent scope. return null; } int insertionPoint = Collections.binarySearch( pairs, Pair.of(offset, null), Comparator.comparing(Pair::getFirst)); if (insertionPoint >= 0) { // Can not be, variable can not be defined in exactly same place. throw new IllegalStateException("Trying to interpret declaration as reference."); } // We need to access the previous element, before the insertion point. int idx = -insertionPoint - 2; if (idx < 0) { // Check the parent scope. return null; } Pair<Long, T> pair = pairs.get(idx); return Pair.of(pair.getFirst(), pair.getSecond()); } public NinjaScope createScopeFromExpandedValues( ImmutableSortedMap<String, List<Pair<Long, String>>> expandedVariables) { NinjaScope scope = new NinjaScope(this, Long.MAX_VALUE); scope.expandedVariables.putAll(expandedVariables); return scope; } public void iterate(Consumer<NinjaScope> consumer) { ArrayDeque<NinjaScope> queue = new ArrayDeque<>(); queue.add(this); while (!queue.isEmpty()) { NinjaScope currentScope = queue.removeFirst(); consumer.accept(currentScope); queue.addAll(currentScope.getIncludedScopes()); queue.addAll(currentScope.getSubNinjaScopes()); } } }
{ "pile_set_name": "Github" }
<a href='http://github.com/angular/angular.js/edit/master/src/ng/cacheFactory.js' class='improve-docs btn btn-primary'><i class="glyphicon glyphicon-edit">&nbsp;</i>Improve this doc</a> <a href='http://github.com/angular/angular.js/tree/master/src/ng/cacheFactory.js#L102' class='view-source pull-right btn btn-primary'> <i class="glyphicon glyphicon-zoom-in">&nbsp;</i>View Source </a> <header class="api-profile-header"> <h1 class="api-profile-header-heading">$cacheFactory.Cache</h1> <ol class="api-profile-header-structure naked-list step-list"> <li> - type in module <a href="api/ng">ng</a> </li> </ol> </header> <div class="api-profile-description"> <p>A cache object used to store and retrieve data, primarily used by <a href="api/ng/service/$http">$http</a> and the <a href="api/ng/directive/script">script</a> directive to cache templates and other data.</p> <pre><code class="lang-js"> angular.module(&#39;superCache&#39;) .factory(&#39;superCache&#39;, [&#39;$cacheFactory&#39;, function($cacheFactory) { return $cacheFactory(&#39;super-cache&#39;); }]);</code></pre> <p>Example test:</p> <pre><code class="lang-js"> it(&#39;should behave like a cache&#39;, inject(function(superCache) { superCache.put(&#39;key&#39;, &#39;value&#39;); superCache.put(&#39;another key&#39;, &#39;another value&#39;); expect(superCache.info()).toEqual({ id: &#39;super-cache&#39;, size: 2 }); superCache.remove(&#39;another key&#39;); expect(superCache.get(&#39;another key&#39;)).toBeUndefined(); superCache.removeAll(); expect(superCache.info()).toEqual({ id: &#39;super-cache&#39;, size: 0 }); }));</code></pre> </div> <div> <h2>Methods</h2> <ul class="methods"> <li id="put"> <h3><p><code>put(key, value);</code></p> </h3> <div><p>Inserts a named entry into the <a href="api/ng/type/$cacheFactory.Cache">Cache</a> object to be retrieved later, and incrementing the size of the cache if the key was not already present in the cache. If behaving like an LRU cache, it will also remove stale entries from the set.</p> <p>It will not insert undefined values into the cache.</p> </div> <h4>Parameters</h4> <table class="variables-matrix input-arguments"> <thead> <tr> <th>Param</th> <th>Type</th> <th>Details</th> </tr> </thead> <tbody> <tr> <td> key </td> <td> <a href="" class="label type-hint type-hint-string">string</a> </td> <td> <p>the key under which the cached data is stored.</p> </td> </tr> <tr> <td> value </td> <td> <a href="" class="label type-hint type-hint-object">*</a> </td> <td> <p>the value to store alongside the key. If it is undefined, the key will not be stored.</p> </td> </tr> </tbody> </table> <h4>Returns</h4> <table class="variables-matrix return-arguments"> <tr> <td><a href="" class="label type-hint type-hint-object">*</a></td> <td><p>the value stored.</p> </td> </tr> </table> </li> <li id="get"> <h3><p><code>get(key);</code></p> </h3> <div><p>Retrieves named data stored in the <a href="api/ng/type/$cacheFactory.Cache">Cache</a> object.</p> </div> <h4>Parameters</h4> <table class="variables-matrix input-arguments"> <thead> <tr> <th>Param</th> <th>Type</th> <th>Details</th> </tr> </thead> <tbody> <tr> <td> key </td> <td> <a href="" class="label type-hint type-hint-string">string</a> </td> <td> <p>the key of the data to be retrieved</p> </td> </tr> </tbody> </table> <h4>Returns</h4> <table class="variables-matrix return-arguments"> <tr> <td><a href="" class="label type-hint type-hint-object">*</a></td> <td><p>the value stored.</p> </td> </tr> </table> </li> <li id="remove"> <h3><p><code>remove(key);</code></p> </h3> <div><p>Removes an entry from the <a href="api/ng/type/$cacheFactory.Cache">Cache</a> object.</p> </div> <h4>Parameters</h4> <table class="variables-matrix input-arguments"> <thead> <tr> <th>Param</th> <th>Type</th> <th>Details</th> </tr> </thead> <tbody> <tr> <td> key </td> <td> <a href="" class="label type-hint type-hint-string">string</a> </td> <td> <p>the key of the entry to be removed</p> </td> </tr> </tbody> </table> </li> <li id="removeAll"> <h3><p><code>removeAll();</code></p> </h3> <div><p>Clears the cache object of any entries.</p> </div> </li> <li id="destroy"> <h3><p><code>destroy();</code></p> </h3> <div><p>Destroys the <a href="api/ng/type/$cacheFactory.Cache">Cache</a> object entirely, removing it from the <a href="api/ng/service/$cacheFactory">$cacheFactory</a> set.</p> </div> </li> <li id="info"> <h3><p><code>info();</code></p> </h3> <div><p>Retrieve information regarding a particular <a href="api/ng/type/$cacheFactory.Cache">Cache</a>.</p> </div> <h4>Returns</h4> <table class="variables-matrix return-arguments"> <tr> <td><a href="" class="label type-hint type-hint-object">object</a></td> <td><p>an object with the following properties: <ul> <li><strong>id</strong>: the id of the cache instance</li> <li><strong>size</strong>: the number of entries kept in the cache instance</li> <li><strong>...</strong>: any additional properties from the options object when creating the cache.</li> </ul></p> </td> </tr> </table> </li> </ul> </div>
{ "pile_set_name": "Github" }
/* * Copyright 1999-2007 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, * CA 95054 USA or visit www.sun.com if you need additional information or * have any questions. */ package java.math; /** * A simple bit sieve used for finding prime number candidates. Allows setting * and clearing of bits in a storage array. The size of the sieve is assumed to * be constant to reduce overhead. All the bits of a new bitSieve are zero, and * bits are removed from it by setting them. * * To reduce storage space and increase efficiency, no even numbers are * represented in the sieve (each bit in the sieve represents an odd number). * The relationship between the index of a bit and the number it represents is * given by * N = offset + (2*index + 1); * Where N is the integer represented by a bit in the sieve, offset is some * even integer offset indicating where the sieve begins, and index is the * index of a bit in the sieve array. * * @see BigInteger * @author Michael McCloskey * @since 1.3 */ class BitSieve { /** * Stores the bits in this bitSieve. */ private long bits[]; /** * Length is how many bits this sieve holds. */ private int length; /** * A small sieve used to filter out multiples of small primes in a search * sieve. */ private static BitSieve smallSieve = new BitSieve(); /** * Construct a "small sieve" with a base of 0. This constructor is * used internally to generate the set of "small primes" whose multiples * are excluded from sieves generated by the main (package private) * constructor, BitSieve(BigInteger base, int searchLen). The length * of the sieve generated by this constructor was chosen for performance; * it controls a tradeoff between how much time is spent constructing * other sieves, and how much time is wasted testing composite candidates * for primality. The length was chosen experimentally to yield good * performance. */ private BitSieve() { length = 150 * 64; bits = new long[(unitIndex(length - 1) + 1)]; // Mark 1 as composite set(0); int nextIndex = 1; int nextPrime = 3; // Find primes and remove their multiples from sieve do { sieveSingle(length, nextIndex + nextPrime, nextPrime); nextIndex = sieveSearch(length, nextIndex + 1); nextPrime = 2*nextIndex + 1; } while((nextIndex > 0) && (nextPrime < length)); } /** * Construct a bit sieve of searchLen bits used for finding prime number * candidates. The new sieve begins at the specified base, which must * be even. */ BitSieve(BigInteger base, int searchLen) { /* * Candidates are indicated by clear bits in the sieve. As a candidates * nonprimality is calculated, a bit is set in the sieve to eliminate * it. To reduce storage space and increase efficiency, no even numbers * are represented in the sieve (each bit in the sieve represents an * odd number). */ bits = new long[(unitIndex(searchLen-1) + 1)]; length = searchLen; int start = 0; int step = smallSieve.sieveSearch(smallSieve.length, start); int convertedStep = (step *2) + 1; // Construct the large sieve at an even offset specified by base MutableBigInteger r = new MutableBigInteger(); MutableBigInteger q = new MutableBigInteger(); do { // Calculate base mod convertedStep r.copyValue(base.mag); r.divideOneWord(convertedStep, q); start = r.value[r.offset]; // Take each multiple of step out of sieve start = convertedStep - start; if (start%2 == 0) start += convertedStep; sieveSingle(searchLen, (start-1)/2, convertedStep); // Find next prime from small sieve step = smallSieve.sieveSearch(smallSieve.length, step+1); convertedStep = (step *2) + 1; } while (step > 0); } /** * Given a bit index return unit index containing it. */ private static int unitIndex(int bitIndex) { return bitIndex >>> 6; } /** * Return a unit that masks the specified bit in its unit. */ private static long bit(int bitIndex) { return 1L << (bitIndex & ((1<<6) - 1)); } /** * Get the value of the bit at the specified index. */ private boolean get(int bitIndex) { int unitIndex = unitIndex(bitIndex); return ((bits[unitIndex] & bit(bitIndex)) != 0); } /** * Set the bit at the specified index. */ private void set(int bitIndex) { int unitIndex = unitIndex(bitIndex); bits[unitIndex] |= bit(bitIndex); } /** * This method returns the index of the first clear bit in the search * array that occurs at or after start. It will not search past the * specified limit. It returns -1 if there is no such clear bit. */ private int sieveSearch(int limit, int start) { if (start >= limit) return -1; int index = start; do { if (!get(index)) return index; index++; } while(index < limit-1); return -1; } /** * Sieve a single set of multiples out of the sieve. Begin to remove * multiples of the specified step starting at the specified start index, * up to the specified limit. */ private void sieveSingle(int limit, int start, int step) { while(start < limit) { set(start); start += step; } } /** * Test probable primes in the sieve and return successful candidates. */ BigInteger retrieve(BigInteger initValue, int certainty, java.util.Random random) { // Examine the sieve one long at a time to find possible primes int offset = 1; for (int i=0; i<bits.length; i++) { long nextLong = ~bits[i]; for (int j=0; j<64; j++) { if ((nextLong & 1) == 1) { BigInteger candidate = initValue.add( BigInteger.valueOf(offset)); if (candidate.primeToCertainty(certainty, random)) return candidate; } nextLong >>>= 1; offset+=2; } } return null; } }
{ "pile_set_name": "Github" }
module Admin::IpPoolsHelper end
{ "pile_set_name": "Github" }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. #include <stdint.h> #include <stdlib.h> #include "azure_c_shared_utility/threadapi.h" #include "azure_c_shared_utility/xlogging.h" DEFINE_ENUM_STRINGS(THREADAPI_RESULT, THREADAPI_RESULT_VALUES); THREADAPI_RESULT ThreadAPI_Create(THREAD_HANDLE* threadHandle, THREAD_START_FUNC func, void* arg) { LogError("ESP8266 RTOS does not support multi-thread function."); return THREADAPI_ERROR; } THREADAPI_RESULT ThreadAPI_Join(THREAD_HANDLE threadHandle, int* res) { LogError("ESP8266 RTOS does not support multi-thread function."); return THREADAPI_ERROR; } void ThreadAPI_Exit(int res) { vTaskDelete(NULL); } void ThreadAPI_Sleep(unsigned int milliseconds) { vTaskDelay(milliseconds); }
{ "pile_set_name": "Github" }
package com.tagtraum.perf.gcviewer.imp; import static org.junit.Assert.assertEquals; import java.io.InputStream; import com.tagtraum.perf.gcviewer.UnittestHelper; import com.tagtraum.perf.gcviewer.UnittestHelper.FOLDER; import com.tagtraum.perf.gcviewer.model.GCModel; import com.tagtraum.perf.gcviewer.model.GcResourceFile; import org.junit.Test; /** * * Date: Jan 30, 2002 * Time: 5:53:55 PM * @author <a href="mailto:[email protected]">Hendrik Schreiber</a> */ public class TestDataReaderHPUX1_2 { @Test public void testParse1() throws Exception { String fileName = "SampleHP-UX1_3.txt"; InputStream in = UnittestHelper.getResourceAsStream(FOLDER.HP, fileName); DataReader reader = new DataReaderHPUX1_2(new GcResourceFile(fileName), in); GCModel model = reader.read(); assertEquals("number of events", 135, model.size()); } }
{ "pile_set_name": "Github" }
function result = set_concat(varargin) % Concatenate continuous signals across time. % Result = set_joinepos(Set1, Set2, ...) % % In: % SetK : The k'th data set to concatenate. % % Out: % Result : A new data set that is the concatenation of all input sets. The following changes are made: % * .data and all other time-series fields are concatenated across time (2nd dimension) % * .event is joined and .latency fields are updated appropriately % * .xmax/.pnts are updated % % Notes: % This function returns a new data set with meta-data set to that of the first input set, and the % time series fields joined across all sets. No checks for meta-data consistency are done. There % is a heavy-duty function for merging inconsistent sets called set_merge, which can merge cats % and dogs. This function does not attempt to keep miscellaneous EEGLAB meta-data consistent, % including: setname,filename,filepath,subject,group,condition,session,comments,urevent,reject,stats,history,etc % % Examples: % % concatenate data sets eegA, eegB and eegC across time % eeg = set_concat(eegA,eegB,eegC) % % See also: % set_joinepos, set_merge % % Christian Kothe, Swartz Center for Computational Neuroscience, UCSD % 2010-03-31 dp; % set_concat_version<1.0> -- for the cache if ~exp_beginfun('editing') return; end declare_properties('name','Concatenate','independent_channels',true,'independent_trials',false); % input validation for k=1:length(varargin) utl_check_fields(varargin{k},{'data','event','pnts','xmin','xmax','srate'},'input','signal'); if ~isempty(varargin{k}.event) if ~isfield(varargin{k}.event,'latency') error('A dataset passed to set_concat is lacking the .event.latency field.'); end latency_numels = cellfun('prodofsize',{varargin{k}.event.latency}); if any(latency_numels == 0) error('One or more of the events in the given data set have an empty .latency field, which is not permitted.'); end if any(latency_numels ~= 1) error('One or more of the events in the given data set have a .latency value that is not a scalar, which is not permitted.'); end end if isfield(varargin{k},'epoch') && ~isempty(varargin{k}.epoch) error('Only continuous data can be concatenated with set_concat -- use set_joinepos for epoched data.'); end end if ~isempty(varargin) result = varargin{1}; if length(varargin) > 1 % concatenate time series fields for field = utl_timeseries_fields(result) data = cellfun(@(x)x.(field{1}),varargin,'UniformOutput',false); try result.(field{1}) = cat(2,data{:}); catch e % concatenation failed: produce a reasonable error message if ~isempty(data) sizes = cellfun('size',data,1); sizes = sizes(sizes ~= 0); if length(sizes) > 1 && ~all(sizes==sizes(1)) error('The time-series field .%s must have the same number of channels in each data set.',field{1}); end if any(cellfun('size',data,3) > 1) error('One or more of the datasets passed to set_concat were epoched -- use set_joinepos to concatenate epoched data.'); end end size_info = hlp_tostring(cellfun(@size,data,'UniformOutput',false)); error('Concatenation of time-series fields failed with error: %s (the data sizes were %s -- make sure that they are mutually compatible).',e.message,size_info); end if isempty(result.(field{1})) result.(field{1}) = []; end end % count events, epochs and samples in each set event_count = cellfun(@(x)length(x.event),varargin); sample_count = cellfun(@(x)x.pnts,varargin); % concatenate .event and .epoch fields event = cellfun(@(x)x.event,varargin,'UniformOutput',false); result.event = [event{:}]; % shift event latencies based on cumulative sample counts if ~isempty(result.event) [result.event.latency] = arraydeal([result.event.latency]+replicate(cumsum(sample_count)-sample_count,event_count)); end % update misc fields [result.nbchan,result.pnts,result.trials,extra_dims] = size(result.data); %#ok<ASGLU,NASGU> result.xmax = result.xmin + (result.pnts-1)/result.srate; end else result = struct('setname','','filename','','filepath','','subject','','group','','condition','','session',[],'comments','','nbchan',0,... 'trials',0,'pnts',0,'srate',1,'xmin',0,'xmax',0,'times',[],'data',[],'icaact',[],'icawinv',[],'icasphere',[],'icaweights',[], ... 'icachansind',[],'chanlocs',[],'urchanlocs',[],'chaninfo',[],'ref',[],'event',[],'urevent',[],'eventdescription',{{}}, ... 'epoch',[],'epochdescription',{{}},'reject',[],'stats',[],'specdata',[],'specicaact',[],'splinefile','','icasplinefile','', ... 'dipfit',[],'history','','saved','no','etc',[]); end exp_endfun; function result = replicate(values,counts) % Replicate each element Values(k) by Count(k) times. result = zeros(1,sum(counts)); k = 0; for p=find(counts) result(k+(1:counts(p))) = values(p); k = k+counts(p); end
{ "pile_set_name": "Github" }
""" ``mifs`` is a Parallelized Mutual Information based Feature Selection module. """ # Based on NiLearn package # License: simplified BSD # PEP0440 compatible formatted version, see: # https://www.python.org/dev/peps/pep-0440/ # # Generic release markers: # X.Y # X.Y.Z # For bugfix releases # # Admissible pre-release markers: # X.YaN # Alpha release # X.YbN # Beta release # X.YrcN # Release Candidate # X.Y # Final release # # Dev branch marker is: 'X.Y.dev' or 'X.Y.devN' where N is an integer. # 'X.Y.dev0' is the canonical version of 'X.Y.dev' # __version__ = '0.0.1.dev0' _MIFS_DATASET_INSTALL_MSG = 'See %s for installation information.' % ( 'https://github.com/glemaitre/mifs') # This is a tuple to preserve order, so that dependencies are checked # in some meaningful order (more => less 'core'). We avoid using # collections.OrderedDict to preserve Python 2.6 compatibility. REQUIRED_MODULE_METADATA = ( ('numpy', { 'min_version': '1.10.4', 'required_at_installation': True, 'install_info': _MIFS_DATASET_INSTALL_MSG}), ('scipy', { 'min_version': '0.17.0', 'required_at_installation': True, 'install_info': _MIFS_DATASET_INSTALL_MSG}), ('sklearn', { 'min_version': '0.17.1', 'required_at_installation': True, 'install_info': _MIFS_DATASET_INSTALL_MSG}), ('bottleneck', { 'min_version': '1.0.0', 'required_at_installation': True, 'install_info': _MIFS_DATASET_INSTALL_MSG})) def _import_module_with_version_check(module_name, minimum_version, install_info=None): """Check that module is installed with a recent enough version """ from distutils.version import LooseVersion try: module = __import__(module_name) except ImportError as exc: user_friendly_info = ('Module "{0}" could not be found. {1}').format( module_name, install_info or 'Please install it properly to use' ' imbalanced-learn.') exc.args += (user_friendly_info,) raise # Avoid choking on modules with no __version__ attribute module_version = getattr(module, '__version__', '0.0.0') version_too_old = (not LooseVersion(module_version) >= LooseVersion(minimum_version)) if version_too_old: message = ( 'A {module_name} version of at least {minimum_version} ' 'is required to use imbalanced-learn. {module_version} was ' 'found. Please upgrade {module_name}').format( module_name=module_name, minimum_version=minimum_version, module_version=module_version) raise ImportError(message) return module def _check_module_dependencies(is_imbalanced_dataset_installing=False): """Throw an exception if imbalanced-learn dependencies are not installed. Parameters ---------- is_imbalanced_dataset_installing: boolean if True, only error on missing packages that cannot be auto-installed. if False, error on any missing package. Throws ------- ImportError """ for (module_name, module_metadata) in REQUIRED_MODULE_METADATA: if not (is_imbalanced_dataset_installing and not module_metadata['required_at_installation']): # Skip check only when installing and it's a module that # will be auto-installed. _import_module_with_version_check( module_name=module_name, minimum_version=module_metadata['min_version'], install_info=module_metadata.get('install_info'))
{ "pile_set_name": "Github" }
import os import sys from configobj import ConfigObj from ._base import BaseFinder, BaseLoader, InvalidIniError class IniFinder(BaseFinder): def __init__(self, *args, **kwargs): self.ext_name = ".ini" super(IniFinder, self).__init__(*args, **kwargs) def find_module(self, fullname, path=None): cfg_file = self.get_cfg_filepath(fullname) if os.path.isfile(cfg_file + self.ext_name): return IniLoader(cfg_file + self.ext_name) else: return None class IniLoader(BaseLoader): def __init__(self, cfg_file, *args, **kwargs): self.e = None self.err_msg = None self.cfg_file = cfg_file super(IniLoader, self).__init__(*args, **kwargs) def load_module(self, fullname): mod = super(IniLoader, self).load_module(fullname) try: config = ConfigObj(self.cfg_file, encoding='UTF8', raise_errors=True) mod.__dict__.update(dict((k, config[k]) for k in config.keys())) except SyntaxError: self.e = "IniError" self.err_msg = sys.exc_info()[1] if self.e == "IniError": err_msg = "\nIni file not valid: " err_msg += self.cfg_file + '\n' err_msg += str(self.err_msg) raise InvalidIniError(err_msg) return mod
{ "pile_set_name": "Github" }
/* * Samsung exynos4210 Pulse Width Modulation Timer * * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. * All rights reserved. * * Evgeny Voevodin <[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. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see <http://www.gnu.org/licenses/>. */ #include "qemu/osdep.h" #include "qemu/log.h" #include "hw/sysbus.h" #include "migration/vmstate.h" #include "qemu/timer.h" #include "qemu/module.h" #include "hw/ptimer.h" #include "hw/arm/exynos4210.h" #include "hw/irq.h" #include "qom/object.h" //#define DEBUG_PWM #ifdef DEBUG_PWM #define DPRINTF(fmt, ...) \ do { fprintf(stdout, "PWM: [%24s:%5d] " fmt, __func__, __LINE__, \ ## __VA_ARGS__); } while (0) #else #define DPRINTF(fmt, ...) do {} while (0) #endif #define EXYNOS4210_PWM_TIMERS_NUM 5 #define EXYNOS4210_PWM_REG_MEM_SIZE 0x50 #define TCFG0 0x0000 #define TCFG1 0x0004 #define TCON 0x0008 #define TCNTB0 0x000C #define TCMPB0 0x0010 #define TCNTO0 0x0014 #define TCNTB1 0x0018 #define TCMPB1 0x001C #define TCNTO1 0x0020 #define TCNTB2 0x0024 #define TCMPB2 0x0028 #define TCNTO2 0x002C #define TCNTB3 0x0030 #define TCMPB3 0x0034 #define TCNTO3 0x0038 #define TCNTB4 0x003C #define TCNTO4 0x0040 #define TINT_CSTAT 0x0044 #define TCNTB(x) (0xC * (x)) #define TCMPB(x) (0xC * (x) + 1) #define TCNTO(x) (0xC * (x) + 2) #define GET_PRESCALER(reg, x) (((reg) & (0xFF << (8 * (x)))) >> 8 * (x)) #define GET_DIVIDER(reg, x) (1 << (((reg) & (0xF << (4 * (x)))) >> (4 * (x)))) /* * Attention! Timer4 doesn't have OUTPUT_INVERTER, * so Auto Reload bit is not accessible by macros! */ #define TCON_TIMER_BASE(x) (((x) ? 1 : 0) * 4 + 4 * (x)) #define TCON_TIMER_START(x) (1 << (TCON_TIMER_BASE(x) + 0)) #define TCON_TIMER_MANUAL_UPD(x) (1 << (TCON_TIMER_BASE(x) + 1)) #define TCON_TIMER_OUTPUT_INV(x) (1 << (TCON_TIMER_BASE(x) + 2)) #define TCON_TIMER_AUTO_RELOAD(x) (1 << (TCON_TIMER_BASE(x) + 3)) #define TCON_TIMER4_AUTO_RELOAD (1 << 22) #define TINT_CSTAT_STATUS(x) (1 << (5 + (x))) #define TINT_CSTAT_ENABLE(x) (1 << (x)) /* timer struct */ typedef struct { uint32_t id; /* timer id */ qemu_irq irq; /* local timer irq */ uint32_t freq; /* timer frequency */ /* use ptimer.c to represent count down timer */ ptimer_state *ptimer; /* timer */ /* registers */ uint32_t reg_tcntb; /* counter register buffer */ uint32_t reg_tcmpb; /* compare register buffer */ struct Exynos4210PWMState *parent; } Exynos4210PWM; #define TYPE_EXYNOS4210_PWM "exynos4210.pwm" OBJECT_DECLARE_SIMPLE_TYPE(Exynos4210PWMState, EXYNOS4210_PWM) struct Exynos4210PWMState { SysBusDevice parent_obj; MemoryRegion iomem; uint32_t reg_tcfg[2]; uint32_t reg_tcon; uint32_t reg_tint_cstat; Exynos4210PWM timer[EXYNOS4210_PWM_TIMERS_NUM]; }; /*** VMState ***/ static const VMStateDescription vmstate_exynos4210_pwm = { .name = "exynos4210.pwm.pwm", .version_id = 1, .minimum_version_id = 1, .fields = (VMStateField[]) { VMSTATE_UINT32(id, Exynos4210PWM), VMSTATE_UINT32(freq, Exynos4210PWM), VMSTATE_PTIMER(ptimer, Exynos4210PWM), VMSTATE_UINT32(reg_tcntb, Exynos4210PWM), VMSTATE_UINT32(reg_tcmpb, Exynos4210PWM), VMSTATE_END_OF_LIST() } }; static const VMStateDescription vmstate_exynos4210_pwm_state = { .name = "exynos4210.pwm", .version_id = 1, .minimum_version_id = 1, .fields = (VMStateField[]) { VMSTATE_UINT32_ARRAY(reg_tcfg, Exynos4210PWMState, 2), VMSTATE_UINT32(reg_tcon, Exynos4210PWMState), VMSTATE_UINT32(reg_tint_cstat, Exynos4210PWMState), VMSTATE_STRUCT_ARRAY(timer, Exynos4210PWMState, EXYNOS4210_PWM_TIMERS_NUM, 0, vmstate_exynos4210_pwm, Exynos4210PWM), VMSTATE_END_OF_LIST() } }; /* * PWM update frequency. * Must be called within a ptimer_transaction_begin/commit block * for s->timer[id].ptimer. */ static void exynos4210_pwm_update_freq(Exynos4210PWMState *s, uint32_t id) { uint32_t freq; freq = s->timer[id].freq; if (id > 1) { s->timer[id].freq = 24000000 / ((GET_PRESCALER(s->reg_tcfg[0], 1) + 1) * (GET_DIVIDER(s->reg_tcfg[1], id))); } else { s->timer[id].freq = 24000000 / ((GET_PRESCALER(s->reg_tcfg[0], 0) + 1) * (GET_DIVIDER(s->reg_tcfg[1], id))); } if (freq != s->timer[id].freq) { ptimer_set_freq(s->timer[id].ptimer, s->timer[id].freq); DPRINTF("freq=%dHz\n", s->timer[id].freq); } } /* * Counter tick handler */ static void exynos4210_pwm_tick(void *opaque) { Exynos4210PWM *s = (Exynos4210PWM *)opaque; Exynos4210PWMState *p = (Exynos4210PWMState *)s->parent; uint32_t id = s->id; bool cmp; DPRINTF("timer %d tick\n", id); /* set irq status */ p->reg_tint_cstat |= TINT_CSTAT_STATUS(id); /* raise IRQ */ if (p->reg_tint_cstat & TINT_CSTAT_ENABLE(id)) { DPRINTF("timer %d IRQ\n", id); qemu_irq_raise(p->timer[id].irq); } /* reload timer */ if (id != 4) { cmp = p->reg_tcon & TCON_TIMER_AUTO_RELOAD(id); } else { cmp = p->reg_tcon & TCON_TIMER4_AUTO_RELOAD; } if (cmp) { DPRINTF("auto reload timer %d count to %x\n", id, p->timer[id].reg_tcntb); ptimer_set_count(p->timer[id].ptimer, p->timer[id].reg_tcntb); ptimer_run(p->timer[id].ptimer, 1); } else { /* stop timer, set status to STOP, see Basic Timer Operation */ p->reg_tcon &= ~TCON_TIMER_START(id); ptimer_stop(p->timer[id].ptimer); } } /* * PWM Read */ static uint64_t exynos4210_pwm_read(void *opaque, hwaddr offset, unsigned size) { Exynos4210PWMState *s = (Exynos4210PWMState *)opaque; uint32_t value = 0; int index; switch (offset) { case TCFG0: case TCFG1: index = (offset - TCFG0) >> 2; value = s->reg_tcfg[index]; break; case TCON: value = s->reg_tcon; break; case TCNTB0: case TCNTB1: case TCNTB2: case TCNTB3: case TCNTB4: index = (offset - TCNTB0) / 0xC; value = s->timer[index].reg_tcntb; break; case TCMPB0: case TCMPB1: case TCMPB2: case TCMPB3: index = (offset - TCMPB0) / 0xC; value = s->timer[index].reg_tcmpb; break; case TCNTO0: case TCNTO1: case TCNTO2: case TCNTO3: case TCNTO4: index = (offset == TCNTO4) ? 4 : (offset - TCNTO0) / 0xC; value = ptimer_get_count(s->timer[index].ptimer); break; case TINT_CSTAT: value = s->reg_tint_cstat; break; default: qemu_log_mask(LOG_GUEST_ERROR, "exynos4210.pwm: bad read offset " TARGET_FMT_plx, offset); break; } return value; } /* * PWM Write */ static void exynos4210_pwm_write(void *opaque, hwaddr offset, uint64_t value, unsigned size) { Exynos4210PWMState *s = (Exynos4210PWMState *)opaque; int index; uint32_t new_val; int i; switch (offset) { case TCFG0: case TCFG1: index = (offset - TCFG0) >> 2; s->reg_tcfg[index] = value; /* update timers frequencies */ for (i = 0; i < EXYNOS4210_PWM_TIMERS_NUM; i++) { ptimer_transaction_begin(s->timer[i].ptimer); exynos4210_pwm_update_freq(s, s->timer[i].id); ptimer_transaction_commit(s->timer[i].ptimer); } break; case TCON: for (i = 0; i < EXYNOS4210_PWM_TIMERS_NUM; i++) { ptimer_transaction_begin(s->timer[i].ptimer); if ((value & TCON_TIMER_MANUAL_UPD(i)) > (s->reg_tcon & TCON_TIMER_MANUAL_UPD(i))) { /* * TCNTB and TCMPB are loaded into TCNT and TCMP. * Update timers. */ /* this will start timer to run, this ok, because * during processing start bit timer will be stopped * if needed */ ptimer_set_count(s->timer[i].ptimer, s->timer[i].reg_tcntb); DPRINTF("set timer %d count to %x\n", i, s->timer[i].reg_tcntb); } if ((value & TCON_TIMER_START(i)) > (s->reg_tcon & TCON_TIMER_START(i))) { /* changed to start */ ptimer_run(s->timer[i].ptimer, 1); DPRINTF("run timer %d\n", i); } if ((value & TCON_TIMER_START(i)) < (s->reg_tcon & TCON_TIMER_START(i))) { /* changed to stop */ ptimer_stop(s->timer[i].ptimer); DPRINTF("stop timer %d\n", i); } ptimer_transaction_commit(s->timer[i].ptimer); } s->reg_tcon = value; break; case TCNTB0: case TCNTB1: case TCNTB2: case TCNTB3: case TCNTB4: index = (offset - TCNTB0) / 0xC; s->timer[index].reg_tcntb = value; break; case TCMPB0: case TCMPB1: case TCMPB2: case TCMPB3: index = (offset - TCMPB0) / 0xC; s->timer[index].reg_tcmpb = value; break; case TINT_CSTAT: new_val = (s->reg_tint_cstat & 0x3E0) + (0x1F & value); new_val &= ~(0x3E0 & value); for (i = 0; i < EXYNOS4210_PWM_TIMERS_NUM; i++) { if ((new_val & TINT_CSTAT_STATUS(i)) < (s->reg_tint_cstat & TINT_CSTAT_STATUS(i))) { qemu_irq_lower(s->timer[i].irq); } } s->reg_tint_cstat = new_val; break; default: qemu_log_mask(LOG_GUEST_ERROR, "exynos4210.pwm: bad write offset " TARGET_FMT_plx, offset); break; } } /* * Set default values to timer fields and registers */ static void exynos4210_pwm_reset(DeviceState *d) { Exynos4210PWMState *s = EXYNOS4210_PWM(d); int i; s->reg_tcfg[0] = 0x0101; s->reg_tcfg[1] = 0x0; s->reg_tcon = 0; s->reg_tint_cstat = 0; for (i = 0; i < EXYNOS4210_PWM_TIMERS_NUM; i++) { s->timer[i].reg_tcmpb = 0; s->timer[i].reg_tcntb = 0; ptimer_transaction_begin(s->timer[i].ptimer); exynos4210_pwm_update_freq(s, s->timer[i].id); ptimer_stop(s->timer[i].ptimer); ptimer_transaction_commit(s->timer[i].ptimer); } } static const MemoryRegionOps exynos4210_pwm_ops = { .read = exynos4210_pwm_read, .write = exynos4210_pwm_write, .endianness = DEVICE_NATIVE_ENDIAN, }; /* * PWM timer initialization */ static void exynos4210_pwm_init(Object *obj) { Exynos4210PWMState *s = EXYNOS4210_PWM(obj); SysBusDevice *dev = SYS_BUS_DEVICE(obj); int i; for (i = 0; i < EXYNOS4210_PWM_TIMERS_NUM; i++) { sysbus_init_irq(dev, &s->timer[i].irq); s->timer[i].ptimer = ptimer_init(exynos4210_pwm_tick, &s->timer[i], PTIMER_POLICY_DEFAULT); s->timer[i].id = i; s->timer[i].parent = s; } memory_region_init_io(&s->iomem, obj, &exynos4210_pwm_ops, s, "exynos4210-pwm", EXYNOS4210_PWM_REG_MEM_SIZE); sysbus_init_mmio(dev, &s->iomem); } static void exynos4210_pwm_class_init(ObjectClass *klass, void *data) { DeviceClass *dc = DEVICE_CLASS(klass); dc->reset = exynos4210_pwm_reset; dc->vmsd = &vmstate_exynos4210_pwm_state; } static const TypeInfo exynos4210_pwm_info = { .name = TYPE_EXYNOS4210_PWM, .parent = TYPE_SYS_BUS_DEVICE, .instance_size = sizeof(Exynos4210PWMState), .instance_init = exynos4210_pwm_init, .class_init = exynos4210_pwm_class_init, }; static void exynos4210_pwm_register_types(void) { type_register_static(&exynos4210_pwm_info); } type_init(exynos4210_pwm_register_types)
{ "pile_set_name": "Github" }
package com.microsoft.cordova; import org.json.JSONObject; import java.io.File; /** * Model class for the CodePush metadata stored alongside a package deployment. */ public class CodePushPackageMetadata { public String deploymentKey; public String packageDescription; public String label; public String appVersion; public boolean isMandatory; public String packageHash; public long packageSize; public String nativeBuildTime; public String localPath; final static class JsonField { public static final String DeploymentKey = "deploymentKey"; public static final String Description = "description"; public static final String Label = "label"; public static final String AppVersion = "appVersion"; public static final String IsMandatory = "isMandatory"; public static final String PackageHash = "packageHash"; public static final String PackageSize = "packageSize"; public static final String NativeBuildTime = "nativeBuildTime"; public static final String LocalPath = "localPath"; } public static CodePushPackageMetadata getPackageMetadata(String filePath) { CodePushPackageMetadata result = null; try { File file = new File(filePath); if (file.exists()) { String content = Utilities.readFileContents(file); result = new CodePushPackageMetadata(); JSONObject jsonObject = new JSONObject(content); if (jsonObject.has(CodePushPackageMetadata.JsonField.DeploymentKey)) { result.deploymentKey = jsonObject.getString(CodePushPackageMetadata.JsonField.DeploymentKey); } if (jsonObject.has(CodePushPackageMetadata.JsonField.Description)) { result.packageDescription = jsonObject.getString(CodePushPackageMetadata.JsonField.Description); } if (jsonObject.has(CodePushPackageMetadata.JsonField.Label)) { result.label = jsonObject.getString(CodePushPackageMetadata.JsonField.Label); } if (jsonObject.has(CodePushPackageMetadata.JsonField.AppVersion)) { result.appVersion = jsonObject.getString(CodePushPackageMetadata.JsonField.AppVersion); } if (jsonObject.has(CodePushPackageMetadata.JsonField.IsMandatory)) { result.isMandatory = jsonObject.getBoolean(CodePushPackageMetadata.JsonField.IsMandatory); } if (jsonObject.has(CodePushPackageMetadata.JsonField.PackageHash)) { result.packageHash = jsonObject.getString(CodePushPackageMetadata.JsonField.PackageHash); } if (jsonObject.has(CodePushPackageMetadata.JsonField.PackageSize)) { result.packageSize = jsonObject.getLong(CodePushPackageMetadata.JsonField.PackageSize); } if (jsonObject.has(CodePushPackageMetadata.JsonField.NativeBuildTime)) { result.nativeBuildTime = jsonObject.getString(CodePushPackageMetadata.JsonField.NativeBuildTime); } if (jsonObject.has(CodePushPackageMetadata.JsonField.LocalPath)) { result.localPath = jsonObject.getString(CodePushPackageMetadata.JsonField.LocalPath); } } } catch (Exception e) { Utilities.logException(e); } return result; } }
{ "pile_set_name": "Github" }
/* * [The "BSD license"] * Copyright (c) 2011 Terence Parr * All rights reserved. * * Conversion to C#: * Copyright (c) 2011 Sam Harwell, Tunnel Vision Laboratories, LLC * All rights reserved. * * 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. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. */ namespace AntlrUnitTests { using Antlr.Runtime; using Antlr.Runtime.Tree; using Microsoft.VisualStudio.TestTools.UnitTesting; using CommonToken = Antlr.Runtime.CommonToken; using IToken = Antlr.Runtime.IToken; using StringBuilder = System.Text.StringBuilder; /** Test the tree node stream. */ [TestClass] public class TestTreeNodeStream : BaseTest { /** Build new stream; let's us override to test other streams. */ public virtual ITreeNodeStream newStream( object t ) { return new CommonTreeNodeStream( t ); } public virtual string ToTokenTypeString( ITreeNodeStream stream ) { return ( (CommonTreeNodeStream)stream ).ToTokenTypeString(); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestSingleNode() { ITree t = new CommonTree( new CommonToken( 101 ) ); ITreeNodeStream stream = newStream( t ); string expecting = " 101"; string found = ToNodesOnlyString( stream ); Assert.AreEqual( expecting, found ); expecting = " 101"; found = ToTokenTypeString( stream ); Assert.AreEqual( expecting, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void Test4Nodes() /*throws Exception*/ { // ^(101 ^(102 103) 104) ITree t = new CommonTree( new CommonToken( 101 ) ); t.AddChild( new CommonTree( new CommonToken( 102 ) ) ); t.GetChild( 0 ).AddChild( new CommonTree( new CommonToken( 103 ) ) ); t.AddChild( new CommonTree( new CommonToken( 104 ) ) ); ITreeNodeStream stream = newStream( t ); string expecting = " 101 102 103 104"; string found = ToNodesOnlyString( stream ); Assert.AreEqual( expecting, found ); expecting = " 101 2 102 2 103 3 104 3"; found = ToTokenTypeString( stream ); Assert.AreEqual( expecting, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestList() /*throws Exception*/ { ITree root = new CommonTree( (IToken)null ); ITree t = new CommonTree( new CommonToken( 101 ) ); t.AddChild( new CommonTree( new CommonToken( 102 ) ) ); t.GetChild( 0 ).AddChild( new CommonTree( new CommonToken( 103 ) ) ); t.AddChild( new CommonTree( new CommonToken( 104 ) ) ); ITree u = new CommonTree( new CommonToken( 105 ) ); root.AddChild( t ); root.AddChild( u ); ITreeNodeStream stream = newStream( root ); string expecting = " 101 102 103 104 105"; string found = ToNodesOnlyString( stream ); Assert.AreEqual( expecting, found ); expecting = " 101 2 102 2 103 3 104 3 105"; found = ToTokenTypeString( stream ); Assert.AreEqual( expecting, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestFlatList() /*throws Exception*/ { ITree root = new CommonTree( (IToken)null ); root.AddChild( new CommonTree( new CommonToken( 101 ) ) ); root.AddChild( new CommonTree( new CommonToken( 102 ) ) ); root.AddChild( new CommonTree( new CommonToken( 103 ) ) ); ITreeNodeStream stream = newStream( root ); string expecting = " 101 102 103"; string found = ToNodesOnlyString( stream ); Assert.AreEqual( expecting, found ); expecting = " 101 102 103"; found = ToTokenTypeString( stream ); Assert.AreEqual( expecting, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestListWithOneNode() /*throws Exception*/ { ITree root = new CommonTree( (IToken)null ); root.AddChild( new CommonTree( new CommonToken( 101 ) ) ); ITreeNodeStream stream = newStream( root ); string expecting = " 101"; string found = ToNodesOnlyString( stream ); Assert.AreEqual( expecting, found ); expecting = " 101"; found = ToTokenTypeString( stream ); Assert.AreEqual( expecting, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestAoverB() /*throws Exception*/ { ITree t = new CommonTree( new CommonToken( 101 ) ); t.AddChild( new CommonTree( new CommonToken( 102 ) ) ); ITreeNodeStream stream = newStream( t ); string expecting = " 101 102"; string found = ToNodesOnlyString( stream ); Assert.AreEqual( expecting, found ); expecting = " 101 2 102 3"; found = ToTokenTypeString( stream ); Assert.AreEqual( expecting, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestLT() /*throws Exception*/ { // ^(101 ^(102 103) 104) ITree t = new CommonTree( new CommonToken( 101 ) ); t.AddChild( new CommonTree( new CommonToken( 102 ) ) ); t.GetChild( 0 ).AddChild( new CommonTree( new CommonToken( 103 ) ) ); t.AddChild( new CommonTree( new CommonToken( 104 ) ) ); ITreeNodeStream stream = newStream( t ); Assert.AreEqual( 101, ( (ITree)stream.LT( 1 ) ).Type ); Assert.AreEqual( TokenTypes.Down, ( (ITree)stream.LT( 2 ) ).Type ); Assert.AreEqual( 102, ( (ITree)stream.LT( 3 ) ).Type ); Assert.AreEqual( TokenTypes.Down, ( (ITree)stream.LT( 4 ) ).Type ); Assert.AreEqual( 103, ( (ITree)stream.LT( 5 ) ).Type ); Assert.AreEqual( TokenTypes.Up, ( (ITree)stream.LT( 6 ) ).Type ); Assert.AreEqual( 104, ( (ITree)stream.LT( 7 ) ).Type ); Assert.AreEqual( TokenTypes.Up, ( (ITree)stream.LT( 8 ) ).Type ); Assert.AreEqual( TokenTypes.EndOfFile, ( (ITree)stream.LT( 9 ) ).Type ); // check way ahead Assert.AreEqual( TokenTypes.EndOfFile, ( (ITree)stream.LT( 100 ) ).Type ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestMarkRewindEntire() /*throws Exception*/ { // ^(101 ^(102 103 ^(106 107) ) 104 105) // stream has 7 real + 6 nav nodes // Sequence of types: 101 DN 102 DN 103 106 DN 107 UP UP 104 105 UP EOF ITree r0 = new CommonTree( new CommonToken( 101 ) ); ITree r1 = new CommonTree( new CommonToken( 102 ) ); r0.AddChild( r1 ); r1.AddChild( new CommonTree( new CommonToken( 103 ) ) ); ITree r2 = new CommonTree( new CommonToken( 106 ) ); r2.AddChild( new CommonTree( new CommonToken( 107 ) ) ); r1.AddChild( r2 ); r0.AddChild( new CommonTree( new CommonToken( 104 ) ) ); r0.AddChild( new CommonTree( new CommonToken( 105 ) ) ); ITreeNodeStream stream = newStream( r0 ); int m = stream.Mark(); // MARK for ( int k = 1; k <= 13; k++ ) { // consume til end stream.LT( 1 ); stream.Consume(); } Assert.AreEqual( TokenTypes.EndOfFile, ( (ITree)stream.LT( 1 ) ).Type ); stream.Rewind( m ); // REWIND // consume til end again :) for ( int k = 1; k <= 13; k++ ) { // consume til end stream.LT( 1 ); stream.Consume(); } Assert.AreEqual( TokenTypes.EndOfFile, ( (ITree)stream.LT( 1 ) ).Type ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestMarkRewindInMiddle() /*throws Exception*/ { // ^(101 ^(102 103 ^(106 107) ) 104 105) // stream has 7 real + 6 nav nodes // Sequence of types: 101 DN 102 DN 103 106 DN 107 UP UP 104 105 UP EOF ITree r0 = new CommonTree( new CommonToken( 101 ) ); ITree r1 = new CommonTree( new CommonToken( 102 ) ); r0.AddChild( r1 ); r1.AddChild( new CommonTree( new CommonToken( 103 ) ) ); ITree r2 = new CommonTree( new CommonToken( 106 ) ); r2.AddChild( new CommonTree( new CommonToken( 107 ) ) ); r1.AddChild( r2 ); r0.AddChild( new CommonTree( new CommonToken( 104 ) ) ); r0.AddChild( new CommonTree( new CommonToken( 105 ) ) ); ITreeNodeStream stream = newStream( r0 ); for ( int k = 1; k <= 7; k++ ) { // consume til middle //System.out.println(((Tree)stream.LT(1)).getType()); stream.Consume(); } Assert.AreEqual( 107, ( (ITree)stream.LT( 1 ) ).Type ); stream.Mark(); // MARK stream.Consume(); // consume 107 stream.Consume(); // consume UP stream.Consume(); // consume UP stream.Consume(); // consume 104 stream.Rewind(); // REWIND stream.Mark(); // keep saving nodes though Assert.AreEqual( 107, ( (ITree)stream.LT( 1 ) ).Type ); stream.Consume(); Assert.AreEqual( TokenTypes.Up, ( (ITree)stream.LT( 1 ) ).Type ); stream.Consume(); Assert.AreEqual( TokenTypes.Up, ( (ITree)stream.LT( 1 ) ).Type ); stream.Consume(); Assert.AreEqual( 104, ( (ITree)stream.LT( 1 ) ).Type ); stream.Consume(); // now we're past rewind position Assert.AreEqual( 105, ( (ITree)stream.LT( 1 ) ).Type ); stream.Consume(); Assert.AreEqual( TokenTypes.Up, ( (ITree)stream.LT( 1 ) ).Type ); stream.Consume(); Assert.AreEqual( TokenTypes.EndOfFile, ( (ITree)stream.LT( 1 ) ).Type ); Assert.AreEqual( TokenTypes.Up, ( (ITree)stream.LT( -1 ) ).Type ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestMarkRewindNested() /*throws Exception*/ { // ^(101 ^(102 103 ^(106 107) ) 104 105) // stream has 7 real + 6 nav nodes // Sequence of types: 101 DN 102 DN 103 106 DN 107 UP UP 104 105 UP EOF ITree r0 = new CommonTree( new CommonToken( 101 ) ); ITree r1 = new CommonTree( new CommonToken( 102 ) ); r0.AddChild( r1 ); r1.AddChild( new CommonTree( new CommonToken( 103 ) ) ); ITree r2 = new CommonTree( new CommonToken( 106 ) ); r2.AddChild( new CommonTree( new CommonToken( 107 ) ) ); r1.AddChild( r2 ); r0.AddChild( new CommonTree( new CommonToken( 104 ) ) ); r0.AddChild( new CommonTree( new CommonToken( 105 ) ) ); ITreeNodeStream stream = newStream( r0 ); int m = stream.Mark(); // MARK at start stream.Consume(); // consume 101 stream.Consume(); // consume DN int m2 = stream.Mark(); // MARK on 102 stream.Consume(); // consume 102 stream.Consume(); // consume DN stream.Consume(); // consume 103 stream.Consume(); // consume 106 stream.Rewind( m2 ); // REWIND to 102 Assert.AreEqual( 102, ( (ITree)stream.LT( 1 ) ).Type ); stream.Consume(); Assert.AreEqual( TokenTypes.Down, ( (ITree)stream.LT( 1 ) ).Type ); stream.Consume(); // stop at 103 and rewind to start stream.Rewind( m ); // REWIND to 101 Assert.AreEqual( 101, ( (ITree)stream.LT( 1 ) ).Type ); stream.Consume(); Assert.AreEqual( TokenTypes.Down, ( (ITree)stream.LT( 1 ) ).Type ); stream.Consume(); Assert.AreEqual( 102, ( (ITree)stream.LT( 1 ) ).Type ); stream.Consume(); Assert.AreEqual( TokenTypes.Down, ( (ITree)stream.LT( 1 ) ).Type ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestSeekFromStart() /*throws Exception*/ { // ^(101 ^(102 103 ^(106 107) ) 104 105) // stream has 7 real + 6 nav nodes // Sequence of types: 101 DN 102 DN 103 106 DN 107 UP UP 104 105 UP EOF ITree r0 = new CommonTree( new CommonToken( 101 ) ); ITree r1 = new CommonTree( new CommonToken( 102 ) ); r0.AddChild( r1 ); r1.AddChild( new CommonTree( new CommonToken( 103 ) ) ); ITree r2 = new CommonTree( new CommonToken( 106 ) ); r2.AddChild( new CommonTree( new CommonToken( 107 ) ) ); r1.AddChild( r2 ); r0.AddChild( new CommonTree( new CommonToken( 104 ) ) ); r0.AddChild( new CommonTree( new CommonToken( 105 ) ) ); ITreeNodeStream stream = newStream( r0 ); stream.Seek( 7 ); // seek to 107 Assert.AreEqual( 107, ( (ITree)stream.LT( 1 ) ).Type ); stream.Consume(); // consume 107 stream.Consume(); // consume UP stream.Consume(); // consume UP Assert.AreEqual( 104, ( (ITree)stream.LT( 1 ) ).Type ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestDeepTree() { // ^(10 100 101 ^(20 ^(30 40 (50 (60 70)))) (80 90))) // stream has 8 real + 10 nav nodes int n = 9; CommonTree[] nodes = new CommonTree[n]; for (int i = 0; i < n; i++) { nodes[i] = new CommonTree(new CommonToken((i + 1) * 10)); } ITree g = nodes[0]; ITree rules = nodes[1]; ITree rule1 = nodes[2]; ITree id = nodes[3]; ITree block = nodes[4]; ITree alt = nodes[5]; ITree s = nodes[6]; ITree rule2 = nodes[7]; ITree id2 = nodes[8]; g.AddChild(new CommonTree(new CommonToken(100))); g.AddChild(new CommonTree(new CommonToken(101))); g.AddChild(rules); rules.AddChild(rule1); rule1.AddChild(id); rule1.AddChild(block); block.AddChild(alt); alt.AddChild(s); rules.AddChild(rule2); rule2.AddChild(id2); ITreeNodeStream stream = newStream(g); string expecting = " 10 2 100 101 20 2 30 2 40 50 2 60 2 70 3 3 3 80 2 90 3 3 3"; string found = ToTokenTypeString(stream); Assert.AreEqual(expecting, found); } public string ToNodesOnlyString( ITreeNodeStream nodes ) { ITreeAdaptor adaptor = nodes.TreeAdaptor; StringBuilder buf = new StringBuilder(); object o = nodes.LT( 1 ); int type = adaptor.GetType( o ); while ( o != null && type != TokenTypes.EndOfFile ) { if ( !( type == TokenTypes.Down || type == TokenTypes.Up ) ) { buf.Append( " " ); buf.Append( type ); } nodes.Consume(); o = nodes.LT( 1 ); type = adaptor.GetType( o ); } return buf.ToString(); } } }
{ "pile_set_name": "Github" }
// Rectangle.h // 创建人:刘瑶 // // 矩形(Rectangle) // 功能说明:定义 BoundingRect 和 SmallestDirRect 里用到的公共结构体。 // // 修订历史: // 2013年01月09日(刘瑶) // 初始版本 // 2013年03月21日(刘瑶) // 将公共结构体的命名由 BR_XXX 统一为 RECT_XXX #ifndef __RECTANGLE_H__ #define __RECTANGLE_H__ #include "Image.h" #include "ErrorCode.h" // 结构体:Quadrangle(有向矩形) // 该结构体定了有向矩形的数据结构,其中包含了矩形的方向角度,4个角的坐标。 typedef struct Quadrangle_st { float angle; // 有向矩形的角度,即矩形的长边与水平方向的顺时针夹角 int points[4][2]; // 有向矩形的四个角坐标,为左上,右上,右下,左下四个点 } Quadrangle; // 结构体:DirectedRect(有向矩形) // 该结构体定了有向矩形的另一种数据结构,其中包含了矩形的方向角度,中心点坐标, // 长边长度,短边长度。 typedef struct DirectedRect_st { float angle; // 有向矩形的角度,即矩形的长边与水平方向的顺时针夹 // 角 int centerPoint[2]; // 有向矩形的中心点坐标 int length1, length2; // 有向矩形的长边,短边长度,length1 ≧ length2 } DirectedRect; // 结构体:RotationInfo(旋转矩阵信息) // 该结构体定义了旋转矩阵的信息,包含了旋转角度,余弦值,正弦值。 typedef struct RotationInfo_st { float radian; // 旋转角度对应的弧度。 float cos; // 旋转角度的余弦值。 float sin; // 旋转角度的正弦值。 } RotationInfo; // 结构体:BoundBox(包围矩形的边界坐标) // 该结构体定义了包围矩形的边界坐标信息。坐标的数据类型为 float。 typedef struct BoundBox_st { float left; // 左边界坐标。 float right; // 右边界坐标。 float top; // 上边界坐标。 float bottom; // 下边界坐标。 } BoundBox; // 结构体:BoundBoxInt(包围矩形的边界坐标) // 该结构体定义了包围矩形的边界坐标信息。坐标的数据类型为 int。 typedef struct BoundBoxInt_st { int left; // 左边界坐标。 int right; // 右边界坐标。 int top; // 上边界坐标。 int bottom; // 下边界坐标。 } BoundBoxInt; // 宏:M_PI // π值。对于某些操作系统,M_PI可能没有定义,这里补充定义 M_PI。 #ifndef M_PI #define M_PI 3.14159265359 #endif // 宏:RECT_ROTATE_POINT // 根据给定的旋转信息,计算旋转后的点坐标。 #define RECT_ROTATE_POINT(ptsor, pttar, rtinfo) do { \ (pttar)[0] = (ptsor)[0] * (rtinfo).cos - \ (ptsor)[1] * (rtinfo).sin; \ (pttar)[1] = (ptsor)[0] * (rtinfo).sin + \ (ptsor)[1] * (rtinfo).cos; \ } while (0) #endif // 宏:RECT_RAD_TO_DEG // 从弧度转换为角度。 #define RECT_RAD_TO_DEG(rad) ((rad) * 180.0f / M_PI) // 宏:RECT_DEG_TO_RAD // 从角度转换为弧度。 #define RECT_DEG_TO_RAD(deg) ((deg) * M_PI / 180.0f)
{ "pile_set_name": "Github" }
# coding=utf-8 """Tests for default value parameter.""" from unittest import TestCase from safe.common.parameters.default_value_parameter import ( DefaultValueParameter) __copyright__ = "Copyright 2016, The InaSAFE Project" __license__ = "GPL version 3" __email__ = "[email protected]" __revision__ = '$Format:%H$' labels = ['Setting', 'Do not report', 'Custom'] options = [0.1, None] class TestDefaultValueParameter(TestCase): """Test For Default Value Parameter.""" def setUp(self): """Set up common object for testing.""" self.parameter = DefaultValueParameter() self.parameter.labels = labels self.parameter.options = options def test_default_value(self): """Test default value.""" self.assertEqual(self.parameter.labels, labels) self.parameter.value = 0.2 self.assertEqual( self.parameter.options[-1], self.parameter.value)
{ "pile_set_name": "Github" }
import { plugin } from 'postcss'; import LayerCache from './lib/layerCache'; export default plugin('postcss-zindex', (opts = {}) => { return (css) => { const cache = new LayerCache(opts); const nodes = []; let abort = false; // First pass; cache all z indexes css.walkDecls(/z-index/i, (decl) => { // Check that no negative values exist. Rebasing is only // safe if all indices are positive numbers. if (decl.value[0] === '-') { abort = true; // Stop PostCSS iterating through the rest of the decls return false; } nodes.push(decl); cache.addValue(decl.value); }); // Abort if we found any negative values // or there are no z-index declarations if (abort || !nodes.length) { return; } cache.optimizeValues(); // Second pass; optimize nodes.forEach((decl) => { // Need to coerce to string so that the // AST is updated correctly decl.value = cache.getValue(decl.value).toString(); }); }; });
{ "pile_set_name": "Github" }
#------------------------------------------------------------------------------ VERSION = BWS.01 #------------------------------------------------------------------------------ !ifndef ROOT ROOT = $(MAKEDIR)\.. !endif #------------------------------------------------------------------------------ MAKE = $(ROOT)\bin\make.exe -$(MAKEFLAGS) -f$** DCC = $(ROOT)\bin\dcc32.exe $** BRCC = $(ROOT)\bin\brcc32.exe $** #------------------------------------------------------------------------------ PROJECTS = Jcl70.bpl JclVcl70.bpl JclContainers70.bpl JclDeveloperTools70.bpl \ JclBaseExpert70.bpl JclDebugExpert70.bpl JclFavoriteFoldersExpert70.bpl \ JclProjectAnalysisExpert70.bpl JclRepositoryExpert70.bpl \ JclSIMDViewExpert70.bpl JclStackTraceViewerExpert70.bpl \ JclUsesExpert70.bpl JclVersionControlExpert70.bpl #------------------------------------------------------------------------------ default: $(PROJECTS) #------------------------------------------------------------------------------ Jcl70.bpl: d7\Jcl.dpk $(DCC) JclVcl70.bpl: d7\JclVcl.dpk $(DCC) JclContainers70.bpl: d7\JclContainers.dpk $(DCC) JclDeveloperTools70.bpl: d7\JclDeveloperTools.dpk $(DCC) JclBaseExpert70.bpl: d7\JclBaseExpert.dpk $(DCC) JclDebugExpert70.bpl: d7\JclDebugExpert.dpk $(DCC) JclFavoriteFoldersExpert70.bpl: d7\JclFavoriteFoldersExpert.dpk $(DCC) JclProjectAnalysisExpert70.bpl: d7\JclProjectAnalysisExpert.dpk $(DCC) JclRepositoryExpert70.bpl: d7\JclRepositoryExpert.dpk $(DCC) JclSIMDViewExpert70.bpl: d7\JclSIMDViewExpert.dpk $(DCC) JclStackTraceViewerExpert70.bpl: d7\JclStackTraceViewerExpert.dpk $(DCC) JclUsesExpert70.bpl: d7\JclUsesExpert.dpk $(DCC) JclVersionControlExpert70.bpl: d7\JclVersionControlExpert.dpk $(DCC)
{ "pile_set_name": "Github" }
/* Public Domain Curses */ /* This file is BSD licensed, Copyright 2011 secunet AG */ #include <libpayload.h> #include "lppdc.h" int PDC_curs_set(int visibility) { int ret_vis; PDC_LOG(("PDC_curs_set() - called: visibility=%d\n", visibility)); ret_vis = SP->visibility; SP->visibility = visibility; #if CONFIG(LP_SERIAL_CONSOLE) if (curses_flags & F_ENABLE_SERIAL) { serial_cursor_enable(visibility); } #endif #if CONFIG(LP_VIDEO_CONSOLE) if (curses_flags & F_ENABLE_CONSOLE) { video_console_cursor_enable(visibility); } #endif return ret_vis; } int PDC_set_blink(bool blinkon) { if (pdc_color_started) COLORS = 16; return ERR; }
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xml:lang="en" lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html;charset=utf-8" /> <meta http-equiv="Content-Style-Type" content="text/css" /> <!-- MOTW-DISABLED saved from url=(0014)about:internet --> <title>Display the result</title> <link rel="StyleSheet" href="css/ScriptingWithJavaScript.css" type="text/css" media="all" /> <link rel="StyleSheet" href="css/webworks.css" type="text/css" media="all" /> <link rel="StyleSheet" href="webworks.css" type="text/css" media="all" /> <script type="text/javascript" language="JavaScript1.2"> <!-- var WebWorksRootPath = ""; // --> </script> </head> <body> <div style="text-align: left;"> <table cellspacing="0" summary=""> <tr> <td> <a href="ScriptingWithJavaScript.22.09.html"><img src="images/prev.gif" alt="Previous" border="0" /></a> </td> <td> <a href="ScriptingWithJavaScript.22.11.html"><img src="images/next.gif" alt="Next" border="0" /></a> </td> </tr> </table> </div> <hr align="left" /> <blockquote> <h3 class="N_TutorialTask">Task 4:&nbsp;&nbsp;<a name="151847">Display the result</a></h3> <p class="b_Body"><a name="151848">To display the count of customers with the string Mini in their names, insert code in a method that runs after the processing of all the rows in the list. One logical place for this code is in the ReportDesign.afterFactorymethod. </a></p> <div class="N_n1_NumList1_outer" style="margin-left: 0pt"> <table border="0" cellspacing="0" cellpadding="0" summary="" role="presentation"> <tr style="vertical-align: baseline"> <td> <div class="N_n1_NumList1_inner" style="width: 14.1732pt; white-space: nowrap"> <span class="zAuto_0023Format">1&nbsp;&nbsp;</span> </div> </td> <td width="100%"> <div class="N_n1_NumList1_inner"><a name="151852">In Outline, select the report design, as shown in </a><a href="#152893" title="Display the result">Figure&nbsp;22-9</a>.</div> </td> </tr> </table> </div> <p class="i2_Image2"><a name="151861"><img class="Default" src="images/tutorial3Shot5A.png" style="display: inline; float: none; left: 0.0; top: 0.0" alt="Figure 23-9 Selecting the report design in Outline" /></a></p> <div class="fc2_FigCall2Title"> <b class="Bold">Figure&nbsp;22-9&nbsp;&nbsp;</b><a name="152893">Selecting the report design in Outline</a></div> <div class="N_n1_NumList1_outer" style="margin-left: 0pt"> <table border="0" cellspacing="0" cellpadding="0" summary="" role="presentation"> <tr style="vertical-align: baseline"> <td> <div class="N_n1_NumList1_inner" style="width: 14.1732pt; white-space: nowrap"> <span class="zAuto_0023Format">2&nbsp;&nbsp;</span> </div> </td> <td width="100%"> <div class="N_n1_NumList1_inner"><a name="151863">Select the afterFactory method from the list of available scripts in the script editor.</a></div> </td> </tr> </table> </div> <div class="N_n1_NumList1_outer" style="margin-left: 0pt"> <table border="0" cellspacing="0" cellpadding="0" summary="" role="presentation"> <tr style="vertical-align: baseline"> <td> <div class="N_n1_NumList1_inner" style="width: 14.1732pt; white-space: nowrap"> <span class="zAuto_0023Format">3&nbsp;&nbsp;</span> </div> </td> <td width="100%"> <div class="N_n1_NumList1_inner"><a name="151864">Type the following code into the afterFactory method:</a></div> </td> </tr> </table> </div> <div class="cfi_CodeFirstIndent"><a name="177318">importPackage(&nbsp;Packages.javax.swing&nbsp;);</a></div> <div class="coi_CodeIndent"><a name="177319">frame = new JFrame(&nbsp;"Count of Minis = " + countOfMinis&nbsp;);</a></div> <div class="coi_CodeIndent"><a name="177320">frame.setBounds(&nbsp;310, 220, 300, 20&nbsp;);</a></div> <div class="coi_CodeIndent"><a name="151868">frame.show(&nbsp;);</a></div> <div class="N_n1_NumList1_outer" style="margin-left: 0pt"> <table border="0" cellspacing="0" cellpadding="0" summary="" role="presentation"> <tr style="vertical-align: baseline"> <td> <div class="N_n1_NumList1_inner" style="width: 14.1732pt; white-space: nowrap"> <span class="zAuto_0023Format">4&nbsp;&nbsp;</span> </div> </td> <td width="100%"> <div class="N_n1_NumList1_inner"><a name="151869">Select Preview to see the results. If there are no errors in the code, you see a report similar to the one in </a><a href="#152907" title="Display the result">Figure&nbsp;22-10</a>.</div> </td> </tr> </table> </div> <p class="i2_Image2"><a name="151881"><img class="Default" src="images/tutorial3Shot6.png" style="display: inline; float: none; left: 0.0; top: 0.0" alt="Figure 22-10 Result of changing the afterFactory( ) method" /></a></p> <div class="fc2_FigCall2Title"> <b class="Bold">Figure&nbsp;22-10&nbsp;&nbsp;</b><a name="152907">Result of changing the afterFactory(&nbsp;) method</a></div> <p class="b_Body"><a name="151883">If you do not see the Count of Minis window, look for it behind the Eclipse window. If the Count of Minis window does not appear, the most likely reason is a scripting error caused by an error in one of your code entries. </a></p> <p class="b_Body"><a name="151884">If you suspect that a scripting error occurred, scroll to the bottom of the report where all scripting error messages appear. In most situations, there is a brief error message next to a plus sign (&nbsp;+&nbsp;). The plus sign indicates that there is a more detailed error message that is only visible after you expand the brief error message. To expand the brief error message, choose the plus sign. Scroll down to see the more detailed error message.</a></p> </blockquote> <hr align="left" /> <table align="right" summary=""> <tr> <td class="WebWorks_Company_Name_Bottom"> <a href="notices.html">(c) Copyright Actuate Corporation 2013</a> </td> </tr> </table> </body> </html>
{ "pile_set_name": "Github" }
%YAML 1.1 %TAG !u! tag:unity3d.com,2011: --- !u!1045 &1 EditorBuildSettings: m_ObjectHideFlags: 0 serializedVersion: 2 m_Scenes: []
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <!-- ~ Copyright (c) 2016, WSO2 Inc. (http://wso2.com) 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. --> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.wso2.msf4j.perftest.echo</groupId> <artifactId>springboot-echo-message</artifactId> <version>1.0-SNAPSHOT</version> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.4.1.RELEASE</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies> <properties> <start-class>org.wso2.msf4j.perftest.echo.springboot.Application</start-class> </properties> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
{ "pile_set_name": "Github" }
水元みほ最新番号 【HET-441】くどきの規律 OL編</a>2008-03-19ホットエンターテイメント$$$芥川54分钟
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>Author</key> <string>osy</string> <key>CodecID</key> <integer>1792</integer> <key>CodecName</key> <string>ALC700</string> <key>Files</key> <dict> <key>Layouts</key> <array> <dict> <key>Comment</key> <string>Custom by osy - Realtek ALC700 for NUC HC</string> <key>Id</key> <integer>11</integer> <key>Path</key> <string>layout11.xml.zlib</string> </dict> </array> <key>Platforms</key> <array> <dict> <key>Comment</key> <string>Custom by osy - Realtek ALC700 for NUC HC</string> <key>Id</key> <integer>11</integer> <key>Path</key> <string>Platforms11.xml.zlib</string> </dict> </array> </dict> <key>Patches</key> <array> <dict> <key>Count</key> <integer>1</integer> <key>Find</key> <data>xgYASIu/aAE=</data> <key>MinKernel</key> <integer>18</integer> <key>Name</key> <string>AppleHDA</string> <key>Replace</key> <data>xgYBSIu/aAE=</data> </dict> <dict> <key>Count</key> <integer>1</integer> <key>Find</key> <data>QcYGAEmLvCQ=</data> <key>MaxKernel</key> <integer>13</integer> <key>MinKernel</key> <integer>13</integer> <key>Name</key> <string>AppleHDA</string> <key>Replace</key> <data>QcYGAUmLvCQ=</data> </dict> <dict> <key>Count</key> <integer>1</integer> <key>Find</key> <data>QcYGAEiLu2g=</data> <key>MinKernel</key> <integer>14</integer> <key>Name</key> <string>AppleHDA</string> <key>Replace</key> <data>QcYGAUiLu2g=</data> </dict> <dict> <key>Count</key> <integer>1</integer> <key>Find</key> <data>QcaGQwEAAAA=</data> <key>MinKernel</key> <integer>13</integer> <key>Name</key> <string>AppleHDA</string> <key>Replace</key> <data>QcaGQwEAAAE=</data> </dict> <dict> <key>Count</key> <integer>2</integer> <key>Find</key> <data>hBnUEQ==</data> <key>MinKernel</key> <integer>13</integer> <key>Name</key> <string>AppleHDA</string> <key>Replace</key> <data>AAfsEA==</data> </dict> <dict> <key>Count</key> <integer>2</integer> <key>Find</key> <data>hAjsEA==</data> <key>MinKernel</key> <integer>13</integer> <key>Name</key> <string>AppleHDA</string> <key>Replace</key> <data>AAAAAA==</data> </dict> <dict> <key>Count</key> <integer>2</integer> <key>Find</key> <data>hQjsEA==</data> <key>MinKernel</key> <integer>13</integer> <key>Name</key> <string>AppleHDA</string> <key>Replace</key> <data>AAAAAA==</data> </dict> <dict> <key>Count</key> <integer>2</integer> <key>Find</key> <data>gxnUEQ==</data> <key>MaxKernel</key> <integer>15</integer> <key>MinKernel</key> <integer>15</integer> <key>Name</key> <string>AppleHDA</string> <key>Replace</key> <data>AAAAAA==</data> </dict> </array> <key>Vendor</key> <string>Realtek</string> </dict> </plist>
{ "pile_set_name": "Github" }
a1cb5f72eafca65d0c5b3d77226f656b5732c2909adc9de669859293a539f0c1 ./openjdk-1.6.0-unofficial-b30-windows-amd64-debug-image.zip
{ "pile_set_name": "Github" }
export function getCursorPosition(event: any) { let touches = event.touches let source = event // jQuery Event normalization does not preserve the 'event.touches' // try to grab touches from the original event if (event.touches === undefined && event.originalEvent !== undefined) { touches = event.originalEvent.touches } // get current touch or mouse position if (touches !== undefined && touches.length > 0) { source = touches[0] } return { x: source.clientX || 0, y: source.clientY || 0 } }
{ "pile_set_name": "Github" }
import * as React from 'react'; import { Mutation, MutationResult, compose } from 'react-apollo'; import { Link } from 'react-router-dom'; import withFlashMessage from 'components/flash/withFlashMessage'; // graphql queries import DELETE_RECIPE from 'graphql/recipes/deleteRecipeMutation.graphql'; import RECIPES from 'graphql/recipes/recipesQuery.graphql'; // typings import { DataProxy } from 'apollo-cache'; import { RecipePreviewFragment, RecipesData, DeleteRecipeData, DeleteRecipeVariables } from 'types'; class DeleteRecipeMutation extends Mutation<DeleteRecipeData, DeleteRecipeVariables> {} interface IProps { recipe: RecipePreviewFragment; notice: (text: string) => void; } class RecipeActions extends React.Component<IProps, {}> { constructor(props: IProps) { super(props); this.onDestroy = this.onDestroy.bind(this); this.updateCache = this.updateCache.bind(this); } private onDestroy(deleteRecipe: Function) { return async (event: React.MouseEvent<HTMLElement>) => { event.preventDefault(); if (window.confirm('êtes vous sûre ?')) { const recipeID: string = this.props.recipe.id; const response: MutationResult<DeleteRecipeData> = await deleteRecipe({ variables: { id: recipeID } }); if (!response.data!.deleteRecipe.errors) { this.props.notice('La recette a bien été supprimé.'); } } return false; }; } private updateCache(cache: DataProxy, { data: { deleteRecipe } }: any) { const recipeDeleted = deleteRecipe.recipe; if (!recipeDeleted) return; const data = cache.readQuery({ query: RECIPES }) as RecipesData; if (!data.recipes) return; data.recipes = data.recipes.filter(recipe => recipe.id !== recipeDeleted.id); data.recipesCount -= 1; cache.writeQuery({ query: RECIPES, data }); } public render() { const { recipe } = this.props; return ( <div className="recipe-actions is-pulled-right"> <Link to={`/recipes/${recipe.id}/edit`} className="edit-recipe-link"> <span className="icon"> <i className="fa fa-edit" /> </span> </Link> <DeleteRecipeMutation mutation={DELETE_RECIPE} update={this.updateCache}> {deleteRecipe => ( <a onClick={this.onDestroy(deleteRecipe)} className="delete-recipe-link"> <span className="icon"> <i className="fa fa-trash-o" /> </span> </a> )} </DeleteRecipeMutation> </div> ); } } export default compose(withFlashMessage)(RecipeActions);
{ "pile_set_name": "Github" }
// getter属性 // 理解从state中取值 export const singer = state => state.singer; export const playing = state => state.playing; export const fullScreen = state => state.fullScreen; export const playList = state => state.playList; export const sequencePlayList = state => state.sequencePlayList; export const currentIndex = state => state.currentIndex; export const currentSong = (state) => { return state.playList[state.currentIndex] || {}; }; export const playMode = state => state.playMode; export const diss = state => state.diss; export const rank = state => state.rank;
{ "pile_set_name": "Github" }
#pragma once /**\file normal_estimation_omp.h * \brief Description... * * @version 1.0 * @author Carlos Miguel Correia da Costa */ // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> <includes> <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // std includes #include <memory> #include <string> #include <vector> // ROS includes #include <ros/ros.h> // PCL includes #include <pcl/point_cloud.h> #include <pcl/point_types.h> #include <pcl/filters/filter.h> #include <pcl/features/normal_3d_omp.h> // project includes #include <dynamic_robot_localization/normal_estimators/normal_estimator.h> // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> </includes> <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< namespace dynamic_robot_localization { // ######################################################################### normal_estimation_omp ######################################################################### /** * \brief Description... */ template <typename PointT> class NormalEstimationOMP : public NormalEstimator<PointT> { // ======================================================================== <public-section> =========================================================================== public: // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> <usings> <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< using Ptr = std::shared_ptr< NormalEstimationOMP<PointT> >; using ConstPtr = std::shared_ptr< const NormalEstimationOMP<PointT> >; // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> </usings> <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> <constructors-destructor> <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< NormalEstimationOMP() {} virtual ~NormalEstimationOMP() {} // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> </constructors-destructor> <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> <NormalEstimationOMP-functions> <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< virtual void setupConfigurationFromParameterServer(ros::NodeHandlePtr& node_handle, ros::NodeHandlePtr& private_node_handle, std::string configuration_namespace = ""); virtual void estimateNormals(typename pcl::PointCloud<PointT>::Ptr& pointcloud, typename pcl::PointCloud<PointT>::Ptr& surface, typename pcl::search::KdTree<PointT>::Ptr& surface_search_method, tf2::Transform& viewpoint_guess, typename pcl::PointCloud<PointT>::Ptr& pointcloud_with_normals_out); // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> </NormalEstimationOMP-functions> <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> <gets> <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> </gets> <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> <sets> <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> </sets> <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // ======================================================================== </public-section> =========================================================================== // ======================================================================== <protected-section> ======================================================================== protected: pcl::NormalEstimationOMP<PointT, PointT> normal_estimator_; // ======================================================================== </protected-section> ======================================================================== }; } /* namespace dynamic_robot_localization */ #ifdef DRL_NO_PRECOMPILE #include <dynamic_robot_localization/normal_estimators/impl/normal_estimation_omp.hpp> #endif
{ "pile_set_name": "Github" }
/* Copyright (C) 2003 Free Software Foundation. Test strlen optimizations on conditional expressions. Written by Jakub Jelinek, June 23, 2003. */ typedef __SIZE_TYPE__ size_t; extern size_t strlen (const char *); extern char *strcpy (char *, const char *); extern int memcmp (const void *, const void *, size_t); extern void abort (void); extern int inside_main; size_t g, h, i, j, k, l; size_t foo (void) { if (l) abort (); return ++l; } void main_test (void) { if (strlen (i ? "foo" + 1 : j ? "bar" + 1 : "baz" + 1) != 2) abort (); if (strlen (g++ ? "foo" : "bar") != 3 || g != 1) abort (); if (strlen (h++ ? "xfoo" + 1 : "bar") != 3 || h != 1) abort (); if (strlen ((i++, "baz")) != 3 || i != 1) abort (); /* The following calls might not optimize strlen call away. */ inside_main = 0; if (strlen (j ? "foo" + k++ : "bar" + k++) != 3 || k != 1) abort (); if (strlen (foo () ? "foo" : "bar") != 3 || l != 1) abort (); }
{ "pile_set_name": "Github" }
/* * An rtc/i2c driver for the Dallas DS1672 * Copyright 2005-06 Tower Technologies * * Author: Alessandro Zummo <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #include <linux/i2c.h> #include <linux/rtc.h> #include <linux/module.h> /* Registers */ #define DS1672_REG_CNT_BASE 0 #define DS1672_REG_CONTROL 4 #define DS1672_REG_TRICKLE 5 #define DS1672_REG_CONTROL_EOSC 0x80 static struct i2c_driver ds1672_driver; /* * In the routines that deal directly with the ds1672 hardware, we use * rtc_time -- month 0-11, hour 0-23, yr = calendar year-epoch * Epoch is initialized as 2000. Time is set to UTC. */ static int ds1672_get_datetime(struct i2c_client *client, struct rtc_time *tm) { unsigned long time; unsigned char addr = DS1672_REG_CNT_BASE; unsigned char buf[4]; struct i2c_msg msgs[] = { {/* setup read ptr */ .addr = client->addr, .len = 1, .buf = &addr }, {/* read date */ .addr = client->addr, .flags = I2C_M_RD, .len = 4, .buf = buf }, }; /* read date registers */ if ((i2c_transfer(client->adapter, &msgs[0], 2)) != 2) { dev_err(&client->dev, "%s: read error\n", __func__); return -EIO; } dev_dbg(&client->dev, "%s: raw read data - counters=%02x,%02x,%02x,%02x\n", __func__, buf[0], buf[1], buf[2], buf[3]); time = (buf[3] << 24) | (buf[2] << 16) | (buf[1] << 8) | buf[0]; rtc_time_to_tm(time, tm); dev_dbg(&client->dev, "%s: tm is secs=%d, mins=%d, hours=%d, " "mday=%d, mon=%d, year=%d, wday=%d\n", __func__, tm->tm_sec, tm->tm_min, tm->tm_hour, tm->tm_mday, tm->tm_mon, tm->tm_year, tm->tm_wday); return 0; } static int ds1672_set_mmss(struct i2c_client *client, unsigned long secs) { int xfer; unsigned char buf[6]; buf[0] = DS1672_REG_CNT_BASE; buf[1] = secs & 0x000000FF; buf[2] = (secs & 0x0000FF00) >> 8; buf[3] = (secs & 0x00FF0000) >> 16; buf[4] = (secs & 0xFF000000) >> 24; buf[5] = 0; /* set control reg to enable counting */ xfer = i2c_master_send(client, buf, 6); if (xfer != 6) { dev_err(&client->dev, "%s: send: %d\n", __func__, xfer); return -EIO; } return 0; } static int ds1672_rtc_read_time(struct device *dev, struct rtc_time *tm) { return ds1672_get_datetime(to_i2c_client(dev), tm); } static int ds1672_rtc_set_mmss(struct device *dev, unsigned long secs) { return ds1672_set_mmss(to_i2c_client(dev), secs); } static int ds1672_get_control(struct i2c_client *client, u8 *status) { unsigned char addr = DS1672_REG_CONTROL; struct i2c_msg msgs[] = { {/* setup read ptr */ .addr = client->addr, .len = 1, .buf = &addr }, {/* read control */ .addr = client->addr, .flags = I2C_M_RD, .len = 1, .buf = status }, }; /* read control register */ if ((i2c_transfer(client->adapter, &msgs[0], 2)) != 2) { dev_err(&client->dev, "%s: read error\n", __func__); return -EIO; } return 0; } /* following are the sysfs callback functions */ static ssize_t show_control(struct device *dev, struct device_attribute *attr, char *buf) { struct i2c_client *client = to_i2c_client(dev); u8 control; int err; err = ds1672_get_control(client, &control); if (err) return err; return sprintf(buf, "%s\n", (control & DS1672_REG_CONTROL_EOSC) ? "disabled" : "enabled"); } static DEVICE_ATTR(control, S_IRUGO, show_control, NULL); static const struct rtc_class_ops ds1672_rtc_ops = { .read_time = ds1672_rtc_read_time, .set_mmss = ds1672_rtc_set_mmss, }; static int ds1672_probe(struct i2c_client *client, const struct i2c_device_id *id) { int err = 0; u8 control; struct rtc_device *rtc; dev_dbg(&client->dev, "%s\n", __func__); if (!i2c_check_functionality(client->adapter, I2C_FUNC_I2C)) return -ENODEV; rtc = devm_rtc_device_register(&client->dev, ds1672_driver.driver.name, &ds1672_rtc_ops, THIS_MODULE); if (IS_ERR(rtc)) return PTR_ERR(rtc); i2c_set_clientdata(client, rtc); /* read control register */ err = ds1672_get_control(client, &control); if (err) { dev_warn(&client->dev, "Unable to read the control register\n"); } if (control & DS1672_REG_CONTROL_EOSC) dev_warn(&client->dev, "Oscillator not enabled. " "Set time to enable.\n"); /* Register sysfs hooks */ err = device_create_file(&client->dev, &dev_attr_control); if (err) dev_err(&client->dev, "Unable to create sysfs entry: %s\n", dev_attr_control.attr.name); return 0; } static struct i2c_device_id ds1672_id[] = { { "ds1672", 0 }, { } }; MODULE_DEVICE_TABLE(i2c, ds1672_id); static struct i2c_driver ds1672_driver = { .driver = { .name = "rtc-ds1672", }, .probe = &ds1672_probe, .id_table = ds1672_id, }; module_i2c_driver(ds1672_driver); MODULE_AUTHOR("Alessandro Zummo <[email protected]>"); MODULE_DESCRIPTION("Dallas/Maxim DS1672 timekeeper driver"); MODULE_LICENSE("GPL");
{ "pile_set_name": "Github" }
// // ======================================================================== // Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // // This program and the accompanying materials are made available under // the terms of the Eclipse Public License 2.0 which is available at // https://www.eclipse.org/legal/epl-2.0 // // This Source Code may also be made available under the following // Secondary Licenses when the conditions for such availability set // forth in the Eclipse Public License, v. 2.0 are satisfied: // the Apache License v2.0 which is available at // https://www.apache.org/licenses/LICENSE-2.0 // // SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 // ======================================================================== // package org.eclipse.jetty.util.ajax; import java.io.IOException; import java.lang.reflect.Array; import java.math.BigDecimal; import java.util.Date; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.TimeZone; import org.eclipse.jetty.util.DateCache; import org.eclipse.jetty.util.ajax.JSON.Output; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.startsWith; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; public class JSONTest { // @checkstyle-disable-check : AvoidEscapedUnicodeCharactersCheck private JSON json; private String test = "\n\n\n\t\t " + "// ignore this ,a [ \" \n" + "/* and this \n" + "/* and * // this \n" + "*/" + "{ " + "\"onehundred\" : 100 ," + "\"small\":-0.2," + "\"name\" : \"fred\" ," + "\"empty\" : {} ," + "\"map\" : {\"a\":-1.0e2} ," + "\"array\" : [\"a\",-1.0e2,[],null,true,false] ," + "\"w0\":{\"class\":\"org.eclipse.jetty.util.ajax.JSONTest$Woggle\",\"name\":\"woggle0\",\"nested\":{\"class\":\"org.eclipse.jetty.util.ajax.JSONTest$Woggle\",\"name\":\"woggle1\",\"nested\":null,\"number\":-101},\"number\":100}," + "\"NaN\": NaN," + "\"undefined\": undefined," + "}"; @BeforeEach public void resetJSON() { json = new JSON(); } @Test public void testToString() { json.addConvertor(Gadget.class, new JSONObjectConvertor(false)); Map<String, Object> map = new HashMap<>(); Map<String, Object> obj6 = new HashMap<>(); Map<String, Object> obj7 = new HashMap<>(); Woggle w0 = new Woggle(); Woggle w1 = new Woggle(); w0.name = "woggle0"; w0.nested = w1; w0.number = 100; w1.name = "woggle1"; w1.nested = null; w1.number = -101; map.put("n1", null); map.put("n2", 2); map.put("n3", -0.00000000003); map.put("n4", "4\n\r\t\"4"); map.put("n5", new Object[]{"a", 'b', 3, new String[]{}, null, Boolean.TRUE, Boolean.FALSE}); map.put("n6", obj6); map.put("n7", obj7); map.put("n8", new int[]{1, 2, 3, 4}); map.put("n9", new JSON.Literal("[{}, [], {}]")); map.put("w0", w0); obj7.put("x", "value"); String s = json.toJSON(map); assertTrue(s.contains("\"n1\":null")); assertTrue(s.contains("\"n2\":2")); assertTrue(s.contains("\"n3\":-3.0E-11")); assertTrue(s.contains("\"n4\":\"4\\n")); assertTrue(s.contains("\"n5\":[\"a\",\"b\",")); assertTrue(s.contains("\"n6\":{}")); assertTrue(s.contains("\"n7\":{\"x\":\"value\"}")); assertTrue(s.contains("\"n8\":[1,2,3,4]")); assertTrue(s.contains("\"n9\":[{}, [], {}]")); assertTrue(s.contains("\"w0\":{\"class\":\"org.eclipse.jetty.util.ajax.JSONTest$Woggle\",\"name\":\"woggle0\",\"nested\":{\"class\":\"org.eclipse.jetty.util.ajax.JSONTest$Woggle\",\"name\":\"woggle1\",\"nested\":null,\"number\":-101},\"number\":100}")); Gadget gadget = new Gadget(); gadget.setModulated(true); gadget.setShields(42); gadget.setWoggles(new Woggle[]{w0, w1}); s = json.toJSON(new Gadget[]{gadget}); assertThat(s, startsWith("[")); assertThat(s, containsString("\"modulated\":" + gadget.isModulated())); assertThat(s, containsString("\"shields\":" + gadget.getShields())); assertThat(s, containsString("\"name\":\"woggle0\"")); assertThat(s, containsString("\"name\":\"woggle1\"")); } @Test public void testParse() { @SuppressWarnings("unchecked") Map<String, Object> map = (Map<String, Object>)json.fromJSON(test); assertEquals((long)100, map.get("onehundred")); assertEquals("fred", map.get("name")); assertEquals(-0.2, map.get("small")); assertTrue(map.get("array").getClass().isArray()); assertTrue(map.get("w0") instanceof Woggle); assertTrue(((Woggle)map.get("w0")).nested instanceof Woggle); assertEquals(-101, ((Woggle)((Woggle)map.get("w0")).nested).number); assertTrue(map.containsKey("NaN")); assertNull(map.get("NaN")); assertTrue(map.containsKey("undefined")); assertNull(map.get("undefined")); } @Test public void testToStringLineFeed() { Map<String, String> map = new HashMap<>(); map.put("str", "line\nfeed"); String jsonStr = json.toJSON(map); assertThat(jsonStr, is("{\"str\":\"line\\nfeed\"}")); } @Test public void testToStringTab() { Map<String, String> map = new HashMap<>(); map.put("str", "tab\tchar"); String jsonStr = json.toJSON(map); assertThat(jsonStr, is("{\"str\":\"tab\\tchar\"}")); } @Test public void testToStringBel() { Map<String, String> map = new HashMap<>(); map.put("str", "ascii\u0007bel"); String jsonStr = json.toJSON(map); assertThat(jsonStr, is("{\"str\":\"ascii\\u0007bel\"}")); } @Test public void testToStringUtf8() { Map<String, String> map = new HashMap<>(); map.put("str", "japanese: 桟橋"); String jsonStr = json.toJSON(map); assertThat(jsonStr, is("{\"str\":\"japanese: 桟橋\"}")); } @Test public void testToJsonUtf8Encoded() { JSON jsonUnicode = new JSON() { @Override protected void escapeUnicode(Appendable buffer, char c) throws IOException { buffer.append(String.format("\\u%04x", (int)c)); } }; Map<String, String> map = new HashMap<>(); map.put("str", "japanese: 桟橋"); String jsonStr = jsonUnicode.toJSON(map); assertThat(jsonStr, is("{\"str\":\"japanese: \\u685f\\u6a4b\"}")); } @Test public void testParseUtf8JsonEncoded() { String jsonStr = "{\"str\": \"japanese: \\u685f\\u6a4b\"}"; @SuppressWarnings("unchecked") Map<String, Object> map = (Map<String, Object>)json.fromJSON(jsonStr); assertThat(map.get("str"), is("japanese: 桟橋")); } @Test public void testParseUtf8JavaEncoded() { String jsonStr = "{\"str\": \"japanese: \u685f\u6a4b\"}"; @SuppressWarnings("unchecked") Map<String, Object> map = (Map<String, Object>)json.fromJSON(jsonStr); assertThat(map.get("str"), is("japanese: 桟橋")); } @Test public void testParseUtf8Raw() { String jsonStr = "{\"str\": \"japanese: 桟橋\"}"; @SuppressWarnings("unchecked") Map<String, Object> map = (Map<String, Object>)json.fromJSON(jsonStr); assertThat(map.get("str"), is("japanese: 桟橋")); } @Test public void testParseReader() { @SuppressWarnings("unchecked") Map<String, Object> map = (Map<String, Object>)json.fromJSON(test); assertEquals((long)100, map.get("onehundred")); assertEquals("fred", map.get("name")); assertTrue(map.get("array").getClass().isArray()); assertTrue(map.get("w0") instanceof Woggle); assertTrue(((Woggle)map.get("w0")).nested instanceof Woggle); } @Test public void testStripComment() { String test = "\n\n\n\t\t " + "// ignore this ,a [ \" \n" + "/* " + "{ " + "\"onehundred\" : 100 ," + "\"name\" : \"fred\" ," + "\"empty\" : {} ," + "\"map\" : {\"a\":-1.0e2} ," + "\"array\" : [\"a\",-1.0e2,[],null,true,false] ," + "} */"; Object o = json.fromJSON(test); assertNull(o); o = json.parse(new JSON.StringSource(test), true); assertTrue(o instanceof Map); @SuppressWarnings("unchecked") Map<String, Object> map = (Map<String, Object>)o; assertEquals("fred", map.get("name")); } @Test public void testQuote() { String test = "\"abc123|\\\"|\\\\|\\/|\\b|\\f|\\n|\\r|\\t|\\uaaaa|\""; String result = (String)json.fromJSON(test); assertEquals("abc123|\"|\\|/|\b|\f|\n|\r|\t|\uaaaa|", result); } @Test public void testBigDecimal() { Object obj = json.fromJSON("1.0E7"); assertTrue(obj instanceof Double); BigDecimal bd = BigDecimal.valueOf(10000000d); String string = json.toJSON(new Object[]{bd}); obj = Array.get(json.fromJSON(string), 0); assertTrue(obj instanceof Double); } @Test public void testZeroByte() { String withzero = "\u0000"; assertEquals("\"\\u0000\"", json.toJSON(withzero)); } public static class Gadget { private boolean modulated; private long shields; private Woggle[] woggles; // Getters and setters required by the POJO convertor. /** * @return the modulated */ public boolean isModulated() { return modulated; } /** * @param modulated the modulated to set */ public void setModulated(boolean modulated) { this.modulated = modulated; } /** * @return the shields */ public long getShields() { return shields; } /** * @param shields the shields to set */ public void setShields(long shields) { this.shields = shields; } /** * @return the woggles */ public Woggle[] getWoggles() { return woggles; } /** * @param woggles the woggles to set */ public void setWoggles(Woggle[] woggles) { this.woggles = woggles; } } @Test public void testConvertor() { // test case#1 - force timezone to GMT JSON json = new JSON(); json.addConvertor(Date.class, new JSONDateConvertor("MM/dd/yyyy HH:mm:ss zzz", TimeZone.getTimeZone("GMT"), false)); json.addConvertor(Object.class, new JSONObjectConvertor()); Woggle w0 = new Woggle(); Gizmo g0 = new Gizmo(); w0.setName("woggle0"); w0.setNested(g0); w0.setNumber(100); g0.setName("woggle1"); g0.setNested(null); g0.setNumber(-101); g0.setTested(true); Map<String, Object> map = new HashMap<>(); Date dummyDate = new Date(1); map.put("date", dummyDate); map.put("w0", w0); StringBuffer buf = new StringBuffer(); json.append(buf, map); String js = buf.toString(); assertTrue(js.contains("\"date\":\"01/01/1970 00:00:00 GMT\"")); assertTrue(js.contains("org.eclipse.jetty.util.ajax.JSONTest$Woggle")); assertFalse(js.contains("org.eclipse.jetty.util.ajax.JSONTest$Gizmo")); assertTrue(js.contains("\"tested\":true")); // test case#3 TimeZone tzone = TimeZone.getTimeZone("JST"); String format = "EEE MMMMM dd HH:mm:ss zzz yyyy"; Locale l = new Locale("ja", "JP"); json.addConvertor(Date.class, new JSONDateConvertor(format, tzone, false, l)); buf = new StringBuffer(); json.append(buf, map); js = buf.toString(); assertTrue(js.contains(" 01 09:00:00 JST 1970\"")); assertTrue(js.contains("org.eclipse.jetty.util.ajax.JSONTest$Woggle")); assertFalse(js.contains("org.eclipse.jetty.util.ajax.JSONTest$Gizmo")); assertTrue(js.contains("\"tested\":true")); // test case#4 json.addConvertor(Date.class, new JSONDateConvertor(true)); w0.nested = null; buf = new StringBuffer(); json.append(buf, map); js = buf.toString(); assertFalse(js.contains("\"date\":\"Thu Jan 01 00:00:00 GMT 1970\"")); assertTrue(js.contains("org.eclipse.jetty.util.ajax.JSONTest$Woggle")); assertFalse(js.contains("org.eclipse.jetty.util.ajax.JSONTest$Gizmo")); @SuppressWarnings("unchecked") Map<String, Object> map1 = (Map<String, Object>)json.fromJSON(js); assertTrue(map1.get("date") instanceof Date); assertTrue(map1.get("w0") instanceof Woggle); } @Test public void testEnumConvertor() { JSON json = new JSON(); Locale l = new Locale("en", "US"); json.addConvertor(Date.class, new JSONDateConvertor(DateCache.DEFAULT_FORMAT, TimeZone.getTimeZone("GMT"), false, l)); json.addConvertor(Enum.class, new JSONEnumConvertor(false)); json.addConvertor(Object.class, new JSONObjectConvertor()); Woggle w0 = new Woggle(); Gizmo g0 = new Gizmo(); w0.setName("woggle0"); w0.setNested(g0); w0.setNumber(100); w0.setOther(Color.Blue); g0.setName("woggle1"); g0.setNested(null); g0.setNumber(-101); g0.setTested(true); g0.setOther(Color.Green); Map<String, Object> map = new HashMap<>(); map.put("date", new Date(1)); map.put("w0", w0); map.put("g0", g0); StringBuffer buf = new StringBuffer(); json.append(buf, map); String js = buf.toString(); assertTrue(js.contains("\"date\":\"Thu Jan 01 00:00:00 GMT 1970\"")); assertTrue(js.contains("org.eclipse.jetty.util.ajax.JSONTest$Woggle")); assertFalse(js.contains("org.eclipse.jetty.util.ajax.JSONTest$Gizmo")); assertTrue(js.contains("\"tested\":true")); assertTrue(js.contains("\"Green\"")); assertFalse(js.contains("\"Blue\"")); json.addConvertor(Date.class, new JSONDateConvertor(DateCache.DEFAULT_FORMAT, TimeZone.getTimeZone("GMT"), true, l)); json.addConvertor(Enum.class, new JSONEnumConvertor(false)); w0.nested = null; buf = new StringBuffer(); json.append(buf, map); js = buf.toString(); assertFalse(js.contains("\"date\":\"Thu Jan 01 00:00:00 GMT 1970\"")); assertTrue(js.contains("org.eclipse.jetty.util.ajax.JSONTest$Woggle")); assertFalse(js.contains("org.eclipse.jetty.util.ajax.JSONTest$Gizmo")); @SuppressWarnings("unchecked") Map<String, Object> map2 = (Map<String, Object>)json.fromJSON(js); assertTrue(map2.get("date") instanceof Date); assertTrue(map2.get("w0") instanceof Woggle); assertNull(((Woggle)map2.get("w0")).other); @SuppressWarnings("unchecked") Map<String, Object> map3 = (Map<String, Object>)map2.get("g0"); assertEquals(Color.Green.toString(), map3.get("other")); json.addConvertor(Date.class, new JSONDateConvertor(DateCache.DEFAULT_FORMAT, TimeZone.getTimeZone("GMT"), true, l)); json.addConvertor(Enum.class, new JSONEnumConvertor(true)); buf = new StringBuffer(); json.append(buf, map); js = buf.toString(); @SuppressWarnings("unchecked") Map<String, Object> map4 = (Map<String, Object>)json.fromJSON(js); assertTrue(map4.get("date") instanceof Date); assertTrue(map4.get("w0") instanceof Woggle); assertNull(((Woggle)map4.get("w0")).other); @SuppressWarnings("unchecked") Map<String, Object> map5 = (Map<String, Object>)map4.get("g0"); Object o = map5.get("other"); assertEquals(Color.Green, o); } public static class Gizmo { String name; Gizmo nested; long number; boolean tested; Object other; // Getters and setters required by the POJO convertor. public String getName() { return name; } public void setName(String name) { this.name = name; } public Gizmo getNested() { return nested; } public void setNested(Gizmo nested) { this.nested = nested; } public long getNumber() { return number; } public void setNumber(long number) { this.number = number; } public boolean isTested() { return tested; } public void setTested(boolean tested) { this.tested = tested; } public Object getOther() { return other; } public void setOther(Object other) { this.other = other; } } public static class Woggle extends Gizmo implements JSON.Convertible { public Woggle() { } @Override public void fromJSON(Map<String, Object> object) { name = (String)object.get("name"); nested = (Gizmo)object.get("nested"); number = ((Number)object.get("number")).intValue(); } @Override public void toJSON(Output out) { out.addClass(Woggle.class); out.add("name", name); out.add("nested", nested); out.add("number", number); } @Override public String toString() { return name + "<<" + nested + ">>" + number; } } }
{ "pile_set_name": "Github" }
"""Common test support for all numpy test scripts. This single module should provide all the common functionality for numpy tests in a single location, so that test scripts can just import it and work right away. """ from __future__ import division, absolute_import, print_function from unittest import TestCase from . import decorators as dec from .nosetester import run_module_suite, NoseTester as Tester from .utils import * test = nosetester._numpy_tester().test
{ "pile_set_name": "Github" }
call mtr.add_suppression("192.0.2.4"); flush status; flush hosts; flush user_resources; flush privileges; select @@global.debug; @@global.debug select @@global.max_connect_errors; @@global.max_connect_errors 100 select @@global.max_user_connections; @@global.max_user_connections 0 select @@global.max_connections; @@global.max_connections 151 select `User`, `Host` from mysql.`user` where `host` like '%\\%%'; User Host select `User`, `Host` from mysql.`user` where `user` like '192.%'; User Host select `User`, `Host` from mysql.`user` where `user` like '2001:%'; User Host select `User`, `Host` from mysql.`user` where `user` like 'santa.claus.%'; User Host select "Con1 is alive"; Con1 is alive Con1 is alive select current_user(); current_user() root@localhost set global debug= "+d,vio_peer_addr_fake_ipv4,getnameinfo_error_noname"; ERROR HY000: Host '192.0.2.4' is not allowed to connect to this MySQL server "Dumping performance_schema.host_cache" IP 192.0.2.4 HOST NULL HOST_VALIDATED YES SUM_CONNECT_ERRORS 0 COUNT_HOST_BLOCKED_ERRORS 0 COUNT_NAMEINFO_TRANSIENT_ERRORS 0 COUNT_NAMEINFO_PERMANENT_ERRORS 1 COUNT_FORMAT_ERRORS 0 COUNT_ADDRINFO_TRANSIENT_ERRORS 0 COUNT_ADDRINFO_PERMANENT_ERRORS 0 COUNT_FCRDNS_ERRORS 0 COUNT_HOST_ACL_ERRORS 1 COUNT_NO_AUTH_PLUGIN_ERRORS 0 COUNT_AUTH_PLUGIN_ERRORS 0 COUNT_HANDSHAKE_ERRORS 0 COUNT_PROXY_USER_ERRORS 0 COUNT_PROXY_USER_ACL_ERRORS 0 COUNT_AUTHENTICATION_ERRORS 0 COUNT_SSL_ERRORS 0 COUNT_MAX_USER_CONNECTIONS_ERRORS 0 COUNT_MAX_USER_CONNECTIONS_PER_HOUR_ERRORS 0 COUNT_DEFAULT_DATABASE_ERRORS 0 COUNT_INIT_CONNECT_ERRORS 0 COUNT_LOCAL_ERRORS 0 COUNT_UNKNOWN_ERRORS 0 FIRST_ERROR_SEEN set LAST_ERROR_SEEN set ERROR HY000: Host '192.0.2.4' is not allowed to connect to this MySQL server "Dumping performance_schema.host_cache" IP 192.0.2.4 HOST NULL HOST_VALIDATED YES SUM_CONNECT_ERRORS 0 COUNT_HOST_BLOCKED_ERRORS 0 COUNT_NAMEINFO_TRANSIENT_ERRORS 0 COUNT_NAMEINFO_PERMANENT_ERRORS 1 COUNT_FORMAT_ERRORS 0 COUNT_ADDRINFO_TRANSIENT_ERRORS 0 COUNT_ADDRINFO_PERMANENT_ERRORS 0 COUNT_FCRDNS_ERRORS 0 COUNT_HOST_ACL_ERRORS 2 COUNT_NO_AUTH_PLUGIN_ERRORS 0 COUNT_AUTH_PLUGIN_ERRORS 0 COUNT_HANDSHAKE_ERRORS 0 COUNT_PROXY_USER_ERRORS 0 COUNT_PROXY_USER_ACL_ERRORS 0 COUNT_AUTHENTICATION_ERRORS 0 COUNT_SSL_ERRORS 0 COUNT_MAX_USER_CONNECTIONS_ERRORS 0 COUNT_MAX_USER_CONNECTIONS_PER_HOUR_ERRORS 0 COUNT_DEFAULT_DATABASE_ERRORS 0 COUNT_INIT_CONNECT_ERRORS 0 COUNT_LOCAL_ERRORS 0 COUNT_UNKNOWN_ERRORS 0 FIRST_ERROR_SEEN set LAST_ERROR_SEEN set set global debug= default;
{ "pile_set_name": "Github" }
#!/usr/bin/env bash # Copyright 2009 The Go Authors. All rights reserved. # Use of this source code is governed by a BSD-style # license that can be found in the LICENSE file. # The plan9 package provides access to the raw system call # interface of the underlying operating system. Porting Go to # a new architecture/operating system combination requires # some manual effort, though there are tools that automate # much of the process. The auto-generated files have names # beginning with z. # # This script runs or (given -n) prints suggested commands to generate z files # for the current system. Running those commands is not automatic. # This script is documentation more than anything else. # # * asm_${GOOS}_${GOARCH}.s # # This hand-written assembly file implements system call dispatch. # There are three entry points: # # func Syscall(trap, a1, a2, a3 uintptr) (r1, r2, err uintptr); # func Syscall6(trap, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2, err uintptr); # func RawSyscall(trap, a1, a2, a3 uintptr) (r1, r2, err uintptr); # # The first and second are the standard ones; they differ only in # how many arguments can be passed to the kernel. # The third is for low-level use by the ForkExec wrapper; # unlike the first two, it does not call into the scheduler to # let it know that a system call is running. # # * syscall_${GOOS}.go # # This hand-written Go file implements system calls that need # special handling and lists "//sys" comments giving prototypes # for ones that can be auto-generated. Mksyscall reads those # comments to generate the stubs. # # * syscall_${GOOS}_${GOARCH}.go # # Same as syscall_${GOOS}.go except that it contains code specific # to ${GOOS} on one particular architecture. # # * types_${GOOS}.c # # This hand-written C file includes standard C headers and then # creates typedef or enum names beginning with a dollar sign # (use of $ in variable names is a gcc extension). The hardest # part about preparing this file is figuring out which headers to # include and which symbols need to be #defined to get the # actual data structures that pass through to the kernel system calls. # Some C libraries present alternate versions for binary compatibility # and translate them on the way in and out of system calls, but # there is almost always a #define that can get the real ones. # See types_darwin.c and types_linux.c for examples. # # * zerror_${GOOS}_${GOARCH}.go # # This machine-generated file defines the system's error numbers, # error strings, and signal numbers. The generator is "mkerrors.sh". # Usually no arguments are needed, but mkerrors.sh will pass its # arguments on to godefs. # # * zsyscall_${GOOS}_${GOARCH}.go # # Generated by mksyscall.pl; see syscall_${GOOS}.go above. # # * zsysnum_${GOOS}_${GOARCH}.go # # Generated by mksysnum_${GOOS}. # # * ztypes_${GOOS}_${GOARCH}.go # # Generated by godefs; see types_${GOOS}.c above. GOOSARCH="${GOOS}_${GOARCH}" # defaults mksyscall="./mksyscall.pl" mkerrors="./mkerrors.sh" zerrors="zerrors_$GOOSARCH.go" mksysctl="" zsysctl="zsysctl_$GOOSARCH.go" mksysnum= mktypes= run="sh" case "$1" in -syscalls) for i in zsyscall*go do sed 1q $i | sed 's;^// ;;' | sh > _$i && gofmt < _$i > $i rm _$i done exit 0 ;; -n) run="cat" shift esac case "$#" in 0) ;; *) echo 'usage: mkall.sh [-n]' 1>&2 exit 2 esac case "$GOOSARCH" in _* | *_ | _) echo 'undefined $GOOS_$GOARCH:' "$GOOSARCH" 1>&2 exit 1 ;; plan9_386) mkerrors= mksyscall="./mksyscall.pl -l32 -plan9" mksysnum="./mksysnum_plan9.sh /n/sources/plan9/sys/src/libc/9syscall/sys.h" mktypes="XXX" ;; *) echo 'unrecognized $GOOS_$GOARCH: ' "$GOOSARCH" 1>&2 exit 1 ;; esac ( if [ -n "$mkerrors" ]; then echo "$mkerrors |gofmt >$zerrors"; fi case "$GOOS" in plan9) syscall_goos="syscall_$GOOS.go" if [ -n "$mksyscall" ]; then echo "$mksyscall $syscall_goos syscall_$GOOSARCH.go |gofmt >zsyscall_$GOOSARCH.go"; fi ;; esac if [ -n "$mksysctl" ]; then echo "$mksysctl |gofmt >$zsysctl"; fi if [ -n "$mksysnum" ]; then echo "$mksysnum |gofmt >zsysnum_$GOOSARCH.go"; fi if [ -n "$mktypes" ]; then echo "$mktypes types_$GOOS.go |gofmt >ztypes_$GOOSARCH.go"; fi ) | $run
{ "pile_set_name": "Github" }
/* * Copyright 2016 Coral realtime streaming analytics (http://coral-streaming.github.io) * * 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.coral.actors.transform import akka.actor.ActorSystem import akka.testkit.{TestActorRef, ImplicitSender, TestKit} import akka.util.Timeout import org.json4s.JObject import org.json4s.JsonAST.JNothing import org.junit.runner.RunWith import org.scalatest.junit.JUnitRunner import org.scalatest.{BeforeAndAfterAll, Matchers, WordSpecLike} import scala.concurrent.duration._ import org.json4s.jackson.JsonMethods._ class FilterActorSpec(_system: ActorSystem) extends TestKit(_system) with ImplicitSender with WordSpecLike with Matchers with BeforeAndAfterAll { implicit val timeout = Timeout(100.millis) def this() = this(ActorSystem("FilterActorSpec")) override def afterAll() { TestKit.shutdownActorSystem(system) } "A FilterActor" should { "not create an actor when no filters are defined" in { val constructor = parse( """"type": "filter", "params": {}}""") val props = FilterActor(constructor) assert(props == None) } "not create an actor when one of the filters definitions is incorrect" in { val constructor = parse( """{"type": "filter", |"params": {"filters": [ |{"type": "startswith", "function": "exclude", "field": "key1", "param": "excluded"}, |{"type": "unknown", "function": "include", "field": "key2", "param": "included"}]}}""".stripMargin) val props = FilterActor(constructor) assert(props == None) } "create an actor" in { val constructor = parse( """{ "type": "filter", |"params": {"filters": [ |{"type": "startswith", "function": "exclude", "field": "key1", "param": "excluded"}, |{"type": "startswith", "function": "include", "field": "key2", "param": "included"}]}}""".stripMargin) val props = FilterActor(constructor) props.get.actorClass should be(classOf[FilterActor]) } "emit when the filter is include and there is a match" in { val constructor = parse( """{ "type": "filter", |"params": {"filters": [ |{"type": "startswith", "function": "include", "field": "key", "param": "start"}]}}""".stripMargin) val props = FilterActor(constructor).get val filter = TestActorRef[FilterActor](props) val trigger = parse( """{"key": "starting"}""").asInstanceOf[JObject] val result = filter.underlyingActor.simpleEmitTrigger(trigger).get assert(result == trigger) } "not emit when the filter is include and there is no match" in { val constructor = parse( """{ "type": "filter", |"params": {"filters": [ |{"type": "startswith", "function": "include", "field": "key", "param": "start"}]}}""".stripMargin) val props = FilterActor(constructor).get val filter = TestActorRef[FilterActor](props) val trigger1 = parse( """{"key": "nostart"}""").asInstanceOf[JObject] val result1 = filter.underlyingActor.simpleEmitTrigger(trigger1).get assert(result1 == JNothing) val trigger2 = parse( """{"anotherkey": "starting"}""").asInstanceOf[JObject] val result2 = filter.underlyingActor.simpleEmitTrigger(trigger2).get assert(result2 == JNothing) } "emit when the filter is exclude and there is no match" in { val constructor = parse( """{ "type": "filter", |"params": {"filters": [ |{"type": "startswith", "function": "exclude", "field": "key", "param": "start"}]}}""".stripMargin) val props = FilterActor(constructor).get val filter = TestActorRef[FilterActor](props) val trigger1 = parse( """{"key": "nostart"}""").asInstanceOf[JObject] val result1 = filter.underlyingActor.simpleEmitTrigger(trigger1).get assert(result1 == trigger1) val trigger2 = parse( """{"anotherkey": "starting"}""").asInstanceOf[JObject] val result2 = filter.underlyingActor.simpleEmitTrigger(trigger2).get assert(result2 == trigger2) } "not emit when the filter is exclude and there is a match" in { val constructor = parse( """{ "type": "filter", |"params": {"filters": [ |{"type": "startswith", "function": "exclude", "field": "key", "param": "start"}]}}""".stripMargin) val props = FilterActor(constructor).get val filter = TestActorRef[FilterActor](props) val trigger = parse( """{"key": "starting"}""").asInstanceOf[JObject] val result = filter.underlyingActor.simpleEmitTrigger(trigger).get assert(result == JNothing) } "emit when all supplied filters are valid" in { val constructor = parse( """{ "type": "filter", |"params": {"filters": [ |{"type": "startswith", "function": "include", "field": "key1", "param": "start"}, |{"type": "startswith", "function": "include", "field": "key2", "param": "begin"}]}}""".stripMargin) val props = FilterActor(constructor).get val filter = TestActorRef[FilterActor](props) val trigger = parse( """{"key1": "starting", "key2": "beginning"}""").asInstanceOf[JObject] val result = filter.underlyingActor.simpleEmitTrigger(trigger).get assert(result == trigger) } "don't emit when one of the supplied filters is not valid" in { val constructor = parse( """{ "type": "filter", |"params": {"filters": [ |{"type": "startswith", "function": "include", "field": "key1", "param": "start"}, |{"type": "startswith", "function": "include", "field": "key2", "param": "begin"}]}}""".stripMargin) val props = FilterActor(constructor).get val filter = TestActorRef[FilterActor](props) val trigger = parse( """{"key1": "starting", "key2": "notbegin"}""").asInstanceOf[JObject] val result = filter.underlyingActor.simpleEmitTrigger(trigger).get assert(result == JNothing) } } }
{ "pile_set_name": "Github" }
<?php /* * Copyright 2016 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ class Google_Service_Genomics_BatchCreateAnnotationsRequest extends Google_Collection { protected $collection_key = 'annotations'; protected $annotationsType = 'Google_Service_Genomics_Annotation'; protected $annotationsDataType = 'array'; public $requestId; public function setAnnotations($annotations) { $this->annotations = $annotations; } public function getAnnotations() { return $this->annotations; } public function setRequestId($requestId) { $this->requestId = $requestId; } public function getRequestId() { return $this->requestId; } }
{ "pile_set_name": "Github" }
// // DefaultCoreDataAdapterDelegateTests.swift // SyncKitCoreDataExampleTests // // Created by Manuel Entrena on 10/06/2019. // Copyright © 2019 Manuel Entrena. All rights reserved. // import Foundation import SyncKit import XCTest import CoreData import CloudKit class DefaultCoreDataAdapterDelegateTests: XCTestCase { var mockContext: MockManagedObjectContext! var adapter: CoreDataAdapter! var adapterDelegate: DefaultCoreDataAdapterDelegate! override func setUp() { super.setUp() mockContext = MockManagedObjectContext(concurrencyType: .privateQueueConcurrencyType) adapterDelegate = DefaultCoreDataAdapterDelegate() adapter = CoreDataAdapter(persistenceStack: CoreDataStack(storeType: NSInMemoryStoreType, model: CoreDataAdapter.persistenceModel, storeURL: nil), targetContext: mockContext, recordZoneID: CKRecordZone.ID(zoneName: "zone", ownerName: "owner"), delegate: adapterDelegate) } override func tearDown() { adapter = nil adapterDelegate = nil mockContext = nil super.tearDown() } func testChangeManagerRequestsContextSave_savesContext() { let expectation = self.expectation(description: "save finished") adapterDelegate.coreDataAdapter(adapter) { (_) in expectation.fulfill() } waitForExpectations(timeout: 1, handler: nil) XCTAssertTrue(mockContext.saveCalled) } func testChangeManagerRequestsContextSave_saveError_returnsError() { mockContext.saveError = TestError.error let expectation = self.expectation(description: "save finished") var receivedError: Error? adapterDelegate.coreDataAdapter(adapter) { (error) in receivedError = error expectation.fulfill() } waitForExpectations(timeout: 1, handler: nil) XCTAssertEqual(receivedError as? TestError, TestError.error) } func testChangeManagerDidImportChanges_savesImportContextThenTargetContext() { let importContext = MockManagedObjectContext(concurrencyType: .privateQueueConcurrencyType) let expectation = self.expectation(description: "save finished") adapterDelegate.coreDataAdapter(adapter, didImportChanges: importContext) { (_) in expectation.fulfill() } waitForExpectations(timeout: 1, handler: nil) XCTAssertTrue(importContext.saveCalled) XCTAssertTrue(mockContext.saveCalled) } }
{ "pile_set_name": "Github" }
package epi; import epi.test_framework.EpiTest; import epi.test_framework.GenericTest; import java.util.ArrayList; import java.util.List; public class TreeWithParentInorder { @EpiTest(testDataFile = "tree_with_parent_inorder.tsv") public static List<Integer> inorderTraversal(BinaryTree<Integer> tree) { BinaryTree<Integer> prev = null, curr = tree; List<Integer> result = new ArrayList<>(); while (curr != null) { BinaryTree<Integer> next; if (curr.parent == prev) { // We came down to curr from prev. if (curr.left != null) { // Keep going left. next = curr.left; } else { result.add(curr.data); // Done with left, so go right if right is not empty. // Otherwise, go up. next = (curr.right != null) ? curr.right : curr.parent; } } else if (curr.left == prev) { result.add(curr.data); // Done with left, so go right if right is not empty. Otherwise, go up. next = (curr.right != null) ? curr.right : curr.parent; } else { // Done with both children, so move up. next = curr.parent; } prev = curr; curr = next; } return result; } public static void main(String[] args) { System.exit( GenericTest .runFromAnnotations(args, "TreeWithParentInorder.java", new Object() {}.getClass().getEnclosingClass()) .ordinal()); } }
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE ldml SYSTEM "../../common/dtd/ldml.dtd"> <!-- Copyright © 1991-2014 Unicode, Inc. CLDR data files are interpreted according to the LDML specification (http://unicode.org/reports/tr35/) For terms of use, see http://www.unicode.org/copyright.html --> <ldml> <identity> <version number="$Revision: 10701 $"/> <generation date="$Date: 2014-07-30 13:14:57 -0700 (Wed, 30 Jul 2014) $"/> <language type="mzz"/> <script type="Latn"/> </identity> <layout> <orientation> <characterOrder>left-to-right</characterOrder> <lineOrder>top-to-bottom</lineOrder> </orientation> </layout> <characters> <exemplarCharacters draft="unconfirmed">[a b {bw} d e g {gw} i k {kw} l m {mw} n o p {pw} q s t u v w y ꞌ]</exemplarCharacters> <exemplarCharacters type="auxiliary" draft="unconfirmed">[c f h j r x z]</exemplarCharacters> </characters> </ldml>
{ "pile_set_name": "Github" }
--- title: "Configuring Riak KV" description: "" project: "riak_kv" project_version: "2.0.9" menu: riak_kv-2.0.9: name: "Configuring" identifier: "configuring" weight: 200 pre: icon-cog toc: true --- [config basic]: ../configuring/basic [config backend]: ../configuring/backend [config manage]: ../configuring/managing [config reference]: ../configuring/reference [config strong consistency]: ../configuring/strong-consistency [config load balance]: ../configuring/load-balancing-proxy [config mapreduce]: ../configuring/mapreduce [config search]: ../configuring/search [config v3 mdc]: ../configuring/v3-multi-datacenter [config v2 mdc]: ../configuring/v2-multi-datacenter ## In This Section #### [Basic Configuration][config basic] A guide covering commonly adjusted parameters when setting up a new cluster. [Learn More >>][config basic] #### [Backend Configuration][config backend] Information on backend-specific configuration parameters. [Learn More >>][config backend] #### [Managing Configuration][config manage] A small guide to retrieving, checking, and debugging your cluster configuration. [Learn More >>][config manage] #### [Configuration Reference][config reference] A detailed list of all possible configuration parameters. [Learn More >>][config reference] #### [Implementing Strong Consistency][config strong consistency] An article providing information on configuring and monitoring a Riak KV cluster's optional strong consistency subsystem. [Learn More >>][config strong consistency] #### [Load Balancing & Proxy][config load balance] A brief guide on commonly used load-balancing and proxy solutions. [Learn More >>][config load balance] #### [MapReduce Settings][config mapreduce] Tutorial on configuring and tuning MapReduce for a cluster. [Learn More >>][config mapreduce] #### [Search Settings][config search] Information on configuring and using Riak KV Search from an operational perspective. [Learn More >>][config search] #### [V3 Multi-Datacenter][config v3 mdc] A guide on configuring Riak Enterprise's V3 Multi-Datacenter Replication [Learn More >>][config v3 mdc]
{ "pile_set_name": "Github" }
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #pragma once #include <aws/securityhub/SecurityHub_EXPORTS.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <utility> namespace Aws { namespace Utils { namespace Json { class JsonValue; class JsonView; } // namespace Json } // namespace Utils namespace SecurityHub { namespace Model { /** * <p>Identifies a finding to update using * <code>BatchUpdateFindings</code>.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/securityhub-2018-10-26/AwsSecurityFindingIdentifier">AWS * API Reference</a></p> */ class AWS_SECURITYHUB_API AwsSecurityFindingIdentifier { public: AwsSecurityFindingIdentifier(); AwsSecurityFindingIdentifier(Aws::Utils::Json::JsonView jsonValue); AwsSecurityFindingIdentifier& operator=(Aws::Utils::Json::JsonView jsonValue); Aws::Utils::Json::JsonValue Jsonize() const; /** * <p>The identifier of the finding that was specified by the finding provider.</p> */ inline const Aws::String& GetId() const{ return m_id; } /** * <p>The identifier of the finding that was specified by the finding provider.</p> */ inline bool IdHasBeenSet() const { return m_idHasBeenSet; } /** * <p>The identifier of the finding that was specified by the finding provider.</p> */ inline void SetId(const Aws::String& value) { m_idHasBeenSet = true; m_id = value; } /** * <p>The identifier of the finding that was specified by the finding provider.</p> */ inline void SetId(Aws::String&& value) { m_idHasBeenSet = true; m_id = std::move(value); } /** * <p>The identifier of the finding that was specified by the finding provider.</p> */ inline void SetId(const char* value) { m_idHasBeenSet = true; m_id.assign(value); } /** * <p>The identifier of the finding that was specified by the finding provider.</p> */ inline AwsSecurityFindingIdentifier& WithId(const Aws::String& value) { SetId(value); return *this;} /** * <p>The identifier of the finding that was specified by the finding provider.</p> */ inline AwsSecurityFindingIdentifier& WithId(Aws::String&& value) { SetId(std::move(value)); return *this;} /** * <p>The identifier of the finding that was specified by the finding provider.</p> */ inline AwsSecurityFindingIdentifier& WithId(const char* value) { SetId(value); return *this;} /** * <p>The ARN generated by Security Hub that uniquely identifies a product that * generates findings. This can be the ARN for a third-party product that is * integrated with Security Hub, or the ARN for a custom integration.</p> */ inline const Aws::String& GetProductArn() const{ return m_productArn; } /** * <p>The ARN generated by Security Hub that uniquely identifies a product that * generates findings. This can be the ARN for a third-party product that is * integrated with Security Hub, or the ARN for a custom integration.</p> */ inline bool ProductArnHasBeenSet() const { return m_productArnHasBeenSet; } /** * <p>The ARN generated by Security Hub that uniquely identifies a product that * generates findings. This can be the ARN for a third-party product that is * integrated with Security Hub, or the ARN for a custom integration.</p> */ inline void SetProductArn(const Aws::String& value) { m_productArnHasBeenSet = true; m_productArn = value; } /** * <p>The ARN generated by Security Hub that uniquely identifies a product that * generates findings. This can be the ARN for a third-party product that is * integrated with Security Hub, or the ARN for a custom integration.</p> */ inline void SetProductArn(Aws::String&& value) { m_productArnHasBeenSet = true; m_productArn = std::move(value); } /** * <p>The ARN generated by Security Hub that uniquely identifies a product that * generates findings. This can be the ARN for a third-party product that is * integrated with Security Hub, or the ARN for a custom integration.</p> */ inline void SetProductArn(const char* value) { m_productArnHasBeenSet = true; m_productArn.assign(value); } /** * <p>The ARN generated by Security Hub that uniquely identifies a product that * generates findings. This can be the ARN for a third-party product that is * integrated with Security Hub, or the ARN for a custom integration.</p> */ inline AwsSecurityFindingIdentifier& WithProductArn(const Aws::String& value) { SetProductArn(value); return *this;} /** * <p>The ARN generated by Security Hub that uniquely identifies a product that * generates findings. This can be the ARN for a third-party product that is * integrated with Security Hub, or the ARN for a custom integration.</p> */ inline AwsSecurityFindingIdentifier& WithProductArn(Aws::String&& value) { SetProductArn(std::move(value)); return *this;} /** * <p>The ARN generated by Security Hub that uniquely identifies a product that * generates findings. This can be the ARN for a third-party product that is * integrated with Security Hub, or the ARN for a custom integration.</p> */ inline AwsSecurityFindingIdentifier& WithProductArn(const char* value) { SetProductArn(value); return *this;} private: Aws::String m_id; bool m_idHasBeenSet; Aws::String m_productArn; bool m_productArnHasBeenSet; }; } // namespace Model } // namespace SecurityHub } // namespace Aws
{ "pile_set_name": "Github" }
// Copyright © 2013, 2014, The Go-LXC Authors. All rights reserved. // Use of this source code is governed by a LGPLv2.1 // license that can be found in the LICENSE file. // +build linux,cgo package main import ( "flag" "io" "log" "os" "sync" "gopkg.in/lxc/go-lxc.v2" ) var ( lxcpath string name string clear bool x86 bool regular bool wg sync.WaitGroup ) func init() { flag.StringVar(&lxcpath, "lxcpath", lxc.DefaultConfigPath(), "Use specified container path") flag.StringVar(&name, "name", "rubik", "Name of the original container") flag.BoolVar(&clear, "clear", false, "Attach with clear environment") flag.BoolVar(&x86, "x86", false, "Attach using x86 personality") flag.BoolVar(&regular, "regular", false, "Attach using a regular user") flag.Parse() } func main() { c, err := lxc.NewContainer(name, lxcpath) if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } defer c.Release() stdoutReader, stdoutWriter, err := os.Pipe() if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } stderrReader, stderrWriter, err := os.Pipe() if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } wg.Add(1) go func() { defer wg.Done() _, err = io.Copy(os.Stdout, stdoutReader) if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } }() wg.Add(1) go func() { defer wg.Done() _, err = io.Copy(os.Stderr, stderrReader) if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } }() options := lxc.DefaultAttachOptions options.StdinFd = os.Stdin.Fd() options.StdoutFd = stdoutWriter.Fd() options.StderrFd = stderrWriter.Fd() options.ClearEnv = false if clear { options.ClearEnv = true } if x86 { options.Arch = lxc.X86 } if regular { options.UID = 1000 options.GID = 1000 } log.Printf("AttachShell\n") if err := c.AttachShell(options); err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } log.Printf("RunCommand\n") _, err = c.RunCommand([]string{"uname", "-a"}, options) if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } if err = stdoutWriter.Close(); err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } if err = stderrWriter.Close(); err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } wg.Wait() }
{ "pile_set_name": "Github" }
{ "_args": [ [ { "raw": "ansi-regex@^2.0.0", "scope": null, "escapedName": "ansi-regex", "name": "ansi-regex", "rawSpec": "^2.0.0", "spec": ">=2.0.0 <3.0.0", "type": "range" }, "C:\\Users\\ionutvmi\\AppData\\Roaming\\Sublime Text 3\\Packages\\jsfmt\\node_modules\\has-ansi" ] ], "_from": "ansi-regex@>=2.0.0 <3.0.0", "_id": "[email protected]", "_inCache": true, "_installable": true, "_location": "/ansi-regex", "_nodeVersion": "0.10.32", "_npmOperationalInternal": { "host": "packages-18-east.internal.npmjs.com", "tmp": "tmp/ansi-regex-2.1.1.tgz_1484363378013_0.4482989883981645" }, "_npmUser": { "name": "qix", "email": "[email protected]" }, "_npmVersion": "2.14.2", "_phantomChildren": {}, "_requested": { "raw": "ansi-regex@^2.0.0", "scope": null, "escapedName": "ansi-regex", "name": "ansi-regex", "rawSpec": "^2.0.0", "spec": ">=2.0.0 <3.0.0", "type": "range" }, "_requiredBy": [ "/has-ansi", "/strip-ansi" ], "_resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz", "_shasum": "c3b33ab5ee360d86e0e628f0468ae7ef27d654df", "_shrinkwrap": null, "_spec": "ansi-regex@^2.0.0", "_where": "C:\\Users\\ionutvmi\\AppData\\Roaming\\Sublime Text 3\\Packages\\jsfmt\\node_modules\\has-ansi", "author": { "name": "Sindre Sorhus", "email": "[email protected]", "url": "sindresorhus.com" }, "bugs": { "url": "https://github.com/chalk/ansi-regex/issues" }, "dependencies": {}, "description": "Regular expression for matching ANSI escape codes", "devDependencies": { "ava": "0.17.0", "xo": "0.16.0" }, "directories": {}, "dist": { "shasum": "c3b33ab5ee360d86e0e628f0468ae7ef27d654df", "tarball": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz" }, "engines": { "node": ">=0.10.0" }, "files": [ "index.js" ], "gitHead": "7c908e7b4eb6cd82bfe1295e33fdf6d166c7ed85", "homepage": "https://github.com/chalk/ansi-regex#readme", "keywords": [ "ansi", "styles", "color", "colour", "colors", "terminal", "console", "cli", "string", "tty", "escape", "formatting", "rgb", "256", "shell", "xterm", "command-line", "text", "regex", "regexp", "re", "match", "test", "find", "pattern" ], "license": "MIT", "maintainers": [ { "name": "qix", "email": "[email protected]" }, { "name": "sindresorhus", "email": "[email protected]" } ], "name": "ansi-regex", "optionalDependencies": {}, "readme": "ERROR: No README data found!", "repository": { "type": "git", "url": "git+https://github.com/chalk/ansi-regex.git" }, "scripts": { "test": "xo && ava --verbose", "view-supported": "node fixtures/view-codes.js" }, "version": "2.1.1", "xo": { "rules": { "guard-for-in": 0, "no-loop-func": 0 } } }
{ "pile_set_name": "Github" }
{ "name": "methods", "version": "0.0.1", "description": "HTTP methods that node supports", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [ "http", "methods" ], "author": { "name": "TJ Holowaychuk" }, "license": "MIT", "readme": "ERROR: No README data found!", "_id": "[email protected]", "_from": "[email protected]" }
{ "pile_set_name": "Github" }
# /* ************************************************************************** # * * # * (C) Copyright Edward Diener 2014. * # * Distributed under the Boost Software License, Version 1.0. (See * # * accompanying file LICENSE_1_0.txt or copy at * # * http://www.boost.org/LICENSE_1_0.txt) * # * * # ************************************************************************** */ # # /* See http://www.boost.org for most recent version. */ # # ifndef BOOST_PREPROCESSOR_TUPLE_DETAIL_IS_SINGLE_RETURN_HPP # define BOOST_PREPROCESSOR_TUPLE_DETAIL_IS_SINGLE_RETURN_HPP # # include <boost/preprocessor/config/config.hpp> # # /* BOOST_PP_TUPLE_IS_SINGLE_RETURN */ # # if BOOST_PP_VARIADICS && BOOST_PP_VARIADICS_MSVC # include <boost/preprocessor/control/iif.hpp> # include <boost/preprocessor/facilities/is_1.hpp> # include <boost/preprocessor/tuple/size.hpp> # define BOOST_PP_TUPLE_IS_SINGLE_RETURN(sr,nsr,tuple) \ BOOST_PP_IIF(BOOST_PP_IS_1(BOOST_PP_TUPLE_SIZE(tuple)),sr,nsr) \ /**/ # endif /* BOOST_PP_VARIADICS && BOOST_PP_VARIADICS_MSVC */ # # endif /* BOOST_PREPROCESSOR_TUPLE_DETAIL_IS_SINGLE_RETURN_HPP */
{ "pile_set_name": "Github" }
// Copyright 2014 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/compiler/js-builtin-reducer.h" #include "src/compilation-dependencies.h" #include "src/compiler/access-builder.h" #include "src/compiler/js-graph.h" #include "src/compiler/node-matchers.h" #include "src/compiler/node-properties.h" #include "src/compiler/simplified-operator.h" #include "src/compiler/type-cache.h" #include "src/compiler/types.h" #include "src/objects-inl.h" namespace v8 { namespace internal { namespace compiler { // Helper class to access JSCallFunction nodes that are potential candidates // for reduction when they have a BuiltinFunctionId associated with them. class JSCallReduction { public: explicit JSCallReduction(Node* node) : node_(node) {} // Determines whether the node is a JSCallFunction operation that targets a // constant callee being a well-known builtin with a BuiltinFunctionId. bool HasBuiltinFunctionId() { if (node_->opcode() != IrOpcode::kJSCallFunction) return false; HeapObjectMatcher m(NodeProperties::GetValueInput(node_, 0)); if (!m.HasValue() || !m.Value()->IsJSFunction()) return false; Handle<JSFunction> function = Handle<JSFunction>::cast(m.Value()); return function->shared()->HasBuiltinFunctionId(); } // Retrieves the BuiltinFunctionId as described above. BuiltinFunctionId GetBuiltinFunctionId() { DCHECK_EQ(IrOpcode::kJSCallFunction, node_->opcode()); HeapObjectMatcher m(NodeProperties::GetValueInput(node_, 0)); Handle<JSFunction> function = Handle<JSFunction>::cast(m.Value()); return function->shared()->builtin_function_id(); } bool ReceiverMatches(Type* type) { return NodeProperties::GetType(receiver())->Is(type); } // Determines whether the call takes zero inputs. bool InputsMatchZero() { return GetJSCallArity() == 0; } // Determines whether the call takes one input of the given type. bool InputsMatchOne(Type* t1) { return GetJSCallArity() == 1 && NodeProperties::GetType(GetJSCallInput(0))->Is(t1); } // Determines whether the call takes two inputs of the given types. bool InputsMatchTwo(Type* t1, Type* t2) { return GetJSCallArity() == 2 && NodeProperties::GetType(GetJSCallInput(0))->Is(t1) && NodeProperties::GetType(GetJSCallInput(1))->Is(t2); } // Determines whether the call takes inputs all of the given type. bool InputsMatchAll(Type* t) { for (int i = 0; i < GetJSCallArity(); i++) { if (!NodeProperties::GetType(GetJSCallInput(i))->Is(t)) { return false; } } return true; } Node* receiver() { return NodeProperties::GetValueInput(node_, 1); } Node* left() { return GetJSCallInput(0); } Node* right() { return GetJSCallInput(1); } int GetJSCallArity() { DCHECK_EQ(IrOpcode::kJSCallFunction, node_->opcode()); // Skip first (i.e. callee) and second (i.e. receiver) operand. return node_->op()->ValueInputCount() - 2; } Node* GetJSCallInput(int index) { DCHECK_EQ(IrOpcode::kJSCallFunction, node_->opcode()); DCHECK_LT(index, GetJSCallArity()); // Skip first (i.e. callee) and second (i.e. receiver) operand. return NodeProperties::GetValueInput(node_, index + 2); } private: Node* node_; }; JSBuiltinReducer::JSBuiltinReducer(Editor* editor, JSGraph* jsgraph, Flags flags, CompilationDependencies* dependencies, Handle<Context> native_context) : AdvancedReducer(editor), dependencies_(dependencies), flags_(flags), jsgraph_(jsgraph), native_context_(native_context), type_cache_(TypeCache::Get()) {} namespace { // TODO(turbofan): Shall we move this to the NodeProperties? Or some (untyped) // alias analyzer? bool IsSame(Node* a, Node* b) { if (a == b) { return true; } else if (a->opcode() == IrOpcode::kCheckHeapObject) { return IsSame(a->InputAt(0), b); } else if (b->opcode() == IrOpcode::kCheckHeapObject) { return IsSame(a, b->InputAt(0)); } return false; } MaybeHandle<Map> GetMapWitness(Node* node) { Node* receiver = NodeProperties::GetValueInput(node, 1); Node* effect = NodeProperties::GetEffectInput(node); // Check if the {node} is dominated by a CheckMaps with a single map // for the {receiver}, and if so use that map for the lowering below. for (Node* dominator = effect;;) { if (dominator->opcode() == IrOpcode::kCheckMaps && IsSame(dominator->InputAt(0), receiver)) { if (dominator->op()->ValueInputCount() == 2) { HeapObjectMatcher m(dominator->InputAt(1)); if (m.HasValue()) return Handle<Map>::cast(m.Value()); } return MaybeHandle<Map>(); } if (dominator->op()->EffectInputCount() != 1) { // Didn't find any appropriate CheckMaps node. return MaybeHandle<Map>(); } dominator = NodeProperties::GetEffectInput(dominator); } } // TODO(turbofan): This was copied from Crankshaft, might be too restrictive. bool IsReadOnlyLengthDescriptor(Handle<Map> jsarray_map) { DCHECK(!jsarray_map->is_dictionary_map()); Isolate* isolate = jsarray_map->GetIsolate(); Handle<Name> length_string = isolate->factory()->length_string(); DescriptorArray* descriptors = jsarray_map->instance_descriptors(); int number = descriptors->SearchWithCache(isolate, *length_string, *jsarray_map); DCHECK_NE(DescriptorArray::kNotFound, number); return descriptors->GetDetails(number).IsReadOnly(); } // TODO(turbofan): This was copied from Crankshaft, might be too restrictive. bool CanInlineArrayResizeOperation(Handle<Map> receiver_map) { Isolate* const isolate = receiver_map->GetIsolate(); if (!receiver_map->prototype()->IsJSArray()) return false; Handle<JSArray> receiver_prototype(JSArray::cast(receiver_map->prototype()), isolate); // Ensure that all prototypes of the {receiver} are stable. for (PrototypeIterator it(isolate, receiver_prototype, kStartAtReceiver); !it.IsAtEnd(); it.Advance()) { Handle<JSReceiver> current = PrototypeIterator::GetCurrent<JSReceiver>(it); if (!current->map()->is_stable()) return false; } return receiver_map->instance_type() == JS_ARRAY_TYPE && IsFastElementsKind(receiver_map->elements_kind()) && !receiver_map->is_dictionary_map() && receiver_map->is_extensible() && (!receiver_map->is_prototype_map() || receiver_map->is_stable()) && isolate->IsFastArrayConstructorPrototypeChainIntact() && isolate->IsAnyInitialArrayPrototype(receiver_prototype) && !IsReadOnlyLengthDescriptor(receiver_map); } bool CanInlineJSArrayIteration(Handle<Map> receiver_map) { Isolate* const isolate = receiver_map->GetIsolate(); // Ensure that the [[Prototype]] is actually an exotic Array if (!receiver_map->prototype()->IsJSArray()) return false; // Don't inline JSArrays with slow elements of any kind if (!IsFastElementsKind(receiver_map->elements_kind())) return false; // If the receiver map has packed elements, no need to check the prototype. // This requires a MapCheck where this is used. if (!IsFastHoleyElementsKind(receiver_map->elements_kind())) return true; Handle<JSArray> receiver_prototype(JSArray::cast(receiver_map->prototype()), isolate); // Ensure all prototypes of the {receiver} are stable. for (PrototypeIterator it(isolate, receiver_prototype, kStartAtReceiver); !it.IsAtEnd(); it.Advance()) { Handle<JSReceiver> current = PrototypeIterator::GetCurrent<JSReceiver>(it); if (!current->map()->is_stable()) return false; } // For holey Arrays, ensure that the array_protector cell is valid (must be // a CompilationDependency), and the JSArray prototype has not been altered. return receiver_map->instance_type() == JS_ARRAY_TYPE && (!receiver_map->is_dictionary_map() || receiver_map->is_stable()) && isolate->IsFastArrayConstructorPrototypeChainIntact() && isolate->IsAnyInitialArrayPrototype(receiver_prototype); } } // namespace Reduction JSBuiltinReducer::ReduceArrayIterator(Node* node, IterationKind kind) { Handle<Map> receiver_map; if (GetMapWitness(node).ToHandle(&receiver_map)) { return ReduceArrayIterator(receiver_map, node, kind, ArrayIteratorKind::kArray); } return NoChange(); } Reduction JSBuiltinReducer::ReduceTypedArrayIterator(Node* node, IterationKind kind) { Handle<Map> receiver_map; if (GetMapWitness(node).ToHandle(&receiver_map) && receiver_map->instance_type() == JS_TYPED_ARRAY_TYPE) { return ReduceArrayIterator(receiver_map, node, kind, ArrayIteratorKind::kTypedArray); } return NoChange(); } Reduction JSBuiltinReducer::ReduceArrayIterator(Handle<Map> receiver_map, Node* node, IterationKind kind, ArrayIteratorKind iter_kind) { Node* receiver = NodeProperties::GetValueInput(node, 1); Node* effect = NodeProperties::GetEffectInput(node); Node* control = NodeProperties::GetControlInput(node); if (iter_kind == ArrayIteratorKind::kTypedArray) { // See if we can skip the neutering check. if (isolate()->IsArrayBufferNeuteringIntact()) { // Add a code dependency so we are deoptimized in case an ArrayBuffer // gets neutered. dependencies()->AssumePropertyCell( factory()->array_buffer_neutering_protector()); } else { // For JSTypedArray iterator methods, deopt if the buffer is neutered. // This is potentially a deopt loop, but should be extremely unlikely. DCHECK_EQ(JS_TYPED_ARRAY_TYPE, receiver_map->instance_type()); Node* buffer = effect = graph()->NewNode( simplified()->LoadField(AccessBuilder::ForJSArrayBufferViewBuffer()), receiver, effect, control); // Deoptimize if the {buffer} has been neutered. Node* check = effect = graph()->NewNode( simplified()->ArrayBufferWasNeutered(), buffer, effect, control); check = graph()->NewNode(simplified()->BooleanNot(), check); effect = graph()->NewNode(simplified()->CheckIf(), check, effect, control); } } int map_index = -1; Node* object_map = jsgraph()->UndefinedConstant(); switch (receiver_map->instance_type()) { case JS_ARRAY_TYPE: if (kind == IterationKind::kKeys) { map_index = Context::FAST_ARRAY_KEY_ITERATOR_MAP_INDEX; } else { map_index = kind == IterationKind::kValues ? Context::FAST_SMI_ARRAY_VALUE_ITERATOR_MAP_INDEX : Context::FAST_SMI_ARRAY_KEY_VALUE_ITERATOR_MAP_INDEX; if (CanInlineJSArrayIteration(receiver_map)) { // Use `generic` elements for holey arrays if there may be elements // on the prototype chain. map_index += static_cast<int>(receiver_map->elements_kind()); object_map = jsgraph()->Constant(receiver_map); if (IsFastHoleyElementsKind(receiver_map->elements_kind())) { Handle<JSObject> initial_array_prototype( native_context()->initial_array_prototype(), isolate()); dependencies()->AssumePrototypeMapsStable(receiver_map, initial_array_prototype); } } else { map_index += (Context::GENERIC_ARRAY_VALUE_ITERATOR_MAP_INDEX - Context::FAST_SMI_ARRAY_VALUE_ITERATOR_MAP_INDEX); } } break; case JS_TYPED_ARRAY_TYPE: if (kind == IterationKind::kKeys) { map_index = Context::TYPED_ARRAY_KEY_ITERATOR_MAP_INDEX; } else { DCHECK_GE(receiver_map->elements_kind(), UINT8_ELEMENTS); DCHECK_LE(receiver_map->elements_kind(), UINT8_CLAMPED_ELEMENTS); map_index = (kind == IterationKind::kValues ? Context::UINT8_ARRAY_VALUE_ITERATOR_MAP_INDEX : Context::UINT8_ARRAY_KEY_VALUE_ITERATOR_MAP_INDEX) + (receiver_map->elements_kind() - UINT8_ELEMENTS); } break; default: if (kind == IterationKind::kKeys) { map_index = Context::GENERIC_ARRAY_KEY_ITERATOR_MAP_INDEX; } else if (kind == IterationKind::kValues) { map_index = Context::GENERIC_ARRAY_VALUE_ITERATOR_MAP_INDEX; } else { map_index = Context::GENERIC_ARRAY_KEY_VALUE_ITERATOR_MAP_INDEX; } break; } DCHECK_GE(map_index, Context::TYPED_ARRAY_KEY_ITERATOR_MAP_INDEX); DCHECK_LE(map_index, Context::GENERIC_ARRAY_VALUE_ITERATOR_MAP_INDEX); Handle<Map> map(Map::cast(native_context()->get(map_index)), isolate()); // allocate new iterator effect = graph()->NewNode( common()->BeginRegion(RegionObservability::kNotObservable), effect); Node* value = effect = graph()->NewNode( simplified()->Allocate(NOT_TENURED), jsgraph()->Constant(JSArrayIterator::kSize), effect, control); effect = graph()->NewNode(simplified()->StoreField(AccessBuilder::ForMap()), value, jsgraph()->Constant(map), effect, control); effect = graph()->NewNode( simplified()->StoreField(AccessBuilder::ForJSObjectProperties()), value, jsgraph()->EmptyFixedArrayConstant(), effect, control); effect = graph()->NewNode( simplified()->StoreField(AccessBuilder::ForJSObjectElements()), value, jsgraph()->EmptyFixedArrayConstant(), effect, control); // attach the iterator to this object effect = graph()->NewNode( simplified()->StoreField(AccessBuilder::ForJSArrayIteratorObject()), value, receiver, effect, control); effect = graph()->NewNode( simplified()->StoreField(AccessBuilder::ForJSArrayIteratorIndex()), value, jsgraph()->ZeroConstant(), effect, control); effect = graph()->NewNode( simplified()->StoreField(AccessBuilder::ForJSArrayIteratorObjectMap()), value, object_map, effect, control); value = effect = graph()->NewNode(common()->FinishRegion(), value, effect); // replace it ReplaceWithValue(node, value, effect, control); return Replace(value); } Reduction JSBuiltinReducer::ReduceFastArrayIteratorNext( Handle<Map> iterator_map, Node* node, IterationKind kind) { Node* iterator = NodeProperties::GetValueInput(node, 1); Node* effect = NodeProperties::GetEffectInput(node); Node* control = NodeProperties::GetControlInput(node); Node* context = NodeProperties::GetContextInput(node); if (kind != IterationKind::kKeys && !isolate()->IsFastArrayIterationIntact()) { // Avoid deopt loops for non-key iteration if the // fast_array_iteration_protector cell has been invalidated. return NoChange(); } ElementsKind elements_kind = JSArrayIterator::ElementsKindForInstanceType( iterator_map->instance_type()); if (IsFastHoleyElementsKind(elements_kind)) { if (!isolate()->IsFastArrayConstructorPrototypeChainIntact()) { return NoChange(); } else { Handle<JSObject> initial_array_prototype( native_context()->initial_array_prototype(), isolate()); dependencies()->AssumePropertyCell(factory()->array_protector()); } } Node* array = effect = graph()->NewNode( simplified()->LoadField(AccessBuilder::ForJSArrayIteratorObject()), iterator, effect, control); Node* check0 = graph()->NewNode(simplified()->ReferenceEqual(), array, jsgraph()->UndefinedConstant()); Node* branch0 = graph()->NewNode(common()->Branch(BranchHint::kFalse), check0, control); Node* vdone_false0; Node* vfalse0; Node* efalse0 = effect; Node* if_false0 = graph()->NewNode(common()->IfFalse(), branch0); { // iterator.[[IteratedObject]] !== undefined, continue iterating. Node* index = efalse0 = graph()->NewNode( simplified()->LoadField(AccessBuilder::ForJSArrayIteratorIndex( JS_ARRAY_TYPE, elements_kind)), iterator, efalse0, if_false0); Node* length = efalse0 = graph()->NewNode( simplified()->LoadField(AccessBuilder::ForJSArrayLength(elements_kind)), array, efalse0, if_false0); Node* check1 = graph()->NewNode(simplified()->NumberLessThan(), index, length); Node* branch1 = graph()->NewNode(common()->Branch(BranchHint::kTrue), check1, if_false0); Node* vdone_true1; Node* vtrue1 = NULL; Node* etrue1 = efalse0; Node* if_true1 = graph()->NewNode(common()->IfTrue(), branch1); { // iterator.[[NextIndex]] < array.length, continue iterating vdone_true1 = jsgraph()->FalseConstant(); if (kind == IterationKind::kKeys) { vtrue1 = index; } else { // For value/entry iteration, first step is a mapcheck to ensure // inlining is still valid. Node* orig_map = etrue1 = graph()->NewNode(simplified()->LoadField( AccessBuilder::ForJSArrayIteratorObjectMap()), iterator, etrue1, if_true1); etrue1 = graph()->NewNode(simplified()->CheckMaps(1), array, orig_map, etrue1, if_true1); } if (kind != IterationKind::kKeys) { Node* elements = etrue1 = graph()->NewNode( simplified()->LoadField(AccessBuilder::ForJSObjectElements()), array, etrue1, if_true1); Node* value = etrue1 = graph()->NewNode( simplified()->LoadElement( AccessBuilder::ForFixedArrayElement(elements_kind)), elements, index, etrue1, if_true1); // Convert hole to undefined if needed. if (elements_kind == FAST_HOLEY_ELEMENTS || elements_kind == FAST_HOLEY_SMI_ELEMENTS) { value = graph()->NewNode(simplified()->ConvertTaggedHoleToUndefined(), value); } else if (elements_kind == FAST_HOLEY_DOUBLE_ELEMENTS) { // TODO(bmeurer): avoid deopt if not all uses of value are truncated. CheckFloat64HoleMode mode = CheckFloat64HoleMode::kAllowReturnHole; value = etrue1 = graph()->NewNode( simplified()->CheckFloat64Hole(mode), value, etrue1, if_true1); } if (kind == IterationKind::kEntries) { // Allocate elements for key/value pair vtrue1 = etrue1 = graph()->NewNode(javascript()->CreateKeyValueArray(), index, value, context, etrue1); } else { DCHECK_EQ(kind, IterationKind::kValues); vtrue1 = value; } } Node* next_index = graph()->NewNode(simplified()->NumberAdd(), index, jsgraph()->OneConstant()); next_index = graph()->NewNode(simplified()->NumberToUint32(), next_index); etrue1 = graph()->NewNode( simplified()->StoreField(AccessBuilder::ForJSArrayIteratorIndex( JS_ARRAY_TYPE, elements_kind)), iterator, next_index, etrue1, if_true1); } Node* vdone_false1; Node* vfalse1 = NULL; Node* efalse1 = efalse0; Node* if_false1 = graph()->NewNode(common()->IfFalse(), branch1); { // iterator.[[NextIndex]] >= array.length, stop iterating. vdone_false1 = jsgraph()->TrueConstant(); vfalse1 = jsgraph()->UndefinedConstant(); efalse1 = graph()->NewNode( simplified()->StoreField(AccessBuilder::ForJSArrayIteratorObject()), iterator, vfalse1, efalse1, if_false1); } if_false0 = graph()->NewNode(common()->Merge(2), if_true1, if_false1); efalse0 = graph()->NewNode(common()->EffectPhi(2), etrue1, efalse1, if_false0); vfalse0 = graph()->NewNode(common()->Phi(MachineRepresentation::kTagged, 2), vtrue1, vfalse1, if_false0); vdone_false0 = graph()->NewNode(common()->Phi(MachineRepresentation::kTagged, 2), vdone_true1, vdone_false1, if_false0); } Node* vdone_true0; Node* vtrue0; Node* etrue0 = effect; Node* if_true0 = graph()->NewNode(common()->IfTrue(), branch0); { // iterator.[[IteratedObject]] === undefined, the iterator is done. vdone_true0 = jsgraph()->TrueConstant(); vtrue0 = jsgraph()->UndefinedConstant(); } control = graph()->NewNode(common()->Merge(2), if_false0, if_true0); effect = graph()->NewNode(common()->EffectPhi(2), efalse0, etrue0, control); Node* value = graph()->NewNode(common()->Phi(MachineRepresentation::kTagged, 2), vfalse0, vtrue0, control); Node* done = graph()->NewNode(common()->Phi(MachineRepresentation::kTagged, 2), vdone_false0, vdone_true0, control); // Create IteratorResult object. value = effect = graph()->NewNode(javascript()->CreateIterResultObject(), value, done, context, effect); ReplaceWithValue(node, value, effect, control); return Replace(value); } Reduction JSBuiltinReducer::ReduceTypedArrayIteratorNext( Handle<Map> iterator_map, Node* node, IterationKind kind) { Node* iterator = NodeProperties::GetValueInput(node, 1); Node* effect = NodeProperties::GetEffectInput(node); Node* control = NodeProperties::GetControlInput(node); Node* context = NodeProperties::GetContextInput(node); ElementsKind elements_kind = JSArrayIterator::ElementsKindForInstanceType( iterator_map->instance_type()); Node* array = effect = graph()->NewNode( simplified()->LoadField(AccessBuilder::ForJSArrayIteratorObject()), iterator, effect, control); Node* check0 = graph()->NewNode(simplified()->ReferenceEqual(), array, jsgraph()->UndefinedConstant()); Node* branch0 = graph()->NewNode(common()->Branch(BranchHint::kFalse), check0, control); Node* vdone_false0; Node* vfalse0; Node* efalse0 = effect; Node* if_false0 = graph()->NewNode(common()->IfFalse(), branch0); { // iterator.[[IteratedObject]] !== undefined, continue iterating. Node* index = efalse0 = graph()->NewNode( simplified()->LoadField(AccessBuilder::ForJSArrayIteratorIndex( JS_TYPED_ARRAY_TYPE, elements_kind)), iterator, efalse0, if_false0); // typedarray.[[ViewedArrayBuffer]] Node* buffer = efalse0 = graph()->NewNode( simplified()->LoadField(AccessBuilder::ForJSArrayBufferViewBuffer()), array, efalse0, if_false0); // See if we can skip the neutering check. if (isolate()->IsArrayBufferNeuteringIntact()) { // Add a code dependency so we are deoptimized in case an ArrayBuffer // gets neutered. dependencies()->AssumePropertyCell( factory()->array_buffer_neutering_protector()); } else { // Deoptimize if the array byuffer was neutered. Node* check1 = efalse0 = graph()->NewNode( simplified()->ArrayBufferWasNeutered(), buffer, efalse0, if_false0); check1 = graph()->NewNode(simplified()->BooleanNot(), check1); efalse0 = graph()->NewNode(simplified()->CheckIf(), check1, efalse0, if_false0); } Node* length = efalse0 = graph()->NewNode( simplified()->LoadField(AccessBuilder::ForJSTypedArrayLength()), array, efalse0, if_false0); Node* check2 = graph()->NewNode(simplified()->NumberLessThan(), index, length); Node* branch2 = graph()->NewNode(common()->Branch(BranchHint::kTrue), check2, if_false0); Node* vdone_true2; Node* vtrue2 = NULL; Node* etrue2 = efalse0; Node* if_true2 = graph()->NewNode(common()->IfTrue(), branch2); { // iterator.[[NextIndex]] < array.length, continue iterating vdone_true2 = jsgraph()->FalseConstant(); if (kind == IterationKind::kKeys) { vtrue2 = index; } Node* next_index = graph()->NewNode(simplified()->NumberAdd(), index, jsgraph()->OneConstant()); next_index = graph()->NewNode(simplified()->NumberToUint32(), next_index); etrue2 = graph()->NewNode( simplified()->StoreField(AccessBuilder::ForJSArrayIteratorIndex( JS_TYPED_ARRAY_TYPE, elements_kind)), iterator, next_index, etrue2, if_true2); if (kind != IterationKind::kKeys) { Node* elements = etrue2 = graph()->NewNode( simplified()->LoadField(AccessBuilder::ForJSObjectElements()), array, etrue2, if_true2); Node* base_ptr = etrue2 = graph()->NewNode( simplified()->LoadField( AccessBuilder::ForFixedTypedArrayBaseBasePointer()), elements, etrue2, if_true2); Node* external_ptr = etrue2 = graph()->NewNode( simplified()->LoadField( AccessBuilder::ForFixedTypedArrayBaseExternalPointer()), elements, etrue2, if_true2); ExternalArrayType array_type = kExternalInt8Array; switch (elements_kind) { #define TYPED_ARRAY_CASE(Type, type, TYPE, ctype, size) \ case TYPE##_ELEMENTS: \ array_type = kExternal##Type##Array; \ break; TYPED_ARRAYS(TYPED_ARRAY_CASE) default: UNREACHABLE(); #undef TYPED_ARRAY_CASE } Node* value = etrue2 = graph()->NewNode(simplified()->LoadTypedElement(array_type), buffer, base_ptr, external_ptr, index, etrue2, if_true2); if (kind == IterationKind::kEntries) { // Allocate elements for key/value pair vtrue2 = etrue2 = graph()->NewNode(javascript()->CreateKeyValueArray(), index, value, context, etrue2); } else { DCHECK(kind == IterationKind::kValues); vtrue2 = value; } } } Node* vdone_false2; Node* vfalse2 = NULL; Node* efalse2 = efalse0; Node* if_false2 = graph()->NewNode(common()->IfFalse(), branch2); { // iterator.[[NextIndex]] >= array.length, stop iterating. vdone_false2 = jsgraph()->TrueConstant(); vfalse2 = jsgraph()->UndefinedConstant(); efalse2 = graph()->NewNode( simplified()->StoreField(AccessBuilder::ForJSArrayIteratorObject()), iterator, vfalse2, efalse2, if_false2); } if_false0 = graph()->NewNode(common()->Merge(2), if_true2, if_false2); efalse0 = graph()->NewNode(common()->EffectPhi(2), etrue2, efalse2, if_false0); vfalse0 = graph()->NewNode(common()->Phi(MachineRepresentation::kTagged, 2), vtrue2, vfalse2, if_false0); vdone_false0 = graph()->NewNode(common()->Phi(MachineRepresentation::kTagged, 2), vdone_true2, vdone_false2, if_false0); } Node* vdone_true0; Node* vtrue0; Node* etrue0 = effect; Node* if_true0 = graph()->NewNode(common()->IfTrue(), branch0); { // iterator.[[IteratedObject]] === undefined, the iterator is done. vdone_true0 = jsgraph()->TrueConstant(); vtrue0 = jsgraph()->UndefinedConstant(); } control = graph()->NewNode(common()->Merge(2), if_false0, if_true0); effect = graph()->NewNode(common()->EffectPhi(2), efalse0, etrue0, control); Node* value = graph()->NewNode(common()->Phi(MachineRepresentation::kTagged, 2), vfalse0, vtrue0, control); Node* done = graph()->NewNode(common()->Phi(MachineRepresentation::kTagged, 2), vdone_false0, vdone_true0, control); // Create IteratorResult object. value = effect = graph()->NewNode(javascript()->CreateIterResultObject(), value, done, context, effect); ReplaceWithValue(node, value, effect, control); return Replace(value); } Reduction JSBuiltinReducer::ReduceArrayIteratorNext(Node* node) { Handle<Map> receiver_map; if (GetMapWitness(node).ToHandle(&receiver_map)) { switch (receiver_map->instance_type()) { case JS_TYPED_ARRAY_KEY_ITERATOR_TYPE: return ReduceTypedArrayIteratorNext(receiver_map, node, IterationKind::kKeys); case JS_FAST_ARRAY_KEY_ITERATOR_TYPE: return ReduceFastArrayIteratorNext(receiver_map, node, IterationKind::kKeys); case JS_INT8_ARRAY_KEY_VALUE_ITERATOR_TYPE: case JS_UINT8_ARRAY_KEY_VALUE_ITERATOR_TYPE: case JS_INT16_ARRAY_KEY_VALUE_ITERATOR_TYPE: case JS_UINT16_ARRAY_KEY_VALUE_ITERATOR_TYPE: case JS_INT32_ARRAY_KEY_VALUE_ITERATOR_TYPE: case JS_UINT32_ARRAY_KEY_VALUE_ITERATOR_TYPE: case JS_FLOAT32_ARRAY_KEY_VALUE_ITERATOR_TYPE: case JS_FLOAT64_ARRAY_KEY_VALUE_ITERATOR_TYPE: case JS_UINT8_CLAMPED_ARRAY_KEY_VALUE_ITERATOR_TYPE: return ReduceTypedArrayIteratorNext(receiver_map, node, IterationKind::kEntries); case JS_FAST_SMI_ARRAY_KEY_VALUE_ITERATOR_TYPE: case JS_FAST_HOLEY_SMI_ARRAY_KEY_VALUE_ITERATOR_TYPE: case JS_FAST_ARRAY_KEY_VALUE_ITERATOR_TYPE: case JS_FAST_HOLEY_ARRAY_KEY_VALUE_ITERATOR_TYPE: case JS_FAST_DOUBLE_ARRAY_KEY_VALUE_ITERATOR_TYPE: case JS_FAST_HOLEY_DOUBLE_ARRAY_KEY_VALUE_ITERATOR_TYPE: return ReduceFastArrayIteratorNext(receiver_map, node, IterationKind::kEntries); case JS_INT8_ARRAY_VALUE_ITERATOR_TYPE: case JS_UINT8_ARRAY_VALUE_ITERATOR_TYPE: case JS_INT16_ARRAY_VALUE_ITERATOR_TYPE: case JS_UINT16_ARRAY_VALUE_ITERATOR_TYPE: case JS_INT32_ARRAY_VALUE_ITERATOR_TYPE: case JS_UINT32_ARRAY_VALUE_ITERATOR_TYPE: case JS_FLOAT32_ARRAY_VALUE_ITERATOR_TYPE: case JS_FLOAT64_ARRAY_VALUE_ITERATOR_TYPE: case JS_UINT8_CLAMPED_ARRAY_VALUE_ITERATOR_TYPE: return ReduceTypedArrayIteratorNext(receiver_map, node, IterationKind::kValues); case JS_FAST_SMI_ARRAY_VALUE_ITERATOR_TYPE: case JS_FAST_HOLEY_SMI_ARRAY_VALUE_ITERATOR_TYPE: case JS_FAST_ARRAY_VALUE_ITERATOR_TYPE: case JS_FAST_HOLEY_ARRAY_VALUE_ITERATOR_TYPE: case JS_FAST_DOUBLE_ARRAY_VALUE_ITERATOR_TYPE: case JS_FAST_HOLEY_DOUBLE_ARRAY_VALUE_ITERATOR_TYPE: return ReduceFastArrayIteratorNext(receiver_map, node, IterationKind::kValues); default: // Slow array iterators are not reduced return NoChange(); } } return NoChange(); } // ES6 section 22.1.3.17 Array.prototype.pop ( ) Reduction JSBuiltinReducer::ReduceArrayPop(Node* node) { Handle<Map> receiver_map; Node* receiver = NodeProperties::GetValueInput(node, 1); Node* effect = NodeProperties::GetEffectInput(node); Node* control = NodeProperties::GetControlInput(node); // TODO(turbofan): Extend this to also handle fast (holey) double elements // once we got the hole NaN mess sorted out in TurboFan/V8. if (GetMapWitness(node).ToHandle(&receiver_map) && CanInlineArrayResizeOperation(receiver_map) && IsFastSmiOrObjectElementsKind(receiver_map->elements_kind())) { // Install code dependencies on the {receiver} prototype maps and the // global array protector cell. dependencies()->AssumePropertyCell(factory()->array_protector()); dependencies()->AssumePrototypeMapsStable(receiver_map); // Load the "length" property of the {receiver}. Node* length = effect = graph()->NewNode( simplified()->LoadField( AccessBuilder::ForJSArrayLength(receiver_map->elements_kind())), receiver, effect, control); // Check if the {receiver} has any elements. Node* check = graph()->NewNode(simplified()->NumberEqual(), length, jsgraph()->ZeroConstant()); Node* branch = graph()->NewNode(common()->Branch(BranchHint::kFalse), check, control); Node* if_true = graph()->NewNode(common()->IfTrue(), branch); Node* etrue = effect; Node* vtrue = jsgraph()->UndefinedConstant(); Node* if_false = graph()->NewNode(common()->IfFalse(), branch); Node* efalse = effect; Node* vfalse; { // Load the elements backing store from the {receiver}. Node* elements = efalse = graph()->NewNode( simplified()->LoadField(AccessBuilder::ForJSObjectElements()), receiver, efalse, if_false); // Ensure that we aren't popping from a copy-on-write backing store. elements = efalse = graph()->NewNode(simplified()->EnsureWritableFastElements(), receiver, elements, efalse, if_false); // Compute the new {length}. length = graph()->NewNode(simplified()->NumberSubtract(), length, jsgraph()->OneConstant()); // Store the new {length} to the {receiver}. efalse = graph()->NewNode( simplified()->StoreField( AccessBuilder::ForJSArrayLength(receiver_map->elements_kind())), receiver, length, efalse, if_false); // Load the last entry from the {elements}. vfalse = efalse = graph()->NewNode( simplified()->LoadElement(AccessBuilder::ForFixedArrayElement( receiver_map->elements_kind())), elements, length, efalse, if_false); // Store a hole to the element we just removed from the {receiver}. efalse = graph()->NewNode( simplified()->StoreElement(AccessBuilder::ForFixedArrayElement( GetHoleyElementsKind(receiver_map->elements_kind()))), elements, length, jsgraph()->TheHoleConstant(), efalse, if_false); } control = graph()->NewNode(common()->Merge(2), if_true, if_false); effect = graph()->NewNode(common()->EffectPhi(2), etrue, efalse, control); Node* value = graph()->NewNode(common()->Phi(MachineRepresentation::kTagged, 2), vtrue, vfalse, control); // Convert the hole to undefined. Do this last, so that we can optimize // conversion operator via some smart strength reduction in many cases. if (IsFastHoleyElementsKind(receiver_map->elements_kind())) { value = graph()->NewNode(simplified()->ConvertTaggedHoleToUndefined(), value); } ReplaceWithValue(node, value, effect, control); return Replace(value); } return NoChange(); } // ES6 section 22.1.3.18 Array.prototype.push ( ) Reduction JSBuiltinReducer::ReduceArrayPush(Node* node) { Handle<Map> receiver_map; // We need exactly target, receiver and value parameters. if (node->op()->ValueInputCount() != 3) return NoChange(); Node* receiver = NodeProperties::GetValueInput(node, 1); Node* effect = NodeProperties::GetEffectInput(node); Node* control = NodeProperties::GetControlInput(node); Node* value = NodeProperties::GetValueInput(node, 2); if (GetMapWitness(node).ToHandle(&receiver_map) && CanInlineArrayResizeOperation(receiver_map)) { // Install code dependencies on the {receiver} prototype maps and the // global array protector cell. dependencies()->AssumePropertyCell(factory()->array_protector()); dependencies()->AssumePrototypeMapsStable(receiver_map); // TODO(turbofan): Perform type checks on the {value}. We are not guaranteed // to learn from these checks in case they fail, as the witness (i.e. the // map check from the LoadIC for a.push) might not be executed in baseline // code (after we stored the value in the builtin and thereby changed the // elements kind of a) before be decide to optimize this function again. We // currently don't have a proper way to deal with this; the proper solution // here is to learn on deopt, i.e. disable Array.prototype.push inlining // for this function. if (IsFastSmiElementsKind(receiver_map->elements_kind())) { value = effect = graph()->NewNode(simplified()->CheckSmi(), value, effect, control); } else if (IsFastDoubleElementsKind(receiver_map->elements_kind())) { value = effect = graph()->NewNode(simplified()->CheckNumber(), value, effect, control); // Make sure we do not store signaling NaNs into double arrays. value = graph()->NewNode(simplified()->NumberSilenceNaN(), value); } // Load the "length" property of the {receiver}. Node* length = effect = graph()->NewNode( simplified()->LoadField( AccessBuilder::ForJSArrayLength(receiver_map->elements_kind())), receiver, effect, control); // Load the elements backing store of the {receiver}. Node* elements = effect = graph()->NewNode( simplified()->LoadField(AccessBuilder::ForJSObjectElements()), receiver, effect, control); // TODO(turbofan): Check if we need to grow the {elements} backing store. // This will deopt if we cannot grow the array further, and we currently // don't necessarily learn from it. See the comment on the value type check // above. GrowFastElementsFlags flags = GrowFastElementsFlag::kArrayObject; if (IsFastDoubleElementsKind(receiver_map->elements_kind())) { flags |= GrowFastElementsFlag::kDoubleElements; } elements = effect = graph()->NewNode(simplified()->MaybeGrowFastElements(flags), receiver, elements, length, length, effect, control); // Append the value to the {elements}. effect = graph()->NewNode( simplified()->StoreElement( AccessBuilder::ForFixedArrayElement(receiver_map->elements_kind())), elements, length, value, effect, control); // Return the new length of the {receiver}. value = graph()->NewNode(simplified()->NumberAdd(), length, jsgraph()->OneConstant()); ReplaceWithValue(node, value, effect, control); return Replace(value); } return NoChange(); } namespace { bool HasInstanceTypeWitness(Node* receiver, Node* effect, InstanceType instance_type) { for (Node* dominator = effect;;) { if (dominator->opcode() == IrOpcode::kCheckMaps && IsSame(dominator->InputAt(0), receiver)) { // Check if all maps have the given {instance_type}. for (int i = 1; i < dominator->op()->ValueInputCount(); ++i) { Node* const map = NodeProperties::GetValueInput(dominator, i); Type* const map_type = NodeProperties::GetType(map); if (!map_type->IsHeapConstant()) return false; Handle<Map> const map_value = Handle<Map>::cast(map_type->AsHeapConstant()->Value()); if (map_value->instance_type() != instance_type) return false; } return true; } switch (dominator->opcode()) { case IrOpcode::kStoreField: { FieldAccess const& access = FieldAccessOf(dominator->op()); if (access.base_is_tagged == kTaggedBase && access.offset == HeapObject::kMapOffset) { return false; } break; } case IrOpcode::kStoreElement: case IrOpcode::kStoreTypedElement: break; default: { DCHECK_EQ(1, dominator->op()->EffectOutputCount()); if (dominator->op()->EffectInputCount() != 1 || !dominator->op()->HasProperty(Operator::kNoWrite)) { // Didn't find any appropriate CheckMaps node. return false; } break; } } dominator = NodeProperties::GetEffectInput(dominator); } } } // namespace // ES6 section 20.3.4.10 Date.prototype.getTime ( ) Reduction JSBuiltinReducer::ReduceDateGetTime(Node* node) { Node* receiver = NodeProperties::GetValueInput(node, 1); Node* effect = NodeProperties::GetEffectInput(node); Node* control = NodeProperties::GetControlInput(node); if (HasInstanceTypeWitness(receiver, effect, JS_DATE_TYPE)) { Node* value = effect = graph()->NewNode( simplified()->LoadField(AccessBuilder::ForJSDateValue()), receiver, effect, control); ReplaceWithValue(node, value, effect, control); return Replace(value); } return NoChange(); } // ES6 section 18.2.2 isFinite ( number ) Reduction JSBuiltinReducer::ReduceGlobalIsFinite(Node* node) { JSCallReduction r(node); if (r.InputsMatchOne(Type::PlainPrimitive())) { // isFinite(a:plain-primitive) -> NumberEqual(a', a') // where a' = NumberSubtract(ToNumber(a), ToNumber(a)) Node* input = ToNumber(r.GetJSCallInput(0)); Node* diff = graph()->NewNode(simplified()->NumberSubtract(), input, input); Node* value = graph()->NewNode(simplified()->NumberEqual(), diff, diff); return Replace(value); } return NoChange(); } // ES6 section 18.2.3 isNaN ( number ) Reduction JSBuiltinReducer::ReduceGlobalIsNaN(Node* node) { JSCallReduction r(node); if (r.InputsMatchOne(Type::PlainPrimitive())) { // isNaN(a:plain-primitive) -> BooleanNot(NumberEqual(a', a')) // where a' = ToNumber(a) Node* input = ToNumber(r.GetJSCallInput(0)); Node* check = graph()->NewNode(simplified()->NumberEqual(), input, input); Node* value = graph()->NewNode(simplified()->BooleanNot(), check); return Replace(value); } return NoChange(); } // ES6 section 20.2.2.1 Math.abs ( x ) Reduction JSBuiltinReducer::ReduceMathAbs(Node* node) { JSCallReduction r(node); if (r.InputsMatchOne(Type::PlainPrimitive())) { // Math.abs(a:plain-primitive) -> NumberAbs(ToNumber(a)) Node* input = ToNumber(r.GetJSCallInput(0)); Node* value = graph()->NewNode(simplified()->NumberAbs(), input); return Replace(value); } return NoChange(); } // ES6 section 20.2.2.2 Math.acos ( x ) Reduction JSBuiltinReducer::ReduceMathAcos(Node* node) { JSCallReduction r(node); if (r.InputsMatchOne(Type::PlainPrimitive())) { // Math.acos(a:plain-primitive) -> NumberAcos(ToNumber(a)) Node* input = ToNumber(r.GetJSCallInput(0)); Node* value = graph()->NewNode(simplified()->NumberAcos(), input); return Replace(value); } return NoChange(); } // ES6 section 20.2.2.3 Math.acosh ( x ) Reduction JSBuiltinReducer::ReduceMathAcosh(Node* node) { JSCallReduction r(node); if (r.InputsMatchOne(Type::PlainPrimitive())) { // Math.acosh(a:plain-primitive) -> NumberAcosh(ToNumber(a)) Node* input = ToNumber(r.GetJSCallInput(0)); Node* value = graph()->NewNode(simplified()->NumberAcosh(), input); return Replace(value); } return NoChange(); } // ES6 section 20.2.2.4 Math.asin ( x ) Reduction JSBuiltinReducer::ReduceMathAsin(Node* node) { JSCallReduction r(node); if (r.InputsMatchOne(Type::PlainPrimitive())) { // Math.asin(a:plain-primitive) -> NumberAsin(ToNumber(a)) Node* input = ToNumber(r.GetJSCallInput(0)); Node* value = graph()->NewNode(simplified()->NumberAsin(), input); return Replace(value); } return NoChange(); } // ES6 section 20.2.2.5 Math.asinh ( x ) Reduction JSBuiltinReducer::ReduceMathAsinh(Node* node) { JSCallReduction r(node); if (r.InputsMatchOne(Type::PlainPrimitive())) { // Math.asinh(a:plain-primitive) -> NumberAsinh(ToNumber(a)) Node* input = ToNumber(r.GetJSCallInput(0)); Node* value = graph()->NewNode(simplified()->NumberAsinh(), input); return Replace(value); } return NoChange(); } // ES6 section 20.2.2.6 Math.atan ( x ) Reduction JSBuiltinReducer::ReduceMathAtan(Node* node) { JSCallReduction r(node); if (r.InputsMatchOne(Type::PlainPrimitive())) { // Math.atan(a:plain-primitive) -> NumberAtan(ToNumber(a)) Node* input = ToNumber(r.GetJSCallInput(0)); Node* value = graph()->NewNode(simplified()->NumberAtan(), input); return Replace(value); } return NoChange(); } // ES6 section 20.2.2.7 Math.atanh ( x ) Reduction JSBuiltinReducer::ReduceMathAtanh(Node* node) { JSCallReduction r(node); if (r.InputsMatchOne(Type::PlainPrimitive())) { // Math.atanh(a:plain-primitive) -> NumberAtanh(ToNumber(a)) Node* input = ToNumber(r.GetJSCallInput(0)); Node* value = graph()->NewNode(simplified()->NumberAtanh(), input); return Replace(value); } return NoChange(); } // ES6 section 20.2.2.8 Math.atan2 ( y, x ) Reduction JSBuiltinReducer::ReduceMathAtan2(Node* node) { JSCallReduction r(node); if (r.InputsMatchTwo(Type::PlainPrimitive(), Type::PlainPrimitive())) { // Math.atan2(a:plain-primitive, // b:plain-primitive) -> NumberAtan2(ToNumber(a), // ToNumber(b)) Node* left = ToNumber(r.left()); Node* right = ToNumber(r.right()); Node* value = graph()->NewNode(simplified()->NumberAtan2(), left, right); return Replace(value); } return NoChange(); } // ES6 section 20.2.2.10 Math.ceil ( x ) Reduction JSBuiltinReducer::ReduceMathCeil(Node* node) { JSCallReduction r(node); if (r.InputsMatchOne(Type::PlainPrimitive())) { // Math.ceil(a:plain-primitive) -> NumberCeil(ToNumber(a)) Node* input = ToNumber(r.GetJSCallInput(0)); Node* value = graph()->NewNode(simplified()->NumberCeil(), input); return Replace(value); } return NoChange(); } // ES6 section 20.2.2.11 Math.clz32 ( x ) Reduction JSBuiltinReducer::ReduceMathClz32(Node* node) { JSCallReduction r(node); if (r.InputsMatchOne(Type::PlainPrimitive())) { // Math.clz32(a:plain-primitive) -> NumberClz32(ToUint32(a)) Node* input = ToUint32(r.GetJSCallInput(0)); Node* value = graph()->NewNode(simplified()->NumberClz32(), input); return Replace(value); } return NoChange(); } // ES6 section 20.2.2.12 Math.cos ( x ) Reduction JSBuiltinReducer::ReduceMathCos(Node* node) { JSCallReduction r(node); if (r.InputsMatchOne(Type::PlainPrimitive())) { // Math.cos(a:plain-primitive) -> NumberCos(ToNumber(a)) Node* input = ToNumber(r.GetJSCallInput(0)); Node* value = graph()->NewNode(simplified()->NumberCos(), input); return Replace(value); } return NoChange(); } // ES6 section 20.2.2.13 Math.cosh ( x ) Reduction JSBuiltinReducer::ReduceMathCosh(Node* node) { JSCallReduction r(node); if (r.InputsMatchOne(Type::PlainPrimitive())) { // Math.cosh(a:plain-primitive) -> NumberCosh(ToNumber(a)) Node* input = ToNumber(r.GetJSCallInput(0)); Node* value = graph()->NewNode(simplified()->NumberCosh(), input); return Replace(value); } return NoChange(); } // ES6 section 20.2.2.14 Math.exp ( x ) Reduction JSBuiltinReducer::ReduceMathExp(Node* node) { JSCallReduction r(node); if (r.InputsMatchOne(Type::PlainPrimitive())) { // Math.exp(a:plain-primitive) -> NumberExp(ToNumber(a)) Node* input = ToNumber(r.GetJSCallInput(0)); Node* value = graph()->NewNode(simplified()->NumberExp(), input); return Replace(value); } return NoChange(); } // ES6 section 20.2.2.15 Math.expm1 ( x ) Reduction JSBuiltinReducer::ReduceMathExpm1(Node* node) { JSCallReduction r(node); if (r.InputsMatchOne(Type::Number())) { // Math.expm1(a:number) -> NumberExpm1(a) Node* value = graph()->NewNode(simplified()->NumberExpm1(), r.left()); return Replace(value); } return NoChange(); } // ES6 section 20.2.2.16 Math.floor ( x ) Reduction JSBuiltinReducer::ReduceMathFloor(Node* node) { JSCallReduction r(node); if (r.InputsMatchOne(Type::PlainPrimitive())) { // Math.floor(a:plain-primitive) -> NumberFloor(ToNumber(a)) Node* input = ToNumber(r.GetJSCallInput(0)); Node* value = graph()->NewNode(simplified()->NumberFloor(), input); return Replace(value); } return NoChange(); } // ES6 section 20.2.2.17 Math.fround ( x ) Reduction JSBuiltinReducer::ReduceMathFround(Node* node) { JSCallReduction r(node); if (r.InputsMatchOne(Type::PlainPrimitive())) { // Math.fround(a:plain-primitive) -> NumberFround(ToNumber(a)) Node* input = ToNumber(r.GetJSCallInput(0)); Node* value = graph()->NewNode(simplified()->NumberFround(), input); return Replace(value); } return NoChange(); } // ES6 section 20.2.2.19 Math.imul ( x, y ) Reduction JSBuiltinReducer::ReduceMathImul(Node* node) { JSCallReduction r(node); if (r.InputsMatchTwo(Type::PlainPrimitive(), Type::PlainPrimitive())) { // Math.imul(a:plain-primitive, // b:plain-primitive) -> NumberImul(ToUint32(a), // ToUint32(b)) Node* left = ToUint32(r.left()); Node* right = ToUint32(r.right()); Node* value = graph()->NewNode(simplified()->NumberImul(), left, right); return Replace(value); } return NoChange(); } // ES6 section 20.2.2.20 Math.log ( x ) Reduction JSBuiltinReducer::ReduceMathLog(Node* node) { JSCallReduction r(node); if (r.InputsMatchOne(Type::PlainPrimitive())) { // Math.log(a:plain-primitive) -> NumberLog(ToNumber(a)) Node* input = ToNumber(r.GetJSCallInput(0)); Node* value = graph()->NewNode(simplified()->NumberLog(), input); return Replace(value); } return NoChange(); } // ES6 section 20.2.2.21 Math.log1p ( x ) Reduction JSBuiltinReducer::ReduceMathLog1p(Node* node) { JSCallReduction r(node); if (r.InputsMatchOne(Type::PlainPrimitive())) { // Math.log1p(a:plain-primitive) -> NumberLog1p(ToNumber(a)) Node* input = ToNumber(r.GetJSCallInput(0)); Node* value = graph()->NewNode(simplified()->NumberLog1p(), input); return Replace(value); } return NoChange(); } // ES6 section 20.2.2.22 Math.log10 ( x ) Reduction JSBuiltinReducer::ReduceMathLog10(Node* node) { JSCallReduction r(node); if (r.InputsMatchOne(Type::Number())) { // Math.log10(a:number) -> NumberLog10(a) Node* value = graph()->NewNode(simplified()->NumberLog10(), r.left()); return Replace(value); } return NoChange(); } // ES6 section 20.2.2.23 Math.log2 ( x ) Reduction JSBuiltinReducer::ReduceMathLog2(Node* node) { JSCallReduction r(node); if (r.InputsMatchOne(Type::Number())) { // Math.log2(a:number) -> NumberLog(a) Node* value = graph()->NewNode(simplified()->NumberLog2(), r.left()); return Replace(value); } return NoChange(); } // ES6 section 20.2.2.24 Math.max ( value1, value2, ...values ) Reduction JSBuiltinReducer::ReduceMathMax(Node* node) { JSCallReduction r(node); if (r.InputsMatchZero()) { // Math.max() -> -Infinity return Replace(jsgraph()->Constant(-V8_INFINITY)); } if (r.InputsMatchAll(Type::PlainPrimitive())) { // Math.max(a:plain-primitive, b:plain-primitive, ...) Node* value = ToNumber(r.GetJSCallInput(0)); for (int i = 1; i < r.GetJSCallArity(); i++) { Node* input = ToNumber(r.GetJSCallInput(i)); value = graph()->NewNode(simplified()->NumberMax(), value, input); } return Replace(value); } return NoChange(); } // ES6 section 20.2.2.25 Math.min ( value1, value2, ...values ) Reduction JSBuiltinReducer::ReduceMathMin(Node* node) { JSCallReduction r(node); if (r.InputsMatchZero()) { // Math.min() -> Infinity return Replace(jsgraph()->Constant(V8_INFINITY)); } if (r.InputsMatchAll(Type::PlainPrimitive())) { // Math.min(a:plain-primitive, b:plain-primitive, ...) Node* value = ToNumber(r.GetJSCallInput(0)); for (int i = 1; i < r.GetJSCallArity(); i++) { Node* input = ToNumber(r.GetJSCallInput(i)); value = graph()->NewNode(simplified()->NumberMin(), value, input); } return Replace(value); } return NoChange(); } // ES6 section 20.2.2.26 Math.pow ( x, y ) Reduction JSBuiltinReducer::ReduceMathPow(Node* node) { JSCallReduction r(node); if (r.InputsMatchTwo(Type::PlainPrimitive(), Type::PlainPrimitive())) { // Math.pow(a:plain-primitive, // b:plain-primitive) -> NumberPow(ToNumber(a), ToNumber(b)) Node* left = ToNumber(r.left()); Node* right = ToNumber(r.right()); Node* value = graph()->NewNode(simplified()->NumberPow(), left, right); return Replace(value); } return NoChange(); } // ES6 section 20.2.2.28 Math.round ( x ) Reduction JSBuiltinReducer::ReduceMathRound(Node* node) { JSCallReduction r(node); if (r.InputsMatchOne(Type::PlainPrimitive())) { // Math.round(a:plain-primitive) -> NumberRound(ToNumber(a)) Node* input = ToNumber(r.GetJSCallInput(0)); Node* value = graph()->NewNode(simplified()->NumberRound(), input); return Replace(value); } return NoChange(); } // ES6 section 20.2.2.9 Math.cbrt ( x ) Reduction JSBuiltinReducer::ReduceMathCbrt(Node* node) { JSCallReduction r(node); if (r.InputsMatchOne(Type::Number())) { // Math.cbrt(a:number) -> NumberCbrt(a) Node* value = graph()->NewNode(simplified()->NumberCbrt(), r.left()); return Replace(value); } return NoChange(); } // ES6 section 20.2.2.29 Math.sign ( x ) Reduction JSBuiltinReducer::ReduceMathSign(Node* node) { JSCallReduction r(node); if (r.InputsMatchOne(Type::PlainPrimitive())) { // Math.sign(a:plain-primitive) -> NumberSign(ToNumber(a)) Node* input = ToNumber(r.GetJSCallInput(0)); Node* value = graph()->NewNode(simplified()->NumberSign(), input); return Replace(value); } return NoChange(); } // ES6 section 20.2.2.30 Math.sin ( x ) Reduction JSBuiltinReducer::ReduceMathSin(Node* node) { JSCallReduction r(node); if (r.InputsMatchOne(Type::PlainPrimitive())) { // Math.sin(a:plain-primitive) -> NumberSin(ToNumber(a)) Node* input = ToNumber(r.GetJSCallInput(0)); Node* value = graph()->NewNode(simplified()->NumberSin(), input); return Replace(value); } return NoChange(); } // ES6 section 20.2.2.31 Math.sinh ( x ) Reduction JSBuiltinReducer::ReduceMathSinh(Node* node) { JSCallReduction r(node); if (r.InputsMatchOne(Type::PlainPrimitive())) { // Math.sinh(a:plain-primitive) -> NumberSinh(ToNumber(a)) Node* input = ToNumber(r.GetJSCallInput(0)); Node* value = graph()->NewNode(simplified()->NumberSinh(), input); return Replace(value); } return NoChange(); } // ES6 section 20.2.2.32 Math.sqrt ( x ) Reduction JSBuiltinReducer::ReduceMathSqrt(Node* node) { JSCallReduction r(node); if (r.InputsMatchOne(Type::PlainPrimitive())) { // Math.sqrt(a:plain-primitive) -> NumberSqrt(ToNumber(a)) Node* input = ToNumber(r.GetJSCallInput(0)); Node* value = graph()->NewNode(simplified()->NumberSqrt(), input); return Replace(value); } return NoChange(); } // ES6 section 20.2.2.33 Math.tan ( x ) Reduction JSBuiltinReducer::ReduceMathTan(Node* node) { JSCallReduction r(node); if (r.InputsMatchOne(Type::PlainPrimitive())) { // Math.tan(a:plain-primitive) -> NumberTan(ToNumber(a)) Node* input = ToNumber(r.GetJSCallInput(0)); Node* value = graph()->NewNode(simplified()->NumberTan(), input); return Replace(value); } return NoChange(); } // ES6 section 20.2.2.34 Math.tanh ( x ) Reduction JSBuiltinReducer::ReduceMathTanh(Node* node) { JSCallReduction r(node); if (r.InputsMatchOne(Type::PlainPrimitive())) { // Math.tanh(a:plain-primitive) -> NumberTanh(ToNumber(a)) Node* input = ToNumber(r.GetJSCallInput(0)); Node* value = graph()->NewNode(simplified()->NumberTanh(), input); return Replace(value); } return NoChange(); } // ES6 section 20.2.2.35 Math.trunc ( x ) Reduction JSBuiltinReducer::ReduceMathTrunc(Node* node) { JSCallReduction r(node); if (r.InputsMatchOne(Type::PlainPrimitive())) { // Math.trunc(a:plain-primitive) -> NumberTrunc(ToNumber(a)) Node* input = ToNumber(r.GetJSCallInput(0)); Node* value = graph()->NewNode(simplified()->NumberTrunc(), input); return Replace(value); } return NoChange(); } // ES6 section 20.1.2.2 Number.isFinite ( number ) Reduction JSBuiltinReducer::ReduceNumberIsFinite(Node* node) { JSCallReduction r(node); if (r.InputsMatchOne(Type::Number())) { // Number.isFinite(a:number) -> NumberEqual(a', a') // where a' = NumberSubtract(a, a) Node* input = r.GetJSCallInput(0); Node* diff = graph()->NewNode(simplified()->NumberSubtract(), input, input); Node* value = graph()->NewNode(simplified()->NumberEqual(), diff, diff); return Replace(value); } return NoChange(); } // ES6 section 20.1.2.3 Number.isInteger ( number ) Reduction JSBuiltinReducer::ReduceNumberIsInteger(Node* node) { JSCallReduction r(node); if (r.InputsMatchOne(Type::Number())) { // Number.isInteger(x:number) -> NumberEqual(NumberSubtract(x, x'), #0) // where x' = NumberTrunc(x) Node* input = r.GetJSCallInput(0); Node* trunc = graph()->NewNode(simplified()->NumberTrunc(), input); Node* diff = graph()->NewNode(simplified()->NumberSubtract(), input, trunc); Node* value = graph()->NewNode(simplified()->NumberEqual(), diff, jsgraph()->ZeroConstant()); return Replace(value); } return NoChange(); } // ES6 section 20.1.2.4 Number.isNaN ( number ) Reduction JSBuiltinReducer::ReduceNumberIsNaN(Node* node) { JSCallReduction r(node); if (r.InputsMatchOne(Type::Number())) { // Number.isNaN(a:number) -> BooleanNot(NumberEqual(a, a)) Node* input = r.GetJSCallInput(0); Node* check = graph()->NewNode(simplified()->NumberEqual(), input, input); Node* value = graph()->NewNode(simplified()->BooleanNot(), check); return Replace(value); } return NoChange(); } // ES6 section 20.1.2.5 Number.isSafeInteger ( number ) Reduction JSBuiltinReducer::ReduceNumberIsSafeInteger(Node* node) { JSCallReduction r(node); if (r.InputsMatchOne(type_cache_.kSafeInteger)) { // Number.isInteger(x:safe-integer) -> #true Node* value = jsgraph()->TrueConstant(); return Replace(value); } return NoChange(); } // ES6 section 20.1.2.13 Number.parseInt ( string, radix ) Reduction JSBuiltinReducer::ReduceNumberParseInt(Node* node) { JSCallReduction r(node); if (r.InputsMatchOne(type_cache_.kSafeInteger) || r.InputsMatchTwo(type_cache_.kSafeInteger, type_cache_.kZeroOrUndefined) || r.InputsMatchTwo(type_cache_.kSafeInteger, type_cache_.kTenOrUndefined)) { // Number.parseInt(a:safe-integer) -> a // Number.parseInt(a:safe-integer,b:#0\/undefined) -> a // Number.parseInt(a:safe-integer,b:#10\/undefined) -> a Node* value = r.GetJSCallInput(0); return Replace(value); } return NoChange(); } // ES6 section 21.1.2.1 String.fromCharCode ( ...codeUnits ) Reduction JSBuiltinReducer::ReduceStringFromCharCode(Node* node) { JSCallReduction r(node); if (r.InputsMatchOne(Type::PlainPrimitive())) { // String.fromCharCode(a:plain-primitive) -> StringFromCharCode(a) Node* input = ToNumber(r.GetJSCallInput(0)); Node* value = graph()->NewNode(simplified()->StringFromCharCode(), input); return Replace(value); } return NoChange(); } namespace { Node* GetStringWitness(Node* node) { Node* receiver = NodeProperties::GetValueInput(node, 1); Type* receiver_type = NodeProperties::GetType(receiver); Node* effect = NodeProperties::GetEffectInput(node); if (receiver_type->Is(Type::String())) return receiver; // Check if the {node} is dominated by a CheckString renaming for // it's {receiver}, and if so use that renaming as {receiver} for // the lowering below. for (Node* dominator = effect;;) { if (dominator->opcode() == IrOpcode::kCheckString && IsSame(dominator->InputAt(0), receiver)) { return dominator; } if (dominator->op()->EffectInputCount() != 1) { // Didn't find any appropriate CheckString node. return nullptr; } dominator = NodeProperties::GetEffectInput(dominator); } } } // namespace // ES6 section 21.1.3.1 String.prototype.charAt ( pos ) Reduction JSBuiltinReducer::ReduceStringCharAt(Node* node) { // We need at least target, receiver and index parameters. if (node->op()->ValueInputCount() >= 3) { Node* index = NodeProperties::GetValueInput(node, 2); Type* index_type = NodeProperties::GetType(index); Node* effect = NodeProperties::GetEffectInput(node); Node* control = NodeProperties::GetControlInput(node); if (index_type->Is(Type::Unsigned32())) { if (Node* receiver = GetStringWitness(node)) { // Determine the {receiver} length. Node* receiver_length = effect = graph()->NewNode( simplified()->LoadField(AccessBuilder::ForStringLength()), receiver, effect, control); // Check if {index} is less than {receiver} length. Node* check = graph()->NewNode(simplified()->NumberLessThan(), index, receiver_length); Node* branch = graph()->NewNode(common()->Branch(BranchHint::kTrue), check, control); Node* if_true = graph()->NewNode(common()->IfTrue(), branch); Node* vtrue; { // Load the character from the {receiver}. vtrue = graph()->NewNode(simplified()->StringCharCodeAt(), receiver, index, if_true); // Return it as single character string. vtrue = graph()->NewNode(simplified()->StringFromCharCode(), vtrue); } // Return the empty string otherwise. Node* if_false = graph()->NewNode(common()->IfFalse(), branch); Node* vfalse = jsgraph()->EmptyStringConstant(); control = graph()->NewNode(common()->Merge(2), if_true, if_false); Node* value = graph()->NewNode(common()->Phi(MachineRepresentation::kTagged, 2), vtrue, vfalse, control); ReplaceWithValue(node, value, effect, control); return Replace(value); } } } return NoChange(); } // ES6 section 21.1.3.2 String.prototype.charCodeAt ( pos ) Reduction JSBuiltinReducer::ReduceStringCharCodeAt(Node* node) { // We need at least target, receiver and index parameters. if (node->op()->ValueInputCount() >= 3) { Node* index = NodeProperties::GetValueInput(node, 2); Type* index_type = NodeProperties::GetType(index); Node* effect = NodeProperties::GetEffectInput(node); Node* control = NodeProperties::GetControlInput(node); if (index_type->Is(Type::Unsigned32())) { if (Node* receiver = GetStringWitness(node)) { // Determine the {receiver} length. Node* receiver_length = effect = graph()->NewNode( simplified()->LoadField(AccessBuilder::ForStringLength()), receiver, effect, control); // Check if {index} is less than {receiver} length. Node* check = graph()->NewNode(simplified()->NumberLessThan(), index, receiver_length); Node* branch = graph()->NewNode(common()->Branch(BranchHint::kTrue), check, control); // Load the character from the {receiver}. Node* if_true = graph()->NewNode(common()->IfTrue(), branch); Node* vtrue = graph()->NewNode(simplified()->StringCharCodeAt(), receiver, index, if_true); // Return NaN otherwise. Node* if_false = graph()->NewNode(common()->IfFalse(), branch); Node* vfalse = jsgraph()->NaNConstant(); control = graph()->NewNode(common()->Merge(2), if_true, if_false); Node* value = graph()->NewNode(common()->Phi(MachineRepresentation::kTagged, 2), vtrue, vfalse, control); ReplaceWithValue(node, value, effect, control); return Replace(value); } } } return NoChange(); } Reduction JSBuiltinReducer::ReduceStringIterator(Node* node) { if (Node* receiver = GetStringWitness(node)) { Node* effect = NodeProperties::GetEffectInput(node); Node* control = NodeProperties::GetControlInput(node); Node* map = jsgraph()->HeapConstant( handle(native_context()->string_iterator_map(), isolate())); // allocate new iterator effect = graph()->NewNode( common()->BeginRegion(RegionObservability::kNotObservable), effect); Node* value = effect = graph()->NewNode( simplified()->Allocate(NOT_TENURED), jsgraph()->Constant(JSStringIterator::kSize), effect, control); effect = graph()->NewNode(simplified()->StoreField(AccessBuilder::ForMap()), value, map, effect, control); effect = graph()->NewNode( simplified()->StoreField(AccessBuilder::ForJSObjectProperties()), value, jsgraph()->EmptyFixedArrayConstant(), effect, control); effect = graph()->NewNode( simplified()->StoreField(AccessBuilder::ForJSObjectElements()), value, jsgraph()->EmptyFixedArrayConstant(), effect, control); // attach the iterator to this string effect = graph()->NewNode( simplified()->StoreField(AccessBuilder::ForJSStringIteratorString()), value, receiver, effect, control); effect = graph()->NewNode( simplified()->StoreField(AccessBuilder::ForJSStringIteratorIndex()), value, jsgraph()->SmiConstant(0), effect, control); value = effect = graph()->NewNode(common()->FinishRegion(), value, effect); // replace it ReplaceWithValue(node, value, effect, control); return Replace(value); } return NoChange(); } Reduction JSBuiltinReducer::ReduceStringIteratorNext(Node* node) { Node* receiver = NodeProperties::GetValueInput(node, 1); Node* effect = NodeProperties::GetEffectInput(node); Node* control = NodeProperties::GetControlInput(node); Node* context = NodeProperties::GetContextInput(node); if (HasInstanceTypeWitness(receiver, effect, JS_STRING_ITERATOR_TYPE)) { Node* string = effect = graph()->NewNode( simplified()->LoadField(AccessBuilder::ForJSStringIteratorString()), receiver, effect, control); Node* index = effect = graph()->NewNode( simplified()->LoadField(AccessBuilder::ForJSStringIteratorIndex()), receiver, effect, control); Node* length = effect = graph()->NewNode( simplified()->LoadField(AccessBuilder::ForStringLength()), string, effect, control); // branch0: if (index < length) Node* check0 = graph()->NewNode(simplified()->NumberLessThan(), index, length); Node* branch0 = graph()->NewNode(common()->Branch(BranchHint::kTrue), check0, control); Node* etrue0 = effect; Node* if_true0 = graph()->NewNode(common()->IfTrue(), branch0); Node* done_true; Node* vtrue0; { done_true = jsgraph()->FalseConstant(); Node* lead = graph()->NewNode(simplified()->StringCharCodeAt(), string, index, if_true0); // branch1: if ((lead & 0xFC00) === 0xD800) Node* check1 = graph()->NewNode(simplified()->NumberEqual(), graph()->NewNode(simplified()->NumberBitwiseAnd(), lead, jsgraph()->Constant(0xFC00)), jsgraph()->Constant(0xD800)); Node* branch1 = graph()->NewNode(common()->Branch(BranchHint::kFalse), check1, if_true0); Node* if_true1 = graph()->NewNode(common()->IfTrue(), branch1); Node* vtrue1; { Node* next_index = graph()->NewNode(simplified()->NumberAdd(), index, jsgraph()->OneConstant()); // branch2: if ((index + 1) < length) Node* check2 = graph()->NewNode(simplified()->NumberLessThan(), next_index, length); Node* branch2 = graph()->NewNode(common()->Branch(BranchHint::kTrue), check2, if_true1); Node* if_true2 = graph()->NewNode(common()->IfTrue(), branch2); Node* vtrue2; { Node* trail = graph()->NewNode(simplified()->StringCharCodeAt(), string, next_index, if_true2); // branch3: if ((trail & 0xFC00) === 0xDC00) Node* check3 = graph()->NewNode( simplified()->NumberEqual(), graph()->NewNode(simplified()->NumberBitwiseAnd(), trail, jsgraph()->Constant(0xFC00)), jsgraph()->Constant(0xDC00)); Node* branch3 = graph()->NewNode(common()->Branch(BranchHint::kTrue), check3, if_true2); Node* if_true3 = graph()->NewNode(common()->IfTrue(), branch3); Node* vtrue3; { vtrue3 = graph()->NewNode( simplified()->NumberBitwiseOr(), // Need to swap the order for big-endian platforms #if V8_TARGET_BIG_ENDIAN graph()->NewNode(simplified()->NumberShiftLeft(), lead, jsgraph()->Constant(16)), trail); #else graph()->NewNode(simplified()->NumberShiftLeft(), trail, jsgraph()->Constant(16)), lead); #endif } Node* if_false3 = graph()->NewNode(common()->IfFalse(), branch3); Node* vfalse3 = lead; if_true2 = graph()->NewNode(common()->Merge(2), if_true3, if_false3); vtrue2 = graph()->NewNode(common()->Phi(MachineRepresentation::kWord32, 2), vtrue3, vfalse3, if_true2); } Node* if_false2 = graph()->NewNode(common()->IfFalse(), branch2); Node* vfalse2 = lead; if_true1 = graph()->NewNode(common()->Merge(2), if_true2, if_false2); vtrue1 = graph()->NewNode(common()->Phi(MachineRepresentation::kWord32, 2), vtrue2, vfalse2, if_true1); } Node* if_false1 = graph()->NewNode(common()->IfFalse(), branch1); Node* vfalse1 = lead; if_true0 = graph()->NewNode(common()->Merge(2), if_true1, if_false1); vtrue0 = graph()->NewNode(common()->Phi(MachineRepresentation::kWord32, 2), vtrue1, vfalse1, if_true0); vtrue0 = graph()->NewNode( simplified()->StringFromCodePoint(UnicodeEncoding::UTF16), vtrue0); // Update iterator.[[NextIndex]] Node* char_length = etrue0 = graph()->NewNode( simplified()->LoadField(AccessBuilder::ForStringLength()), vtrue0, etrue0, if_true0); index = graph()->NewNode(simplified()->NumberAdd(), index, char_length); etrue0 = graph()->NewNode( simplified()->StoreField(AccessBuilder::ForJSStringIteratorIndex()), receiver, index, etrue0, if_true0); } Node* if_false0 = graph()->NewNode(common()->IfFalse(), branch0); Node* done_false; Node* vfalse0; { vfalse0 = jsgraph()->UndefinedConstant(); done_false = jsgraph()->TrueConstant(); } control = graph()->NewNode(common()->Merge(2), if_true0, if_false0); effect = graph()->NewNode(common()->EffectPhi(2), etrue0, effect, control); Node* value = graph()->NewNode(common()->Phi(MachineRepresentation::kTagged, 2), vtrue0, vfalse0, control); Node* done = graph()->NewNode(common()->Phi(MachineRepresentation::kTagged, 2), done_true, done_false, control); value = effect = graph()->NewNode(javascript()->CreateIterResultObject(), value, done, context, effect); ReplaceWithValue(node, value, effect, control); return Replace(value); } return NoChange(); } Reduction JSBuiltinReducer::ReduceArrayBufferViewAccessor( Node* node, InstanceType instance_type, FieldAccess const& access) { Node* receiver = NodeProperties::GetValueInput(node, 1); Node* effect = NodeProperties::GetEffectInput(node); Node* control = NodeProperties::GetControlInput(node); if (HasInstanceTypeWitness(receiver, effect, instance_type)) { // Load the {receiver}s field. Node* value = effect = graph()->NewNode(simplified()->LoadField(access), receiver, effect, control); // See if we can skip the neutering check. if (isolate()->IsArrayBufferNeuteringIntact()) { // Add a code dependency so we are deoptimized in case an ArrayBuffer // gets neutered. dependencies()->AssumePropertyCell( factory()->array_buffer_neutering_protector()); } else { // Check if the {receiver}s buffer was neutered. Node* receiver_buffer = effect = graph()->NewNode( simplified()->LoadField(AccessBuilder::ForJSArrayBufferViewBuffer()), receiver, effect, control); Node* check = effect = graph()->NewNode(simplified()->ArrayBufferWasNeutered(), receiver_buffer, effect, control); // Default to zero if the {receiver}s buffer was neutered. value = graph()->NewNode( common()->Select(MachineRepresentation::kTagged, BranchHint::kFalse), check, jsgraph()->ZeroConstant(), value); } ReplaceWithValue(node, value, effect, control); return Replace(value); } return NoChange(); } Reduction JSBuiltinReducer::Reduce(Node* node) { Reduction reduction = NoChange(); JSCallReduction r(node); // Dispatch according to the BuiltinFunctionId if present. if (!r.HasBuiltinFunctionId()) return NoChange(); switch (r.GetBuiltinFunctionId()) { case kArrayEntries: return ReduceArrayIterator(node, IterationKind::kEntries); case kArrayKeys: return ReduceArrayIterator(node, IterationKind::kKeys); case kArrayValues: return ReduceArrayIterator(node, IterationKind::kValues); case kArrayIteratorNext: return ReduceArrayIteratorNext(node); case kArrayPop: return ReduceArrayPop(node); case kArrayPush: return ReduceArrayPush(node); case kDateGetTime: return ReduceDateGetTime(node); case kGlobalIsFinite: reduction = ReduceGlobalIsFinite(node); break; case kGlobalIsNaN: reduction = ReduceGlobalIsNaN(node); break; case kMathAbs: reduction = ReduceMathAbs(node); break; case kMathAcos: reduction = ReduceMathAcos(node); break; case kMathAcosh: reduction = ReduceMathAcosh(node); break; case kMathAsin: reduction = ReduceMathAsin(node); break; case kMathAsinh: reduction = ReduceMathAsinh(node); break; case kMathAtan: reduction = ReduceMathAtan(node); break; case kMathAtanh: reduction = ReduceMathAtanh(node); break; case kMathAtan2: reduction = ReduceMathAtan2(node); break; case kMathCbrt: reduction = ReduceMathCbrt(node); break; case kMathCeil: reduction = ReduceMathCeil(node); break; case kMathClz32: reduction = ReduceMathClz32(node); break; case kMathCos: reduction = ReduceMathCos(node); break; case kMathCosh: reduction = ReduceMathCosh(node); break; case kMathExp: reduction = ReduceMathExp(node); break; case kMathExpm1: reduction = ReduceMathExpm1(node); break; case kMathFloor: reduction = ReduceMathFloor(node); break; case kMathFround: reduction = ReduceMathFround(node); break; case kMathImul: reduction = ReduceMathImul(node); break; case kMathLog: reduction = ReduceMathLog(node); break; case kMathLog1p: reduction = ReduceMathLog1p(node); break; case kMathLog10: reduction = ReduceMathLog10(node); break; case kMathLog2: reduction = ReduceMathLog2(node); break; case kMathMax: reduction = ReduceMathMax(node); break; case kMathMin: reduction = ReduceMathMin(node); break; case kMathPow: reduction = ReduceMathPow(node); break; case kMathRound: reduction = ReduceMathRound(node); break; case kMathSign: reduction = ReduceMathSign(node); break; case kMathSin: reduction = ReduceMathSin(node); break; case kMathSinh: reduction = ReduceMathSinh(node); break; case kMathSqrt: reduction = ReduceMathSqrt(node); break; case kMathTan: reduction = ReduceMathTan(node); break; case kMathTanh: reduction = ReduceMathTanh(node); break; case kMathTrunc: reduction = ReduceMathTrunc(node); break; case kNumberIsFinite: reduction = ReduceNumberIsFinite(node); break; case kNumberIsInteger: reduction = ReduceNumberIsInteger(node); break; case kNumberIsNaN: reduction = ReduceNumberIsNaN(node); break; case kNumberIsSafeInteger: reduction = ReduceNumberIsSafeInteger(node); break; case kNumberParseInt: reduction = ReduceNumberParseInt(node); break; case kStringFromCharCode: reduction = ReduceStringFromCharCode(node); break; case kStringCharAt: return ReduceStringCharAt(node); case kStringCharCodeAt: return ReduceStringCharCodeAt(node); case kStringIterator: return ReduceStringIterator(node); case kStringIteratorNext: return ReduceStringIteratorNext(node); case kDataViewByteLength: return ReduceArrayBufferViewAccessor( node, JS_DATA_VIEW_TYPE, AccessBuilder::ForJSArrayBufferViewByteLength()); case kDataViewByteOffset: return ReduceArrayBufferViewAccessor( node, JS_DATA_VIEW_TYPE, AccessBuilder::ForJSArrayBufferViewByteOffset()); case kTypedArrayByteLength: return ReduceArrayBufferViewAccessor( node, JS_TYPED_ARRAY_TYPE, AccessBuilder::ForJSArrayBufferViewByteLength()); case kTypedArrayByteOffset: return ReduceArrayBufferViewAccessor( node, JS_TYPED_ARRAY_TYPE, AccessBuilder::ForJSArrayBufferViewByteOffset()); case kTypedArrayLength: return ReduceArrayBufferViewAccessor( node, JS_TYPED_ARRAY_TYPE, AccessBuilder::ForJSTypedArrayLength()); case kTypedArrayEntries: return ReduceTypedArrayIterator(node, IterationKind::kEntries); case kTypedArrayKeys: return ReduceTypedArrayIterator(node, IterationKind::kKeys); case kTypedArrayValues: return ReduceTypedArrayIterator(node, IterationKind::kValues); default: break; } // Replace builtin call assuming replacement nodes are pure values that don't // produce an effect. Replaces {node} with {reduction} and relaxes effects. if (reduction.Changed()) ReplaceWithValue(node, reduction.replacement()); return reduction; } Node* JSBuiltinReducer::ToNumber(Node* input) { Type* input_type = NodeProperties::GetType(input); if (input_type->Is(Type::Number())) return input; return graph()->NewNode(simplified()->PlainPrimitiveToNumber(), input); } Node* JSBuiltinReducer::ToUint32(Node* input) { input = ToNumber(input); Type* input_type = NodeProperties::GetType(input); if (input_type->Is(Type::Unsigned32())) return input; return graph()->NewNode(simplified()->NumberToUint32(), input); } Graph* JSBuiltinReducer::graph() const { return jsgraph()->graph(); } Factory* JSBuiltinReducer::factory() const { return isolate()->factory(); } Isolate* JSBuiltinReducer::isolate() const { return jsgraph()->isolate(); } CommonOperatorBuilder* JSBuiltinReducer::common() const { return jsgraph()->common(); } SimplifiedOperatorBuilder* JSBuiltinReducer::simplified() const { return jsgraph()->simplified(); } JSOperatorBuilder* JSBuiltinReducer::javascript() const { return jsgraph()->javascript(); } } // namespace compiler } // namespace internal } // namespace v8
{ "pile_set_name": "Github" }
#!/bin/sh # Copyright (C) 2006-2010 OpenWrt.org # Copyright (C) 2010 Vertical Communications do_mount_no_jffs2() { check_skip || { mount_no_jffs2 && pi_mount_skip_next=true } } boot_hook_add preinit_mount_root do_mount_no_jffs2
{ "pile_set_name": "Github" }
# # test/unit/bio/appl/paml/codeml/test_report_single.rb - Unit test for Bio::PAML::Codeml::Report # # Copyright:: Copyright (C) 2008 Michael D. Barton <[email protected]> # License:: The Ruby License # # loading helper routine for testing bioruby require 'pathname' load Pathname.new(File.join(File.dirname(__FILE__), ['..'] * 5, 'bioruby_test_helper.rb')).cleanpath.to_s # libraries needed for the tests require 'test/unit' require 'bio/appl/paml/codeml/report' module Bio; module TestPAMLCodeml class TestCodemlReport < Test::Unit::TestCase TEST_DATA = Pathname.new(File.join(BioRubyTestDataPath, 'paml', 'codeml')).cleanpath.to_s def setup str = File.read(File.join(TEST_DATA, 'output.txt')) @example_report = Bio::PAML::Codeml::Report.new(str) end def test_tree_log_likelihood assert_equal(-1817.465211, @example_report.tree_log_likelihood) end def test_tree_length assert_equal(0.77902, @example_report.tree_length) end def test_alpha assert_equal(0.58871, @example_report.alpha) end def test_tree tree = "(((rabbit: 0.082889, rat: 0.187866): 0.038008, human: 0.055050): 0.033639, goat-cow: 0.096992, marsupial: 0.284574);" assert_equal(tree, @example_report.tree) end end end; end #module TestPAMLCodeml; module Bio
{ "pile_set_name": "Github" }
import React, { memo } from 'react' import { Emoji } from './Emoji' import { CountryCode } from './types' import { useContext } from './CountryContext' import { useAsync } from 'react-async-hook' import { Image, StyleSheet, PixelRatio, Text, View, ActivityIndicator, } from 'react-native' const styles = StyleSheet.create({ container: { justifyContent: 'center', alignItems: 'center', width: 30, marginRight: 10, }, emojiFlag: { alignItems: 'center', justifyContent: 'center', borderWidth: 1 / PixelRatio.get(), borderColor: 'transparent', backgroundColor: 'transparent', }, imageFlag: { resizeMode: 'contain', width: 25, height: 19, borderWidth: 1 / PixelRatio.get(), opacity: 0.8, }, }) interface FlagType { countryCode: CountryCode withEmoji?: boolean withFlagButton?: boolean flagSize: number } const ImageFlag = memo(({ countryCode, flagSize }: FlagType) => { const { getImageFlagAsync } = useContext() const asyncResult = useAsync(getImageFlagAsync, [countryCode]) if (asyncResult.loading) { return <ActivityIndicator size={'small'} /> } return ( <Image resizeMode={'contain'} style={[ styles.imageFlag, { borderColor: 'transparent', height: flagSize }, ]} source={{ uri: asyncResult.result }} /> ) }) const EmojiFlag = memo(({ countryCode, flagSize }: FlagType) => { const { getEmojiFlagAsync } = useContext() const asyncResult = useAsync(getEmojiFlagAsync, [countryCode]) if (asyncResult.loading) { return <ActivityIndicator size={'small'} /> } return ( <Text style={[styles.emojiFlag, { fontSize: flagSize }]} allowFontScaling={false} > <Emoji {...{ name: asyncResult.result! }} /> </Text> ) }) export const Flag = ({ countryCode, withEmoji, withFlagButton, flagSize, }: FlagType) => withFlagButton ? ( <View style={styles.container}> {withEmoji ? ( <EmojiFlag {...{ countryCode, flagSize }} /> ) : ( <ImageFlag {...{ countryCode, flagSize }} /> )} </View> ) : null Flag.defaultProps = { withEmoji: true, withFlagButton: true, }
{ "pile_set_name": "Github" }
// // File: BeamPixelDipServer.java (W.Badgett, G.Y.Jeng) // package cms.dip.tracker.beamspot; import cern.dip.*; import java.lang.Thread; import java.io.*; import java.text.*; import java.util.Date; import java.util.BitSet; public class BeamPixelDipServer extends Thread implements Runnable,DipPublicationErrorHandler { // Input parameters public static boolean verbose = false; public static boolean overwriteQuality = true; //if true, change quality to qualities[0] public static String subjectCMS = "dip/CMS/Tracker/BeamPixel"; public static String subjectLHC = "dip/CMS/LHCTEST/LuminousRegion"; // public static String subjectDummy = "dummy";//to have same # of arug as in BeamSpot file as same class run both of them with same # of arguemnts public static String sourceFile = "/nfshome0/dqmpro/BeamMonitorDQM/BeamPixelResults.txt"; public static int[] timeoutLS = {5,10}; //LumiSections public final static boolean publishStatErrors = true; public final static int secPerLS = 23; public final static int rad2urad = 1000000; public final static int cm2um = 10000; public final static int cm2mm = 10; public final static String[] qualities = {"Uncertain","Bad","Good"}; DipFactory dip; DipData messageCMS; DipData messageLHC; DipPublication publicationCMS; DipPublication publicationLHC; int runnum = 0; String startTime = getDateTime(); String endTime = getDateTime(); long startTimeStamp = 0; long endTimeStamp = 0; String lumiRange = "0 - 0"; String quality = "Uncertain"; int type = -1; float x = 0; float y = 0; float z = 0; float dxdz = 0; float dydz = 0; float err_x = 0; float err_y = 0; float err_z = 0; float err_dxdz = 0; float err_dydz = 0; float width_x = 0; float width_y = 0; float sigma_z = 0; float err_width_x = 0; float err_width_y = 0; float err_sigma_z = 0; float Size[] = new float[3]; float Centroid[] = new float[3]; float Tilt[] = new float[2]; boolean keepRunning; long lastFitTime = 0; long lastModTime = 0; BitSet alive = new BitSet(8); int idleTime = 0; int lsCount = 0; public void handleException(DipPublication publication, DipException e) { System.out.println("handleException: " + getDateTime()); System.out.println("Error handler for " + publication.getTopicName() + " called because " + e.getMessage()); e.printStackTrace(); } public void run() { java.util.Date now = new java.util.Date(); try { dip = Dip.create("CmsBeamPixel_"+now.getTime()); System.out.println("Server Started at " + getDateTime()); System.out.println("Making publication " + subjectCMS); publicationCMS = dip.createDipPublication(subjectCMS, this); messageCMS = dip.createDipData(); System.out.println("Making publication " + subjectLHC); publicationLHC = dip.createDipPublication(subjectLHC, this); messageLHC = dip.createDipData(); keepRunning = true; } catch ( DipException e ) { System.err.println("DipException: " + getDateTime()); keepRunning = false; } quality = qualities[0]; while (keepRunning) { try { File logFile = new File(sourceFile); if (!logFile.exists()) { polling(); continue; } else { FileReader fr = new FileReader(logFile); BufferedReader br = new BufferedReader(fr); lastModTime = logFile.lastModified(); if (lastFitTime == 0) lastFitTime = lastModTime; if (logFile.length() == 0) { lastFitTime = lastModTime; if (!alive.get(6)) { System.out.println("New run starts"); if (verbose) System.out.println("Initial lastModTime = " + getDateTime(lastModTime)); alive.flip(6); } } if (lastModTime > lastFitTime) { if (verbose) { System.out.println("Time of last fit = " + getDateTime(lastFitTime)); System.out.println("Time of current fit = " + getDateTime(lastModTime)); } lastFitTime = lastModTime; if (logFile.length() > 0) { if (verbose) System.out.println("Read record from " + sourceFile); if (readRcd(br)) { trueRcd(); alive.clear(); alive.flip(7); } else fakeRcd(); if (verbose) System.out.println("Publish new record"); lsCount = 0; idleTime = 0; } br.close(); fr.close(); } else{ br.close(); fr.close(); polling(); continue; } } // Quality of the publish results if (overwriteQuality) publishRcd(qualities[0],"Testing",true,true); else if (quality == qualities[1]) publishRcd(quality,"No BeamFit or Fit Fails",true,true); else publishRcd(quality,"",true,true); } catch (IOException e) { System.err.println("IOException: " + getDateTime()); e.printStackTrace(); }; } } private void polling() { if (lsCount != 0 && lsCount%60 == 0) { System.out.println("Waiting for data..." + getDateTime()); } try { Thread.sleep(1000); }//every sec catch(InterruptedException e) { System.err.println("InterruptedException: " + getDateTime()); e.printStackTrace(); keepRunning = false; } lsCount++; idleTime++; if ((lsCount%(timeoutLS[0]*secPerLS) == 0) && (lsCount%(timeoutLS[1]*secPerLS) != 0)) {//fist time out if (!alive.get(1)) alive.flip(1); if (!alive.get(2)) { if (!alive.get(7)) fakeRcd(); else trueRcd(); publishRcd("Uncertain","No new data for " + idleTime + " seconds",false,false); } else { fakeRcd(); publishRcd("Bad","No new data for " + idleTime + " seconds",false,false); } } else if (lsCount%(timeoutLS[1]*secPerLS) == 0) {//second time out if (!alive.get(2)) alive.flip(2); //if(!alive.get(7)) fakeRcd(); //else trueRcd(); publishRcd("Bad","No new data for " + idleTime + " seconds",false,false); } } private boolean readRcd(BufferedReader file_) { int nthLnInRcd = 0; String record = new String(); boolean rcdQlty = false; try { while ((record = file_.readLine()) != null) { //System.out.println(record); nthLnInRcd ++; String[] tmp; tmp = record.split("\\s"); switch(nthLnInRcd) { case 1: if (!record.startsWith("Run")){ System.out.println("Reading of results text file interrupted. " + getDateTime()); return false; } runnum = new Integer(tmp[1]); System.out.println("Run: " + runnum); break; case 2: //startTime = record.substring(15); startTime = tmp[1]+" "+tmp[2]+" "+tmp[3]; startTimeStamp = new Long(tmp[4]); //System.out.println("Time of begin run: " + startTime); break; case 3: //endTime = record.substring(13); endTime = tmp[1]+" "+tmp[2]+" "+tmp[3]; endTimeStamp = new Long(tmp[4]); System.out.println("Time of fit: " + endTime); break; case 4: lumiRange = record.substring(10); System.out.println("LS: " + lumiRange); break; case 5: type = new Integer(tmp[1]); if (overwriteQuality) quality = qualities[0]; else if (type >= 2) quality = qualities[2]; else quality = qualities[1]; break; case 6: x = new Float(tmp[1]); System.out.println("x0 = " + x + " [cm]"); break; case 7: y = new Float(tmp[1]); System.out.println("y0 = " + y + " [cm]"); break; case 8: z = new Float(tmp[1]); System.out.println("z0 = " + z + " [cm]"); break; case 9: sigma_z = new Float(tmp[1]); System.out.println("sigma_z = " + sigma_z + " [cm]"); break; case 10: dxdz = new Float(tmp[1]); break; case 11: dydz = new Float(tmp[1]); break; case 12: width_x = new Float(tmp[1]); break; case 13: width_y = new Float(tmp[1]); break; case 14: err_x = new Float(Math.sqrt(Double.parseDouble(tmp[1]))); //System.out.println(err_x); break; case 15: err_y = new Float(Math.sqrt(Double.parseDouble(tmp[2]))); //System.out.println(err_y); break; case 16: err_z = new Float(Math.sqrt(Double.parseDouble(tmp[3]))); //System.out.println(err_z); break; case 17: err_sigma_z = new Float(Math.sqrt(Double.parseDouble(tmp[4]))); //System.out.println(err_sigma_z); break; case 18: err_dxdz = new Float(Math.sqrt(Double.parseDouble(tmp[5]))); //System.out.println(err_dxdz); break; case 19: err_dydz = new Float(Math.sqrt(Double.parseDouble(tmp[6]))); //System.out.println(err_dydz); break; case 20: err_width_x = new Float(Math.sqrt(Double.parseDouble(tmp[7]))); err_width_y = err_width_x; rcdQlty = true; System.out.println("End of results"); break; default: break; } } file_.close(); } catch (IOException e) { System.err.println("IOException: " + getDateTime()); e.printStackTrace(); } return rcdQlty; } private void trueRcd() { try { Centroid[0] = x*-1*cm2um; Centroid[1] = y*cm2um; Centroid[2] = z*-1*cm2mm; Size[0] = width_x*cm2um; Size[1] = width_y*cm2um; Size[2] = sigma_z*cm2mm; Tilt[0] = dxdz*rad2urad; Tilt[1] = dydz*-1*rad2urad; messageCMS.insert("runnum",runnum); messageCMS.insert("startTime",startTime); messageCMS.insert("endTime",endTime); messageCMS.insert("startTimeStamp",startTimeStamp); messageCMS.insert("endTimeStamp",endTimeStamp); messageCMS.insert("lumiRange",lumiRange); messageCMS.insert("quality",quality); messageCMS.insert("type",type); //Unknown=-1, Fake=0, Tracker=2(Good) messageCMS.insert("x",x); messageCMS.insert("y",y); messageCMS.insert("z",z); messageCMS.insert("dxdz",dxdz); messageCMS.insert("dydz",dydz); messageCMS.insert("width_x",width_x); messageCMS.insert("width_y",width_y); messageCMS.insert("sigma_z",sigma_z); if (publishStatErrors) { messageCMS.insert("err_x",err_x); messageCMS.insert("err_y",err_y); messageCMS.insert("err_z",err_z); messageCMS.insert("err_dxdz",err_dxdz); messageCMS.insert("err_dydz",err_dydz); messageCMS.insert("err_width_x",err_width_x); messageCMS.insert("err_width_y",err_width_y); messageCMS.insert("err_sigma_z",err_sigma_z); } messageLHC.insert("Size",Size); messageLHC.insert("Centroid",Centroid); messageLHC.insert("Tilt",Tilt); } catch (DipException e){ System.err.println("DipException: " + getDateTime()); System.err.println("Failed to send data because " + e.getMessage()); e.printStackTrace(); } } private void fakeRcd() { try { Centroid[0] = 0; Centroid[1] = 0; Centroid[2] = 0; Size[0] = 0; Size[1] = 0; Size[2] = 0; Tilt[0] = 0; Tilt[1] = 0; messageLHC.insert("Size",Size); messageLHC.insert("Centroid",Centroid); messageLHC.insert("Tilt",Tilt); } catch (DipException e){ System.err.println("DipException: " + getDateTime()); System.err.println("Failed to send data because " + e.getMessage()); e.printStackTrace(); } } private void publishRcd(String qlty_,String err_, boolean pubCMS_, boolean fitTime_) { try { try { DipTimestamp zeit; if (fitTime_) { long epoch = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss zz").parse(endTime).getTime(); zeit = new DipTimestamp(epoch); } else zeit = new DipTimestamp(); if(pubCMS_) publicationCMS.send(messageCMS, zeit); publicationLHC.send(messageLHC, zeit); } catch (ParseException e) { System.err.println("ParseException: " + getDateTime()); System.err.println("Publishing failed due to time parsing because " + e.getMessage()); e.printStackTrace(); } if (qlty_ == qualities[0]) { if (pubCMS_) publicationCMS.setQualityUncertain(err_); publicationLHC.setQualityUncertain(err_); } else if (qlty_ == qualities[1]) { if (pubCMS_) publicationCMS.setQualityBad(err_); publicationLHC.setQualityBad(err_); } } catch (DipException e){ System.err.println("DipException: " + getDateTime()); System.err.println("Failed to send data because " + e.getMessage()); e.printStackTrace(); } } private String getDateTime() { DateFormat dateFormat = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss z"); Date date = new Date(); return dateFormat.format(date); } private String getDateTime(long epoch) { DateFormat dateFormat = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss z"); Date date = new Date(epoch); return dateFormat.format(date); } private BeamPixelDipServer(String args[]) { this.verbose = args[0].matches("true"); this.overwriteQuality = args[1].matches("true"); this.subjectCMS = args[2]; this.subjectLHC = args[3]; this.sourceFile = args[4]; this.timeoutLS[0] = new Integer(args[5]); this.timeoutLS[1] = new Integer(args[6]); // this.subjectDummy = args[7]; } public static void main(String args[]) { BeamPixelDipServer server = new BeamPixelDipServer(args); server.start(); } }
{ "pile_set_name": "Github" }
/* * Copyright (c) 1998, 2001, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* __ieee754_log10(x) * Return the base 10 logarithm of x * * Method : * Let log10_2hi = leading 40 bits of log10(2) and * log10_2lo = log10(2) - log10_2hi, * ivln10 = 1/log(10) rounded. * Then * n = ilogb(x), * if(n<0) n = n+1; * x = scalbn(x,-n); * log10(x) := n*log10_2hi + (n*log10_2lo + ivln10*log(x)) * * Note 1: * To guarantee log10(10**n)=n, where 10**n is normal, the rounding * mode must set to Round-to-Nearest. * Note 2: * [1/log(10)] rounded to 53 bits has error .198 ulps; * log10 is monotonic at all binary break points. * * Special cases: * log10(x) is NaN with signal if x < 0; * log10(+INF) is +INF with no signal; log10(0) is -INF with signal; * log10(NaN) is that NaN with no signal; * log10(10**N) = N for N=0,1,...,22. * * Constants: * The hexadecimal values are the intended ones for the following constants. * The decimal values may be used, provided that the compiler will convert * from decimal to binary accurately enough to produce the hexadecimal values * shown. */ #include "fdlibm.h" #ifdef __STDC__ static const double #else static double #endif two54 = 1.80143985094819840000e+16, /* 0x43500000, 0x00000000 */ ivln10 = 4.34294481903251816668e-01, /* 0x3FDBCB7B, 0x1526E50E */ log10_2hi = 3.01029995663611771306e-01, /* 0x3FD34413, 0x509F6000 */ log10_2lo = 3.69423907715893078616e-13; /* 0x3D59FEF3, 0x11F12B36 */ static double zero = 0.0; #ifdef __STDC__ double __ieee754_log10(double x) #else double __ieee754_log10(x) double x; #endif { double y,z; int i,k,hx; unsigned lx; hx = __HI(x); /* high word of x */ lx = __LO(x); /* low word of x */ k=0; if (hx < 0x00100000) { /* x < 2**-1022 */ if (((hx&0x7fffffff)|lx)==0) return -two54/zero; /* log(+-0)=-inf */ if (hx<0) return (x-x)/zero; /* log(-#) = NaN */ k -= 54; x *= two54; /* subnormal number, scale up x */ hx = __HI(x); /* high word of x */ } if (hx >= 0x7ff00000) return x+x; k += (hx>>20)-1023; i = ((unsigned)k&0x80000000)>>31; hx = (hx&0x000fffff)|((0x3ff-i)<<20); y = (double)(k+i); __HI(x) = hx; z = y*log10_2lo + ivln10*__ieee754_log(x); return z+y*log10_2hi; }
{ "pile_set_name": "Github" }
<texture> <address coord="u" mode="border" /> <address coord="v" mode="border" /> <border color="0 0 0 0" /> <mipmap enable="false" /> <quality low="0" /> </texture>
{ "pile_set_name": "Github" }
namespace ClassLib017 { public class Class022 { public static string Property => "ClassLib017"; } }
{ "pile_set_name": "Github" }
// RUN: %check_clang_tidy -std=c++14-or-later %s modernize-make-unique %t -- -- -I %S/Inputs/modernize-smart-ptr #include "unique_ptr.h" #include "initializer_list.h" // CHECK-FIXES: #include <memory> struct Base { Base(); Base(int, int); }; struct Derived : public Base { Derived(); Derived(int, int); }; struct APair { int a, b; }; struct DPair { DPair() : a(0), b(0) {} DPair(int x, int y) : a(y), b(x) {} int a, b; }; template<typename T> struct MyVector { MyVector(std::initializer_list<T>); }; struct Empty {}; struct E { E(std::initializer_list<int>); E(); }; struct F { F(std::initializer_list<int>); F(); int a; }; struct G { G(std::initializer_list<int>); G(int); }; struct H { H(std::vector<int>); H(std::vector<int> &, double); H(MyVector<int>, int); }; struct I { I(G); }; struct J { J(E e, int); }; namespace { class Foo {}; } // namespace namespace bar { class Bar {}; } // namespace bar template <class T> using unique_ptr_ = std::unique_ptr<T>; void *operator new(__SIZE_TYPE__ Count, void *Ptr); int g(std::unique_ptr<int> P); std::unique_ptr<Base> getPointer() { return std::unique_ptr<Base>(new Base); // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: use std::make_unique instead // CHECK-FIXES: return std::make_unique<Base>(); } void basic() { std::unique_ptr<int> P1 = std::unique_ptr<int>(new int()); // CHECK-MESSAGES: :[[@LINE-1]]:29: warning: use std::make_unique instead [modernize-make-unique] // CHECK-FIXES: std::unique_ptr<int> P1 = std::make_unique<int>(); P1.reset(new int()); // CHECK-MESSAGES: :[[@LINE-1]]:6: warning: use std::make_unique instead [modernize-make-unique] // CHECK-FIXES: P1 = std::make_unique<int>(); P1 = std::unique_ptr<int>(new int()); // CHECK-MESSAGES: :[[@LINE-1]]:8: warning: use std::make_unique instead [modernize-make-unique] // CHECK-FIXES: P1 = std::make_unique<int>(); // Without parenthesis. std::unique_ptr<int> P2 = std::unique_ptr<int>(new int); // CHECK-MESSAGES: :[[@LINE-1]]:29: warning: use std::make_unique instead [modernize-make-unique] // CHECK-FIXES: std::unique_ptr<int> P2 = std::make_unique<int>(); P2.reset(new int); // CHECK-MESSAGES: :[[@LINE-1]]:6: warning: use std::make_unique instead [modernize-make-unique] // CHECK-FIXES: P2 = std::make_unique<int>(); P2 = std::unique_ptr<int>(new int); // CHECK-MESSAGES: :[[@LINE-1]]:8: warning: use std::make_unique instead [modernize-make-unique] // CHECK-FIXES: P2 = std::make_unique<int>(); // With auto. auto P3 = std::unique_ptr<int>(new int()); // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: use std::make_unique instead // CHECK-FIXES: auto P3 = std::make_unique<int>(); std::unique_ptr<int> P4 = std::unique_ptr<int>((new int)); // CHECK-MESSAGES: :[[@LINE-1]]:29: warning: use std::make_unique instead [modernize-make-unique] // CHECK-FIXES: std::unique_ptr<int> P4 = std::make_unique<int>(); P4.reset((new int)); // CHECK-MESSAGES: :[[@LINE-1]]:6: warning: use std::make_unique instead [modernize-make-unique] // CHECK-FIXES: P4 = std::make_unique<int>(); std::unique_ptr<int> P5 = std::unique_ptr<int>((((new int)))); // CHECK-MESSAGES: :[[@LINE-1]]:29: warning: use std::make_unique instead [modernize-make-unique] // CHECK-FIXES: std::unique_ptr<int> P5 = std::make_unique<int>(); P5.reset(((((new int))))); // CHECK-MESSAGES: :[[@LINE-1]]:6: warning: use std::make_unique instead [modernize-make-unique] // CHECK-FIXES: P5 = std::make_unique<int>(); { // No std. using namespace std; unique_ptr<int> Q = unique_ptr<int>(new int()); // CHECK-MESSAGES: :[[@LINE-1]]:25: warning: use std::make_unique instead // CHECK-FIXES: unique_ptr<int> Q = std::make_unique<int>(); Q = unique_ptr<int>(new int()); // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: use std::make_unique instead // CHECK-FIXES: Q = std::make_unique<int>(); } std::unique_ptr<int> R(new int()); // Create the unique_ptr as a parameter to a function. int T = g(std::unique_ptr<int>(new int())); // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: use std::make_unique instead // CHECK-FIXES: int T = g(std::make_unique<int>()); // Only replace if the type in the template is the same as the type returned // by the new operator. auto Pderived = std::unique_ptr<Base>(new Derived()); // OK to replace for reset and assign Pderived.reset(new Derived()); // CHECK-MESSAGES: :[[@LINE-1]]:12: warning: use std::make_unique instead // CHECK-FIXES: Pderived = std::make_unique<Derived>(); Pderived = std::unique_ptr<Derived>(new Derived()); // CHECK-MESSAGES: :[[@LINE-1]]:14: warning: use std::make_unique instead // CHECK-FIXES: Pderived = std::make_unique<Derived>(); // FIXME: OK to replace if assigned to unique_ptr<Base> Pderived = std::unique_ptr<Base>(new Derived()); // FIXME: OK to replace when auto is not used std::unique_ptr<Base> PBase = std::unique_ptr<Base>(new Derived()); // The pointer is returned by the function, nothing to do. std::unique_ptr<Base> RetPtr = getPointer(); // This emulates std::move. std::unique_ptr<int> Move = static_cast<std::unique_ptr<int> &&>(P1); // Placement arguments should not be removed. int *PInt = new int; std::unique_ptr<int> Placement = std::unique_ptr<int>(new (PInt) int{3}); Placement.reset(new (PInt) int{3}); Placement = std::unique_ptr<int>(new (PInt) int{3}); } // Calling make_smart_ptr from within a member function of a type with a // private or protected constructor would be ill-formed. class Private { private: Private(int z) {} public: Private() {} void create() { auto callsPublic = std::unique_ptr<Private>(new Private); // CHECK-MESSAGES: :[[@LINE-1]]:24: warning: use std::make_unique instead // CHECK-FIXES: auto callsPublic = std::make_unique<Private>(); auto ptr = std::unique_ptr<Private>(new Private(42)); ptr.reset(new Private(42)); ptr = std::unique_ptr<Private>(new Private(42)); } virtual ~Private(); }; class Protected { protected: Protected() {} public: Protected(int, int) {} void create() { auto callsPublic = std::unique_ptr<Protected>(new Protected(1, 2)); // CHECK-MESSAGES: :[[@LINE-1]]:24: warning: use std::make_unique instead // CHECK-FIXES: auto callsPublic = std::make_unique<Protected>(1, 2); auto ptr = std::unique_ptr<Protected>(new Protected); ptr.reset(new Protected); ptr = std::unique_ptr<Protected>(new Protected); } }; void initialization(int T, Base b) { // Test different kinds of initialization of the pointee. // Direct initialization with parenthesis. std::unique_ptr<DPair> PDir1 = std::unique_ptr<DPair>(new DPair(1, T)); // CHECK-MESSAGES: :[[@LINE-1]]:34: warning: use std::make_unique instead // CHECK-FIXES: std::unique_ptr<DPair> PDir1 = std::make_unique<DPair>(1, T); PDir1.reset(new DPair(1, T)); // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: use std::make_unique instead // CHECK-FIXES: PDir1 = std::make_unique<DPair>(1, T); // Direct initialization with braces. std::unique_ptr<DPair> PDir2 = std::unique_ptr<DPair>(new DPair{2, T}); // CHECK-MESSAGES: :[[@LINE-1]]:34: warning: use std::make_unique instead // CHECK-FIXES: std::unique_ptr<DPair> PDir2 = std::make_unique<DPair>(2, T); PDir2.reset(new DPair{2, T}); // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: use std::make_unique instead // CHECK-FIXES: PDir2 = std::make_unique<DPair>(2, T); // Aggregate initialization. std::unique_ptr<APair> PAggr = std::unique_ptr<APair>(new APair{T, 1}); // CHECK-MESSAGES: :[[@LINE-1]]:34: warning: use std::make_unique instead // CHECK-FIXES: std::unique_ptr<APair> PAggr = std::make_unique<APair>(APair{T, 1}); PAggr.reset(new APair{T, 1}); // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: use std::make_unique instead // CHECK-FIXES: std::make_unique<APair>(APair{T, 1}); // Check aggregate init with intermediate temporaries. std::unique_ptr<APair> PAggrTemp = std::unique_ptr<APair>(new APair({T, 1})); // CHECK-MESSAGES: :[[@LINE-1]]:38: warning: use std::make_unique instead // CHECK-FIXES: std::unique_ptr<APair> PAggrTemp = std::unique_ptr<APair>(new APair({T, 1})); PAggrTemp.reset(new APair({T, 1})); // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: use std::make_unique instead // CHECK-FIXES: PAggrTemp.reset(new APair({T, 1})); // Test different kinds of initialization of the pointee, when the unique_ptr // is initialized with braces. // Direct initialization with parenthesis. std::unique_ptr<DPair> PDir3 = std::unique_ptr<DPair>{new DPair(3, T)}; // CHECK-MESSAGES: :[[@LINE-1]]:34: warning: use std::make_unique instead // CHECK-FIXES: std::unique_ptr<DPair> PDir3 = std::make_unique<DPair>(3, T); // Direct initialization with braces. std::unique_ptr<DPair> PDir4 = std::unique_ptr<DPair>{new DPair{4, T}}; // CHECK-MESSAGES: :[[@LINE-1]]:34: warning: use std::make_unique instead // CHECK-FIXES: std::unique_ptr<DPair> PDir4 = std::make_unique<DPair>(4, T); // Aggregate initialization. std::unique_ptr<APair> PAggr2 = std::unique_ptr<APair>{new APair{T, 2}}; // CHECK-MESSAGES: :[[@LINE-1]]:35: warning: use std::make_unique instead // CHECK-FIXES: std::unique_ptr<APair> PAggr2 = std::make_unique<APair>(APair{T, 2}); // Direct initialization with parenthesis, without arguments. std::unique_ptr<DPair> PDir5 = std::unique_ptr<DPair>(new DPair()); // CHECK-MESSAGES: :[[@LINE-1]]:34: warning: use std::make_unique instead // CHECK-FIXES: std::unique_ptr<DPair> PDir5 = std::make_unique<DPair>(); // Direct initialization with braces, without arguments. std::unique_ptr<DPair> PDir6 = std::unique_ptr<DPair>(new DPair{}); // CHECK-MESSAGES: :[[@LINE-1]]:34: warning: use std::make_unique instead // CHECK-FIXES: std::unique_ptr<DPair> PDir6 = std::make_unique<DPair>(); // Aggregate initialization without arguments. std::unique_ptr<Empty> PEmpty = std::unique_ptr<Empty>(new Empty{}); // CHECK-MESSAGES: :[[@LINE-1]]:35: warning: use std::make_unique instead // CHECK-FIXES: std::unique_ptr<Empty> PEmpty = std::make_unique<Empty>(Empty{}); // Initialization with default constructor. std::unique_ptr<E> PE1 = std::unique_ptr<E>(new E{}); // CHECK-MESSAGES: :[[@LINE-1]]:28: warning: use std::make_unique instead // CHECK-FIXES: std::unique_ptr<E> PE1 = std::make_unique<E>(); PE1.reset(new E{}); // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use std::make_unique instead // CHECK-FIXES: PE1 = std::make_unique<E>(); // No warnings for `auto` new expression. PE1.reset(new auto(E())); //============================================================================ // NOTE: For initializer-list constructors, the check only gives warnings, // and no fixes are generated. //============================================================================ // Initialization with the initializer-list constructor. std::unique_ptr<E> PE2 = std::unique_ptr<E>(new E{1, 2}); // CHECK-MESSAGES: :[[@LINE-1]]:28: warning: use std::make_unique instead // CHECK-FIXES: std::unique_ptr<E> PE2 = std::unique_ptr<E>(new E{1, 2}); PE2.reset(new E{1, 2}); // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use std::make_unique instead // CHECK-FIXES: PE2.reset(new E{1, 2}); // Initialization with default constructor. std::unique_ptr<F> PF1 = std::unique_ptr<F>(new F()); // CHECK-MESSAGES: :[[@LINE-1]]:28: warning: use std::make_unique instead // CHECK-FIXES: std::unique_ptr<F> PF1 = std::make_unique<F>(); PF1.reset(new F()); // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use std::make_unique instead // CHECK-FIXES: PF1 = std::make_unique<F>(); // Initialization with default constructor. std::unique_ptr<F> PF2 = std::unique_ptr<F>(new F{}); // CHECK-MESSAGES: :[[@LINE-1]]:28: warning: use std::make_unique instead // CHECK-FIXES: std::unique_ptr<F> PF2 = std::make_unique<F>(); PF2.reset(new F()); // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use std::make_unique instead // CHECK-FIXES: PF2 = std::make_unique<F>(); // Initialization with the initializer-list constructor. std::unique_ptr<F> PF3 = std::unique_ptr<F>(new F{1}); // CHECK-MESSAGES: :[[@LINE-1]]:28: warning: use std::make_unique instead // CHECK-FIXES: std::unique_ptr<F> PF3 = std::unique_ptr<F>(new F{1}); PF3.reset(new F{1}); // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use std::make_unique instead // CHECK-FIXES: PF3.reset(new F{1}); // Initialization with the initializer-list constructor. std::unique_ptr<F> PF4 = std::unique_ptr<F>(new F{1, 2}); // CHECK-MESSAGES: :[[@LINE-1]]:28: warning: use std::make_unique instead // CHECK-FIXES: std::unique_ptr<F> PF4 = std::unique_ptr<F>(new F{1, 2}); // Initialization with the initializer-list constructor. std::unique_ptr<F> PF5 = std::unique_ptr<F>(new F({1, 2})); // CHECK-MESSAGES: :[[@LINE-1]]:28: warning: use std::make_unique instead // CHECK-FIXES: std::unique_ptr<F> PF5 = std::unique_ptr<F>(new F({1, 2})); // Initialization with the initializer-list constructor as the default // constructor is not present. std::unique_ptr<G> PG1 = std::unique_ptr<G>(new G{}); // CHECK-MESSAGES: :[[@LINE-1]]:28: warning: use std::make_unique instead // CHECK-FIXES: std::unique_ptr<G> PG1 = std::unique_ptr<G>(new G{}); PG1.reset(new G{}); // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use std::make_unique instead // CHECK-FIXES: PG1.reset(new G{}); // Initialization with the initializer-list constructor. std::unique_ptr<G> PG2 = std::unique_ptr<G>(new G{1}); // CHECK-MESSAGES: :[[@LINE-1]]:28: warning: use std::make_unique instead // CHECK-FIXES: std::unique_ptr<G> PG2 = std::unique_ptr<G>(new G{1}); // Initialization with the initializer-list constructor. std::unique_ptr<G> PG3 = std::unique_ptr<G>(new G{1, 2}); // CHECK-MESSAGES: :[[@LINE-1]]:28: warning: use std::make_unique instead // CHECK-FIXES: std::unique_ptr<G> PG3 = std::unique_ptr<G>(new G{1, 2}); std::unique_ptr<H> PH1 = std::unique_ptr<H>(new H({1, 2, 3})); // CHECK-MESSAGES: :[[@LINE-1]]:28: warning: use std::make_unique instead // CHECK-FIXES: std::unique_ptr<H> PH1 = std::unique_ptr<H>(new H({1, 2, 3})); PH1.reset(new H({1, 2, 3})); // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use std::make_unique instead // CHECK-FIXES: PH1.reset(new H({1, 2, 3})); std::unique_ptr<H> PH2 = std::unique_ptr<H>(new H({1, 2, 3}, 1)); // CHECK-MESSAGES: :[[@LINE-1]]:28: warning: use std::make_unique instead // CHECK-FIXES: std::unique_ptr<H> PH2 = std::unique_ptr<H>(new H({1, 2, 3}, 1)); PH2.reset(new H({1, 2, 3}, 1)); // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use std::make_unique instead // CHECK-FIXES: PH2.reset(new H({1, 2, 3}, 1)); std::unique_ptr<H> PH3 = std::unique_ptr<H>(new H({1, 2, 3}, 1.0)); // CHECK-MESSAGES: :[[@LINE-1]]:28: warning: use std::make_unique instead // CHECK-FIXES: std::unique_ptr<H> PH3 = std::unique_ptr<H>(new H({1, 2, 3}, 1.0)); PH3.reset(new H({1, 2, 3}, 1.0)); // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use std::make_unique instead // CHECK-FIXES: PH3.reset(new H({1, 2, 3}, 1.0)); std::unique_ptr<I> PI1 = std::unique_ptr<I>(new I(G({1, 2, 3}))); // CHECK-MESSAGES: :[[@LINE-1]]:28: warning: use std::make_unique instead // CHECK-FIXES: std::unique_ptr<I> PI1 = std::make_unique<I>(G({1, 2, 3})); PI1.reset(new I(G({1, 2, 3}))); // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use std::make_unique instead // CHECK-FIXES: PI1 = std::make_unique<I>(G({1, 2, 3})); std::unique_ptr<J> PJ1 = std::unique_ptr<J>(new J({1, 2}, 1)); // CHECK-MESSAGES: :[[@LINE-1]]:28: warning: use std::make_unique instead // CHECK-FIXES: std::unique_ptr<J> PJ1 = std::unique_ptr<J>(new J({1, 2}, 1)); PJ1.reset(new J({1, 2}, 1)); // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use std::make_unique instead // CHECK-FIXES: PJ1.reset(new J({1, 2}, 1)); std::unique_ptr<J> PJ2 = std::unique_ptr<J>(new J(E{1, 2}, 1)); // CHECK-MESSAGES: :[[@LINE-1]]:28: warning: use std::make_unique instead // CHECK-FIXES: std::unique_ptr<J> PJ2 = std::unique_ptr<J>(new J(E{1, 2}, 1)); PJ2.reset(new J(E{1, 2}, 1)); // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use std::make_unique instead // CHECK-FIXES: PJ2.reset(new J(E{1, 2}, 1)); std::unique_ptr<J> PJ3 = std::unique_ptr<J>(new J{ {1, 2}, 1 }); // CHECK-MESSAGES: :[[@LINE-1]]:28: warning: use std::make_unique instead // CHECK-FIXES: std::unique_ptr<J> PJ3 = std::unique_ptr<J>(new J{ {1, 2}, 1 }); PJ3.reset(new J{ {1, 2}, 1 }); // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use std::make_unique instead // CHECK-FIXES: PJ3.reset(new J{ {1, 2}, 1 }); std::unique_ptr<J> PJ4 = std::unique_ptr<J>(new J{E{1, 2}, 1}); // CHECK-MESSAGES: :[[@LINE-1]]:28: warning: use std::make_unique instead // CHECK-FIXES: std::unique_ptr<J> PJ4 = std::unique_ptr<J>(new J{E{1, 2}, 1}); PJ4.reset(new J{E{1, 2}, 1}); // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use std::make_unique instead // CHECK-FIXES: PJ4.reset(new J{E{1, 2}, 1}); std::unique_ptr<Foo> FF = std::unique_ptr<Foo>(new Foo()); // CHECK-MESSAGES: :[[@LINE-1]]:29: warning: // CHECK-FIXES: std::unique_ptr<Foo> FF = std::make_unique<Foo>(); FF.reset(new Foo()); // CHECK-MESSAGES: :[[@LINE-1]]:6: warning: // CHECK-FIXES: FF = std::make_unique<Foo>(); std::unique_ptr<bar::Bar> BB = std::unique_ptr<bar::Bar>(new bar::Bar()); // CHECK-MESSAGES: :[[@LINE-1]]:34: warning: // CHECK-FIXES: std::unique_ptr<bar::Bar> BB = std::make_unique<bar::Bar>(); BB.reset(new bar::Bar()); // CHECK-MESSAGES: :[[@LINE-1]]:6: warning: // CHECK-FIXES: BB = std::make_unique<bar::Bar>(); std::unique_ptr<Foo[]> FFs; FFs.reset(new Foo[5]); // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: // CHECK-FIXES: FFs = std::make_unique<Foo[]>(5); FFs.reset(new Foo[5]()); // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: // CHECK-FIXES: FFs = std::make_unique<Foo[]>(5); const int Num = 1; FFs.reset(new Foo[Num]); // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: // CHECK-FIXES: FFs = std::make_unique<Foo[]>(Num); int Num2 = 1; FFs.reset(new Foo[Num2]); // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: // CHECK-FIXES: FFs = std::make_unique<Foo[]>(Num2); std::unique_ptr<int[]> FI; FI.reset(new int[5]()); // default initialization. // CHECK-MESSAGES: :[[@LINE-1]]:6: warning: // CHECK-FIXES: FI = std::make_unique<int[]>(5); // The check doesn't give warnings and fixes for cases where the original new // expression doesn't do any initialization. FI.reset(new int[5]); FI.reset(new int[Num]); FI.reset(new int[Num2]); } void aliases() { typedef std::unique_ptr<int> IntPtr; IntPtr Typedef = IntPtr(new int); // CHECK-MESSAGES: :[[@LINE-1]]:20: warning: use std::make_unique instead // CHECK-FIXES: IntPtr Typedef = std::make_unique<int>(); // We use 'bool' instead of '_Bool'. typedef std::unique_ptr<bool> BoolPtr; BoolPtr BoolType = BoolPtr(new bool); // CHECK-MESSAGES: :[[@LINE-1]]:22: warning: use std::make_unique instead // CHECK-FIXES: BoolPtr BoolType = std::make_unique<bool>(); // We use 'Base' instead of 'struct Base'. typedef std::unique_ptr<Base> BasePtr; BasePtr StructType = BasePtr(new Base); // CHECK-MESSAGES: :[[@LINE-1]]:24: warning: use std::make_unique instead // CHECK-FIXES: BasePtr StructType = std::make_unique<Base>(); #define PTR unique_ptr<int> std::unique_ptr<int> Macro = std::PTR(new int); // CHECK-MESSAGES: :[[@LINE-1]]:32: warning: use std::make_unique instead // CHECK-FIXES: std::unique_ptr<int> Macro = std::make_unique<int>(); #undef PTR std::unique_ptr<int> Using = unique_ptr_<int>(new int); // CHECK-MESSAGES: :[[@LINE-1]]:32: warning: use std::make_unique instead // CHECK-FIXES: std::unique_ptr<int> Using = std::make_unique<int>(); } void whitespaces() { // clang-format off auto Space = std::unique_ptr <int>(new int()); // CHECK-MESSAGES: :[[@LINE-1]]:16: warning: use std::make_unique instead // CHECK-FIXES: auto Space = std::make_unique<int>(); auto Spaces = std :: unique_ptr <int>(new int()); // CHECK-MESSAGES: :[[@LINE-1]]:17: warning: use std::make_unique instead // CHECK-FIXES: auto Spaces = std::make_unique<int>(); // clang-format on } void nesting() { auto Nest = std::unique_ptr<std::unique_ptr<int>>(new std::unique_ptr<int>(new int)); // CHECK-MESSAGES: :[[@LINE-1]]:15: warning: use std::make_unique instead // CHECK-FIXES: auto Nest = std::make_unique<std::unique_ptr<int>>(new int); Nest.reset(new std::unique_ptr<int>(new int)); // CHECK-MESSAGES: :[[@LINE-1]]:8: warning: use std::make_unique instead // CHECK-FIXES: Nest = std::make_unique<std::unique_ptr<int>>(new int); Nest->reset(new int); // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: use std::make_unique instead // CHECK-FIXES: *Nest = std::make_unique<int>(); } void reset() { std::unique_ptr<int> P; P.reset(); P.reset(nullptr); P.reset(new int()); // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: use std::make_unique instead // CHECK-FIXES: P = std::make_unique<int>(); auto Q = &P; Q->reset(new int()); // CHECK-MESSAGES: :[[@LINE-1]]:6: warning: use std::make_unique instead // CHECK-FIXES: *Q = std::make_unique<int>(); } #define DEFINE(...) __VA_ARGS__ template<typename T> void g2(std::unique_ptr<Foo> *t) { DEFINE(auto p = std::unique_ptr<Foo>(new Foo); t->reset(new Foo);); } void macro() { std::unique_ptr<Foo> *t; g2<bar::Bar>(t); } #undef DEFINE class UniqueFoo : public std::unique_ptr<Foo> { public: void foo() { reset(new Foo); this->reset(new Foo); // CHECK-MESSAGES: :[[@LINE-1]]:11: warning: use std::make_unique instead // CHECK-FIXES: *this = std::make_unique<Foo>(); (*this).reset(new Foo); // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: use std::make_unique instead // CHECK-FIXES: (*this) = std::make_unique<Foo>(); } }; // Ignore statements inside a template instantiation. template<typename T> void template_fun(T* t) { std::unique_ptr<T> t2 = std::unique_ptr<T>(new T); t2.reset(new T); } void invoke_template() { Foo* foo; template_fun(foo); } void no_fix_for_invalid_new_loc() { // FIXME: Although the code is valid, the end location of `new struct Base` is // invalid. Correct it once https://bugs.llvm.org/show_bug.cgi?id=35952 is // fixed. auto T = std::unique_ptr<Base>(new struct Base); // CHECK-MESSAGES: :[[@LINE-1]]:12: warning: use std::make_unique instead // CHECK-FIXES: auto T = std::unique_ptr<Base>(new struct Base); }
{ "pile_set_name": "Github" }
# # Copyright (C) 2014 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # engine_qml_folder.source = Engine/qml engine_qml_folder.target = Engine engine_shaders_folder.source = Engine/shaders engine_shaders_folder.target = Engine DEPLOYMENTFOLDERS += engine_qml_folder engine_shaders_folder CONFIG += staticlib defined ( LIQUIDFUN ) { LIQUIDFUN_DIR = $$(LIQUIDFUN) } else { # Note: This needs to simply be changed to "liquidfun" for release. LIQUIDFUN_DIR = $$PWD/../../third_party/liquidfun/liquidfun } # TODO: limit this scope of this to just the headers/sources in this file. INCLUDEPATH += $$PWD $$PWD/../.. HEADERS += \ $$PWD/../../third_party/poly2tri/poly2tri/common/shapes.h \ $$PWD/../../third_party/poly2tri/poly2tri/common/utils.h \ $$PWD/../../third_party/poly2tri/poly2tri/poly2tri.h \ $$PWD/../../third_party/poly2tri/poly2tri/sweep/advancing_front.h \ $$PWD/../../third_party/poly2tri/poly2tri/sweep/cdt.h \ $$PWD/../../third_party/poly2tri/poly2tri/sweep/sweep.h \ $$PWD/../../third_party/poly2tri/poly2tri/sweep/sweep_context.h \ $$PWD/Achievement.h \ $$PWD/Actor.h \ $$PWD/Body.h \ $$PWD/Camera.h \ $$PWD/Engine.h \ $$PWD/Environment.h \ $$PWD/Joint.h \ $$PWD/Joints.h \ $$PWD/Level.h \ $$PWD/LevelInfo.h \ $$PWD/Logic.h \ $$PWD/audio/SoundEffectInstance.h \ $$PWD/audio/SoundManager.h \ $$PWD/bodies/CircleBody.h \ $$PWD/bodies/PolygonBody.h \ $$PWD/graphics/AnimatedImageRenderer.h \ $$PWD/graphics/Graphic.h \ $$PWD/graphics/ImageRenderer.h \ $$PWD/graphics/LiquidFunDebugDraw.h \ $$PWD/graphics/ParallaxTransformItem.h \ $$PWD/graphics/ParticleRendererItem.h \ $$PWD/graphics/PolygonMesh.h \ $$PWD/graphics/PolygonVertexAttributeArray.h \ $$PWD/graphics/TerrainMaterialDef.h \ $$PWD/graphics/TerrainMaterials.h \ $$PWD/graphics/TerrainMeshRenderer.h \ $$PWD/graphics/TerrainShader.h \ $$PWD/graphics/TextureManager.h \ $$PWD/inputs/InputArea.h \ $$PWD/inputs/TouchScreenButtonController.h \ $$PWD/joints/RevoluteJoint.h \ $$PWD/joints/WeldJoint.h \ $$PWD/logics/CameraMovementLogic.h \ $$PWD/logics/InterpolationLogic.h \ $$PWD/logics/JavaScriptLogic.h \ $$PWD/logics/StopwatchLogic.h \ $$PWD/logics/Trigger.h \ $$PWD/logics/events/ContactEvent.h \ $$PWD/logics/triggers/ContactTrigger.h \ $$PWD/particles/Particle.h \ $$PWD/particles/ParticleLayer.h \ $$PWD/particles/WaterParticle.h \ $$PWD/particles/WaterParticleSet.h \ $$PWD/utils/Box2dUtil.h \ $$PWD/utils/Constants.h \ $$PWD/utils/ContactListener.h \ $$PWD/utils/DebugMetricsMonitor.h \ $$PWD/utils/DestructionListener.h \ $$PWD/utils/GraphicsUtil.h \ $$PWD/utils/QmlUtil.h \ $$PWD/utils/Util.h \ $$PWD/utils/VariantConverter.h \ SOURCES += \ $$PWD/../../third_party/poly2tri/poly2tri/common/shapes.cc \ $$PWD/../../third_party/poly2tri/poly2tri/sweep/advancing_front.cc \ $$PWD/../../third_party/poly2tri/poly2tri/sweep/cdt.cc \ $$PWD/../../third_party/poly2tri/poly2tri/sweep/sweep.cc \ $$PWD/../../third_party/poly2tri/poly2tri/sweep/sweep_context.cc \ $$PWD/Achievement.cpp \ $$PWD/Actor.cpp \ $$PWD/Body.cpp \ $$PWD/Camera.cpp \ $$PWD/Engine.cpp \ $$PWD/Environment.cpp \ $$PWD/Joint.cpp \ $$PWD/Joints.cpp \ $$PWD/Level.cpp \ $$PWD/LevelInfo.cpp \ $$PWD/Logic.cpp \ $$PWD/audio/SoundEffectInstance.cpp \ $$PWD/audio/SoundManager.cpp \ $$PWD/bodies/CircleBody.cpp \ $$PWD/bodies/PolygonBody.cpp \ $$PWD/graphics/AnimatedImageRenderer.cpp \ $$PWD/graphics/Graphic.cpp \ $$PWD/graphics/ImageRenderer.cpp \ $$PWD/graphics/LiquidFunDebugDraw.cpp \ $$PWD/graphics/ParallaxTransformItem.cpp \ $$PWD/graphics/ParticleRendererItem.cpp \ $$PWD/graphics/PolygonMesh.cpp \ $$PWD/graphics/PolygonVertexAttributeArray.cpp \ $$PWD/graphics/TerrainMaterialDef.cpp \ $$PWD/graphics/TerrainMaterials.cpp \ $$PWD/graphics/TerrainMeshRenderer.cpp \ $$PWD/graphics/TerrainShader.cpp \ $$PWD/graphics/TextureManager.cpp \ $$PWD/inputs/InputArea.cpp \ $$PWD/inputs/TouchScreenButtonController.cpp \ $$PWD/joints/RevoluteJoint.cpp \ $$PWD/joints/WeldJoint.cpp \ $$PWD/logics/CameraMovementLogic.cpp \ $$PWD/logics/InterpolationLogic.cpp \ $$PWD/logics/JavaScriptLogic.cpp \ $$PWD/logics/StopwatchLogic.cpp \ $$PWD/logics/Trigger.cpp \ $$PWD/logics/events/ContactEvent.cpp \ $$PWD/logics/triggers/ContactTrigger.cpp \ $$PWD/particles/Particle.cpp \ $$PWD/particles/ParticleLayer.cpp \ $$PWD/particles/WaterParticle.cpp \ $$PWD/particles/WaterParticleSet.cpp \ $$PWD/utils/Constants.cpp \ $$PWD/utils/ContactListener.cpp \ $$PWD/utils/DebugMetricsMonitor.cpp \ $$PWD/utils/DestructionListener.cpp \ $$PWD/utils/GraphicsUtil.cpp \ $$PWD/utils/QmlUtil.cpp \ $$PWD/utils/Util.cpp \ android { HEADERS += \ $$PWD/android/AndroidActivity.h \ $$PWD/android/SelfDetachingJNIEnv.h \ SOURCES += \ $$PWD/android/AndroidActivity.cpp \ $$PWD/android/AndroidJNI.cpp \ $$PWD/android/SelfDetachingJNIEnv.cpp \ # Have QtCreator list our Java and XML source files for easy editing OTHER_FILES += \ $$PWD/android/deploy/AndroidManifest.xml \ $$PWD/android/deploy/res/drawable-ldpi/icon.png \ $$PWD/android/deploy/res/drawable-xhdpi/logo.png \ $$PWD/android/deploy/res/values/voltairactivity_strings.xml \ $$PWD/android/deploy/res/values/googleplayserviceshelper_strings.xml \ $$PWD/android/deploy/res/values/ids.xml \ $$PWD/android/deploy/res/xml/voltair_tracker.xml \ $$PWD/android/deploy/src/com/google/fpl/voltair/VoltAirActivity.java \ $$PWD/android/deploy/src/com/google/fpl/utils/GooglePlayServicesHelper.java \ $$PWD/android/deploy/src/com/google/fpl/utils/SoundManager.java \ LIBS += \ $$LIQUIDFUN_DIR/Box2D/obj/local/armeabi-v7a/libliquidfun_static.a \ QMAKE_CXXFLAGS_WARN_ON += -Wno-pragmas } macx { LIBS += \ $$LIQUIDFUN_DIR/Box2D/Box2D/Debug/libliquidfun.a \ } # For linux-specific statements, there is a slightly more complex predicate. unix:!mac:!android { LIBS += \ $$LIQUIDFUN_DIR/Box2D/Box2D/Release/libliquidfun.a \ } # Have Qt pick up our custom android source android { ANDROID_PACKAGE_SOURCE_DIR = $$PWD/android/deploy } INCLUDEPATH += \ $$PWD/$$LIQUIDFUN_DIR/Box2D \
{ "pile_set_name": "Github" }
// This file is part of libigl, a simple c++ geometry processing library. // // Copyright (C) 2014 Daniele Panozzo <[email protected]>, Olga Diamanti <[email protected]> // // This Source Code Form is subject to the terms of the Mozilla Public License // v. 2.0. If a copy of the MPL was not distributed with this file, You can // obtain one at http://mozilla.org/MPL/2.0/. #ifndef IGL_CROSS_FIELD_MISSMATCH_H #define IGL_CROSS_FIELD_MISSMATCH_H #include "igl_inline.h" #include <Eigen/Core> namespace igl { // Calculates the missmatch (integer), at each face edge, of a cross field defined on the mesh faces. // The integer missmatch is a multiple of pi/2 that transforms the cross on one side of the edge to // the cross on the other side. It represents the deviation from a Lie connection across the edge. // Inputs: // V #V by 3 eigen Matrix of mesh vertex 3D positions // F #F by 3 eigen Matrix of face (quad) indices // PD1 #F by 3 eigen Matrix of the first per face cross field vector // PD2 #F by 3 eigen Matrix of the second per face cross field vector // isCombed boolean, specifying whether the field is combed (i.e. matching has been precomputed. // If not, the field is combed first. // Output: // Handle_MMatch #F by 3 eigen Matrix containing the integer missmatch of the cross field // across all face edges // template <typename DerivedV, typename DerivedF, typename DerivedM> IGL_INLINE void cross_field_missmatch(const Eigen::PlainObjectBase<DerivedV> &V, const Eigen::PlainObjectBase<DerivedF> &F, const Eigen::PlainObjectBase<DerivedV> &PD1, const Eigen::PlainObjectBase<DerivedV> &PD2, const bool isCombed, Eigen::PlainObjectBase<DerivedM> &missmatch); } #ifndef IGL_STATIC_LIBRARY #include "cross_field_missmatch.cpp" #endif #endif
{ "pile_set_name": "Github" }
// Copyright (c) 2017 Daniel Cooke // Use of this source code is governed by the MIT license that can be found in the LICENSE file. #include <boost/test/unit_test.hpp> namespace octopus { namespace test { BOOST_AUTO_TEST_SUITE(core) BOOST_AUTO_TEST_SUITE(reassembler) BOOST_AUTO_TEST_SUITE_END() BOOST_AUTO_TEST_SUITE_END() } // namespace test } // namespace octopus
{ "pile_set_name": "Github" }
<!DOCTYPE html> <!-- Copyright 2012 The Polymer Authors. All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. --> <html> <head> <title></title> <script src="lib/loader.js"></script> <style> div, g-A { display: block; border: 1px dotted red; margin: 8px; padding: 8px; } </style> <script> change = function() { A = $("g-A"); A.webkitCreateShadowRoot().appendChild($("template#Ab").content); A.webkitCreateShadowRoot().appendChild($("template#A").content); }; </script> </head> <body onload="change();"> <g-A><span>Where am I?</span></g-A> <template id="Ab">A's base template, content: [<content></content>]</template> <template id="A"><span>A's template, shadow: {<shadow></shadow>}</span></template> <hr/> Expected output (also, see console): <div><span>A's template, shadow: {A's base template, content: [ Where am I? ]}</span></div> </body> </html>
{ "pile_set_name": "Github" }
/* * Copyright (c) 1997, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.crypto; import java.util.StringTokenizer; import java.util.NoSuchElementException; import java.security.AlgorithmParameters; import java.security.Provider; import java.security.Key; import java.security.SecureRandom; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.InvalidKeyException; import java.security.InvalidAlgorithmParameterException; import java.security.ProviderException; import java.security.spec.AlgorithmParameterSpec; import java.nio.ByteBuffer; /** * This class defines the <i>Service Provider Interface</i> (<b>SPI</b>) * for the <code>Cipher</code> class. * All the abstract methods in this class must be implemented by each * cryptographic service provider who wishes to supply the implementation * of a particular cipher algorithm. * * <p>In order to create an instance of <code>Cipher</code>, which * encapsulates an instance of this <code>CipherSpi</code> class, an * application calls one of the * {@link Cipher#getInstance(java.lang.String) getInstance} * factory methods of the * {@link Cipher Cipher} engine class and specifies the requested * <i>transformation</i>. * Optionally, the application may also specify the name of a provider. * * <p>A <i>transformation</i> is a string that describes the operation (or * set of operations) to be performed on the given input, to produce some * output. A transformation always includes the name of a cryptographic * algorithm (e.g., <i>AES</i>), and may be followed by a feedback mode and * padding scheme. * * <p> A transformation is of the form: * * <ul> * <li>"<i>algorithm/mode/padding</i>" or * * <li>"<i>algorithm</i>" * </ul> * * <P> (in the latter case, * provider-specific default values for the mode and padding scheme are used). * For example, the following is a valid transformation: * * <pre> * Cipher c = Cipher.getInstance("<i>AES/CBC/PKCS5Padding</i>"); * </pre> * * <p>A provider may supply a separate class for each combination * of <i>algorithm/mode/padding</i>, or may decide to provide more generic * classes representing sub-transformations corresponding to * <i>algorithm</i> or <i>algorithm/mode</i> or <i>algorithm//padding</i> * (note the double slashes), * in which case the requested mode and/or padding are set automatically by * the <code>getInstance</code> methods of <code>Cipher</code>, which invoke * the {@link #engineSetMode(java.lang.String) engineSetMode} and * {@link #engineSetPadding(java.lang.String) engineSetPadding} * methods of the provider's subclass of <code>CipherSpi</code>. * * <p>A <code>Cipher</code> property in a provider master class may have one of * the following formats: * * <ul> * * <li> * <pre> * // provider's subclass of "CipherSpi" implements "algName" with * // pluggable mode and padding * <code>Cipher.</code><i>algName</i> * </pre> * * <li> * <pre> * // provider's subclass of "CipherSpi" implements "algName" in the * // specified "mode", with pluggable padding * <code>Cipher.</code><i>algName/mode</i> * </pre> * * <li> * <pre> * // provider's subclass of "CipherSpi" implements "algName" with the * // specified "padding", with pluggable mode * <code>Cipher.</code><i>algName//padding</i> * </pre> * * <li> * <pre> * // provider's subclass of "CipherSpi" implements "algName" with the * // specified "mode" and "padding" * <code>Cipher.</code><i>algName/mode/padding</i> * </pre> * * </ul> * * <p>For example, a provider may supply a subclass of <code>CipherSpi</code> * that implements <i>AES/ECB/PKCS5Padding</i>, one that implements * <i>AES/CBC/PKCS5Padding</i>, one that implements * <i>AES/CFB/PKCS5Padding</i>, and yet another one that implements * <i>AES/OFB/PKCS5Padding</i>. That provider would have the following * <code>Cipher</code> properties in its master class: * * <ul> * * <li> * <pre> * <code>Cipher.</code><i>AES/ECB/PKCS5Padding</i> * </pre> * * <li> * <pre> * <code>Cipher.</code><i>AES/CBC/PKCS5Padding</i> * </pre> * * <li> * <pre> * <code>Cipher.</code><i>AES/CFB/PKCS5Padding</i> * </pre> * * <li> * <pre> * <code>Cipher.</code><i>AES/OFB/PKCS5Padding</i> * </pre> * * </ul> * * <p>Another provider may implement a class for each of the above modes * (i.e., one class for <i>ECB</i>, one for <i>CBC</i>, one for <i>CFB</i>, * and one for <i>OFB</i>), one class for <i>PKCS5Padding</i>, * and a generic <i>AES</i> class that subclasses from <code>CipherSpi</code>. * That provider would have the following * <code>Cipher</code> properties in its master class: * * <ul> * * <li> * <pre> * <code>Cipher.</code><i>AES</i> * </pre> * * </ul> * * <p>The <code>getInstance</code> factory method of the <code>Cipher</code> * engine class follows these rules in order to instantiate a provider's * implementation of <code>CipherSpi</code> for a * transformation of the form "<i>algorithm</i>": * * <ol> * <li> * Check if the provider has registered a subclass of <code>CipherSpi</code> * for the specified "<i>algorithm</i>". * <p>If the answer is YES, instantiate this * class, for whose mode and padding scheme default values (as supplied by * the provider) are used. * <p>If the answer is NO, throw a <code>NoSuchAlgorithmException</code> * exception. * </ol> * * <p>The <code>getInstance</code> factory method of the <code>Cipher</code> * engine class follows these rules in order to instantiate a provider's * implementation of <code>CipherSpi</code> for a * transformation of the form "<i>algorithm/mode/padding</i>": * * <ol> * <li> * Check if the provider has registered a subclass of <code>CipherSpi</code> * for the specified "<i>algorithm/mode/padding</i>" transformation. * <p>If the answer is YES, instantiate it. * <p>If the answer is NO, go to the next step. * <li> * Check if the provider has registered a subclass of <code>CipherSpi</code> * for the sub-transformation "<i>algorithm/mode</i>". * <p>If the answer is YES, instantiate it, and call * <code>engineSetPadding(<i>padding</i>)</code> on the new instance. * <p>If the answer is NO, go to the next step. * <li> * Check if the provider has registered a subclass of <code>CipherSpi</code> * for the sub-transformation "<i>algorithm//padding</i>" (note the double * slashes). * <p>If the answer is YES, instantiate it, and call * <code>engineSetMode(<i>mode</i>)</code> on the new instance. * <p>If the answer is NO, go to the next step. * <li> * Check if the provider has registered a subclass of <code>CipherSpi</code> * for the sub-transformation "<i>algorithm</i>". * <p>If the answer is YES, instantiate it, and call * <code>engineSetMode(<i>mode</i>)</code> and * <code>engineSetPadding(<i>padding</i>)</code> on the new instance. * <p>If the answer is NO, throw a <code>NoSuchAlgorithmException</code> * exception. * </ol> * * @author Jan Luehe * @see KeyGenerator * @see SecretKey * @since 1.4 */ public abstract class CipherSpi { /** * Sets the mode of this cipher. * * @param mode the cipher mode * * @exception NoSuchAlgorithmException if the requested cipher mode does * not exist */ protected abstract void engineSetMode(String mode) throws NoSuchAlgorithmException; /** * Sets the padding mechanism of this cipher. * * @param padding the padding mechanism * * @exception NoSuchPaddingException if the requested padding mechanism * does not exist */ protected abstract void engineSetPadding(String padding) throws NoSuchPaddingException; /** * Returns the block size (in bytes). * * @return the block size (in bytes), or 0 if the underlying algorithm is * not a block cipher */ protected abstract int engineGetBlockSize(); /** * Returns the length in bytes that an output buffer would * need to be in order to hold the result of the next <code>update</code> * or <code>doFinal</code> operation, given the input length * <code>inputLen</code> (in bytes). * * <p>This call takes into account any unprocessed (buffered) data from a * previous <code>update</code> call, padding, and AEAD tagging. * * <p>The actual output length of the next <code>update</code> or * <code>doFinal</code> call may be smaller than the length returned by * this method. * * @param inputLen the input length (in bytes) * * @return the required output buffer size (in bytes) */ protected abstract int engineGetOutputSize(int inputLen); /** * Returns the initialization vector (IV) in a new buffer. * * <p> This is useful in the context of password-based encryption or * decryption, where the IV is derived from a user-provided passphrase. * * @return the initialization vector in a new buffer, or null if the * underlying algorithm does not use an IV, or if the IV has not yet * been set. */ protected abstract byte[] engineGetIV(); /** * Returns the parameters used with this cipher. * * <p>The returned parameters may be the same that were used to initialize * this cipher, or may contain a combination of default and random * parameter values used by the underlying cipher implementation if this * cipher requires algorithm parameters but was not initialized with any. * * @return the parameters used with this cipher, or null if this cipher * does not use any parameters. */ protected abstract AlgorithmParameters engineGetParameters(); /** * Initializes this cipher with a key and a source * of randomness. * * <p>The cipher is initialized for one of the following four operations: * encryption, decryption, key wrapping or key unwrapping, depending on * the value of <code>opmode</code>. * * <p>If this cipher requires any algorithm parameters that cannot be * derived from the given <code>key</code>, the underlying cipher * implementation is supposed to generate the required parameters itself * (using provider-specific default or random values) if it is being * initialized for encryption or key wrapping, and raise an * <code>InvalidKeyException</code> if it is being * initialized for decryption or key unwrapping. * The generated parameters can be retrieved using * {@link #engineGetParameters() engineGetParameters} or * {@link #engineGetIV() engineGetIV} (if the parameter is an IV). * * <p>If this cipher requires algorithm parameters that cannot be * derived from the input parameters, and there are no reasonable * provider-specific default values, initialization will * necessarily fail. * * <p>If this cipher (including its underlying feedback or padding scheme) * requires any random bytes (e.g., for parameter generation), it will get * them from <code>random</code>. * * <p>Note that when a Cipher object is initialized, it loses all * previously-acquired state. In other words, initializing a Cipher is * equivalent to creating a new instance of that Cipher and initializing * it. * * @param opmode the operation mode of this cipher (this is one of * the following: * <code>ENCRYPT_MODE</code>, <code>DECRYPT_MODE</code>, * <code>WRAP_MODE</code> or <code>UNWRAP_MODE</code>) * @param key the encryption key * @param random the source of randomness * * @exception InvalidKeyException if the given key is inappropriate for * initializing this cipher, or requires * algorithm parameters that cannot be * determined from the given key. * @throws UnsupportedOperationException if {@code opmode} is * {@code WRAP_MODE} or {@code UNWRAP_MODE} is not implemented * by the cipher. */ protected abstract void engineInit(int opmode, Key key, SecureRandom random) throws InvalidKeyException; /** * Initializes this cipher with a key, a set of * algorithm parameters, and a source of randomness. * * <p>The cipher is initialized for one of the following four operations: * encryption, decryption, key wrapping or key unwrapping, depending on * the value of <code>opmode</code>. * * <p>If this cipher requires any algorithm parameters and * <code>params</code> is null, the underlying cipher implementation is * supposed to generate the required parameters itself (using * provider-specific default or random values) if it is being * initialized for encryption or key wrapping, and raise an * <code>InvalidAlgorithmParameterException</code> if it is being * initialized for decryption or key unwrapping. * The generated parameters can be retrieved using * {@link #engineGetParameters() engineGetParameters} or * {@link #engineGetIV() engineGetIV} (if the parameter is an IV). * * <p>If this cipher requires algorithm parameters that cannot be * derived from the input parameters, and there are no reasonable * provider-specific default values, initialization will * necessarily fail. * * <p>If this cipher (including its underlying feedback or padding scheme) * requires any random bytes (e.g., for parameter generation), it will get * them from <code>random</code>. * * <p>Note that when a Cipher object is initialized, it loses all * previously-acquired state. In other words, initializing a Cipher is * equivalent to creating a new instance of that Cipher and initializing * it. * * @param opmode the operation mode of this cipher (this is one of * the following: * <code>ENCRYPT_MODE</code>, <code>DECRYPT_MODE</code>, * <code>WRAP_MODE</code> or <code>UNWRAP_MODE</code>) * @param key the encryption key * @param params the algorithm parameters * @param random the source of randomness * * @exception InvalidKeyException if the given key is inappropriate for * initializing this cipher * @exception InvalidAlgorithmParameterException if the given algorithm * parameters are inappropriate for this cipher, * or if this cipher requires * algorithm parameters and <code>params</code> is null. * @throws UnsupportedOperationException if {@code opmode} is * {@code WRAP_MODE} or {@code UNWRAP_MODE} is not implemented * by the cipher. */ protected abstract void engineInit(int opmode, Key key, AlgorithmParameterSpec params, SecureRandom random) throws InvalidKeyException, InvalidAlgorithmParameterException; /** * Initializes this cipher with a key, a set of * algorithm parameters, and a source of randomness. * * <p>The cipher is initialized for one of the following four operations: * encryption, decryption, key wrapping or key unwrapping, depending on * the value of <code>opmode</code>. * * <p>If this cipher requires any algorithm parameters and * <code>params</code> is null, the underlying cipher implementation is * supposed to generate the required parameters itself (using * provider-specific default or random values) if it is being * initialized for encryption or key wrapping, and raise an * <code>InvalidAlgorithmParameterException</code> if it is being * initialized for decryption or key unwrapping. * The generated parameters can be retrieved using * {@link #engineGetParameters() engineGetParameters} or * {@link #engineGetIV() engineGetIV} (if the parameter is an IV). * * <p>If this cipher requires algorithm parameters that cannot be * derived from the input parameters, and there are no reasonable * provider-specific default values, initialization will * necessarily fail. * * <p>If this cipher (including its underlying feedback or padding scheme) * requires any random bytes (e.g., for parameter generation), it will get * them from <code>random</code>. * * <p>Note that when a Cipher object is initialized, it loses all * previously-acquired state. In other words, initializing a Cipher is * equivalent to creating a new instance of that Cipher and initializing * it. * * @param opmode the operation mode of this cipher (this is one of * the following: * <code>ENCRYPT_MODE</code>, <code>DECRYPT_MODE</code>, * <code>WRAP_MODE</code> or <code>UNWRAP_MODE</code>) * @param key the encryption key * @param params the algorithm parameters * @param random the source of randomness * * @exception InvalidKeyException if the given key is inappropriate for * initializing this cipher * @exception InvalidAlgorithmParameterException if the given algorithm * parameters are inappropriate for this cipher, * or if this cipher requires * algorithm parameters and <code>params</code> is null. * @throws UnsupportedOperationException if {@code opmode} is * {@code WRAP_MODE} or {@code UNWRAP_MODE} is not implemented * by the cipher. */ protected abstract void engineInit(int opmode, Key key, AlgorithmParameters params, SecureRandom random) throws InvalidKeyException, InvalidAlgorithmParameterException; /** * Continues a multiple-part encryption or decryption operation * (depending on how this cipher was initialized), processing another data * part. * * <p>The first <code>inputLen</code> bytes in the <code>input</code> * buffer, starting at <code>inputOffset</code> inclusive, are processed, * and the result is stored in a new buffer. * * @param input the input buffer * @param inputOffset the offset in <code>input</code> where the input * starts * @param inputLen the input length * * @return the new buffer with the result, or null if the underlying * cipher is a block cipher and the input data is too short to result in a * new block. */ protected abstract byte[] engineUpdate(byte[] input, int inputOffset, int inputLen); /** * Continues a multiple-part encryption or decryption operation * (depending on how this cipher was initialized), processing another data * part. * * <p>The first <code>inputLen</code> bytes in the <code>input</code> * buffer, starting at <code>inputOffset</code> inclusive, are processed, * and the result is stored in the <code>output</code> buffer, starting at * <code>outputOffset</code> inclusive. * * <p>If the <code>output</code> buffer is too small to hold the result, * a <code>ShortBufferException</code> is thrown. * * @param input the input buffer * @param inputOffset the offset in <code>input</code> where the input * starts * @param inputLen the input length * @param output the buffer for the result * @param outputOffset the offset in <code>output</code> where the result * is stored * * @return the number of bytes stored in <code>output</code> * * @exception ShortBufferException if the given output buffer is too small * to hold the result */ protected abstract int engineUpdate(byte[] input, int inputOffset, int inputLen, byte[] output, int outputOffset) throws ShortBufferException; /** * Continues a multiple-part encryption or decryption operation * (depending on how this cipher was initialized), processing another data * part. * * <p>All <code>input.remaining()</code> bytes starting at * <code>input.position()</code> are processed. The result is stored * in the output buffer. * Upon return, the input buffer's position will be equal * to its limit; its limit will not have changed. The output buffer's * position will have advanced by n, where n is the value returned * by this method; the output buffer's limit will not have changed. * * <p>If <code>output.remaining()</code> bytes are insufficient to * hold the result, a <code>ShortBufferException</code> is thrown. * * <p>Subclasses should consider overriding this method if they can * process ByteBuffers more efficiently than byte arrays. * * @param input the input ByteBuffer * @param output the output ByteByffer * * @return the number of bytes stored in <code>output</code> * * @exception ShortBufferException if there is insufficient space in the * output buffer * * @throws NullPointerException if either parameter is <CODE>null</CODE> * @since 1.5 */ protected int engineUpdate(ByteBuffer input, ByteBuffer output) throws ShortBufferException { try { return bufferCrypt(input, output, true); } catch (IllegalBlockSizeException e) { // never thrown for engineUpdate() throw new ProviderException("Internal error in update()"); } catch (BadPaddingException e) { // never thrown for engineUpdate() throw new ProviderException("Internal error in update()"); } } /** * Encrypts or decrypts data in a single-part operation, * or finishes a multiple-part operation. * The data is encrypted or decrypted, depending on how this cipher was * initialized. * * <p>The first <code>inputLen</code> bytes in the <code>input</code> * buffer, starting at <code>inputOffset</code> inclusive, and any input * bytes that may have been buffered during a previous <code>update</code> * operation, are processed, with padding (if requested) being applied. * If an AEAD mode such as GCM/CCM is being used, the authentication * tag is appended in the case of encryption, or verified in the * case of decryption. * The result is stored in a new buffer. * * <p>Upon finishing, this method resets this cipher object to the state * it was in when previously initialized via a call to * <code>engineInit</code>. * That is, the object is reset and available to encrypt or decrypt * (depending on the operation mode that was specified in the call to * <code>engineInit</code>) more data. * * <p>Note: if any exception is thrown, this cipher object may need to * be reset before it can be used again. * * @param input the input buffer * @param inputOffset the offset in <code>input</code> where the input * starts * @param inputLen the input length * * @return the new buffer with the result * * @exception IllegalBlockSizeException if this cipher is a block cipher, * no padding has been requested (only in encryption mode), and the total * input length of the data processed by this cipher is not a multiple of * block size; or if this encryption algorithm is unable to * process the input data provided. * @exception BadPaddingException if this cipher is in decryption mode, * and (un)padding has been requested, but the decrypted data is not * bounded by the appropriate padding bytes * @exception AEADBadTagException if this cipher is decrypting in an * AEAD mode (such as GCM/CCM), and the received authentication tag * does not match the calculated value */ protected abstract byte[] engineDoFinal(byte[] input, int inputOffset, int inputLen) throws IllegalBlockSizeException, BadPaddingException; /** * Encrypts or decrypts data in a single-part operation, * or finishes a multiple-part operation. * The data is encrypted or decrypted, depending on how this cipher was * initialized. * * <p>The first <code>inputLen</code> bytes in the <code>input</code> * buffer, starting at <code>inputOffset</code> inclusive, and any input * bytes that may have been buffered during a previous <code>update</code> * operation, are processed, with padding (if requested) being applied. * If an AEAD mode such as GCM/CCM is being used, the authentication * tag is appended in the case of encryption, or verified in the * case of decryption. * The result is stored in the <code>output</code> buffer, starting at * <code>outputOffset</code> inclusive. * * <p>If the <code>output</code> buffer is too small to hold the result, * a <code>ShortBufferException</code> is thrown. * * <p>Upon finishing, this method resets this cipher object to the state * it was in when previously initialized via a call to * <code>engineInit</code>. * That is, the object is reset and available to encrypt or decrypt * (depending on the operation mode that was specified in the call to * <code>engineInit</code>) more data. * * <p>Note: if any exception is thrown, this cipher object may need to * be reset before it can be used again. * * @param input the input buffer * @param inputOffset the offset in <code>input</code> where the input * starts * @param inputLen the input length * @param output the buffer for the result * @param outputOffset the offset in <code>output</code> where the result * is stored * * @return the number of bytes stored in <code>output</code> * * @exception IllegalBlockSizeException if this cipher is a block cipher, * no padding has been requested (only in encryption mode), and the total * input length of the data processed by this cipher is not a multiple of * block size; or if this encryption algorithm is unable to * process the input data provided. * @exception ShortBufferException if the given output buffer is too small * to hold the result * @exception BadPaddingException if this cipher is in decryption mode, * and (un)padding has been requested, but the decrypted data is not * bounded by the appropriate padding bytes * @exception AEADBadTagException if this cipher is decrypting in an * AEAD mode (such as GCM/CCM), and the received authentication tag * does not match the calculated value */ protected abstract int engineDoFinal(byte[] input, int inputOffset, int inputLen, byte[] output, int outputOffset) throws ShortBufferException, IllegalBlockSizeException, BadPaddingException; /** * Encrypts or decrypts data in a single-part operation, * or finishes a multiple-part operation. * The data is encrypted or decrypted, depending on how this cipher was * initialized. * * <p>All <code>input.remaining()</code> bytes starting at * <code>input.position()</code> are processed. * If an AEAD mode such as GCM/CCM is being used, the authentication * tag is appended in the case of encryption, or verified in the * case of decryption. * The result is stored in the output buffer. * Upon return, the input buffer's position will be equal * to its limit; its limit will not have changed. The output buffer's * position will have advanced by n, where n is the value returned * by this method; the output buffer's limit will not have changed. * * <p>If <code>output.remaining()</code> bytes are insufficient to * hold the result, a <code>ShortBufferException</code> is thrown. * * <p>Upon finishing, this method resets this cipher object to the state * it was in when previously initialized via a call to * <code>engineInit</code>. * That is, the object is reset and available to encrypt or decrypt * (depending on the operation mode that was specified in the call to * <code>engineInit</code>) more data. * * <p>Note: if any exception is thrown, this cipher object may need to * be reset before it can be used again. * * <p>Subclasses should consider overriding this method if they can * process ByteBuffers more efficiently than byte arrays. * * @param input the input ByteBuffer * @param output the output ByteByffer * * @return the number of bytes stored in <code>output</code> * * @exception IllegalBlockSizeException if this cipher is a block cipher, * no padding has been requested (only in encryption mode), and the total * input length of the data processed by this cipher is not a multiple of * block size; or if this encryption algorithm is unable to * process the input data provided. * @exception ShortBufferException if there is insufficient space in the * output buffer * @exception BadPaddingException if this cipher is in decryption mode, * and (un)padding has been requested, but the decrypted data is not * bounded by the appropriate padding bytes * @exception AEADBadTagException if this cipher is decrypting in an * AEAD mode (such as GCM/CCM), and the received authentication tag * does not match the calculated value * * @throws NullPointerException if either parameter is <CODE>null</CODE> * @since 1.5 */ protected int engineDoFinal(ByteBuffer input, ByteBuffer output) throws ShortBufferException, IllegalBlockSizeException, BadPaddingException { return bufferCrypt(input, output, false); } // copied from sun.security.jca.JCAUtil // will be changed to reference that method once that code has been // integrated and promoted static int getTempArraySize(int totalSize) { return Math.min(4096, totalSize); } /** * Implementation for encryption using ByteBuffers. Used for both * engineUpdate() and engineDoFinal(). */ private int bufferCrypt(ByteBuffer input, ByteBuffer output, boolean isUpdate) throws ShortBufferException, IllegalBlockSizeException, BadPaddingException { if ((input == null) || (output == null)) { throw new NullPointerException ("Input and output buffers must not be null"); } int inPos = input.position(); int inLimit = input.limit(); int inLen = inLimit - inPos; if (isUpdate && (inLen == 0)) { return 0; } int outLenNeeded = engineGetOutputSize(inLen); if (output.remaining() < outLenNeeded) { throw new ShortBufferException("Need at least " + outLenNeeded + " bytes of space in output buffer"); } // detecting input and output buffer overlap may be tricky // we can only write directly into output buffer when we // are 100% sure it's safe to do so boolean a1 = input.hasArray(); boolean a2 = output.hasArray(); int total = 0; if (a1) { // input has an accessible byte[] byte[] inArray = input.array(); int inOfs = input.arrayOffset() + inPos; if (a2) { // output has an accessible byte[] byte[] outArray = output.array(); int outPos = output.position(); int outOfs = output.arrayOffset() + outPos; // check array address and offsets and use temp output buffer // if output offset is larger than input offset and // falls within the range of input data boolean useTempOut = false; if (inArray == outArray && ((inOfs < outOfs) && (outOfs < inOfs + inLen))) { useTempOut = true; outArray = new byte[outLenNeeded]; outOfs = 0; } if (isUpdate) { total = engineUpdate(inArray, inOfs, inLen, outArray, outOfs); } else { total = engineDoFinal(inArray, inOfs, inLen, outArray, outOfs); } if (useTempOut) { output.put(outArray, outOfs, total); } else { // adjust output position manually output.position(outPos + total); } // adjust input position manually input.position(inLimit); } else { // output does not have an accessible byte[] byte[] outArray = null; if (isUpdate) { outArray = engineUpdate(inArray, inOfs, inLen); } else { outArray = engineDoFinal(inArray, inOfs, inLen); } if (outArray != null && outArray.length != 0) { output.put(outArray); total = outArray.length; } // adjust input position manually input.position(inLimit); } } else { // input does not have an accessible byte[] // have to assume the worst, since we have no way of determine // if input and output overlaps or not byte[] tempOut = new byte[outLenNeeded]; int outOfs = 0; byte[] tempIn = new byte[getTempArraySize(inLen)]; do { int chunk = Math.min(inLen, tempIn.length); if (chunk > 0) { input.get(tempIn, 0, chunk); } int n; if (isUpdate || (inLen > chunk)) { n = engineUpdate(tempIn, 0, chunk, tempOut, outOfs); } else { n = engineDoFinal(tempIn, 0, chunk, tempOut, outOfs); } outOfs += n; total += n; inLen -= chunk; } while (inLen > 0); if (total > 0) { output.put(tempOut, 0, total); } } return total; } /** * Wrap a key. * * <p>This concrete method has been added to this previously-defined * abstract class. (For backwards compatibility, it cannot be abstract.) * It may be overridden by a provider to wrap a key. * Such an override is expected to throw an IllegalBlockSizeException or * InvalidKeyException (under the specified circumstances), * if the given key cannot be wrapped. * If this method is not overridden, it always throws an * UnsupportedOperationException. * * @param key the key to be wrapped. * * @return the wrapped key. * * @exception IllegalBlockSizeException if this cipher is a block cipher, * no padding has been requested, and the length of the encoding of the * key to be wrapped is not a multiple of the block size. * * @exception InvalidKeyException if it is impossible or unsafe to * wrap the key with this cipher (e.g., a hardware protected key is * being passed to a software-only cipher). * * @throws UnsupportedOperationException if this method is not supported. */ protected byte[] engineWrap(Key key) throws IllegalBlockSizeException, InvalidKeyException { throw new UnsupportedOperationException(); } /** * Unwrap a previously wrapped key. * * <p>This concrete method has been added to this previously-defined * abstract class. (For backwards compatibility, it cannot be abstract.) * It may be overridden by a provider to unwrap a previously wrapped key. * Such an override is expected to throw an InvalidKeyException if * the given wrapped key cannot be unwrapped. * If this method is not overridden, it always throws an * UnsupportedOperationException. * * @param wrappedKey the key to be unwrapped. * * @param wrappedKeyAlgorithm the algorithm associated with the wrapped * key. * * @param wrappedKeyType the type of the wrapped key. This is one of * <code>SECRET_KEY</code>, <code>PRIVATE_KEY</code>, or * <code>PUBLIC_KEY</code>. * * @return the unwrapped key. * * @exception NoSuchAlgorithmException if no installed providers * can create keys of type <code>wrappedKeyType</code> for the * <code>wrappedKeyAlgorithm</code>. * * @exception InvalidKeyException if <code>wrappedKey</code> does not * represent a wrapped key of type <code>wrappedKeyType</code> for * the <code>wrappedKeyAlgorithm</code>. * * @throws UnsupportedOperationException if this method is not supported. */ protected Key engineUnwrap(byte[] wrappedKey, String wrappedKeyAlgorithm, int wrappedKeyType) throws InvalidKeyException, NoSuchAlgorithmException { throw new UnsupportedOperationException(); } /** * Returns the key size of the given key object in bits. * <p>This concrete method has been added to this previously-defined * abstract class. It throws an <code>UnsupportedOperationException</code> * if it is not overridden by the provider. * * @param key the key object. * * @return the key size of the given key object. * * @exception InvalidKeyException if <code>key</code> is invalid. */ protected int engineGetKeySize(Key key) throws InvalidKeyException { throw new UnsupportedOperationException(); } /** * Continues a multi-part update of the Additional Authentication * Data (AAD), using a subset of the provided buffer. * <p> * Calls to this method provide AAD to the cipher when operating in * modes such as AEAD (GCM/CCM). If this cipher is operating in * either GCM or CCM mode, all AAD must be supplied before beginning * operations on the ciphertext (via the {@code update} and {@code * doFinal} methods). * * @param src the buffer containing the AAD * @param offset the offset in {@code src} where the AAD input starts * @param len the number of AAD bytes * * @throws IllegalStateException if this cipher is in a wrong state * (e.g., has not been initialized), does not accept AAD, or if * operating in either GCM or CCM mode and one of the {@code update} * methods has already been called for the active * encryption/decryption operation * @throws UnsupportedOperationException if this method * has not been overridden by an implementation * * @since 1.7 */ protected void engineUpdateAAD(byte[] src, int offset, int len) { throw new UnsupportedOperationException( "The underlying Cipher implementation " + "does not support this method"); } /** * Continues a multi-part update of the Additional Authentication * Data (AAD). * <p> * Calls to this method provide AAD to the cipher when operating in * modes such as AEAD (GCM/CCM). If this cipher is operating in * either GCM or CCM mode, all AAD must be supplied before beginning * operations on the ciphertext (via the {@code update} and {@code * doFinal} methods). * <p> * All {@code src.remaining()} bytes starting at * {@code src.position()} are processed. * Upon return, the input buffer's position will be equal * to its limit; its limit will not have changed. * * @param src the buffer containing the AAD * * @throws IllegalStateException if this cipher is in a wrong state * (e.g., has not been initialized), does not accept AAD, or if * operating in either GCM or CCM mode and one of the {@code update} * methods has already been called for the active * encryption/decryption operation * @throws UnsupportedOperationException if this method * has not been overridden by an implementation * * @since 1.7 */ protected void engineUpdateAAD(ByteBuffer src) { throw new UnsupportedOperationException( "The underlying Cipher implementation " + "does not support this method"); } }
{ "pile_set_name": "Github" }
#include <string.h> #include <stdio.h> #include <stdlib.h> #include "fitsio.h" int main(int argc, char *argv[]) { fitsfile *infptr, *outfptr; /* FITS file pointers defined in fitsio.h */ int status = 0, tstatus, ii = 1, iteration = 0, single = 0, hdupos; int hdutype, bitpix, bytepix, naxis = 0, nkeys, datatype = 0, anynul; long naxes[9] = {1, 1, 1, 1, 1, 1, 1, 1, 1}; long first, totpix = 0, npix; double *array, bscale = 1.0, bzero = 0.0, nulval = 0.; char card[81]; if (argc != 3) { printf("\n"); printf("Usage: imcopy inputImage outputImage[compress]\n"); printf("\n"); printf("Copy an input image to an output image, optionally compressing\n"); printf("or uncompressing the image in the process. If the [compress]\n"); printf("qualifier is appended to the output file name then the input image\n"); printf("will be compressed using the tile-compressed format. In this format,\n"); printf("the image is divided into rectangular tiles and each tile of pixels\n"); printf("is compressed and stored in a variable-length row of a binary table.\n"); printf("If the [compress] qualifier is omitted, and the input image is\n"); printf("in tile-compressed format, then the output image will be uncompressed.\n"); printf("\n"); printf("If an extension name or number is appended to the input file name, \n"); printf("enclosed in square brackets, then only that single extension will be\n"); printf("copied to the output file. Otherwise, every extension in the input file\n"); printf("will be processed in turn and copied to the output file.\n"); printf("\n"); printf("Examples:\n"); printf("\n"); printf("1) imcopy image.fit 'cimage.fit[compress]'\n"); printf("\n"); printf(" This compresses the input image using the default parameters, i.e.,\n"); printf(" using the Rice compression algorithm and using row by row tiles.\n"); printf("\n"); printf("2) imcopy cimage.fit image2.fit\n"); printf("\n"); printf(" This uncompresses the image created in the first example.\n"); printf(" image2.fit should be identical to image.fit if the image\n"); printf(" has an integer datatype. There will be small differences\n"); printf(" in the pixel values if it is a floating point image.\n"); printf("\n"); printf("3) imcopy image.fit 'cimage.fit[compress GZIP 100,100;q 16]'\n"); printf("\n"); printf(" This compresses the input image using the following parameters:\n"); printf(" GZIP compression algorithm;\n"); printf(" 100 X 100 pixel compression tiles;\n"); printf(" quantization level = 16 (only used with floating point images)\n"); printf("\n"); printf("The full syntax of the compression qualifier is:\n"); printf(" [compress ALGORITHM TDIM1,TDIM2,...; q QLEVEL s SCALE]\n"); printf("where the allowed ALGORITHM values are:\n"); printf(" Rice, HCOMPRESS, HSCOMPRESS, GZIP, or PLIO. \n"); printf(" (HSCOMPRESS is a variant of HCOMPRESS in which a small\n"); printf(" amount of smoothing is applied to the uncompressed image\n"); printf(" to help suppress blocky compression artifacts in the image\n"); printf(" when using large values for the 'scale' parameter).\n"); printf("TDIMn is the size of the compression tile in each dimension,\n"); printf("\n"); printf("QLEVEL specifies the quantization level when converting a floating\n"); printf("point image into integers, prior to compressing the image. The\n"); printf("default value = 16, which means the image will be quantized into\n"); printf("integer levels that are spaced at intervals of sigma/16., where \n"); printf("sigma is the estimated noise level in background areas of the image.\n"); printf("If QLEVEL is negative, this means use the absolute value for the\n"); printf("quantization spacing (e.g. 'q -0.005' means quantize the floating\n"); printf("point image such that the scaled integers represent steps of 0.005\n"); printf("in the original image).\n"); printf("\n"); printf("SCALE is the integer scale factor that only applies to the HCOMPRESS\n"); printf("algorithm. The default value SCALE = 0 forces the image to be\n"); printf("losslessly compressed; Greater amounts of lossy compression (resulting\n"); printf("in smaller compressed files) can be specified with larger SCALE values.\n"); printf("\n"); printf("\n"); printf("Note that it may be necessary to enclose the file names\n"); printf("in single quote characters on the Unix command line.\n"); return(0); } /* Open the input file and create output file */ fits_open_file(&infptr, argv[1], READONLY, &status); fits_create_file(&outfptr, argv[2], &status); if (status != 0) { fits_report_error(stderr, status); return(status); } fits_get_hdu_num(infptr, &hdupos); /* Get the current HDU position */ /* Copy only a single HDU if a specific extension was given */ if (hdupos != 1 || strchr(argv[1], '[')) single = 1; for (; !status; hdupos++) /* Main loop through each extension */ { fits_get_hdu_type(infptr, &hdutype, &status); if (hdutype == IMAGE_HDU) { /* get image dimensions and total number of pixels in image */ for (ii = 0; ii < 9; ii++) naxes[ii] = 1; fits_get_img_param(infptr, 9, &bitpix, &naxis, naxes, &status); totpix = naxes[0] * naxes[1] * naxes[2] * naxes[3] * naxes[4] * naxes[5] * naxes[6] * naxes[7] * naxes[8]; } if (hdutype != IMAGE_HDU || naxis == 0 || totpix == 0) { /* just copy tables and null images */ fits_copy_hdu(infptr, outfptr, 0, &status); } else { /* Explicitly create new image, to support compression */ fits_create_img(outfptr, bitpix, naxis, naxes, &status); if (status) { fits_report_error(stderr, status); return(status); } if (fits_is_compressed_image(outfptr, &status)) { /* write default EXTNAME keyword if it doesn't already exist */ tstatus = 0; fits_read_card(infptr, "EXTNAME", card, &tstatus); if (tstatus) { strcpy(card, "EXTNAME = 'COMPRESSED_IMAGE' / name of this binary table extension"); fits_write_record(outfptr, card, &status); } } /* copy all the user keywords (not the structural keywords) */ fits_get_hdrspace(infptr, &nkeys, NULL, &status); for (ii = 1; ii <= nkeys; ii++) { fits_read_record(infptr, ii, card, &status); if (fits_get_keyclass(card) > TYP_CMPRS_KEY) fits_write_record(outfptr, card, &status); } /* delete default EXTNAME keyword if it exists */ /* if (!fits_is_compressed_image(outfptr, &status)) { tstatus = 0; fits_read_key(outfptr, TSTRING, "EXTNAME", card, NULL, &tstatus); if (!tstatus) { if (strcmp(card, "COMPRESSED_IMAGE") == 0) fits_delete_key(outfptr, "EXTNAME", &status); } } */ switch(bitpix) { case BYTE_IMG: datatype = TBYTE; break; case SHORT_IMG: datatype = TSHORT; break; case LONG_IMG: datatype = TINT; break; case FLOAT_IMG: datatype = TFLOAT; break; case DOUBLE_IMG: datatype = TDOUBLE; break; } bytepix = abs(bitpix) / 8; npix = totpix; iteration = 0; /* try to allocate memory for the entire image */ /* use double type to force memory alignment */ array = (double *) calloc(npix, bytepix); /* if allocation failed, divide size by 2 and try again */ while (!array && iteration < 10) { iteration++; npix = npix / 2; array = (double *) calloc(npix, bytepix); } if (!array) { printf("Memory allocation error\n"); return(0); } /* turn off any scaling so that we copy the raw pixel values */ fits_set_bscale(infptr, bscale, bzero, &status); fits_set_bscale(outfptr, bscale, bzero, &status); first = 1; while (totpix > 0 && !status) { /* read all or part of image then write it back to the output file */ fits_read_img(infptr, datatype, first, npix, &nulval, array, &anynul, &status); fits_write_img(outfptr, datatype, first, npix, array, &status); totpix = totpix - npix; first = first + npix; } free(array); } if (single) break; /* quit if only copying a single HDU */ fits_movrel_hdu(infptr, 1, NULL, &status); /* try to move to next HDU */ } if (status == END_OF_FILE) status = 0; /* Reset after normal error */ fits_close_file(outfptr, &status); fits_close_file(infptr, &status); /* if error occurred, print out error message */ if (status) fits_report_error(stderr, status); return(status); }
{ "pile_set_name": "Github" }
/* Copyright (c) 2006-2010 by OpenLayers Contributors (see authors.txt for * full list of contributors). Published under the Clear BSD license. * See http://svn.openlayers.org/trunk/openlayers/license.txt for the * full text of the license. */ /** * @requires OpenLayers/Control.js * @requires OpenLayers/BaseTypes.js * @requires OpenLayers/Events.js */ /** * Class: OpenLayers.Control.OverviewMap * The OverMap control creates a small overview map, useful to display the * extent of a zoomed map and your main map and provide additional * navigation options to the User. By default the overview map is drawn in * the lower right corner of the main map. Create a new overview map with the * <OpenLayers.Control.OverviewMap> constructor. * * Inerits from: * - <OpenLayers.Control> */ OpenLayers.Control.OverviewMap = OpenLayers.Class(OpenLayers.Control, { /** * Property: element * {DOMElement} The DOM element that contains the overview map */ element: null, /** * APIProperty: ovmap * {<OpenLayers.Map>} A reference to the overview map itself. */ ovmap: null, /** * APIProperty: size * {<OpenLayers.Size>} The overvew map size in pixels. Note that this is * the size of the map itself - the element that contains the map (default * class name olControlOverviewMapElement) may have padding or other style * attributes added via CSS. */ size: new OpenLayers.Size(180, 90), /** * APIProperty: layers * {Array(<OpenLayers.Layer>)} Ordered list of layers in the overview map. * If none are sent at construction, the base layer for the main map is used. */ layers: null, /** * APIProperty: minRectSize * {Integer} The minimum width or height (in pixels) of the extent * rectangle on the overview map. When the extent rectangle reaches * this size, it will be replaced depending on the value of the * <minRectDisplayClass> property. Default is 15 pixels. */ minRectSize: 15, /** * APIProperty: minRectDisplayClass * {String} Replacement style class name for the extent rectangle when * <minRectSize> is reached. This string will be suffixed on to the * displayClass. Default is "RectReplacement". * * Example CSS declaration: * (code) * .olControlOverviewMapRectReplacement { * overflow: hidden; * cursor: move; * background-image: url("img/overview_replacement.gif"); * background-repeat: no-repeat; * background-position: center; * } * (end) */ minRectDisplayClass: "RectReplacement", /** * APIProperty: minRatio * {Float} The ratio of the overview map resolution to the main map * resolution at which to zoom farther out on the overview map. */ minRatio: 8, /** * APIProperty: maxRatio * {Float} The ratio of the overview map resolution to the main map * resolution at which to zoom farther in on the overview map. */ maxRatio: 32, /** * APIProperty: mapOptions * {Object} An object containing any non-default properties to be sent to * the overview map's map constructor. These should include any * non-default options that the main map was constructed with. */ mapOptions: null, /** * APIProperty: autoPan * {Boolean} Always pan the overview map, so the extent marker remains in * the center. Default is false. If true, when you drag the extent * marker, the overview map will update itself so the marker returns * to the center. */ autoPan: false, /** * Property: handlers * {Object} */ handlers: null, /** * Property: resolutionFactor * {Object} */ resolutionFactor: 1, /** * APIProperty: maximized * {Boolean} Start as maximized (visible). Defaults to false. */ maximized: false, /** * Constructor: OpenLayers.Control.OverviewMap * Create a new overview map * * Parameters: * object - {Object} Properties of this object will be set on the overview * map object. Note, to set options on the map object contained in this * control, set <mapOptions> as one of the options properties. */ initialize: function(options) { this.layers = []; this.handlers = {}; OpenLayers.Control.prototype.initialize.apply(this, [options]); }, /** * APIMethod: destroy * Deconstruct the control */ destroy: function() { if (!this.mapDiv) { // we've already been destroyed return; } if (this.handlers.click) { this.handlers.click.destroy(); } if (this.handlers.drag) { this.handlers.drag.destroy(); } this.mapDiv.removeChild(this.extentRectangle); this.extentRectangle = null; if (this.rectEvents) { this.rectEvents.destroy(); this.rectEvents = null; } if (this.ovmap) { this.ovmap.destroy(); this.ovmap = null; } this.element.removeChild(this.mapDiv); this.mapDiv = null; this.div.removeChild(this.element); this.element = null; if (this.maximizeDiv) { OpenLayers.Event.stopObservingElement(this.maximizeDiv); this.div.removeChild(this.maximizeDiv); this.maximizeDiv = null; } if (this.minimizeDiv) { OpenLayers.Event.stopObservingElement(this.minimizeDiv); this.div.removeChild(this.minimizeDiv); this.minimizeDiv = null; } this.map.events.un({ "moveend": this.update, "changebaselayer": this.baseLayerDraw, scope: this }); OpenLayers.Control.prototype.destroy.apply(this, arguments); }, /** * Method: draw * Render the control in the browser. */ draw: function() { OpenLayers.Control.prototype.draw.apply(this, arguments); if(!(this.layers.length > 0)) { if (this.map.baseLayer) { var layer = this.map.baseLayer.clone(); this.layers = [layer]; } else { this.map.events.register("changebaselayer", this, this.baseLayerDraw); return this.div; } } // create overview map DOM elements this.element = document.createElement('div'); this.element.className = this.displayClass + 'Element'; this.element.style.display = 'none'; this.mapDiv = document.createElement('div'); this.mapDiv.style.width = this.size.w + 'px'; this.mapDiv.style.height = this.size.h + 'px'; this.mapDiv.style.position = 'relative'; this.mapDiv.style.overflow = 'hidden'; this.mapDiv.id = OpenLayers.Util.createUniqueID('overviewMap'); this.extentRectangle = document.createElement('div'); this.extentRectangle.style.position = 'absolute'; this.extentRectangle.style.zIndex = 1000; //HACK this.extentRectangle.className = this.displayClass+'ExtentRectangle'; this.mapDiv.appendChild(this.extentRectangle); this.element.appendChild(this.mapDiv); this.div.appendChild(this.element); // Optionally add min/max buttons if the control will go in the // map viewport. if(!this.outsideViewport) { this.div.className += " " + this.displayClass + 'Container'; var imgLocation = OpenLayers.Util.getImagesLocation(); // maximize button div var img = imgLocation + 'layer-switcher-maximize.png'; this.maximizeDiv = OpenLayers.Util.createAlphaImageDiv( this.displayClass + 'MaximizeButton', null, new OpenLayers.Size(18,18), img, 'absolute'); this.maximizeDiv.style.display = 'none'; this.maximizeDiv.className = this.displayClass + 'MaximizeButton'; OpenLayers.Event.observe(this.maximizeDiv, 'click', OpenLayers.Function.bindAsEventListener(this.maximizeControl, this) ); this.div.appendChild(this.maximizeDiv); // minimize button div var img = imgLocation + 'layer-switcher-minimize.png'; this.minimizeDiv = OpenLayers.Util.createAlphaImageDiv( 'OpenLayers_Control_minimizeDiv', null, new OpenLayers.Size(18,18), img, 'absolute'); this.minimizeDiv.style.display = 'none'; this.minimizeDiv.className = this.displayClass + 'MinimizeButton'; OpenLayers.Event.observe(this.minimizeDiv, 'click', OpenLayers.Function.bindAsEventListener(this.minimizeControl, this) ); this.div.appendChild(this.minimizeDiv); var eventsToStop = ['dblclick','mousedown']; for (var i=0, len=eventsToStop.length; i<len; i++) { OpenLayers.Event.observe(this.maximizeDiv, eventsToStop[i], OpenLayers.Event.stop); OpenLayers.Event.observe(this.minimizeDiv, eventsToStop[i], OpenLayers.Event.stop); } this.minimizeControl(); } else { // show the overview map this.element.style.display = ''; } if(this.map.getExtent()) { this.update(); } this.map.events.register('moveend', this, this.update); if (this.maximized) { this.maximizeControl(); } return this.div; }, /** * Method: baseLayerDraw * Draw the base layer - called if unable to complete in the initial draw */ baseLayerDraw: function() { this.draw(); this.map.events.unregister("changebaselayer", this, this.baseLayerDraw); }, /** * Method: rectDrag * Handle extent rectangle drag * * Parameters: * px - {<OpenLayers.Pixel>} The pixel location of the drag. */ rectDrag: function(px) { var deltaX = this.handlers.drag.last.x - px.x; var deltaY = this.handlers.drag.last.y - px.y; if(deltaX != 0 || deltaY != 0) { var rectTop = this.rectPxBounds.top; var rectLeft = this.rectPxBounds.left; var rectHeight = Math.abs(this.rectPxBounds.getHeight()); var rectWidth = this.rectPxBounds.getWidth(); // don't allow dragging off of parent element var newTop = Math.max(0, (rectTop - deltaY)); newTop = Math.min(newTop, this.ovmap.size.h - this.hComp - rectHeight); var newLeft = Math.max(0, (rectLeft - deltaX)); newLeft = Math.min(newLeft, this.ovmap.size.w - this.wComp - rectWidth); this.setRectPxBounds(new OpenLayers.Bounds(newLeft, newTop + rectHeight, newLeft + rectWidth, newTop)); } }, /** * Method: mapDivClick * Handle browser events * * Parameters: * evt - {<OpenLayers.Event>} evt */ mapDivClick: function(evt) { var pxCenter = this.rectPxBounds.getCenterPixel(); var deltaX = evt.xy.x - pxCenter.x; var deltaY = evt.xy.y - pxCenter.y; var top = this.rectPxBounds.top; var left = this.rectPxBounds.left; var height = Math.abs(this.rectPxBounds.getHeight()); var width = this.rectPxBounds.getWidth(); var newTop = Math.max(0, (top + deltaY)); newTop = Math.min(newTop, this.ovmap.size.h - height); var newLeft = Math.max(0, (left + deltaX)); newLeft = Math.min(newLeft, this.ovmap.size.w - width); this.setRectPxBounds(new OpenLayers.Bounds(newLeft, newTop + height, newLeft + width, newTop)); this.updateMapToRect(); }, /** * Method: maximizeControl * Unhide the control. Called when the control is in the map viewport. * * Parameters: * e - {<OpenLayers.Event>} */ maximizeControl: function(e) { this.element.style.display = ''; this.showToggle(false); if (e != null) { OpenLayers.Event.stop(e); } }, /** * Method: minimizeControl * Hide all the contents of the control, shrink the size, * add the maximize icon * * Parameters: * e - {<OpenLayers.Event>} */ minimizeControl: function(e) { this.element.style.display = 'none'; this.showToggle(true); if (e != null) { OpenLayers.Event.stop(e); } }, /** * Method: showToggle * Hide/Show the toggle depending on whether the control is minimized * * Parameters: * minimize - {Boolean} */ showToggle: function(minimize) { this.maximizeDiv.style.display = minimize ? '' : 'none'; this.minimizeDiv.style.display = minimize ? 'none' : ''; }, /** * Method: update * Update the overview map after layers move. */ update: function() { if(this.ovmap == null) { this.createMap(); } if(this.autoPan || !this.isSuitableOverview()) { this.updateOverview(); } // update extent rectangle this.updateRectToMap(); }, /** * Method: isSuitableOverview * Determines if the overview map is suitable given the extent and * resolution of the main map. */ isSuitableOverview: function() { var mapExtent = this.map.getExtent(); var maxExtent = this.map.maxExtent; var testExtent = new OpenLayers.Bounds( Math.max(mapExtent.left, maxExtent.left), Math.max(mapExtent.bottom, maxExtent.bottom), Math.min(mapExtent.right, maxExtent.right), Math.min(mapExtent.top, maxExtent.top)); if (this.ovmap.getProjection() != this.map.getProjection()) { testExtent = testExtent.transform( this.map.getProjectionObject(), this.ovmap.getProjectionObject() ); } var resRatio = this.ovmap.getResolution() / this.map.getResolution(); return ((resRatio > this.minRatio) && (resRatio <= this.maxRatio) && (this.ovmap.getExtent().containsBounds(testExtent))); }, /** * Method updateOverview * Called by <update> if <isSuitableOverview> returns true */ updateOverview: function() { var mapRes = this.map.getResolution(); var targetRes = this.ovmap.getResolution(); var resRatio = targetRes / mapRes; if(resRatio > this.maxRatio) { // zoom in overview map targetRes = this.minRatio * mapRes; } else if(resRatio <= this.minRatio) { // zoom out overview map targetRes = this.maxRatio * mapRes; } var center; if (this.ovmap.getProjection() != this.map.getProjection()) { center = this.map.center.clone(); center.transform(this.map.getProjectionObject(), this.ovmap.getProjectionObject() ); } else { center = this.map.center; } this.ovmap.setCenter(center, this.ovmap.getZoomForResolution( targetRes * this.resolutionFactor)); this.updateRectToMap(); }, /** * Method: createMap * Construct the map that this control contains */ createMap: function() { // create the overview map var options = OpenLayers.Util.extend( {controls: [], maxResolution: 'auto', fallThrough: false}, this.mapOptions); this.ovmap = new OpenLayers.Map(this.mapDiv, options); // prevent ovmap from being destroyed when the page unloads, because // the OverviewMap control has to do this (and does it). OpenLayers.Event.stopObserving(window, 'unload', this.ovmap.unloadDestroy); this.ovmap.addLayers(this.layers); this.ovmap.zoomToMaxExtent(); // check extent rectangle border width this.wComp = parseInt(OpenLayers.Element.getStyle(this.extentRectangle, 'border-left-width')) + parseInt(OpenLayers.Element.getStyle(this.extentRectangle, 'border-right-width')); this.wComp = (this.wComp) ? this.wComp : 2; this.hComp = parseInt(OpenLayers.Element.getStyle(this.extentRectangle, 'border-top-width')) + parseInt(OpenLayers.Element.getStyle(this.extentRectangle, 'border-bottom-width')); this.hComp = (this.hComp) ? this.hComp : 2; this.handlers.drag = new OpenLayers.Handler.Drag( this, {move: this.rectDrag, done: this.updateMapToRect}, {map: this.ovmap} ); this.handlers.click = new OpenLayers.Handler.Click( this, { "click": this.mapDivClick },{ "single": true, "double": false, "stopSingle": true, "stopDouble": true, "pixelTolerance": 1, map: this.ovmap } ); this.handlers.click.activate(); this.rectEvents = new OpenLayers.Events(this, this.extentRectangle, null, true); this.rectEvents.register("mouseover", this, function(e) { if(!this.handlers.drag.active && !this.map.dragging) { this.handlers.drag.activate(); } }); this.rectEvents.register("mouseout", this, function(e) { if(!this.handlers.drag.dragging) { this.handlers.drag.deactivate(); } }); if (this.ovmap.getProjection() != this.map.getProjection()) { var sourceUnits = this.map.getProjectionObject().getUnits() || this.map.units || this.map.baseLayer.units; var targetUnits = this.ovmap.getProjectionObject().getUnits() || this.ovmap.units || this.ovmap.baseLayer.units; this.resolutionFactor = sourceUnits && targetUnits ? OpenLayers.INCHES_PER_UNIT[sourceUnits] / OpenLayers.INCHES_PER_UNIT[targetUnits] : 1; } }, /** * Method: updateRectToMap * Updates the extent rectangle position and size to match the map extent */ updateRectToMap: function() { // If the projections differ we need to reproject var bounds; if (this.ovmap.getProjection() != this.map.getProjection()) { bounds = this.map.getExtent().transform( this.map.getProjectionObject(), this.ovmap.getProjectionObject() ); } else { bounds = this.map.getExtent(); } var pxBounds = this.getRectBoundsFromMapBounds(bounds); if (pxBounds) { this.setRectPxBounds(pxBounds); } }, /** * Method: updateMapToRect * Updates the map extent to match the extent rectangle position and size */ updateMapToRect: function() { var lonLatBounds = this.getMapBoundsFromRectBounds(this.rectPxBounds); if (this.ovmap.getProjection() != this.map.getProjection()) { lonLatBounds = lonLatBounds.transform( this.ovmap.getProjectionObject(), this.map.getProjectionObject() ); } this.map.panTo(lonLatBounds.getCenterLonLat()); }, /** * Method: setRectPxBounds * Set extent rectangle pixel bounds. * * Parameters: * pxBounds - {<OpenLayers.Bounds>} */ setRectPxBounds: function(pxBounds) { var top = Math.max(pxBounds.top, 0); var left = Math.max(pxBounds.left, 0); var bottom = Math.min(pxBounds.top + Math.abs(pxBounds.getHeight()), this.ovmap.size.h - this.hComp); var right = Math.min(pxBounds.left + pxBounds.getWidth(), this.ovmap.size.w - this.wComp); var width = Math.max(right - left, 0); var height = Math.max(bottom - top, 0); if(width < this.minRectSize || height < this.minRectSize) { this.extentRectangle.className = this.displayClass + this.minRectDisplayClass; var rLeft = left + (width / 2) - (this.minRectSize / 2); var rTop = top + (height / 2) - (this.minRectSize / 2); this.extentRectangle.style.top = Math.round(rTop) + 'px'; this.extentRectangle.style.left = Math.round(rLeft) + 'px'; this.extentRectangle.style.height = this.minRectSize + 'px'; this.extentRectangle.style.width = this.minRectSize + 'px'; } else { this.extentRectangle.className = this.displayClass + 'ExtentRectangle'; this.extentRectangle.style.top = Math.round(top) + 'px'; this.extentRectangle.style.left = Math.round(left) + 'px'; this.extentRectangle.style.height = Math.round(height) + 'px'; this.extentRectangle.style.width = Math.round(width) + 'px'; } this.rectPxBounds = new OpenLayers.Bounds( Math.round(left), Math.round(bottom), Math.round(right), Math.round(top) ); }, /** * Method: getRectBoundsFromMapBounds * Get the rect bounds from the map bounds. * * Parameters: * lonLatBounds - {<OpenLayers.Bounds>} * * Returns: * {<OpenLayers.Bounds>}A bounds which is the passed-in map lon/lat extent * translated into pixel bounds for the overview map */ getRectBoundsFromMapBounds: function(lonLatBounds) { var leftBottomLonLat = new OpenLayers.LonLat(lonLatBounds.left, lonLatBounds.bottom); var rightTopLonLat = new OpenLayers.LonLat(lonLatBounds.right, lonLatBounds.top); var leftBottomPx = this.getOverviewPxFromLonLat(leftBottomLonLat); var rightTopPx = this.getOverviewPxFromLonLat(rightTopLonLat); var bounds = null; if (leftBottomPx && rightTopPx) { bounds = new OpenLayers.Bounds(leftBottomPx.x, leftBottomPx.y, rightTopPx.x, rightTopPx.y); } return bounds; }, /** * Method: getMapBoundsFromRectBounds * Get the map bounds from the rect bounds. * * Parameters: * pxBounds - {<OpenLayers.Bounds>} * * Returns: * {<OpenLayers.Bounds>} Bounds which is the passed-in overview rect bounds * translated into lon/lat bounds for the overview map */ getMapBoundsFromRectBounds: function(pxBounds) { var leftBottomPx = new OpenLayers.Pixel(pxBounds.left, pxBounds.bottom); var rightTopPx = new OpenLayers.Pixel(pxBounds.right, pxBounds.top); var leftBottomLonLat = this.getLonLatFromOverviewPx(leftBottomPx); var rightTopLonLat = this.getLonLatFromOverviewPx(rightTopPx); return new OpenLayers.Bounds(leftBottomLonLat.lon, leftBottomLonLat.lat, rightTopLonLat.lon, rightTopLonLat.lat); }, /** * Method: getLonLatFromOverviewPx * Get a map location from a pixel location * * Parameters: * overviewMapPx - {<OpenLayers.Pixel>} * * Returns: * {<OpenLayers.LonLat>} Location which is the passed-in overview map * OpenLayers.Pixel, translated into lon/lat by the overview map */ getLonLatFromOverviewPx: function(overviewMapPx) { var size = this.ovmap.size; var res = this.ovmap.getResolution(); var center = this.ovmap.getExtent().getCenterLonLat(); var delta_x = overviewMapPx.x - (size.w / 2); var delta_y = overviewMapPx.y - (size.h / 2); return new OpenLayers.LonLat(center.lon + delta_x * res , center.lat - delta_y * res); }, /** * Method: getOverviewPxFromLonLat * Get a pixel location from a map location * * Parameters: * lonlat - {<OpenLayers.LonLat>} * * Returns: * {<OpenLayers.Pixel>} Location which is the passed-in OpenLayers.LonLat, * translated into overview map pixels */ getOverviewPxFromLonLat: function(lonlat) { var res = this.ovmap.getResolution(); var extent = this.ovmap.getExtent(); var px = null; if (extent) { px = new OpenLayers.Pixel( Math.round(1/res * (lonlat.lon - extent.left)), Math.round(1/res * (extent.top - lonlat.lat))); } return px; }, CLASS_NAME: 'OpenLayers.Control.OverviewMap' });
{ "pile_set_name": "Github" }
inline val a = "" extension (x: Int) def combine (y: Int) = x + y def combine(x: Int, y: Int, z: Int) = x + y + z def combine = 0 def foo = "foo"
{ "pile_set_name": "Github" }
/* * $Id: pa_unix_util.c 1232 2007-06-16 14:49:43Z rossb $ * Portable Audio I/O Library * UNIX platform-specific support functions * * Based on the Open Source API proposed by Ross Bencina * Copyright (c) 1999-2000 Ross Bencina * * 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. */ /* * The text above constitutes the entire PortAudio license; however, * the PortAudio community also makes the following non-binding requests: * * Any person wishing to distribute modifications to the Software is * requested to send the modifications to the original developer so that * they can be incorporated into the canonical version. It is also * requested that these non-binding requests be included along with the * license above. */ /** @file @ingroup unix_src */ #include <pthread.h> #include <unistd.h> #include <stdlib.h> #include <time.h> #include <sys/time.h> #include <assert.h> #include <string.h> /* For memset */ #include <math.h> #include <errno.h> #include "pa_util.h" #include "pa_unix_util.h" #include "pa_debugprint.h" /* Track memory allocations to avoid leaks. */ #if PA_TRACK_MEMORY static int numAllocations_ = 0; #endif void *PaUtil_AllocateMemory( long size ) { void *result = malloc( size ); #if PA_TRACK_MEMORY if( result != NULL ) numAllocations_ += 1; #endif return result; } void PaUtil_FreeMemory( void *block ) { if( block != NULL ) { free( block ); #if PA_TRACK_MEMORY numAllocations_ -= 1; #endif } } int PaUtil_CountCurrentlyAllocatedBlocks( void ) { #if PA_TRACK_MEMORY return numAllocations_; #else return 0; #endif } void Pa_Sleep( long msec ) { #ifdef HAVE_NANOSLEEP struct timespec req = {0}, rem = {0}; PaTime time = msec / 1.e3; req.tv_sec = (time_t)time; assert(time - req.tv_sec < 1.0); req.tv_nsec = (long)((time - req.tv_sec) * 1.e9); nanosleep(&req, &rem); /* XXX: Try sleeping the remaining time (contained in rem) if interrupted by a signal? */ #else while( msec > 999 ) /* For OpenBSD and IRIX, argument */ { /* to usleep must be < 1000000. */ usleep( 999000 ); msec -= 999; } usleep( msec * 1000 ); #endif } /* *** NOT USED YET: *** static int usePerformanceCounter_; static double microsecondsPerTick_; */ void PaUtil_InitializeClock( void ) { /* TODO */ } PaTime PaUtil_GetTime( void ) { #ifdef HAVE_CLOCK_GETTIME struct timespec tp; clock_gettime(CLOCK_REALTIME, &tp); return (PaTime)(tp.tv_sec + tp.tv_nsec / 1.e9); #else struct timeval tv; gettimeofday( &tv, NULL ); return (PaTime) tv.tv_usec / 1000000. + tv.tv_sec; #endif } PaError PaUtil_InitializeThreading( PaUtilThreading *threading ) { (void) paUtilErr_; return paNoError; } void PaUtil_TerminateThreading( PaUtilThreading *threading ) { } PaError PaUtil_StartThreading( PaUtilThreading *threading, void *(*threadRoutine)(void *), void *data ) { pthread_create( &threading->callbackThread, NULL, threadRoutine, data ); return paNoError; } PaError PaUtil_CancelThreading( PaUtilThreading *threading, int wait, PaError *exitResult ) { PaError result = paNoError; void *pret; if( exitResult ) *exitResult = paNoError; /* Only kill the thread if it isn't in the process of stopping (flushing adaptation buffers) */ if( !wait ) pthread_cancel( threading->callbackThread ); /* XXX: Safe to call this if the thread has exited on its own? */ pthread_join( threading->callbackThread, &pret ); #ifdef PTHREAD_CANCELED if( pret && PTHREAD_CANCELED != pret ) #else /* !wait means the thread may have been canceled */ if( pret && wait ) #endif { if( exitResult ) *exitResult = *(PaError *) pret; free( pret ); } return result; } /* Threading */ /* paUnixMainThread * We have to be a bit careful with defining this global variable, * as explained below. */ #ifdef __apple__ /* apple/gcc has a "problem" with global vars and dynamic libs. Initializing it seems to fix the problem. Described a bit in this thread: http://gcc.gnu.org/ml/gcc/2005-06/msg00179.html */ pthread_t paUnixMainThread = 0; #else /*pthreads are opaque. We don't know that asigning it an int value always makes sense, so we don't initialize it unless we have to.*/ pthread_t paUnixMainThread = 0; #endif PaError PaUnixThreading_Initialize() { paUnixMainThread = pthread_self(); return paNoError; } static PaError BoostPriority( PaUnixThread* self ) { PaError result = paNoError; struct sched_param spm = { 0 }; /* Priority should only matter between contending FIFO threads? */ spm.sched_priority = 1; assert( self ); if( pthread_setschedparam( self->thread, SCHED_FIFO, &spm ) != 0 ) { PA_UNLESS( errno == EPERM, paInternalError ); /* Lack permission to raise priority */ PA_DEBUG(( "Failed bumping priority\n" )); result = 0; } else { result = 1; /* Success */ } error: return result; } PaError PaUnixThread_New( PaUnixThread* self, void* (*threadFunc)( void* ), void* threadArg, PaTime waitForChild, int rtSched ) { PaError result = paNoError; pthread_attr_t attr; int started = 0; memset( self, 0, sizeof (PaUnixThread) ); PaUnixMutex_Initialize( &self->mtx ); PA_ASSERT_CALL( pthread_cond_init( &self->cond, NULL ), 0 ); self->parentWaiting = 0 != waitForChild; /* Spawn thread */ /* Temporarily disabled since we should test during configuration for presence of required mman.h header */ #if 0 #if defined _POSIX_MEMLOCK && (_POSIX_MEMLOCK != -1) if( rtSched ) { if( mlockall( MCL_CURRENT | MCL_FUTURE ) < 0 ) { int savedErrno = errno; /* In case errno gets overwritten */ assert( savedErrno != EINVAL ); /* Most likely a programmer error */ PA_UNLESS( (savedErrno == EPERM), paInternalError ); PA_DEBUG(( "%s: Failed locking memory\n", __FUNCTION__ )); } else PA_DEBUG(( "%s: Successfully locked memory\n", __FUNCTION__ )); } #endif #endif PA_UNLESS( !pthread_attr_init( &attr ), paInternalError ); /* Priority relative to other processes */ PA_UNLESS( !pthread_attr_setscope( &attr, PTHREAD_SCOPE_SYSTEM ), paInternalError ); PA_UNLESS( !pthread_create( &self->thread, &attr, threadFunc, threadArg ), paInternalError ); started = 1; if( rtSched ) { #if 0 if( self->useWatchdog ) { int err; struct sched_param wdSpm = { 0 }; /* Launch watchdog, watchdog sets callback thread priority */ int prio = PA_MIN( self->rtPrio + 4, sched_get_priority_max( SCHED_FIFO ) ); wdSpm.sched_priority = prio; PA_UNLESS( !pthread_attr_init( &attr ), paInternalError ); PA_UNLESS( !pthread_attr_setinheritsched( &attr, PTHREAD_EXPLICIT_SCHED ), paInternalError ); PA_UNLESS( !pthread_attr_setscope( &attr, PTHREAD_SCOPE_SYSTEM ), paInternalError ); PA_UNLESS( !pthread_attr_setschedpolicy( &attr, SCHED_FIFO ), paInternalError ); PA_UNLESS( !pthread_attr_setschedparam( &attr, &wdSpm ), paInternalError ); if( (err = pthread_create( &self->watchdogThread, &attr, &WatchdogFunc, self )) ) { PA_UNLESS( err == EPERM, paInternalError ); /* Permission error, go on without realtime privileges */ PA_DEBUG(( "Failed bumping priority\n" )); } else { int policy; self->watchdogRunning = 1; PA_ENSURE_SYSTEM( pthread_getschedparam( self->watchdogThread, &policy, &wdSpm ), 0 ); /* Check if priority is right, policy could potentially differ from SCHED_FIFO (but that's alright) */ if( wdSpm.sched_priority != prio ) { PA_DEBUG(( "Watchdog priority not set correctly (%d)\n", wdSpm.sched_priority )); PA_ENSURE( paInternalError ); } } } else #endif PA_ENSURE( BoostPriority( self ) ); { int policy; struct sched_param spm; pthread_getschedparam(self->thread, &policy, &spm); } } if( self->parentWaiting ) { PaTime till; struct timespec ts; int res = 0; PaTime now; PA_ENSURE( PaUnixMutex_Lock( &self->mtx ) ); /* Wait for stream to be started */ now = PaUtil_GetTime(); till = now + waitForChild; while( self->parentWaiting && !res ) { if( waitForChild > 0 ) { ts.tv_sec = (time_t) floor( till ); ts.tv_nsec = (long) ((till - floor( till )) * 1e9); res = pthread_cond_timedwait( &self->cond, &self->mtx.mtx, &ts ); } else { res = pthread_cond_wait( &self->cond, &self->mtx.mtx ); } } PA_ENSURE( PaUnixMutex_Unlock( &self->mtx ) ); PA_UNLESS( !res || ETIMEDOUT == res, paInternalError ); PA_DEBUG(( "%s: Waited for %g seconds for stream to start\n", __FUNCTION__, PaUtil_GetTime() - now )); if( ETIMEDOUT == res ) { PA_ENSURE( paTimedOut ); } } end: return result; error: if( started ) { PaUnixThread_Terminate( self, 0, NULL ); } goto end; } PaError PaUnixThread_Terminate( PaUnixThread* self, int wait, PaError* exitResult ) { PaError result = paNoError; void* pret; if( exitResult ) { *exitResult = paNoError; } #if 0 if( watchdogExitResult ) *watchdogExitResult = paNoError; if( th->watchdogRunning ) { pthread_cancel( th->watchdogThread ); PA_ENSURE_SYSTEM( pthread_join( th->watchdogThread, &pret ), 0 ); if( pret && pret != PTHREAD_CANCELED ) { if( watchdogExitResult ) *watchdogExitResult = *(PaError *) pret; free( pret ); } } #endif /* Only kill the thread if it isn't in the process of stopping (flushing adaptation buffers) */ /* TODO: Make join time out */ self->stopRequested = wait; if( !wait ) { PA_DEBUG(( "%s: Canceling thread %d\n", __FUNCTION__, self->thread )); /* XXX: Safe to call this if the thread has exited on its own? */ pthread_cancel( self->thread ); } PA_DEBUG(( "%s: Joining thread %d\n", __FUNCTION__, self->thread )); PA_ENSURE_SYSTEM( pthread_join( self->thread, &pret ), 0 ); if( pret && PTHREAD_CANCELED != pret ) { if( exitResult ) { *exitResult = *(PaError*)pret; } free( pret ); } error: PA_ASSERT_CALL( PaUnixMutex_Terminate( &self->mtx ), paNoError ); PA_ASSERT_CALL( pthread_cond_destroy( &self->cond ), 0 ); return result; } PaError PaUnixThread_PrepareNotify( PaUnixThread* self ) { PaError result = paNoError; PA_UNLESS( self->parentWaiting, paInternalError ); PA_ENSURE( PaUnixMutex_Lock( &self->mtx ) ); self->locked = 1; error: return result; } PaError PaUnixThread_NotifyParent( PaUnixThread* self ) { PaError result = paNoError; PA_UNLESS( self->parentWaiting, paInternalError ); if( !self->locked ) { PA_ENSURE( PaUnixMutex_Lock( &self->mtx ) ); self->locked = 1; } self->parentWaiting = 0; pthread_cond_signal( &self->cond ); PA_ENSURE( PaUnixMutex_Unlock( &self->mtx ) ); self->locked = 0; error: return result; } int PaUnixThread_StopRequested( PaUnixThread* self ) { return self->stopRequested; } PaError PaUnixMutex_Initialize( PaUnixMutex* self ) { PaError result = paNoError; PA_ASSERT_CALL( pthread_mutex_init( &self->mtx, NULL ), 0 ); return result; } PaError PaUnixMutex_Terminate( PaUnixMutex* self ) { PaError result = paNoError; PA_ASSERT_CALL( pthread_mutex_destroy( &self->mtx ), 0 ); return result; } /** Lock mutex. * * We're disabling thread cancellation while the thread is holding a lock, so mutexes are * properly unlocked at termination time. */ PaError PaUnixMutex_Lock( PaUnixMutex* self ) { PaError result = paNoError; int oldState; PA_ENSURE_SYSTEM( pthread_setcancelstate( PTHREAD_CANCEL_DISABLE, &oldState ), 0 ); PA_ENSURE_SYSTEM( pthread_mutex_lock( &self->mtx ), 0 ); error: return result; } /** Unlock mutex. * * Thread cancellation is enabled again after the mutex is properly unlocked. */ PaError PaUnixMutex_Unlock( PaUnixMutex* self ) { PaError result = paNoError; int oldState; PA_ENSURE_SYSTEM( pthread_mutex_unlock( &self->mtx ), 0 ); PA_ENSURE_SYSTEM( pthread_setcancelstate( PTHREAD_CANCEL_ENABLE, &oldState ), 0 ); error: return result; } #if 0 static void OnWatchdogExit( void *userData ) { PaAlsaThreading *th = (PaAlsaThreading *) userData; struct sched_param spm = { 0 }; assert( th ); PA_ASSERT_CALL( pthread_setschedparam( th->callbackThread, SCHED_OTHER, &spm ), 0 ); /* Lower before exiting */ PA_DEBUG(( "Watchdog exiting\n" )); } static void *WatchdogFunc( void *userData ) { PaError result = paNoError, *pres = NULL; int err; PaAlsaThreading *th = (PaAlsaThreading *) userData; unsigned intervalMsec = 500; const PaTime maxSeconds = 3.; /* Max seconds between callbacks */ PaTime timeThen = PaUtil_GetTime(), timeNow, timeElapsed, cpuTimeThen, cpuTimeNow, cpuTimeElapsed; double cpuLoad, avgCpuLoad = 0.; int throttled = 0; assert( th ); /* Execute OnWatchdogExit when exiting */ pthread_cleanup_push( &OnWatchdogExit, th ); /* Boost priority of callback thread */ PA_ENSURE( result = BoostPriority( th ) ); if( !result ) { /* Boost failed, might as well exit */ pthread_exit( NULL ); } cpuTimeThen = th->callbackCpuTime; { int policy; struct sched_param spm = { 0 }; pthread_getschedparam( pthread_self(), &policy, &spm ); PA_DEBUG(( "%s: Watchdog priority is %d\n", __FUNCTION__, spm.sched_priority )); } while( 1 ) { double lowpassCoeff = 0.9, lowpassCoeff1 = 0.99999 - lowpassCoeff; /* Test before and after in case whatever underlying sleep call isn't interrupted by pthread_cancel */ pthread_testcancel(); Pa_Sleep( intervalMsec ); pthread_testcancel(); if( PaUtil_GetTime() - th->callbackTime > maxSeconds ) { PA_DEBUG(( "Watchdog: Terminating callback thread\n" )); /* Tell thread to terminate */ err = pthread_kill( th->callbackThread, SIGKILL ); pthread_exit( NULL ); } PA_DEBUG(( "%s: PortAudio reports CPU load: %g\n", __FUNCTION__, PaUtil_GetCpuLoad( th->cpuLoadMeasurer ) )); /* Check if we should throttle, or unthrottle :P */ cpuTimeNow = th->callbackCpuTime; cpuTimeElapsed = cpuTimeNow - cpuTimeThen; cpuTimeThen = cpuTimeNow; timeNow = PaUtil_GetTime(); timeElapsed = timeNow - timeThen; timeThen = timeNow; cpuLoad = cpuTimeElapsed / timeElapsed; avgCpuLoad = avgCpuLoad * lowpassCoeff + cpuLoad * lowpassCoeff1; /* if( throttled ) PA_DEBUG(( "Watchdog: CPU load: %g, %g\n", avgCpuLoad, cpuTimeElapsed )); */ if( PaUtil_GetCpuLoad( th->cpuLoadMeasurer ) > .925 ) { static int policy; static struct sched_param spm = { 0 }; static const struct sched_param defaultSpm = { 0 }; PA_DEBUG(( "%s: Throttling audio thread, priority %d\n", __FUNCTION__, spm.sched_priority )); pthread_getschedparam( th->callbackThread, &policy, &spm ); if( !pthread_setschedparam( th->callbackThread, SCHED_OTHER, &defaultSpm ) ) { throttled = 1; } else PA_DEBUG(( "Watchdog: Couldn't lower priority of audio thread: %s\n", strerror( errno ) )); /* Give other processes a go, before raising priority again */ PA_DEBUG(( "%s: Watchdog sleeping for %lu msecs before unthrottling\n", __FUNCTION__, th->throttledSleepTime )); Pa_Sleep( th->throttledSleepTime ); /* Reset callback priority */ if( pthread_setschedparam( th->callbackThread, SCHED_FIFO, &spm ) != 0 ) { PA_DEBUG(( "%s: Couldn't raise priority of audio thread: %s\n", __FUNCTION__, strerror( errno ) )); } if( PaUtil_GetCpuLoad( th->cpuLoadMeasurer ) >= .99 ) intervalMsec = 50; else intervalMsec = 100; /* lowpassCoeff = .97; lowpassCoeff1 = .99999 - lowpassCoeff; */ } else if( throttled && avgCpuLoad < .8 ) { intervalMsec = 500; throttled = 0; /* lowpassCoeff = .9; lowpassCoeff1 = .99999 - lowpassCoeff; */ } } pthread_cleanup_pop( 1 ); /* Execute cleanup on exit */ error: /* Shouldn't get here in the normal case */ /* Pass on error code */ pres = malloc( sizeof (PaError) ); *pres = result; pthread_exit( pres ); } static void CallbackUpdate( PaAlsaThreading *th ) { th->callbackTime = PaUtil_GetTime(); th->callbackCpuTime = PaUtil_GetCpuLoad( th->cpuLoadMeasurer ); } /* static void *CanaryFunc( void *userData ) { const unsigned intervalMsec = 1000; PaUtilThreading *th = (PaUtilThreading *) userData; while( 1 ) { th->canaryTime = PaUtil_GetTime(); pthread_testcancel(); Pa_Sleep( intervalMsec ); } pthread_exit( NULL ); } */ #endif
{ "pile_set_name": "Github" }
// // Copyright (c) .NET Foundation and Contributors // Portions Copyright (c) 2006..2015 Giovanni Di Sirio. All rights reserved. // See LICENSE file in the project root for full license information. // #ifndef MCUCONF_H #define MCUCONF_H /* * STM32F4xx drivers configuration. * The following settings override the default settings present in * the various device driver implementation headers. * Note that the settings for each driver only have effect if the whole * driver is enabled in halconf.h. * * IRQ priorities: * 15...0 Lowest...Highest. * * DMA priorities: * 0...3 Lowest...Highest. */ #define STM32F4xx_MCUCONF /* * HAL driver system settings. */ #define STM32_NO_INIT FALSE #define STM32_HSI_ENABLED TRUE #define STM32_LSI_ENABLED TRUE #define STM32_HSE_ENABLED TRUE #define STM32_LSE_ENABLED FALSE #define STM32_CLOCK48_REQUIRED TRUE #define STM32_SW STM32_SW_PLL #define STM32_PLLSRC STM32_PLLSRC_HSE #define STM32_PLLM_VALUE 25 #define STM32_PLLN_VALUE 336 #define STM32_PLLP_VALUE 2 #define STM32_PLLQ_VALUE 7 #define STM32_HPRE STM32_HPRE_DIV1 #define STM32_PPRE1 STM32_PPRE1_DIV4 #define STM32_PPRE2 STM32_PPRE2_DIV2 #define STM32_RTCSEL STM32_RTCSEL_LSI #define STM32_RTCPRE_VALUE 8 #define STM32_MCO1SEL STM32_MCO1SEL_HSI #define STM32_MCO1PRE STM32_MCO1PRE_DIV1 #define STM32_MCO2SEL STM32_MCO2SEL_SYSCLK #define STM32_MCO2PRE STM32_MCO2PRE_DIV1 #define STM32_I2SSRC STM32_I2SSRC_PLLI2S #define STM32_PLLI2SN_VALUE 192 #define STM32_PLLI2SR_VALUE 2 #define STM32_PVD_ENABLE FALSE #define STM32_PLS STM32_PLS_LEV0 #define STM32_BKPRAM_ENABLE FALSE /* * IRQ system settings. */ #define STM32_IRQ_EXTI0_PRIORITY 6 #define STM32_IRQ_EXTI1_PRIORITY 6 #define STM32_IRQ_EXTI2_PRIORITY 6 #define STM32_IRQ_EXTI3_PRIORITY 6 #define STM32_IRQ_EXTI4_PRIORITY 6 #define STM32_IRQ_EXTI5_9_PRIORITY 6 #define STM32_IRQ_EXTI10_15_PRIORITY 6 #define STM32_IRQ_EXTI16_PRIORITY 6 #define STM32_IRQ_EXTI17_PRIORITY 15 #define STM32_IRQ_EXTI18_PRIORITY 6 #define STM32_IRQ_EXTI19_PRIORITY 6 #define STM32_IRQ_EXTI20_PRIORITY 6 #define STM32_IRQ_EXTI21_PRIORITY 15 #define STM32_IRQ_EXTI22_PRIORITY 15 /* * ADC driver system settings. */ #define STM32_ADC_ADCPRE ADC_CCR_ADCPRE_DIV4 #define STM32_ADC_USE_ADC1 FALSE #define STM32_ADC_USE_ADC2 FALSE #define STM32_ADC_USE_ADC3 FALSE #define STM32_ADC_ADC1_DMA_STREAM STM32_DMA_STREAM_ID(2, 4) #define STM32_ADC_ADC2_DMA_STREAM STM32_DMA_STREAM_ID(2, 2) #define STM32_ADC_ADC3_DMA_STREAM STM32_DMA_STREAM_ID(2, 1) #define STM32_ADC_ADC1_DMA_PRIORITY 2 #define STM32_ADC_ADC2_DMA_PRIORITY 2 #define STM32_ADC_ADC3_DMA_PRIORITY 2 #define STM32_ADC_IRQ_PRIORITY 6 #define STM32_ADC_ADC1_DMA_IRQ_PRIORITY 6 #define STM32_ADC_ADC2_DMA_IRQ_PRIORITY 6 #define STM32_ADC_ADC3_DMA_IRQ_PRIORITY 6 /* * CAN driver system settings. */ #define STM32_CAN_USE_CAN1 FALSE #define STM32_CAN_USE_CAN2 FALSE #define STM32_CAN_CAN1_IRQ_PRIORITY 11 #define STM32_CAN_CAN2_IRQ_PRIORITY 11 /* * DAC driver system settings. */ #define STM32_DAC_DUAL_MODE FALSE #define STM32_DAC_USE_DAC1_CH1 FALSE #define STM32_DAC_USE_DAC1_CH2 FALSE #define STM32_DAC_DAC1_CH1_IRQ_PRIORITY 10 #define STM32_DAC_DAC1_CH2_IRQ_PRIORITY 10 #define STM32_DAC_DAC1_CH1_DMA_PRIORITY 2 #define STM32_DAC_DAC1_CH2_DMA_PRIORITY 2 #define STM32_DAC_DAC1_CH1_DMA_STREAM STM32_DMA_STREAM_ID(1, 5) #define STM32_DAC_DAC1_CH2_DMA_STREAM STM32_DMA_STREAM_ID(1, 6) /* * GPT driver system settings. */ #define STM32_GPT_USE_TIM1 FALSE #define STM32_GPT_USE_TIM2 FALSE #define STM32_GPT_USE_TIM3 FALSE #define STM32_GPT_USE_TIM4 FALSE #define STM32_GPT_USE_TIM5 FALSE #define STM32_GPT_USE_TIM6 FALSE #define STM32_GPT_USE_TIM7 FALSE #define STM32_GPT_USE_TIM8 FALSE #define STM32_GPT_USE_TIM9 FALSE #define STM32_GPT_USE_TIM11 FALSE #define STM32_GPT_USE_TIM12 FALSE #define STM32_GPT_USE_TIM14 FALSE #define STM32_GPT_TIM1_IRQ_PRIORITY 7 #define STM32_GPT_TIM2_IRQ_PRIORITY 7 #define STM32_GPT_TIM3_IRQ_PRIORITY 7 #define STM32_GPT_TIM4_IRQ_PRIORITY 7 #define STM32_GPT_TIM5_IRQ_PRIORITY 7 #define STM32_GPT_TIM6_IRQ_PRIORITY 7 #define STM32_GPT_TIM7_IRQ_PRIORITY 7 #define STM32_GPT_TIM8_IRQ_PRIORITY 7 #define STM32_GPT_TIM9_IRQ_PRIORITY 7 #define STM32_GPT_TIM11_IRQ_PRIORITY 7 #define STM32_GPT_TIM12_IRQ_PRIORITY 7 #define STM32_GPT_TIM14_IRQ_PRIORITY 7 /* * I2C driver system settings. */ #define STM32_I2C_USE_I2C1 FALSE #define STM32_I2C_USE_I2C2 FALSE #define STM32_I2C_USE_I2C3 FALSE #define STM32_I2C_BUSY_TIMEOUT 50 #define STM32_I2C_I2C1_RX_DMA_STREAM STM32_DMA_STREAM_ID(1, 0) #define STM32_I2C_I2C1_TX_DMA_STREAM STM32_DMA_STREAM_ID(1, 7) #define STM32_I2C_I2C2_RX_DMA_STREAM STM32_DMA_STREAM_ID(1, 2) #define STM32_I2C_I2C2_TX_DMA_STREAM STM32_DMA_STREAM_ID(1, 7) #define STM32_I2C_I2C3_RX_DMA_STREAM STM32_DMA_STREAM_ID(1, 2) #define STM32_I2C_I2C3_TX_DMA_STREAM STM32_DMA_STREAM_ID(1, 4) #define STM32_I2C_I2C1_IRQ_PRIORITY 5 #define STM32_I2C_I2C2_IRQ_PRIORITY 5 #define STM32_I2C_I2C3_IRQ_PRIORITY 5 #define STM32_I2C_I2C1_DMA_PRIORITY 3 #define STM32_I2C_I2C2_DMA_PRIORITY 3 #define STM32_I2C_I2C3_DMA_PRIORITY 3 #define STM32_I2C_DMA_ERROR_HOOK(i2cp) osalSysHalt("DMA failure") /* * I2S driver system settings. */ #define STM32_I2S_USE_SPI2 FALSE #define STM32_I2S_USE_SPI3 FALSE #define STM32_I2S_SPI2_IRQ_PRIORITY 10 #define STM32_I2S_SPI3_IRQ_PRIORITY 10 #define STM32_I2S_SPI2_DMA_PRIORITY 1 #define STM32_I2S_SPI3_DMA_PRIORITY 1 #define STM32_I2S_SPI2_RX_DMA_STREAM STM32_DMA_STREAM_ID(1, 3) #define STM32_I2S_SPI2_TX_DMA_STREAM STM32_DMA_STREAM_ID(1, 4) #define STM32_I2S_SPI3_RX_DMA_STREAM STM32_DMA_STREAM_ID(1, 0) #define STM32_I2S_SPI3_TX_DMA_STREAM STM32_DMA_STREAM_ID(1, 7) #define STM32_I2S_DMA_ERROR_HOOK(i2sp) osalSysHalt("DMA failure") /* * ICU driver system settings. */ #define STM32_ICU_USE_TIM1 FALSE #define STM32_ICU_USE_TIM2 FALSE #define STM32_ICU_USE_TIM3 FALSE #define STM32_ICU_USE_TIM4 FALSE #define STM32_ICU_USE_TIM5 FALSE #define STM32_ICU_USE_TIM8 FALSE #define STM32_ICU_USE_TIM9 FALSE #define STM32_ICU_TIM1_IRQ_PRIORITY 7 #define STM32_ICU_TIM2_IRQ_PRIORITY 7 #define STM32_ICU_TIM3_IRQ_PRIORITY 7 #define STM32_ICU_TIM4_IRQ_PRIORITY 7 #define STM32_ICU_TIM5_IRQ_PRIORITY 7 #define STM32_ICU_TIM8_IRQ_PRIORITY 7 #define STM32_ICU_TIM9_IRQ_PRIORITY 7 /* * MAC driver system settings. */ #define STM32_MAC_TRANSMIT_BUFFERS 2 #define STM32_MAC_RECEIVE_BUFFERS 4 #define STM32_MAC_BUFFERS_SIZE 1522 #define STM32_MAC_PHY_TIMEOUT 100 #define STM32_MAC_ETH1_CHANGE_PHY_STATE TRUE #define STM32_MAC_ETH1_IRQ_PRIORITY 13 #define STM32_MAC_IP_CHECKSUM_OFFLOAD 0 /* * PWM driver system settings. */ #define STM32_PWM_USE_ADVANCED FALSE #define STM32_PWM_USE_TIM1 FALSE #define STM32_PWM_USE_TIM2 FALSE #define STM32_PWM_USE_TIM3 FALSE #define STM32_PWM_USE_TIM4 FALSE #define STM32_PWM_USE_TIM5 FALSE #define STM32_PWM_USE_TIM8 FALSE #define STM32_PWM_USE_TIM9 FALSE #define STM32_PWM_TIM1_IRQ_PRIORITY 7 #define STM32_PWM_TIM2_IRQ_PRIORITY 7 #define STM32_PWM_TIM3_IRQ_PRIORITY 7 #define STM32_PWM_TIM4_IRQ_PRIORITY 7 #define STM32_PWM_TIM5_IRQ_PRIORITY 7 #define STM32_PWM_TIM8_IRQ_PRIORITY 7 #define STM32_PWM_TIM9_IRQ_PRIORITY 7 /* * SDC driver system settings. */ #define STM32_SDC_SDIO_DMA_PRIORITY 3 #define STM32_SDC_SDIO_IRQ_PRIORITY 9 #define STM32_SDC_WRITE_TIMEOUT_MS 250 #define STM32_SDC_READ_TIMEOUT_MS 25 #define STM32_SDC_CLOCK_ACTIVATION_DELAY 10 #define STM32_SDC_SDIO_UNALIGNED_SUPPORT TRUE #define STM32_SDC_SDIO_DMA_STREAM STM32_DMA_STREAM_ID(2, 3) /* * SERIAL driver system settings. */ #define STM32_SERIAL_USE_USART1 FALSE #define STM32_SERIAL_USE_USART2 TRUE #define STM32_SERIAL_USE_USART3 FALSE #define STM32_SERIAL_USE_UART4 FALSE #define STM32_SERIAL_USE_UART5 FALSE #define STM32_SERIAL_USE_USART6 FALSE #define STM32_SERIAL_USART1_PRIORITY 12 #define STM32_SERIAL_USART2_PRIORITY 12 #define STM32_SERIAL_USART3_PRIORITY 12 #define STM32_SERIAL_UART4_PRIORITY 12 #define STM32_SERIAL_UART5_PRIORITY 12 #define STM32_SERIAL_USART6_PRIORITY 12 /* * SPI driver system settings. */ #define STM32_SPI_USE_SPI1 FALSE #define STM32_SPI_USE_SPI2 FALSE #define STM32_SPI_USE_SPI3 FALSE #define STM32_SPI_SPI1_RX_DMA_STREAM STM32_DMA_STREAM_ID(2, 0) #define STM32_SPI_SPI1_TX_DMA_STREAM STM32_DMA_STREAM_ID(2, 3) #define STM32_SPI_SPI2_RX_DMA_STREAM STM32_DMA_STREAM_ID(1, 3) #define STM32_SPI_SPI2_TX_DMA_STREAM STM32_DMA_STREAM_ID(1, 4) #define STM32_SPI_SPI3_RX_DMA_STREAM STM32_DMA_STREAM_ID(1, 2) #define STM32_SPI_SPI3_TX_DMA_STREAM STM32_DMA_STREAM_ID(1, 5) #define STM32_SPI_SPI1_DMA_PRIORITY 1 #define STM32_SPI_SPI2_DMA_PRIORITY 1 #define STM32_SPI_SPI3_DMA_PRIORITY 1 #define STM32_SPI_SPI1_IRQ_PRIORITY 10 #define STM32_SPI_SPI2_IRQ_PRIORITY 10 #define STM32_SPI_SPI3_IRQ_PRIORITY 10 #define STM32_SPI_DMA_ERROR_HOOK(spip) osalSysHalt("DMA failure") /* * ST driver system settings. */ #define STM32_ST_IRQ_PRIORITY 8 #define STM32_ST_USE_TIMER 2 /* * UART driver system settings. */ #define STM32_UART_USE_USART1 FALSE #define STM32_UART_USE_USART2 FALSE #define STM32_UART_USE_USART3 FALSE #define STM32_UART_USE_UART4 FALSE #define STM32_UART_USE_UART5 FALSE #define STM32_UART_USE_USART6 FALSE #define STM32_UART_USART1_RX_DMA_STREAM STM32_DMA_STREAM_ID(2, 2) #define STM32_UART_USART1_TX_DMA_STREAM STM32_DMA_STREAM_ID(2, 7) #define STM32_UART_USART2_RX_DMA_STREAM STM32_DMA_STREAM_ID(1, 5) #define STM32_UART_USART2_TX_DMA_STREAM STM32_DMA_STREAM_ID(1, 6) #define STM32_UART_USART3_RX_DMA_STREAM STM32_DMA_STREAM_ID(1, 1) #define STM32_UART_USART3_TX_DMA_STREAM STM32_DMA_STREAM_ID(1, 3) #define STM32_UART_UART4_RX_DMA_STREAM STM32_DMA_STREAM_ID(1, 2) #define STM32_UART_UART4_TX_DMA_STREAM STM32_DMA_STREAM_ID(1, 4) #define STM32_UART_UART5_RX_DMA_STREAM STM32_DMA_STREAM_ID(1, 0) #define STM32_UART_UART5_TX_DMA_STREAM STM32_DMA_STREAM_ID(1, 7) #define STM32_UART_USART6_RX_DMA_STREAM STM32_DMA_STREAM_ID(2, 1) #define STM32_UART_USART6_TX_DMA_STREAM STM32_DMA_STREAM_ID(2, 6) #define STM32_UART_USART1_IRQ_PRIORITY 12 #define STM32_UART_USART2_IRQ_PRIORITY 12 #define STM32_UART_USART3_IRQ_PRIORITY 12 #define STM32_UART_UART4_IRQ_PRIORITY 12 #define STM32_UART_UART5_IRQ_PRIORITY 12 #define STM32_UART_USART6_IRQ_PRIORITY 12 #define STM32_UART_USART1_DMA_PRIORITY 0 #define STM32_UART_USART2_DMA_PRIORITY 0 #define STM32_UART_USART3_DMA_PRIORITY 0 #define STM32_UART_UART4_DMA_PRIORITY 0 #define STM32_UART_UART5_DMA_PRIORITY 0 #define STM32_UART_USART6_DMA_PRIORITY 0 #define STM32_UART_DMA_ERROR_HOOK(uartp) osalSysHalt("DMA failure") /* * USB driver system settings. */ #define STM32_USB_USE_OTG1 TRUE #define STM32_USB_USE_OTG2 FALSE #define STM32_USB_OTG1_IRQ_PRIORITY 14 #define STM32_USB_OTG2_IRQ_PRIORITY 14 #define STM32_USB_OTG1_RX_FIFO_SIZE 512 #define STM32_USB_OTG2_RX_FIFO_SIZE 1024 #define STM32_USB_OTG_THREAD_PRIO LOWPRIO #define STM32_USB_OTG_THREAD_STACK_SIZE 128 #define STM32_USB_OTGFIFO_FILL_BASEPRI 0 /* * WDG driver system settings. */ #define STM32_WDG_USE_IWDG FALSE // header for nanoFramework overlay drivers #include "mcuconf_nf.h" #endif /* MCUCONF_H */
{ "pile_set_name": "Github" }
SEGDREAD - read an SEG-D tape segdread > stdout tape= Required parameters: tape= input tape device tape=- to read from stdin Optional parameters: use_stdio=0 for record devices (9-track reel tape drive) =1 for pipe, disk and fixed-block 8mm drives verbose=0 silent operation = 1 ; echo every 'vblock' traces = 2 ; echo information about blocks vblock=50 echo every 'vblock' traces under verbose option ptmin=1 first shot to read ptmax=INT_MAX last shot to read gain=0 no application of gain aux=0 no recovery of auxiliary traces errmax=0 allowable number of consecutive tape IO errors ns=0 override of computed ns to work around SEG-D flaws. Ignored when use_stdio=0. pivot_year=30 Use current century for 2 digit yrs less than pivot_year, previous century otherwise. type: sudoc segdread for further information Credits: for version 1: IPRA, Pau, France: Dominique Rousset, [email protected] for version 2.2: EOST, Strasbourg, France: Celine Girard for versions 2.3: EOST, Strasbourg, France: Marc Schaming, [email protected] for version 2.4: SEP, Stanford University: Stew Levin, [email protected] a) Changed definitions of BCD_FF/BCD_FFFF b) Corrected decoding of general_header_1 in info_gh1. c) Changed buff=0 to use_stdio=1 to avoid confusion (stdio IS buffered I/O). Kept old buff= internally for backwards compatibility. d) Changed F8015 decoding of negative mantissas to avoid 1 part in 2^14th decoding error on 2's complement platforms. e) Adapted F8015 to F0015 decoding routine. Unused, but now available. f) Use AT&T sfio package for tape read. g) Handle endian and wordsize dependencies portably (I think). g) Allow tape=- command line argument to accept input from stdin. h) Compute trace length explicitly from headers so that disk data input can work. i) Correct tape trace length calculation to account for demux trace header extensions. j) Fix a couple of typos in comments and selfdoc k) Added F8022 for 1 byte quaternary exponent demux. l) Added F8024 for 2 byte quaternary exponent demux. m) Added F8042 for 1 byte hexadecimal exponent demux. n) Added F8044 for 2 byte hexadecimal exponent demux. o) Added F8048 for 4 byte hexadecimal exponent demux. p) Added F8036 for 2 byte 2's complement integer demux. q) Added F8038 for 4 byte 2's complement integer demux. r) Added F8058 for 4 byte IEEE float demux. s) Added ns= parameter to work around bad SEG-D trace length specifications in headers. for version 2.5: SEP, Stanford University: Stew Levin, [email protected] a) Added pivot_year to disambiguate decoding of 2-digit yrs b) Modified decode of 2-byte BCD to avoid endian problems c) Modified debug printout to fix endian BCD display problems d) Don't let dem_trace_header override ns specified on command line e) Removed extra factor of two in decoding of general_header_1.r f) Removed conditional disabling of sfio for version 2.6: SEP, Stanford University: Stew Levin, [email protected] a) tightened test for Sercel 358 b) modified 8015 conversion to handle Sercel 358/368 misuse of two's complement instead of one's complement. -------------------------------------------------------------------- SEGDREAD: Version 2.1, 10/10/94 Version 2.2, 17/08/95 Version 2.3, 04/1997 Thu Apr 10 11:55:45 DFT 1997 Version 2.4, 10/03/98 Tue Mar 10 1998 Version 2.5, Feb 4, 2001 Version 2.6, May 26, 2009 --------------------------------------------------------------------
{ "pile_set_name": "Github" }
/* * Copyright (c) 2008-2020, Hazelcast, 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. */ package com.hazelcast.client.impl.clientside; import com.hazelcast.client.HazelcastClient; import com.hazelcast.client.config.ClientConfig; import com.hazelcast.client.config.ClientFailoverConfig; import com.hazelcast.client.config.ClientNetworkConfig; import com.hazelcast.config.InvalidConfigurationException; import com.hazelcast.core.HazelcastException; import java.util.List; /** * Static methods to resolve and validate multiple client configs for blue green feature */ public final class FailoverClientConfigSupport { private FailoverClientConfigSupport() { } /** * Loads failover configuration using the search logic described in * {@link HazelcastClient#newHazelcastFailoverClient()} and builds * {@link ClientFailoverConfig}. * * @return resolvedConfigs * @throws HazelcastException if no failover configuration is found * @throws InvalidConfigurationException when given config is not valid */ public static ClientFailoverConfig resolveClientFailoverConfig() { return resolveClientFailoverConfig(null); } /** * If {@code clientFailoverConfig} passed {@code null}, then loads * failover configuration using the search logic described in * {@link HazelcastClient#newHazelcastFailoverClient()} and builds * {@link ClientFailoverConfig}. * * @param clientFailoverConfig provided via {@link HazelcastClient#newHazelcastFailoverClient(ClientFailoverConfig)} * @return resolvedConfigs * @throws HazelcastException if {@code clientFailoverConfig} is {@code null} and * no failover configuration is found * @throws InvalidConfigurationException when given config is not valid */ public static ClientFailoverConfig resolveClientFailoverConfig(ClientFailoverConfig clientFailoverConfig) { if (clientFailoverConfig == null) { clientFailoverConfig = ClientFailoverConfig.load(); } checkValidAlternative(clientFailoverConfig.getClientConfigs()); return clientFailoverConfig; } /** * If clientConfig is {@code null}, the client configuration is loaded * using the resolution logic as described in {@link HazelcastClient#newHazelcastClient()} * <p/> * Used with * {@link HazelcastClient#newHazelcastClient} or * {@link HazelcastClient#newHazelcastClient(ClientConfig)} * * @param config provided via {@link HazelcastClient#newHazelcastClient(ClientConfig)} * @return resolvedConfigs * @throws InvalidConfigurationException when given config is not valid */ public static ClientConfig resolveClientConfig(ClientConfig config) { if (config == null) { return ClientConfig.load(); } return config; } /** * For a client to be valid alternative, all configurations should be equal except * Cluster name * SecurityConfig * Discovery related parts of NetworkConfig * Credentials related configs * * @param alternativeClientConfigs to check if they are valid alternative for a single client two switch between clusters * @throws InvalidConfigurationException when given configs are not valid */ private static void checkValidAlternative(List<ClientConfig> alternativeClientConfigs) { if (alternativeClientConfigs.isEmpty()) { throw new InvalidConfigurationException("ClientFailoverConfig should have at least one client config."); } ClientConfig mainConfig = alternativeClientConfigs.get(0); for (ClientConfig alternativeClientConfig : alternativeClientConfigs.subList(1, alternativeClientConfigs.size())) { checkValidAlternative(mainConfig, alternativeClientConfig); } } private static void throwInvalidConfigurationException(String rootClusterName, String clusterName, String configName) { throw new InvalidConfigurationException("Alternative config with cluster name " + clusterName + " has a different config than the initial config with cluster name " + rootClusterName + " for " + configName); } /** * @return false when both objects are null or they are equal, true otherwise */ private static boolean notEqual(Object l, Object r) { return l != null ? !l.equals(r) : r != null; } @SuppressWarnings({"checkstyle:cyclomaticcomplexity", "checkstyle:npathcomplexity", "checkstyle:methodlength"}) private static void checkValidAlternative(ClientConfig mainConfig, ClientConfig alternativeConfig) { String mainClusterName = mainConfig.getClusterName(); String alterNativeClusterName = alternativeConfig.getClusterName(); checkValidAlternativeForNetwork(mainConfig, alternativeConfig); if (notEqual(mainConfig.getProperties(), alternativeConfig.getProperties())) { throwInvalidConfigurationException(mainClusterName, alterNativeClusterName, "properties"); } if (notEqual(mainConfig.getLoadBalancer(), alternativeConfig.getLoadBalancer())) { throwInvalidConfigurationException(mainClusterName, alterNativeClusterName, "loadBalancer"); } if (notEqual(mainConfig.getLoadBalancerClassName(), alternativeConfig.getLoadBalancerClassName())) { throwInvalidConfigurationException(mainClusterName, alterNativeClusterName, "loadBalancerClassName"); } if (notEqual(mainConfig.getListenerConfigs(), alternativeConfig.getListenerConfigs())) { throwInvalidConfigurationException(mainClusterName, alterNativeClusterName, "listeners"); } if (notEqual(mainConfig.getInstanceName(), alternativeConfig.getInstanceName())) { throwInvalidConfigurationException(mainClusterName, alterNativeClusterName, "instanceName"); } if (notEqual(mainConfig.getConfigPatternMatcher(), alternativeConfig.getConfigPatternMatcher())) { throwInvalidConfigurationException(mainClusterName, alterNativeClusterName, "configPatternMatcher"); } if (notEqual(mainConfig.getNearCacheConfigMap(), alternativeConfig.getNearCacheConfigMap())) { throwInvalidConfigurationException(mainClusterName, alterNativeClusterName, "nearCache"); } if (notEqual(mainConfig.getReliableTopicConfigMap(), alternativeConfig.getReliableTopicConfigMap())) { throwInvalidConfigurationException(mainClusterName, alterNativeClusterName, "reliableTopic"); } if (notEqual(mainConfig.getQueryCacheConfigs(), alternativeConfig.getQueryCacheConfigs())) { throwInvalidConfigurationException(mainClusterName, alterNativeClusterName, "queryCacheConfigs"); } if (notEqual(mainConfig.getSerializationConfig(), alternativeConfig.getSerializationConfig())) { throwInvalidConfigurationException(mainClusterName, alterNativeClusterName, "serializationConfig"); } if (notEqual(mainConfig.getNativeMemoryConfig(), alternativeConfig.getNativeMemoryConfig())) { throwInvalidConfigurationException(mainClusterName, alterNativeClusterName, "nativeMemory"); } if (notEqual(mainConfig.getProxyFactoryConfigs(), alternativeConfig.getProxyFactoryConfigs())) { throwInvalidConfigurationException(mainClusterName, alterNativeClusterName, "proxyFactory"); } if (notEqual(mainConfig.getManagedContext(), alternativeConfig.getManagedContext())) { throwInvalidConfigurationException(mainClusterName, alterNativeClusterName, "managedContext"); } if (notEqual(mainConfig.getClassLoader(), alternativeConfig.getClassLoader())) { throwInvalidConfigurationException(mainClusterName, alterNativeClusterName, "classLoader"); } if (notEqual(mainConfig.getConnectionStrategyConfig(), alternativeConfig.getConnectionStrategyConfig())) { throwInvalidConfigurationException(mainClusterName, alterNativeClusterName, "connectionStrategy"); } if (notEqual(mainConfig.getUserCodeDeploymentConfig(), alternativeConfig.getUserCodeDeploymentConfig())) { throwInvalidConfigurationException(mainClusterName, alterNativeClusterName, "userCodeDeployment"); } if (notEqual(mainConfig.getFlakeIdGeneratorConfigMap(), alternativeConfig.getFlakeIdGeneratorConfigMap())) { throwInvalidConfigurationException(mainClusterName, alterNativeClusterName, "flakeIdGenerator"); } if (notEqual(mainConfig.getLabels(), alternativeConfig.getLabels())) { throwInvalidConfigurationException(mainClusterName, alterNativeClusterName, "labels"); } if (notEqual(mainConfig.getUserContext(), alternativeConfig.getUserContext())) { throwInvalidConfigurationException(mainClusterName, alterNativeClusterName, "userContext"); } if (notEqual(mainConfig.getMetricsConfig(), alternativeConfig.getMetricsConfig())) { throwInvalidConfigurationException(mainClusterName, alterNativeClusterName, "metricsConfig"); } if (notEqual(mainConfig.getInstanceTrackingConfig(), alternativeConfig.getInstanceTrackingConfig())) { throwInvalidConfigurationException(mainClusterName, alterNativeClusterName, "instanceTrackingConfig"); } if (mainConfig.isBackupAckToClientEnabled() != alternativeConfig.isBackupAckToClientEnabled()) { throwInvalidConfigurationException(mainClusterName, alterNativeClusterName, "isBackupAckToClientEnabled"); } } @SuppressWarnings({"checkstyle:cyclomaticcomplexity", "checkstyle:npathcomplexity", "checkstyle:methodlength"}) private static void checkValidAlternativeForNetwork(ClientConfig mainConfig, ClientConfig alternativeConfig) { String mainClusterName = mainConfig.getClusterName(); String alterNativeClusterName = alternativeConfig.getClusterName(); ClientNetworkConfig mainNetworkConfig = mainConfig.getNetworkConfig(); ClientNetworkConfig alternativeNetworkConfig = alternativeConfig.getNetworkConfig(); if (mainNetworkConfig == null && alternativeNetworkConfig == null) { return; } if (mainNetworkConfig == null || alternativeNetworkConfig == null) { throwInvalidConfigurationException(mainClusterName, alterNativeClusterName, "network"); } if (mainNetworkConfig.isSmartRouting() != alternativeNetworkConfig.isSmartRouting()) { throwInvalidConfigurationException(mainClusterName, alterNativeClusterName, "network:smartRouting"); } if (mainNetworkConfig.isRedoOperation() != alternativeNetworkConfig.isRedoOperation()) { throwInvalidConfigurationException(mainClusterName, alterNativeClusterName, "network:redoOperation"); } if (mainNetworkConfig.getConnectionTimeout() != alternativeNetworkConfig.getConnectionTimeout()) { throwInvalidConfigurationException(mainClusterName, alterNativeClusterName, "network:connectionTimeout"); } if (notEqual(mainNetworkConfig.getSocketOptions(), alternativeNetworkConfig.getSocketOptions())) { throwInvalidConfigurationException(mainClusterName, alterNativeClusterName, "network:socketOptions"); } if (notEqual(mainNetworkConfig.getOutboundPortDefinitions(), alternativeNetworkConfig.getOutboundPortDefinitions())) { throwInvalidConfigurationException(mainClusterName, alterNativeClusterName, "network:outboundPortDefinitions"); } if (notEqual(mainNetworkConfig.getOutboundPorts(), alternativeNetworkConfig.getOutboundPorts())) { throwInvalidConfigurationException(mainClusterName, alterNativeClusterName, "network:smartRouting"); } if (notEqual(mainNetworkConfig.getClientIcmpPingConfig(), alternativeNetworkConfig.getClientIcmpPingConfig())) { throwInvalidConfigurationException(mainClusterName, alterNativeClusterName, "network:clientIcmp"); } } }
{ "pile_set_name": "Github" }
AC3Db MATERIAL "DefaultWhite" rgb 1 1 1 amb 1 1 1 emis 0 0 0 spec 0.5 0.5 0.5 shi 64 trans 0 MATERIAL "glass" rgb 0.1 0.1 0.1 amb 0.5 0.5 0.5 emis 0 0 0 spec 1 1 1 shi 32 trans 0.601077 OBJECT world kids 1 OBJECT poly name "noshadow.screenglass" data 8 Cube.008 crease 30.000000 numvert 8 1.28824 1.725076 -0.02227 1.28824 1.725076 0.022271 1.185811 1.414937 0.022271 1.185811 1.414937 -0.02227 1.28824 1.725076 -0.620687 1.28824 1.725076 0.620687 1.185811 1.414937 0.620687 1.185811 1.414936 -0.620687 numsurf 2 SURF 0x20 mat 1 refs 4 1 0 0 2 0 0 6 0 0 5 0 0 SURF 0x20 mat 1 refs 4 0 0 0 4 0 0 7 0 0 3 0 0 kids 0
{ "pile_set_name": "Github" }
/* * This program is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License, version 2.1 as published by the Free Software * Foundation. * * You should have received a copy of the GNU Lesser General Public License along with this * program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html * or from the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * Copyright (c) 2001 - 2013 Object Refinery Ltd, Hitachi Vantara and Contributors.. All rights reserved. */ package org.pentaho.reporting.engine.classic.core.modules.gui.base.about; import java.awt.BorderLayout; import java.awt.Dialog; import java.awt.Dimension; import java.awt.Frame; import java.awt.GridLayout; import java.util.ResourceBundle; import javax.swing.BorderFactory; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTabbedPane; import javax.swing.JTextArea; import javax.swing.SwingConstants; import javax.swing.border.Border; import org.pentaho.reporting.engine.classic.core.modules.gui.base.SwingPreviewModule; import org.pentaho.reporting.libraries.base.versioning.Licenses; import org.pentaho.reporting.libraries.base.versioning.ProjectInformation; /** * A dialog that displays information about the demonstration application. * * @author David Gilbert */ public class AboutDialog extends JDialog { /** * The preferred size for the frame. */ public static final Dimension PREFERRED_SIZE = new Dimension( 560, 360 ); /** * The default border for the panels in the tabbed pane. */ public static final Border STANDARD_BORDER = BorderFactory.createEmptyBorder( 5, 5, 5, 5 ); /** * Localised resources. */ private ResourceBundle resources; /** * The application name. */ private String application; /** * The application version. */ private String version; /** * The copyright string. */ private String copyright; /** * Other info about the application. */ private String info; /** * The licence. */ private String licence; /** * Constructs an about frame. * * @param title * the frame title. * @param project * information about the project. */ public AboutDialog( final String title, final ProjectInformation project ) { init( title, project ); } /** * Creates a non-modal dialog without a title with the specifed <code>Frame</code> as its owner. * * @param owner * the <code>Frame</code> from which the dialog is displayed */ public AboutDialog( final Frame owner, final String title, final ProjectInformation project ) { super( owner ); init( title, project ); } /** * Creates a non-modal dialog without a title with the specifed <code>Dialog</code> as its owner. * * @param owner * the <code>Dialog</code> from which the dialog is displayed */ public AboutDialog( final Dialog owner, final String title, final ProjectInformation project ) { super( owner ); init( title, project ); } /** * Constructs an 'About' frame. * * @param title * the frame title. * @param libraries * a list of libraries. */ private void init( final String title, final ProjectInformation libraries ) { setTitle( title ); setDefaultCloseOperation( JDialog.DISPOSE_ON_CLOSE ); this.application = libraries.getName(); this.version = libraries.getVersion(); this.copyright = libraries.getCopyright(); this.info = libraries.getInfo(); if ( "GPL".equalsIgnoreCase( libraries.getLicenseName() ) ) { // NON-NLS this.licence = Licenses.getInstance().getGPL(); } else if ( "LGPL".equalsIgnoreCase( libraries.getLicenseName() ) ) { // NON-NLS this.licence = Licenses.getInstance().getLGPL(); } else { this.licence = libraries.getLicenseName(); } this.resources = ResourceBundle.getBundle( SwingPreviewModule.BUNDLE_NAME ); final JPanel content = new JPanel( new BorderLayout() ); content.setBorder( AboutDialog.STANDARD_BORDER ); final JTabbedPane tabs = createTabs( libraries ); content.add( tabs ); setContentPane( content ); pack(); } /** * Returns the preferred size for the about frame. * * @return the preferred size. */ public Dimension getPreferredSize() { return AboutDialog.PREFERRED_SIZE; } /** * Creates a tabbed pane containing an about panel and a system properties panel. * * @return a tabbed pane. */ private JTabbedPane createTabs( final ProjectInformation info ) { final JTabbedPane tabs = new JTabbedPane(); final JPanel aboutPanel = createAboutPanel( info ); aboutPanel.setBorder( AboutDialog.STANDARD_BORDER ); final String aboutTab = this.resources.getString( "about-frame.tab.about" ); // NON-NLS tabs.add( aboutTab, aboutPanel ); final JPanel systemPanel = new SystemPropertiesPanel(); systemPanel.setBorder( AboutDialog.STANDARD_BORDER ); final String systemTab = this.resources.getString( "about-frame.tab.system" ); // NON-NLS tabs.add( systemTab, systemPanel ); return tabs; } /** * Creates a panel showing information about the application, including the name, version, copyright notice, URL for * further information, and a list of contributors. * * @return a panel. */ private JPanel createAboutPanel( final ProjectInformation info ) { final JPanel about = new JPanel( new BorderLayout() ); final JPanel details = createAboutTab(); boolean includetabs = false; final JTabbedPane tabs = new JTabbedPane(); if ( this.licence != null ) { final JPanel licencePanel = createLicencePanel(); licencePanel.setBorder( AboutDialog.STANDARD_BORDER ); final String licenceTab = this.resources.getString( "about-frame.tab.licence" ); // NON-NLS tabs.add( licenceTab, licencePanel ); includetabs = true; } if ( info != null ) { final JPanel librariesPanel = new LibraryPanel( info ); librariesPanel.setBorder( AboutDialog.STANDARD_BORDER ); final String librariesTab = this.resources.getString( "about-frame.tab.libraries" ); // NON-NLS tabs.add( librariesTab, librariesPanel ); includetabs = true; } about.add( details, BorderLayout.NORTH ); if ( includetabs ) { about.add( tabs ); } return about; } private JPanel createAboutTab() { final JPanel textPanel = new JPanel( new GridLayout( 4, 1, 0, 4 ) ); final JPanel appPanel = new JPanel(); final JLabel appLabel = new JLabel( application ); appLabel.setHorizontalTextPosition( SwingConstants.CENTER ); appPanel.add( appLabel ); final JPanel verPanel = new JPanel(); final JLabel verLabel = new JLabel( version ); verLabel.setHorizontalTextPosition( SwingConstants.CENTER ); verPanel.add( verLabel ); final JPanel copyrightPanel = new JPanel(); final JLabel copyrightLabel = new JLabel( copyright ); copyrightLabel.setHorizontalTextPosition( SwingConstants.CENTER ); copyrightPanel.add( copyrightLabel ); final JPanel infoPanel = new JPanel(); final JLabel infoLabel = new JLabel( info ); infoLabel.setHorizontalTextPosition( SwingConstants.CENTER ); infoPanel.add( infoLabel ); textPanel.add( appPanel ); textPanel.add( verPanel ); textPanel.add( copyrightPanel ); textPanel.add( infoPanel ); return textPanel; } /** * Creates a panel showing the licence. * * @return a panel. */ private JPanel createLicencePanel() { final JPanel licencePanel = new JPanel( new BorderLayout() ); final JTextArea area = new JTextArea( this.licence ); area.setLineWrap( true ); area.setWrapStyleWord( true ); area.setCaretPosition( 0 ); area.setEditable( false ); licencePanel.add( new JScrollPane( area ) ); return licencePanel; } }
{ "pile_set_name": "Github" }
using System; namespace Tests.Diagnostics { public sealed class SealedDisposable : IDisposable { public void Dispose() { } } public class SimpleDisposable : IDisposable // Noncompliant {{Fix this implementation of 'IDisposable' to conform to the dispose pattern.}} { public void Dispose() => Dispose(true); // Secondary {{'SimpleDisposable.Dispose()' should also call 'GC.SuppressFinalize(this)'.}} protected virtual void Dispose(bool disposing) { } } public class SimpleDisposableWithSuppressFinalize : IDisposable { public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { } } public class DisposableWithMoreThanTwoStatements : IDisposable // Noncompliant { public void Dispose() // Secondary {{'DisposableWithMoreThanTwoStatements.Dispose()' should call 'Dispose(true)', 'GC.SuppressFinalize(this)' and nothing else.}} { Dispose(true); Console.WriteLine("Extra statement"); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { } } public class DerivedDisposable : SimpleDisposable { protected override void Dispose(bool disposing) { base.Dispose(disposing); } } public class FinalizedDisposable : IDisposable { public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { } ~FinalizedDisposable() { Dispose(false); } } public class FinalizedDisposableExpression : IDisposable { public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { } ~FinalizedDisposableExpression() => Dispose(false); } public class NoVirtualDispose : IDisposable // ^^^^^^^^^^^^^^^^ Noncompliant {{Fix this implementation of 'IDisposable' to conform to the dispose pattern.}} // ^^^^^^^^^^^^^^^^ Secondary@-1 {{Provide 'protected' overridable implementation of 'Dispose(bool)' on 'NoVirtualDispose' or mark the type as 'sealed'.}} { public void Dispose() { } // ^^^^^^^ Secondary {{'NoVirtualDispose.Dispose()' should call 'Dispose(true)' and 'GC.SuppressFinalize(this)'.}} public virtual void Dispose(bool a, bool b) { } // This should not affect the implementation } public class ExplicitImplementation : IDisposable // Noncompliant { void IDisposable.Dispose() // ^^^^^^^ Secondary {{'ExplicitImplementation.Dispose()' should also call 'GC.SuppressFinalize(this)'.}} // ^^^^^^^ Secondary@-1 {{'ExplicitImplementation.Dispose()' should be 'public'.}} { Dispose(true); } protected virtual void Dispose(bool disposing) { } } public class VirtualImplementation : IDisposable // Noncompliant { public virtual void Dispose() // ^^^^^^^ Secondary {{'VirtualImplementation.Dispose()' should not be 'virtual' or 'abstract'.}} // ^^^^^^^ Secondary@-1 {{'VirtualImplementation.Dispose()' should also call 'GC.SuppressFinalize(this)'.}} { Dispose(true); } protected virtual void Dispose(bool disposing) { } } public class WithFinalizer : IDisposable // Noncompliant { public void Dispose() // ^^^^^^^ Secondary {{'WithFinalizer.Dispose()' should also call 'GC.SuppressFinalize(this)'.}} { Dispose(true); } protected virtual void Dispose(bool disposing) { } ~WithFinalizer() { } // ^^^^^^^^^^^^^ Secondary {{Modify 'WithFinalizer.~WithFinalizer()' so that it calls 'Dispose(false)' and then returns.}} } public class WithFinalizer2 : IDisposable // Noncompliant { public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { } ~WithFinalizer2() // Secondary, more than one line { Dispose(false); Console.WriteLine(1); Console.WriteLine(2); } } public class DerivedDisposable1 : NoVirtualDispose // Compliant, we are not in charge of our base { } public class DerivedDisposable2 : SimpleDisposable // Compliant, we do not override Dispose(bool) { } public class DisposeNotCallingBase1 : SimpleDisposable // Noncompliant { protected override void Dispose(bool disposing) { } // ^^^^^^^ Secondary {{Modify 'Dispose(disposing)' so that it calls 'base.Dispose(disposing)'.}} } public class DisposeNotCallingBase2 : DerivedDisposable2 // Noncompliant, checking for deeper inheritance here { protected override void Dispose(bool disposing) // ^^^^^^^ Secondary {{Modify 'Dispose(disposing)' so that it calls 'base.Dispose(disposing)'.}} { } } public interface IMyDisposable : IDisposable // Compliant, interface { } public class DerivedWithInterface1 : NoVirtualDispose, IDisposable // ^^^^^^^^^^^^^^^^^^^^^ Noncompliant // ^^^^^^^^^^^ Secondary@-1 {{Remove 'IDisposable' from the list of interfaces implemented by 'DerivedWithInterface1' and override the base class 'Dispose' implementation instead.}} { } public class DerivedWithInterface2 : NoVirtualDispose, IMyDisposable // Compliant, we are not in charge of the interface { } } namespace Rspec_Compliant_Samples { // Sealed class public sealed class Foo1 : IDisposable { public void Dispose() { // Cleanup } } // Simple implementation public class Foo2 : IDisposable { public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { // Cleanup } } // Implementation with a finalizer public class Foo3 : IDisposable { public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { // Cleanup } ~Foo3() { Dispose(false); } } // Base disposable class public class Foo4 : Foo2 { protected override void Dispose(bool disposing) { // Cleanup // Do not forget to call base base.Dispose(disposing); } } // Base disposable class, expression body public class Foo5 : Foo2 { protected override void Dispose(bool disposing) => // Cleanup // Do not forget to call base base.Dispose(disposing); } public ref struct Struct { public void Dispose() { } } public ref struct Struct2 { public void Dispose(bool disposing) // Compliant - FN: for ref structs the pattern is to have Dispose without parameters { } } } namespace VS_Generated_Implementation { // NOTE: this is not compliant public class Foo3 : IDisposable // Noncompliant { #region IDisposable Support private bool disposedValue = false; // To detect redundant calls protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { // TODO: dispose managed state (managed objects). } // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below. // TODO: set large fields to null. disposedValue = true; } } // TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources. // ~Foo3() { // // Do not change this code. Put cleanup code in Dispose(bool disposing) above. // Dispose(false); // } // This code added to correctly implement the disposable pattern. public void Dispose() // Secondary { // Do not change this code. Put cleanup code in Dispose(bool disposing) above. Dispose(true); // TODO: uncomment the following line if the finalizer is overridden above. // GC.SuppressFinalize(this); } #endregion } }
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <parent> <artifactId>niubi-job-framework</artifactId> <groupId>com.zuoxiaolong</groupId> <version>0.9.6.1-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>niubi-job-scanner</artifactId> <packaging>jar</packaging> <name>${project.groupId}:${project.artifactId}</name> <dependencies> <dependency> <groupId>com.zuoxiaolong</groupId> <artifactId>niubi-job-core</artifactId> </dependency> </dependencies> </project>
{ "pile_set_name": "Github" }
// RUN: %clang_cc1 -fsyntax-only -verify %s template<typename T> class X0 { public: void f(T t); struct Inner { void g(T t); }; }; template<typename T> void X0<T>::f(T t) { t = 17; // expected-error{{incompatible}} } extern template class X0<int>; extern template class X0<int*>; template<typename T> void X0<T>::Inner::g(T t) { t = 17; // expected-error{{incompatible}} } void test_intptr(X0<int*> xi, X0<int*>::Inner xii) { xi.f(0); xii.g(0); } extern template class X0<long*>; void test_longptr(X0<long*> xl, X0<long*>::Inner xli) { xl.f(0); xli.g(0); } template class X0<long*>; // expected-note 2{{instantiation}} template<typename T> class X1 { public: void f(T t) { t += 2; } void g(T t); }; template<typename T> void X1<T>::g(T t) { t += 2; } extern template class X1<void*>; void g_X1(X1<void*> x1, void *ptr) { x1.g(ptr); } extern template void X1<const void*>::g(const void*); void g_X1_2(X1<const void *> x1, const void *ptr) { x1.g(ptr); }
{ "pile_set_name": "Github" }
/* Copyright 2016 Goldman Sachs. 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.gs.fw.common.mithra.attribute; import com.gs.fw.common.mithra.tempobject.ArrayTuple; import com.gs.fw.common.mithra.tempobject.Tuple; import com.gs.fw.common.mithra.tempobject.TupleTempContext; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectStreamException; public class SingleColumnTupleByteArrayAttribute<Owner> extends SingleColumnByteArrayAttribute<Owner> { private int pos; private TupleTempContext tupleTempContext; public SingleColumnTupleByteArrayAttribute(int pos, int maxLength, TupleTempContext tupleTempContext) { super("c"+pos, "", "c"+pos, "", "", false, false, tupleTempContext.getRelatedFinder(), null, true, false, maxLength); this.tupleTempContext = tupleTempContext; this.pos = pos; } @Override public void setValue(Owner o, byte[] newValue) { ((ArrayTuple)o).setAttribute(this.pos, newValue); } public void setByteArrayValue(Object o, byte[] newValue) { throw new RuntimeException("not implemented"); } public byte[] byteArrayValueOf(Object o) { return ((Tuple)o).getAttributeAsByteArray(this.pos); } protected Object writeReplace() throws ObjectStreamException { return this; } private synchronized void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); this.setAll("c"+pos, "", "", false, this.tupleTempContext.getRelatedFinder(), null, true); this.setColumnName("c"+pos); } }
{ "pile_set_name": "Github" }
<?php /* * This file is part of the Monolog package. * * (c) Jordi Boggiano <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Monolog\Handler; use Monolog\Formatter\NormalizerFormatter; use Monolog\Logger; /** * Handler sending logs to Zend Monitor * * @author Christian Bergau <[email protected]> */ class ZendMonitorHandler extends AbstractProcessingHandler { /** * Monolog level / ZendMonitor Custom Event priority map * * @var array */ protected $levelMap = array( Logger::DEBUG => 1, Logger::INFO => 2, Logger::NOTICE => 3, Logger::WARNING => 4, Logger::ERROR => 5, Logger::CRITICAL => 6, Logger::ALERT => 7, Logger::EMERGENCY => 0, ); /** * Construct * * @param int $level * @param bool $bubble * @throws MissingExtensionException */ public function __construct($level = Logger::DEBUG, $bubble = true) { if (!function_exists('zend_monitor_custom_event')) { throw new MissingExtensionException('You must have Zend Server installed in order to use this handler'); } parent::__construct($level, $bubble); } /** * {@inheritdoc} */ protected function write(array $record) { $this->writeZendMonitorCustomEvent( $this->levelMap[$record['level']], $record['message'], $record['formatted'] ); } /** * Write a record to Zend Monitor * * @param int $level * @param string $message * @param array $formatted */ protected function writeZendMonitorCustomEvent($level, $message, $formatted) { zend_monitor_custom_event($level, $message, $formatted); } /** * {@inheritdoc} */ public function getDefaultFormatter() { return new NormalizerFormatter(); } /** * Get the level map * * @return array */ public function getLevelMap() { return $this->levelMap; } }
{ "pile_set_name": "Github" }
/** * @author Richard Davey <[email protected]> * @copyright 2016 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} */ /** * The Physics Body is typically linked to a single Sprite and defines properties that determine how the physics body is simulated. * These properties affect how the body reacts to forces, what forces it generates on itself (to simulate friction), and how it reacts to collisions in the scene. * In most cases, the properties are used to simulate physical effects. Each body also has its own property values that determine exactly how it reacts to forces and collisions in the scene. * By default a single Rectangle shape is added to the Body that matches the dimensions of the parent Sprite. See addShape, removeShape, clearShapes to add extra shapes around the Body. * Note: When bound to a Sprite to avoid single-pixel jitters on mobile devices we strongly recommend using Sprite sizes that are even on both axis, i.e. 128x128 not 127x127. * Note: When a game object is given a P2 body it has its anchor x/y set to 0.5, so it becomes centered. * * @class Phaser.Physics.P2.Body * @constructor * @param {Phaser.Game} game - Game reference to the currently running game. * @param {Phaser.Sprite} [sprite] - The Sprite object this physics body belongs to. * @param {number} [x=0] - The x coordinate of this Body. * @param {number} [y=0] - The y coordinate of this Body. * @param {number} [mass=1] - The default mass of this Body (0 = static). */ Phaser.Physics.P2.Body = function (game, sprite, x, y, mass) { sprite = sprite || null; x = x || 0; y = y || 0; if (mass === undefined) { mass = 1; } /** * @property {Phaser.Game} game - Local reference to game. */ this.game = game; /** * @property {Phaser.Physics.P2} world - Local reference to the P2 World. */ this.world = game.physics.p2; /** * @property {Phaser.Sprite} sprite - Reference to the parent Sprite. */ this.sprite = sprite; /** * @property {number} type - The type of physics system this body belongs to. */ this.type = Phaser.Physics.P2JS; /** * @property {Phaser.Point} offset - The offset of the Physics Body from the Sprite x/y position. */ this.offset = new Phaser.Point(); /** * @property {p2.Body} data - The p2 Body data. * @protected */ this.data = new p2.Body({ position: [ this.world.pxmi(x), this.world.pxmi(y) ], mass: mass }); this.data.parent = this; /** * @property {Phaser.Physics.P2.InversePointProxy} velocity - The velocity of the body. Set velocity.x to a negative value to move to the left, position to the right. velocity.y negative values move up, positive move down. */ this.velocity = new Phaser.Physics.P2.InversePointProxy(this.world, this.data.velocity); /** * @property {Phaser.Physics.P2.InversePointProxy} force - The force applied to the body. */ this.force = new Phaser.Physics.P2.InversePointProxy(this.world, this.data.force); /** * @property {Phaser.Point} gravity - A locally applied gravity force to the Body. Applied directly before the world step. NOTE: Not currently implemented. */ this.gravity = new Phaser.Point(); /** * Dispatched when a first contact is created between shapes in two bodies. * This event is fired during the step, so collision has already taken place. * * The event will be sent 5 arguments in this order: * * The Phaser.Physics.P2.Body it is in contact with. *This might be null* if the Body was created directly in the p2 world. * The p2.Body this Body is in contact with. * The Shape from this body that caused the contact. * The Shape from the contact body. * The Contact Equation data array. * * @property {Phaser.Signal} onBeginContact */ this.onBeginContact = new Phaser.Signal(); /** * Dispatched when contact ends between shapes in two bodies. * This event is fired during the step, so collision has already taken place. * * The event will be sent 4 arguments in this order: * * The Phaser.Physics.P2.Body it is in contact with. *This might be null* if the Body was created directly in the p2 world. * The p2.Body this Body has ended contact with. * The Shape from this body that caused the original contact. * The Shape from the contact body. * * @property {Phaser.Signal} onEndContact */ this.onEndContact = new Phaser.Signal(); /** * @property {array} collidesWith - Array of CollisionGroups that this Bodies shapes collide with. */ this.collidesWith = []; /** * @property {boolean} removeNextStep - To avoid deleting this body during a physics step, and causing all kinds of problems, set removeNextStep to true to have it removed in the next preUpdate. */ this.removeNextStep = false; /** * @property {Phaser.Physics.P2.BodyDebug} debugBody - Reference to the debug body. */ this.debugBody = null; /** * @property {boolean} dirty - Internally used by Sprite.x/y */ this.dirty = false; /** * @property {boolean} _collideWorldBounds - Internal var that determines if this Body collides with the world bounds or not. * @private */ this._collideWorldBounds = true; /** * @property {object} _bodyCallbacks - Array of Body callbacks. * @private */ this._bodyCallbacks = {}; /** * @property {object} _bodyCallbackContext - Array of Body callback contexts. * @private */ this._bodyCallbackContext = {}; /** * @property {object} _groupCallbacks - Array of Group callbacks. * @private */ this._groupCallbacks = {}; /** * @property {object} _bodyCallbackContext - Array of Grouo callback contexts. * @private */ this._groupCallbackContext = {}; /** * @property {boolean} _reset - Internal var. * @private */ this._reset = false; // Set-up the default shape if (sprite) { this.setRectangleFromSprite(sprite); if (sprite.exists) { this.game.physics.p2.addBody(this); } } }; Phaser.Physics.P2.Body.prototype = { /** * Sets a callback to be fired any time a shape in this Body impacts with a shape in the given Body. The impact test is performed against body.id values. * The callback will be sent 4 parameters: This body, the body that impacted, the Shape in this body and the shape in the impacting body. * Note that the impact event happens after collision resolution, so it cannot be used to prevent a collision from happening. * It also happens mid-step. So do not destroy a Body during this callback, instead set safeDestroy to true so it will be killed on the next preUpdate. * * @method Phaser.Physics.P2.Body#createBodyCallback * @param {Phaser.Sprite|Phaser.TileSprite|Phaser.Physics.P2.Body|p2.Body} object - The object to send impact events for. * @param {function} callback - The callback to fire on impact. Set to null to clear a previously set callback. * @param {object} callbackContext - The context under which the callback will fire. */ createBodyCallback: function (object, callback, callbackContext) { var id = -1; if (object['id']) { id = object.id; } else if (object['body']) { id = object.body.id; } if (id > -1) { if (callback === null) { delete (this._bodyCallbacks[id]); delete (this._bodyCallbackContext[id]); } else { this._bodyCallbacks[id] = callback; this._bodyCallbackContext[id] = callbackContext; } } }, /** * Sets a callback to be fired any time this Body impacts with the given Group. The impact test is performed against shape.collisionGroup values. * The callback will be sent 4 parameters: This body, the body that impacted, the Shape in this body and the shape in the impacting body. * This callback will only fire if this Body has been assigned a collision group. * Note that the impact event happens after collision resolution, so it cannot be used to prevent a collision from happening. * It also happens mid-step. So do not destroy a Body during this callback, instead set safeDestroy to true so it will be killed on the next preUpdate. * * @method Phaser.Physics.P2.Body#createGroupCallback * @param {Phaser.Physics.CollisionGroup} group - The Group to send impact events for. * @param {function} callback - The callback to fire on impact. Set to null to clear a previously set callback. * @param {object} callbackContext - The context under which the callback will fire. */ createGroupCallback: function (group, callback, callbackContext) { if (callback === null) { delete (this._groupCallbacks[group.mask]); delete (this._groupCallbackContext[group.mask]); } else { this._groupCallbacks[group.mask] = callback; this._groupCallbackContext[group.mask] = callbackContext; } }, /** * Gets the collision bitmask from the groups this body collides with. * * @method Phaser.Physics.P2.Body#getCollisionMask * @return {number} The bitmask. */ getCollisionMask: function () { var mask = 0; if (this._collideWorldBounds) { mask = this.game.physics.p2.boundsCollisionGroup.mask; } for (var i = 0; i < this.collidesWith.length; i++) { mask = mask | this.collidesWith[i].mask; } return mask; }, /** * Updates the collisionMask. * * @method Phaser.Physics.P2.Body#updateCollisionMask * @param {p2.Shape} [shape] - An optional Shape. If not provided the collision group will be added to all Shapes in this Body. */ updateCollisionMask: function (shape) { var mask = this.getCollisionMask(); if (shape === undefined) { for (var i = this.data.shapes.length - 1; i >= 0; i--) { this.data.shapes[i].collisionMask = mask; } } else { shape.collisionMask = mask; } }, /** * Sets the given CollisionGroup to be the collision group for all shapes in this Body, unless a shape is specified. * This also resets the collisionMask. * * @method Phaser.Physics.P2.Body#setCollisionGroup * @param {Phaser.Physics.CollisionGroup} group - The Collision Group that this Bodies shapes will use. * @param {p2.Shape} [shape] - An optional Shape. If not provided the collision group will be added to all Shapes in this Body. */ setCollisionGroup: function (group, shape) { var mask = this.getCollisionMask(); if (shape === undefined) { for (var i = this.data.shapes.length - 1; i >= 0; i--) { this.data.shapes[i].collisionGroup = group.mask; this.data.shapes[i].collisionMask = mask; } } else { shape.collisionGroup = group.mask; shape.collisionMask = mask; } }, /** * Clears the collision data from the shapes in this Body. Optionally clears Group and/or Mask. * * @method Phaser.Physics.P2.Body#clearCollision * @param {boolean} [clearGroup=true] - Clear the collisionGroup value from the shape/s? * @param {boolean} [clearMask=true] - Clear the collisionMask value from the shape/s? * @param {p2.Shape} [shape] - An optional Shape. If not provided the collision data will be cleared from all Shapes in this Body. */ clearCollision: function (clearGroup, clearMask, shape) { if (clearGroup === undefined) { clearGroup = true; } if (clearMask === undefined) { clearMask = true; } if (shape === undefined) { for (var i = this.data.shapes.length - 1; i >= 0; i--) { if (clearGroup) { this.data.shapes[i].collisionGroup = null; } if (clearMask) { this.data.shapes[i].collisionMask = null; } } } else { if (clearGroup) { shape.collisionGroup = null; } if (clearMask) { shape.collisionMask = null; } } if (clearGroup) { this.collidesWith.length = 0; } }, /** * Removes the given CollisionGroup, or array of CollisionGroups, from the list of groups that this body will collide with and updates the collision masks. * * @method Phaser.Physics.P2.Body#removeCollisionGroup * @param {Phaser.Physics.CollisionGroup|array} group - The Collision Group or Array of Collision Groups that this Bodies shapes should not collide with anymore. * @param {boolean} [clearCallback=true] - Clear the callback that will be triggered when this Body impacts with the given Group? * @param {p2.Shape} [shape] - An optional Shape. If not provided the updated collision mask will be added to all Shapes in this Body. */ removeCollisionGroup: function (group, clearCallback, shape) { if (clearCallback === undefined) { clearCallback = true; } var index; if (Array.isArray(group)) { for (var i = 0; i < group.length; i++) { index = this.collidesWith.indexOf(group[i]); if (index > -1) { this.collidesWith.splice(index, 1); if (clearCallback) { delete (this._groupCallbacks[group.mask]); delete (this._groupCallbackContext[group.mask]); } } } } else { index = this.collidesWith.indexOf(group); if (index > -1) { this.collidesWith.splice(index, 1); if (clearCallback) { delete (this._groupCallbacks[group.mask]); delete (this._groupCallbackContext[group.mask]); } } } var mask = this.getCollisionMask(); if (shape === undefined) { for (var i = this.data.shapes.length - 1; i >= 0; i--) { this.data.shapes[i].collisionMask = mask; } } else { shape.collisionMask = mask; } }, /** * Adds the given CollisionGroup, or array of CollisionGroups, to the list of groups that this body will collide with and updates the collision masks. * * @method Phaser.Physics.P2.Body#collides * @param {Phaser.Physics.CollisionGroup|array} group - The Collision Group or Array of Collision Groups that this Bodies shapes will collide with. * @param {function} [callback] - Optional callback that will be triggered when this Body impacts with the given Group. * @param {object} [callbackContext] - The context under which the callback will be called. * @param {p2.Shape} [shape] - An optional Shape. If not provided the collision mask will be added to all Shapes in this Body. */ collides: function (group, callback, callbackContext, shape) { if (Array.isArray(group)) { for (var i = 0; i < group.length; i++) { if (this.collidesWith.indexOf(group[i]) === -1) { this.collidesWith.push(group[i]); if (callback) { this.createGroupCallback(group[i], callback, callbackContext); } } } } else { if (this.collidesWith.indexOf(group) === -1) { this.collidesWith.push(group); if (callback) { this.createGroupCallback(group, callback, callbackContext); } } } var mask = this.getCollisionMask(); if (shape === undefined) { for (var i = this.data.shapes.length - 1; i >= 0; i--) { this.data.shapes[i].collisionMask = mask; } } else { shape.collisionMask = mask; } }, /** * Moves the shape offsets so their center of mass becomes the body center of mass. * * @method Phaser.Physics.P2.Body#adjustCenterOfMass */ adjustCenterOfMass: function () { this.data.adjustCenterOfMass(); this.shapeChanged(); }, /** * Gets the velocity of a point in the body. * * @method Phaser.Physics.P2.Body#getVelocityAtPoint * @param {Array} result - A vector to store the result in. * @param {Array} relativePoint - A world oriented vector, indicating the position of the point to get the velocity from. * @return {Array} The result vector. */ getVelocityAtPoint: function (result, relativePoint) { return this.data.getVelocityAtPoint(result, relativePoint); }, /** * Apply damping, see http://code.google.com/p/bullet/issues/detail?id=74 for details. * * @method Phaser.Physics.P2.Body#applyDamping * @param {number} dt - Current time step. */ applyDamping: function (dt) { this.data.applyDamping(dt); }, /** * Apply impulse to a point relative to the body. * This could for example be a point on the Body surface. An impulse is a force added to a body during a short * period of time (impulse = force * time). Impulses will be added to Body.velocity and Body.angularVelocity. * * @method Phaser.Physics.P2.Body#applyImpulse * @param {Float32Array|Array} impulse - The impulse vector to add, oriented in world space. * @param {number} worldX - A point relative to the body in world space. If not given, it is set to zero and all of the impulse will be exerted on the center of mass. * @param {number} worldY - A point relative to the body in world space. If not given, it is set to zero and all of the impulse will be exerted on the center of mass. */ applyImpulse: function (impulse, worldX, worldY) { this.data.applyImpulse(impulse, [this.world.pxmi(worldX), this.world.pxmi(worldY)]); }, /** * Apply impulse to a point local to the body. * * This could for example be a point on the Body surface. An impulse is a force added to a body during a short * period of time (impulse = force * time). Impulses will be added to Body.velocity and Body.angularVelocity. * * @method Phaser.Physics.P2.Body#applyImpulseLocal * @param {Float32Array|Array} impulse - The impulse vector to add, oriented in local space. * @param {number} localX - A local point on the body. * @param {number} localY - A local point on the body. */ applyImpulseLocal: function (impulse, localX, localY) { this.data.applyImpulseLocal(impulse, [this.world.pxmi(localX), this.world.pxmi(localY)]); }, /** * Apply force to a world point. * * This could for example be a point on the RigidBody surface. Applying force * this way will add to Body.force and Body.angularForce. * * @method Phaser.Physics.P2.Body#applyForce * @param {Float32Array|Array} force - The force vector to add. * @param {number} worldX - The world x point to apply the force on. * @param {number} worldY - The world y point to apply the force on. */ applyForce: function (force, worldX, worldY) { this.data.applyForce(force, [this.world.pxmi(worldX), this.world.pxmi(worldY)]); }, /** * Sets the force on the body to zero. * * @method Phaser.Physics.P2.Body#setZeroForce */ setZeroForce: function () { this.data.setZeroForce(); }, /** * If this Body is dynamic then this will zero its angular velocity. * * @method Phaser.Physics.P2.Body#setZeroRotation */ setZeroRotation: function () { this.data.angularVelocity = 0; }, /** * If this Body is dynamic then this will zero its velocity on both axis. * * @method Phaser.Physics.P2.Body#setZeroVelocity */ setZeroVelocity: function () { this.data.velocity[0] = 0; this.data.velocity[1] = 0; }, /** * Sets the Body damping and angularDamping to zero. * * @method Phaser.Physics.P2.Body#setZeroDamping */ setZeroDamping: function () { this.data.damping = 0; this.data.angularDamping = 0; }, /** * Transform a world point to local body frame. * * @method Phaser.Physics.P2.Body#toLocalFrame * @param {Float32Array|Array} out - The vector to store the result in. * @param {Float32Array|Array} worldPoint - The input world vector. */ toLocalFrame: function (out, worldPoint) { return this.data.toLocalFrame(out, worldPoint); }, /** * Transform a local point to world frame. * * @method Phaser.Physics.P2.Body#toWorldFrame * @param {Array} out - The vector to store the result in. * @param {Array} localPoint - The input local vector. */ toWorldFrame: function (out, localPoint) { return this.data.toWorldFrame(out, localPoint); }, /** * This will rotate the Body by the given speed to the left (counter-clockwise). * * @method Phaser.Physics.P2.Body#rotateLeft * @param {number} speed - The speed at which it should rotate. */ rotateLeft: function (speed) { this.data.angularVelocity = this.world.pxm(-speed); }, /** * This will rotate the Body by the given speed to the left (clockwise). * * @method Phaser.Physics.P2.Body#rotateRight * @param {number} speed - The speed at which it should rotate. */ rotateRight: function (speed) { this.data.angularVelocity = this.world.pxm(speed); }, /** * Moves the Body forwards based on its current angle and the given speed. * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). * * @method Phaser.Physics.P2.Body#moveForward * @param {number} speed - The speed at which it should move forwards. */ moveForward: function (speed) { var magnitude = this.world.pxmi(-speed); var angle = this.data.angle + Math.PI / 2; this.data.velocity[0] = magnitude * Math.cos(angle); this.data.velocity[1] = magnitude * Math.sin(angle); }, /** * Moves the Body backwards based on its current angle and the given speed. * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). * * @method Phaser.Physics.P2.Body#moveBackward * @param {number} speed - The speed at which it should move backwards. */ moveBackward: function (speed) { var magnitude = this.world.pxmi(-speed); var angle = this.data.angle + Math.PI / 2; this.data.velocity[0] = -(magnitude * Math.cos(angle)); this.data.velocity[1] = -(magnitude * Math.sin(angle)); }, /** * Applies a force to the Body that causes it to 'thrust' forwards, based on its current angle and the given speed. * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). * * @method Phaser.Physics.P2.Body#thrust * @param {number} speed - The speed at which it should thrust. */ thrust: function (speed) { var magnitude = this.world.pxmi(-speed); var angle = this.data.angle + Math.PI / 2; this.data.force[0] += magnitude * Math.cos(angle); this.data.force[1] += magnitude * Math.sin(angle); }, /** * Applies a force to the Body that causes it to 'thrust' to the left, based on its current angle and the given speed. * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). * * @method Phaser.Physics.P2.Body#thrustLeft * @param {number} speed - The speed at which it should move to the left. */ thrustLeft: function (speed) { var magnitude = this.world.pxmi(-speed); var angle = this.data.angle; this.data.force[0] += magnitude * Math.cos(angle); this.data.force[1] += magnitude * Math.sin(angle); }, /** * Applies a force to the Body that causes it to 'thrust' to the right, based on its current angle and the given speed. * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). * * @method Phaser.Physics.P2.Body#thrustRight * @param {number} speed - The speed at which it should move to the right. */ thrustRight: function (speed) { var magnitude = this.world.pxmi(-speed); var angle = this.data.angle; this.data.force[0] -= magnitude * Math.cos(angle); this.data.force[1] -= magnitude * Math.sin(angle); }, /** * Applies a force to the Body that causes it to 'thrust' backwards (in reverse), based on its current angle and the given speed. * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). * * @method Phaser.Physics.P2.Body#reverse * @param {number} speed - The speed at which it should reverse. */ reverse: function (speed) { var magnitude = this.world.pxmi(-speed); var angle = this.data.angle + Math.PI / 2; this.data.force[0] -= magnitude * Math.cos(angle); this.data.force[1] -= magnitude * Math.sin(angle); }, /** * If this Body is dynamic then this will move it to the left by setting its x velocity to the given speed. * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). * * @method Phaser.Physics.P2.Body#moveLeft * @param {number} speed - The speed at which it should move to the left, in pixels per second. */ moveLeft: function (speed) { this.data.velocity[0] = this.world.pxmi(-speed); }, /** * If this Body is dynamic then this will move it to the right by setting its x velocity to the given speed. * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). * * @method Phaser.Physics.P2.Body#moveRight * @param {number} speed - The speed at which it should move to the right, in pixels per second. */ moveRight: function (speed) { this.data.velocity[0] = this.world.pxmi(speed); }, /** * If this Body is dynamic then this will move it up by setting its y velocity to the given speed. * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). * * @method Phaser.Physics.P2.Body#moveUp * @param {number} speed - The speed at which it should move up, in pixels per second. */ moveUp: function (speed) { this.data.velocity[1] = this.world.pxmi(-speed); }, /** * If this Body is dynamic then this will move it down by setting its y velocity to the given speed. * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). * * @method Phaser.Physics.P2.Body#moveDown * @param {number} speed - The speed at which it should move down, in pixels per second. */ moveDown: function (speed) { this.data.velocity[1] = this.world.pxmi(speed); }, /** * Internal method. This is called directly before the sprites are sent to the renderer and after the update function has finished. * * @method Phaser.Physics.P2.Body#preUpdate * @protected */ preUpdate: function () { this.dirty = true; if (this.removeNextStep) { this.removeFromWorld(); this.removeNextStep = false; } }, /** * Internal method. This is called directly before the sprites are sent to the renderer and after the update function has finished. * * @method Phaser.Physics.P2.Body#postUpdate * @protected */ postUpdate: function () { this.sprite.x = this.world.mpxi(this.data.position[0]) + this.offset.x; this.sprite.y = this.world.mpxi(this.data.position[1]) + this.offset.y; if (!this.fixedRotation) { this.sprite.rotation = this.data.angle; } if (this.debugBody) { this.debugBody.updateSpriteTransform(); } this.dirty = false; }, /** * Resets the Body force, velocity (linear and angular) and rotation. Optionally resets damping and mass. * * @method Phaser.Physics.P2.Body#reset * @param {number} x - The new x position of the Body. * @param {number} y - The new x position of the Body. * @param {boolean} [resetDamping=false] - Resets the linear and angular damping. * @param {boolean} [resetMass=false] - Sets the Body mass back to 1. */ reset: function (x, y, resetDamping, resetMass) { if (resetDamping === undefined) { resetDamping = false; } if (resetMass === undefined) { resetMass = false; } this.setZeroForce(); this.setZeroVelocity(); this.setZeroRotation(); if (resetDamping) { this.setZeroDamping(); } if (resetMass) { this.mass = 1; } this.x = x; this.y = y; }, /** * Adds this physics body to the world. * * @method Phaser.Physics.P2.Body#addToWorld */ addToWorld: function () { if (this.game.physics.p2._toRemove) { for (var i = 0; i < this.game.physics.p2._toRemove.length; i++) { if (this.game.physics.p2._toRemove[i] === this) { this.game.physics.p2._toRemove.splice(i, 1); } } } if (this.data.world !== this.game.physics.p2.world) { this.game.physics.p2.addBody(this); } }, /** * Removes this physics body from the world. * * @method Phaser.Physics.P2.Body#removeFromWorld */ removeFromWorld: function () { if (this.data.world === this.game.physics.p2.world) { this.game.physics.p2.removeBodyNextStep(this); } }, /** * Destroys this Body and all references it holds to other objects. * * @method Phaser.Physics.P2.Body#destroy */ destroy: function () { this.removeFromWorld(); this.clearShapes(); this._bodyCallbacks = {}; this._bodyCallbackContext = {}; this._groupCallbacks = {}; this._groupCallbackContext = {}; if (this.debugBody) { this.debugBody.destroy(true, true); } this.debugBody = null; if (this.sprite) { this.sprite.body = null; this.sprite = null; } }, /** * Removes all Shapes from this Body. * * @method Phaser.Physics.P2.Body#clearShapes */ clearShapes: function () { var i = this.data.shapes.length; while (i--) { this.data.removeShape(this.data.shapes[i]); } this.shapeChanged(); }, /** * Add a shape to the body. You can pass a local transform when adding a shape, so that the shape gets an offset and an angle relative to the body center of mass. * Will automatically update the mass properties and bounding radius. * If this Body had a previously set Collision Group you will need to re-apply it to the new Shape this creates. * * @method Phaser.Physics.P2.Body#addShape * @param {p2.Shape} shape - The shape to add to the body. * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. * @return {p2.Shape} The shape that was added to the body. */ addShape: function (shape, offsetX, offsetY, rotation) { if (offsetX === undefined) { offsetX = 0; } if (offsetY === undefined) { offsetY = 0; } if (rotation === undefined) { rotation = 0; } this.data.addShape(shape, [this.world.pxmi(offsetX), this.world.pxmi(offsetY)], rotation); this.shapeChanged(); return shape; }, /** * Adds a Circle shape to this Body. You can control the offset from the center of the body and the rotation. * * @method Phaser.Physics.P2.Body#addCircle * @param {number} radius - The radius of this circle (in pixels) * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. * @return {p2.Circle} The Circle shape that was added to the Body. */ addCircle: function (radius, offsetX, offsetY, rotation) { var shape = new p2.Circle({ radius: this.world.pxm(radius) }); return this.addShape(shape, offsetX, offsetY, rotation); }, /** * Adds a Rectangle shape to this Body. You can control the offset from the center of the body and the rotation. * * @method Phaser.Physics.P2.Body#addRectangle * @param {number} width - The width of the rectangle in pixels. * @param {number} height - The height of the rectangle in pixels. * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. * @return {p2.Box} The shape that was added to the Body. */ addRectangle: function (width, height, offsetX, offsetY, rotation) { var shape = new p2.Box({ width: this.world.pxm(width), height: this.world.pxm(height)}); return this.addShape(shape, offsetX, offsetY, rotation); }, /** * Adds a Plane shape to this Body. The plane is facing in the Y direction. You can control the offset from the center of the body and the rotation. * * @method Phaser.Physics.P2.Body#addPlane * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. * @return {p2.Plane} The Plane shape that was added to the Body. */ addPlane: function (offsetX, offsetY, rotation) { var shape = new p2.Plane(); return this.addShape(shape, offsetX, offsetY, rotation); }, /** * Adds a Particle shape to this Body. You can control the offset from the center of the body and the rotation. * * @method Phaser.Physics.P2.Body#addParticle * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. * @return {p2.Particle} The Particle shape that was added to the Body. */ addParticle: function (offsetX, offsetY, rotation) { var shape = new p2.Particle(); return this.addShape(shape, offsetX, offsetY, rotation); }, /** * Adds a Line shape to this Body. * The line shape is along the x direction, and stretches from [-length/2, 0] to [length/2,0]. * You can control the offset from the center of the body and the rotation. * * @method Phaser.Physics.P2.Body#addLine * @param {number} length - The length of this line (in pixels) * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. * @return {p2.Line} The Line shape that was added to the Body. */ addLine: function (length, offsetX, offsetY, rotation) { var shape = new p2.Line({ length: this.world.pxm(length)}); return this.addShape(shape, offsetX, offsetY, rotation); }, /** * Adds a Capsule shape to this Body. * You can control the offset from the center of the body and the rotation. * * @method Phaser.Physics.P2.Body#addCapsule * @param {number} length - The distance between the end points in pixels. * @param {number} radius - Radius of the capsule in pixels. * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. * @return {p2.Capsule} The Capsule shape that was added to the Body. */ addCapsule: function (length, radius, offsetX, offsetY, rotation) { var shape = new p2.Capsule({ length: this.world.pxm(length), radius: this.world.pxm(radius) }); return this.addShape(shape, offsetX, offsetY, rotation); }, /** * Reads a polygon shape path, and assembles convex shapes from that and puts them at proper offset points. The shape must be simple and without holes. * This function expects the x.y values to be given in pixels. If you want to provide them at p2 world scales then call Body.data.fromPolygon directly. * * @method Phaser.Physics.P2.Body#addPolygon * @param {object} options - An object containing the build options: * @param {boolean} [options.optimalDecomp=false] - Set to true if you need optimal decomposition. Warning: very slow for polygons with more than 10 vertices. * @param {boolean} [options.skipSimpleCheck=false] - Set to true if you already know that the path is not intersecting itself. * @param {boolean|number} [options.removeCollinearPoints=false] - Set to a number (angle threshold value) to remove collinear points, or false to keep all points. * @param {(number[]|...number)} points - An array of 2d vectors that form the convex or concave polygon. * Either [[0,0], [0,1],...] or a flat array of numbers that will be interpreted as [x,y, x,y, ...], * or the arguments passed can be flat x,y values e.g. `setPolygon(options, x,y, x,y, x,y, ...)` where `x` and `y` are numbers. * @return {boolean} True on success, else false. */ addPolygon: function (options, points) { options = options || {}; if (!Array.isArray(points)) { points = Array.prototype.slice.call(arguments, 1); } var path = []; // Did they pass in a single array of points? if (points.length === 1 && Array.isArray(points[0])) { path = points[0].slice(0); } else if (Array.isArray(points[0])) { path = points.slice(); } else if (typeof points[0] === 'number') { // We've a list of numbers for (var i = 0, len = points.length; i < len; i += 2) { path.push([points[i], points[i + 1]]); } } // top and tail var idx = path.length - 1; if (path[idx][0] === path[0][0] && path[idx][1] === path[0][1]) { path.pop(); } // Now process them into p2 values for (var p = 0; p < path.length; p++) { path[p][0] = this.world.pxmi(path[p][0]); path[p][1] = this.world.pxmi(path[p][1]); } var result = this.data.fromPolygon(path, options); this.shapeChanged(); return result; }, /** * Remove a shape from the body. Will automatically update the mass properties and bounding radius. * * @method Phaser.Physics.P2.Body#removeShape * @param {p2.Circle|p2.Rectangle|p2.Plane|p2.Line|p2.Particle} shape - The shape to remove from the body. * @return {boolean} True if the shape was found and removed, else false. */ removeShape: function (shape) { var result = this.data.removeShape(shape); this.shapeChanged(); return result; }, /** * Clears any previously set shapes. Then creates a new Circle shape and adds it to this Body. * If this Body had a previously set Collision Group you will need to re-apply it to the new Shape this creates. * * @method Phaser.Physics.P2.Body#setCircle * @param {number} radius - The radius of this circle (in pixels) * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. */ setCircle: function (radius, offsetX, offsetY, rotation) { this.clearShapes(); return this.addCircle(radius, offsetX, offsetY, rotation); }, /** * Clears any previously set shapes. The creates a new Rectangle shape at the given size and offset, and adds it to this Body. * If you wish to create a Rectangle to match the size of a Sprite or Image see Body.setRectangleFromSprite. * If this Body had a previously set Collision Group you will need to re-apply it to the new Shape this creates. * * @method Phaser.Physics.P2.Body#setRectangle * @param {number} [width=16] - The width of the rectangle in pixels. * @param {number} [height=16] - The height of the rectangle in pixels. * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. * @return {p2.Rectangle} The Rectangle shape that was added to the Body. */ setRectangle: function (width, height, offsetX, offsetY, rotation) { if (width === undefined) { width = 16; } if (height === undefined) { height = 16; } this.clearShapes(); return this.addRectangle(width, height, offsetX, offsetY, rotation); }, /** * Clears any previously set shapes. * Then creates a Rectangle shape sized to match the dimensions and orientation of the Sprite given. * If no Sprite is given it defaults to using the parent of this Body. * If this Body had a previously set Collision Group you will need to re-apply it to the new Shape this creates. * * @method Phaser.Physics.P2.Body#setRectangleFromSprite * @param {Phaser.Sprite|Phaser.Image} [sprite] - The Sprite on which the Rectangle will get its dimensions. * @return {p2.Rectangle} The Rectangle shape that was added to the Body. */ setRectangleFromSprite: function (sprite) { if (sprite === undefined) { sprite = this.sprite; } this.clearShapes(); return this.addRectangle(sprite.width, sprite.height, 0, 0, sprite.rotation); }, /** * Adds the given Material to all Shapes that belong to this Body. * If you only wish to apply it to a specific Shape in this Body then provide that as the 2nd parameter. * * @method Phaser.Physics.P2.Body#setMaterial * @param {Phaser.Physics.P2.Material} material - The Material that will be applied. * @param {p2.Shape} [shape] - An optional Shape. If not provided the Material will be added to all Shapes in this Body. */ setMaterial: function (material, shape) { if (shape === undefined) { for (var i = this.data.shapes.length - 1; i >= 0; i--) { this.data.shapes[i].material = material; } } else { shape.material = material; } }, /** * Updates the debug draw if any body shapes change. * * @method Phaser.Physics.P2.Body#shapeChanged */ shapeChanged: function() { if (this.debugBody) { this.debugBody.draw(); } }, /** * Reads the shape data from a physics data file stored in the Game.Cache and adds it as a polygon to this Body. * The shape data format is based on the output of the * {@link https://github.com/photonstorm/phaser/tree/master/resources/PhysicsEditor%20Exporter|custom phaser exporter} for * {@link https://www.codeandweb.com/physicseditor|PhysicsEditor} * * @method Phaser.Physics.P2.Body#addPhaserPolygon * @param {string} key - The key of the Physics Data file as stored in Game.Cache. * @param {string} object - The key of the object within the Physics data file that you wish to load the shape data from. * @returns {Array} A list of created fixtures to be used with Phaser.Physics.P2.FixtureList */ addPhaserPolygon: function (key, object) { var data = this.game.cache.getPhysicsData(key, object); var createdFixtures = []; // Cycle through the fixtures for (var i = 0; i < data.length; i++) { var fixtureData = data[i]; var shapesOfFixture = this.addFixture(fixtureData); // Always add to a group createdFixtures[fixtureData.filter.group] = createdFixtures[fixtureData.filter.group] || []; createdFixtures[fixtureData.filter.group] = createdFixtures[fixtureData.filter.group].concat(shapesOfFixture); // if (unique) fixture key is provided if (fixtureData.fixtureKey) { createdFixtures[fixtureData.fixtureKey] = shapesOfFixture; } } this.data.aabbNeedsUpdate = true; this.shapeChanged(); return createdFixtures; }, /** * Add a polygon fixture. This is used during #loadPolygon. * * @method Phaser.Physics.P2.Body#addFixture * @param {string} fixtureData - The data for the fixture. It contains: isSensor, filter (collision) and the actual polygon shapes. * @return {array} An array containing the generated shapes for the given polygon. */ addFixture: function (fixtureData) { var generatedShapes = []; if (fixtureData.circle) { var shape = new p2.Circle({ radius: this.world.pxm(fixtureData.circle.radius) }); shape.collisionGroup = fixtureData.filter.categoryBits; shape.collisionMask = fixtureData.filter.maskBits; shape.sensor = fixtureData.isSensor; var offset = p2.vec2.create(); offset[0] = this.world.pxmi(fixtureData.circle.position[0] - this.sprite.width/2); offset[1] = this.world.pxmi(fixtureData.circle.position[1] - this.sprite.height/2); this.data.addShape(shape, offset); generatedShapes.push(shape); } else { var polygons = fixtureData.polygons; var cm = p2.vec2.create(); for (var i = 0; i < polygons.length; i++) { var shapes = polygons[i]; var vertices = []; for (var s = 0; s < shapes.length; s += 2) { vertices.push([ this.world.pxmi(shapes[s]), this.world.pxmi(shapes[s + 1]) ]); } var shape = new p2.Convex({ vertices: vertices }); // Move all vertices so its center of mass is in the local center of the convex for (var j = 0; j !== shape.vertices.length; j++) { var v = shape.vertices[j]; p2.vec2.sub(v, v, shape.centerOfMass); } p2.vec2.scale(cm, shape.centerOfMass, 1); cm[0] -= this.world.pxmi(this.sprite.width / 2); cm[1] -= this.world.pxmi(this.sprite.height / 2); shape.updateTriangles(); shape.updateCenterOfMass(); shape.updateBoundingRadius(); shape.collisionGroup = fixtureData.filter.categoryBits; shape.collisionMask = fixtureData.filter.maskBits; shape.sensor = fixtureData.isSensor; this.data.addShape(shape, cm); generatedShapes.push(shape); } } return generatedShapes; }, /** * Reads the shape data from a physics data file stored in the Game.Cache and adds it as a polygon to this Body. * * As well as reading the data from the Cache you can also pass `null` as the first argument and a * physics data object as the second. When doing this you must ensure the structure of the object is correct in advance. * * For more details see the format of the Lime / Corona Physics Editor export. * * @method Phaser.Physics.P2.Body#loadPolygon * @param {string} key - The key of the Physics Data file as stored in Game.Cache. Alternatively set to `null` and pass the * data as the 2nd argument. * @param {string|object} object - The key of the object within the Physics data file that you wish to load the shape data from, * or if key is null pass the actual physics data object itself as this parameter. * @return {boolean} True on success, else false. */ loadPolygon: function (key, object) { if (key === null) { var data = object; } else { var data = this.game.cache.getPhysicsData(key, object); } // We've multiple Convex shapes, they should be CCW automatically var cm = p2.vec2.create(); for (var i = 0; i < data.length; i++) { var vertices = []; for (var s = 0; s < data[i].shape.length; s += 2) { vertices.push([ this.world.pxmi(data[i].shape[s]), this.world.pxmi(data[i].shape[s + 1]) ]); } var c = new p2.Convex({ vertices: vertices }); // Move all vertices so its center of mass is in the local center of the convex for (var j = 0; j !== c.vertices.length; j++) { var v = c.vertices[j]; p2.vec2.sub(v, v, c.centerOfMass); } p2.vec2.scale(cm, c.centerOfMass, 1); cm[0] -= this.world.pxmi(this.sprite.width / 2); cm[1] -= this.world.pxmi(this.sprite.height / 2); c.updateTriangles(); c.updateCenterOfMass(); c.updateBoundingRadius(); this.data.addShape(c, cm); } this.data.aabbNeedsUpdate = true; this.shapeChanged(); return true; } }; Phaser.Physics.P2.Body.prototype.constructor = Phaser.Physics.P2.Body; /** * Dynamic body. Dynamic bodies body can move and respond to collisions and forces. * @property DYNAMIC * @type {Number} * @static */ Phaser.Physics.P2.Body.DYNAMIC = 1; /** * Static body. Static bodies do not move, and they do not respond to forces or collision. * @property STATIC * @type {Number} * @static */ Phaser.Physics.P2.Body.STATIC = 2; /** * Kinematic body. Kinematic bodies only moves according to its .velocity, and does not respond to collisions or force. * @property KINEMATIC * @type {Number} * @static */ Phaser.Physics.P2.Body.KINEMATIC = 4; /** * @name Phaser.Physics.P2.Body#static * @property {boolean} static - Returns true if the Body is static. Setting Body.static to 'false' will make it dynamic. */ Object.defineProperty(Phaser.Physics.P2.Body.prototype, "static", { get: function () { return (this.data.type === Phaser.Physics.P2.Body.STATIC); }, set: function (value) { if (value && this.data.type !== Phaser.Physics.P2.Body.STATIC) { this.data.type = Phaser.Physics.P2.Body.STATIC; this.mass = 0; } else if (!value && this.data.type === Phaser.Physics.P2.Body.STATIC) { this.data.type = Phaser.Physics.P2.Body.DYNAMIC; this.mass = 1; } } }); /** * @name Phaser.Physics.P2.Body#dynamic * @property {boolean} dynamic - Returns true if the Body is dynamic. Setting Body.dynamic to 'false' will make it static. */ Object.defineProperty(Phaser.Physics.P2.Body.prototype, "dynamic", { get: function () { return (this.data.type === Phaser.Physics.P2.Body.DYNAMIC); }, set: function (value) { if (value && this.data.type !== Phaser.Physics.P2.Body.DYNAMIC) { this.data.type = Phaser.Physics.P2.Body.DYNAMIC; this.mass = 1; } else if (!value && this.data.type === Phaser.Physics.P2.Body.DYNAMIC) { this.data.type = Phaser.Physics.P2.Body.STATIC; this.mass = 0; } } }); /** * @name Phaser.Physics.P2.Body#kinematic * @property {boolean} kinematic - Returns true if the Body is kinematic. Setting Body.kinematic to 'false' will make it static. */ Object.defineProperty(Phaser.Physics.P2.Body.prototype, "kinematic", { get: function () { return (this.data.type === Phaser.Physics.P2.Body.KINEMATIC); }, set: function (value) { if (value && this.data.type !== Phaser.Physics.P2.Body.KINEMATIC) { this.data.type = Phaser.Physics.P2.Body.KINEMATIC; this.mass = 4; } else if (!value && this.data.type === Phaser.Physics.P2.Body.KINEMATIC) { this.data.type = Phaser.Physics.P2.Body.STATIC; this.mass = 0; } } }); /** * @name Phaser.Physics.P2.Body#allowSleep * @property {boolean} allowSleep - */ Object.defineProperty(Phaser.Physics.P2.Body.prototype, "allowSleep", { get: function () { return this.data.allowSleep; }, set: function (value) { if (value !== this.data.allowSleep) { this.data.allowSleep = value; } } }); /** * The angle of the Body in degrees from its original orientation. Values from 0 to 180 represent clockwise rotation; values from 0 to -180 represent counterclockwise rotation. * Values outside this range are added to or subtracted from 360 to obtain a value within the range. For example, the statement Body.angle = 450 is the same as Body.angle = 90. * If you wish to work in radians instead of degrees use the property Body.rotation instead. Working in radians is faster as it doesn't have to convert values. * * @name Phaser.Physics.P2.Body#angle * @property {number} angle - The angle of this Body in degrees. */ Object.defineProperty(Phaser.Physics.P2.Body.prototype, "angle", { get: function() { return Phaser.Math.wrapAngle(Phaser.Math.radToDeg(this.data.angle)); }, set: function(value) { this.data.angle = Phaser.Math.degToRad(Phaser.Math.wrapAngle(value)); } }); /** * Damping is specified as a value between 0 and 1, which is the proportion of velocity lost per second. * @name Phaser.Physics.P2.Body#angularDamping * @property {number} angularDamping - The angular damping acting acting on the body. */ Object.defineProperty(Phaser.Physics.P2.Body.prototype, "angularDamping", { get: function () { return this.data.angularDamping; }, set: function (value) { this.data.angularDamping = value; } }); /** * @name Phaser.Physics.P2.Body#angularForce * @property {number} angularForce - The angular force acting on the body. */ Object.defineProperty(Phaser.Physics.P2.Body.prototype, "angularForce", { get: function () { return this.data.angularForce; }, set: function (value) { this.data.angularForce = value; } }); /** * @name Phaser.Physics.P2.Body#angularVelocity * @property {number} angularVelocity - The angular velocity of the body. */ Object.defineProperty(Phaser.Physics.P2.Body.prototype, "angularVelocity", { get: function () { return this.data.angularVelocity; }, set: function (value) { this.data.angularVelocity = value; } }); /** * Damping is specified as a value between 0 and 1, which is the proportion of velocity lost per second. * @name Phaser.Physics.P2.Body#damping * @property {number} damping - The linear damping acting on the body in the velocity direction. */ Object.defineProperty(Phaser.Physics.P2.Body.prototype, "damping", { get: function () { return this.data.damping; }, set: function (value) { this.data.damping = value; } }); /** * @name Phaser.Physics.P2.Body#fixedRotation * @property {boolean} fixedRotation - */ Object.defineProperty(Phaser.Physics.P2.Body.prototype, "fixedRotation", { get: function () { return this.data.fixedRotation; }, set: function (value) { if (value !== this.data.fixedRotation) { this.data.fixedRotation = value; } } }); /** * @name Phaser.Physics.P2.Body#inertia * @property {number} inertia - The inertia of the body around the Z axis.. */ Object.defineProperty(Phaser.Physics.P2.Body.prototype, "inertia", { get: function () { return this.data.inertia; }, set: function (value) { this.data.inertia = value; } }); /** * @name Phaser.Physics.P2.Body#mass * @property {number} mass - The mass of the body. */ Object.defineProperty(Phaser.Physics.P2.Body.prototype, "mass", { get: function () { return this.data.mass; }, set: function (value) { if (value !== this.data.mass) { this.data.mass = value; this.data.updateMassProperties(); } } }); /** * @name Phaser.Physics.P2.Body#motionState * @property {number} motionState - The type of motion this body has. Should be one of: Body.STATIC (the body does not move), Body.DYNAMIC (body can move and respond to collisions) and Body.KINEMATIC (only moves according to its .velocity). */ Object.defineProperty(Phaser.Physics.P2.Body.prototype, "motionState", { get: function () { return this.data.type; }, set: function (value) { if (value !== this.data.type) { this.data.type = value; } } }); /** * The angle of the Body in radians. * If you wish to work in degrees instead of radians use the Body.angle property instead. Working in radians is faster as it doesn't have to convert values. * * @name Phaser.Physics.P2.Body#rotation * @property {number} rotation - The angle of this Body in radians. */ Object.defineProperty(Phaser.Physics.P2.Body.prototype, "rotation", { get: function() { return this.data.angle; }, set: function(value) { this.data.angle = value; } }); /** * @name Phaser.Physics.P2.Body#sleepSpeedLimit * @property {number} sleepSpeedLimit - . */ Object.defineProperty(Phaser.Physics.P2.Body.prototype, "sleepSpeedLimit", { get: function () { return this.data.sleepSpeedLimit; }, set: function (value) { this.data.sleepSpeedLimit = value; } }); /** * @name Phaser.Physics.P2.Body#x * @property {number} x - The x coordinate of this Body. */ Object.defineProperty(Phaser.Physics.P2.Body.prototype, "x", { get: function () { return this.world.mpxi(this.data.position[0]); }, set: function (value) { this.data.position[0] = this.world.pxmi(value); } }); /** * @name Phaser.Physics.P2.Body#y * @property {number} y - The y coordinate of this Body. */ Object.defineProperty(Phaser.Physics.P2.Body.prototype, "y", { get: function () { return this.world.mpxi(this.data.position[1]); }, set: function (value) { this.data.position[1] = this.world.pxmi(value); } }); /** * @name Phaser.Physics.P2.Body#id * @property {number} id - The Body ID. Each Body that has been added to the World has a unique ID. * @readonly */ Object.defineProperty(Phaser.Physics.P2.Body.prototype, "id", { get: function () { return this.data.id; } }); /** * @name Phaser.Physics.P2.Body#debug * @property {boolean} debug - Enable or disable debug drawing of this body */ Object.defineProperty(Phaser.Physics.P2.Body.prototype, "debug", { get: function () { return (this.debugBody !== null); }, set: function (value) { if (value && !this.debugBody) { // This will be added to the global space this.debugBody = new Phaser.Physics.P2.BodyDebug(this.game, this.data); } else if (!value && this.debugBody) { this.debugBody.destroy(); this.debugBody = null; } } }); /** * A Body can be set to collide against the World bounds automatically if this is set to true. Otherwise it will leave the World. * Note that this only applies if your World has bounds! The response to the collision should be managed via CollisionMaterials. * Also note that when you set this it will only effect Body shapes that already exist. If you then add further shapes to your Body * after setting this it will *not* proactively set them to collide with the bounds. * * @name Phaser.Physics.P2.Body#collideWorldBounds * @property {boolean} collideWorldBounds - Should the Body collide with the World bounds? */ Object.defineProperty(Phaser.Physics.P2.Body.prototype, "collideWorldBounds", { get: function () { return this._collideWorldBounds; }, set: function (value) { if (value && !this._collideWorldBounds) { this._collideWorldBounds = true; this.updateCollisionMask(); } else if (!value && this._collideWorldBounds) { this._collideWorldBounds = false; this.updateCollisionMask(); } } });
{ "pile_set_name": "Github" }
package timex import "time" // Max returns the maximum duration func Max(values ...time.Duration) time.Duration { var ( max time.Duration ) for _, v := range values { if v > max { max = v } } return max }
{ "pile_set_name": "Github" }
<html> <head> <meta http-equiv="Content-Language" content="en-us"> <meta name="keywords" conent="c c++ objective-c programming optimization"> <meta name="description" content="ParsedStrUtil.h"> <link rel="stylesheet" href="../stylesheet.css" type="text/css"> <link rel="stylesheet" title="Default" href="../styles/idea.css"> <title>ParsedStrUtil.h</title> </head> <body> <pre><code class="cpp"> #ifndef PARSED_STR_UTIL_H__ #define PARSED_STR_UTIL_H__ char *delim_str_iter(char **str); void str_skip(char **str); const char *get_str(const char *str, int i); #endif </code></pre> <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-194516-1', 'auto'); ga('send', 'pageview'); </script> <script type="text/javascript" src="../highlight.js"></script> <script type="text/javascript"> initHighlightingOnLoad(); </script> </body> </html>
{ "pile_set_name": "Github" }
/* * * Copyright (C) 1997-2018, OFFIS e.V. * All rights reserved. See COPYRIGHT file for details. * * This software and supporting documentation were developed by * * OFFIS e.V. * R&D Division Health * Escherweg 2 * D-26121 Oldenburg, Germany * * * Module: dcmjpeg * * Author: Marco Eichelberg, Norbert Olges * * Purpose: compression routines of the IJG JPEG library configured for 16 bits/sample. * */ #include "dcmtk/config/osconfig.h" #include "dcmtk/dcmjpeg/djeijg16.h" #include "dcmtk/dcmjpeg/djcparam.h" #include "dcmtk/dcmdata/dcerror.h" #define INCLUDE_CSTDIO #define INCLUDE_CSETJMP #define INCLUDE_CSTRING #include "dcmtk/ofstd/ofstdinc.h" // These two macros are re-defined in the IJG header files. // We undefine them here and hope that IJG's configure has // come to the same conclusion that we have... #ifdef HAVE_STDLIB_H #undef HAVE_STDLIB_H #endif #ifdef HAVE_STDDEF_H #undef HAVE_STDDEF_H #endif // use 16K blocks for temporary storage of compressed JPEG data #define IJGE16_BLOCKSIZE 16384 BEGIN_EXTERN_C #define boolean ijg_boolean #include "jpeglib16.h" #include "jerror16.h" #include "jpegint16.h" #undef boolean // disable any preprocessor magic the IJG library might be doing with the "const" keyword #ifdef const #undef const #endif #ifdef USE_STD_CXX_INCLUDES // Solaris defines longjmp() in namespace std, other compilers don't... namespace std { } using namespace std; #endif // private error handler struct struct DJEIJG16ErrorStruct { // the standard IJG error handler object struct jpeg_error_mgr pub; // our jump buffer jmp_buf setjmp_buffer; // pointer to this DJCompressIJG16Bit *instance; }; // callback forward declarations void DJEIJG16ErrorExit(j_common_ptr); void DJEIJG16EmitMessage(j_common_ptr cinfo, int msg_level); void DJEIJG16initDestination(j_compress_ptr cinfo); ijg_boolean DJEIJG16emptyOutputBuffer(j_compress_ptr cinfo); void DJEIJG16termDestination(j_compress_ptr cinfo); // helper methods to fix old-style casts warnings static void OFjpeg_create_compress(j_compress_ptr cinfo) { jpeg_create_compress(cinfo); } static void OF_ERREXIT1(j_compress_ptr cinfo, int code, int p1) { ERREXIT1(cinfo, code, p1); } END_EXTERN_C // error handler, executes longjmp void DJEIJG16ErrorExit(j_common_ptr cinfo) { DJEIJG16ErrorStruct *myerr = OFreinterpret_cast(DJEIJG16ErrorStruct*, cinfo->err); longjmp(myerr->setjmp_buffer, 1); } // message handler for warning messages and the like void DJEIJG16EmitMessage(j_common_ptr cinfo, int msg_level) { DJEIJG16ErrorStruct *myerr = OFreinterpret_cast(DJEIJG16ErrorStruct*, cinfo->err); myerr->instance->emitMessage(cinfo, msg_level); } // callbacks for compress-destination-manager void DJEIJG16initDestination(j_compress_ptr cinfo) { DJCompressIJG16Bit *encoder = OFreinterpret_cast(DJCompressIJG16Bit*, cinfo->client_data); encoder->initDestination(cinfo); } ijg_boolean DJEIJG16emptyOutputBuffer(j_compress_ptr cinfo) { DJCompressIJG16Bit *encoder = OFreinterpret_cast(DJCompressIJG16Bit*, cinfo->client_data); return encoder->emptyOutputBuffer(cinfo); } void DJEIJG16termDestination(j_compress_ptr cinfo) { DJCompressIJG16Bit *encoder = OFreinterpret_cast(DJCompressIJG16Bit*, cinfo->client_data); encoder->termDestination(cinfo); } // converts dcmtk color space to IJG color space static J_COLOR_SPACE getJpegColorSpace(EP_Interpretation interpr) { switch (interpr) { case EPI_Unknown :return JCS_UNKNOWN; case EPI_Monochrome1 : return JCS_GRAYSCALE; case EPI_Monochrome2 : return JCS_GRAYSCALE; case EPI_PaletteColor : return JCS_UNKNOWN; case EPI_RGB : return JCS_RGB; case EPI_HSV : return JCS_UNKNOWN; case EPI_ARGB : return JCS_RGB; case EPI_CMYK : return JCS_CMYK; case EPI_YBR_Full : return JCS_YCbCr; case EPI_YBR_Full_422 : return JCS_YCbCr; case EPI_YBR_Partial_422 : return JCS_YCbCr; default : return JCS_UNKNOWN; } } DJCompressIJG16Bit::DJCompressIJG16Bit(const DJCodecParameter& cp, EJ_Mode mode, int prediction, int ptrans) : DJEncoder() , cparam(&cp) , psv(prediction) , pt(ptrans) , modeofOperation(mode) , pixelDataList() , bytesInLastBlock(0) { assert(mode == EJM_lossless); } DJCompressIJG16Bit::~DJCompressIJG16Bit() { cleanup(); } OFCondition DJCompressIJG16Bit::encode( Uint16 /* columns */, Uint16 /* rows */, EP_Interpretation /* interpr */, Uint16 /* samplesPerPixel */, Uint8 * /* image_buffer */, Uint8 *& /* to */, Uint32 & /* length */) { return EC_IllegalCall; } OFCondition DJCompressIJG16Bit::encode( Uint16 columns, Uint16 rows, EP_Interpretation colorSpace, Uint16 samplesPerPixel, Uint16 * image_buffer, Uint8 * & to, Uint32 & length) { struct jpeg_compress_struct cinfo; struct DJEIJG16ErrorStruct jerr; cinfo.err = jpeg_std_error(&jerr.pub); jerr.instance = this; jerr.pub.error_exit = DJEIJG16ErrorExit; jerr.pub.emit_message = DJEIJG16EmitMessage; if (setjmp(jerr.setjmp_buffer)) { // the IJG error handler will cause the following code to be executed char buffer[JMSG_LENGTH_MAX]; (*cinfo.err->format_message)(OFreinterpret_cast(jpeg_common_struct*, &cinfo), buffer); /* Create the message */ jpeg_destroy_compress(&cinfo); return makeOFCondition(OFM_dcmjpeg, EJCode_IJG16_Compression, OF_error, buffer); } OFjpeg_create_compress(&cinfo); // initialize client_data cinfo.client_data = this; // Specify destination manager jpeg_destination_mgr dest; dest.init_destination = DJEIJG16initDestination; dest.empty_output_buffer = DJEIJG16emptyOutputBuffer; dest.term_destination = DJEIJG16termDestination; cinfo.dest = &dest; cinfo.image_width = columns; cinfo.image_height = rows; cinfo.input_components = samplesPerPixel; cinfo.in_color_space = getJpegColorSpace(colorSpace); jpeg_set_defaults(&cinfo); if (cparam->getCompressionColorSpaceConversion() != ECC_lossyYCbCr) { // prevent IJG library from doing any color space conversion jpeg_set_colorspace (&cinfo, cinfo.in_color_space); } cinfo.optimize_coding = OFTrue; // must always be true for 16 bit compression switch (modeofOperation) { case EJM_lossless: // always disables any kind of color space conversion jpeg_simple_lossless(&cinfo,psv,pt); break; default: return makeOFCondition(OFM_dcmjpeg, EJCode_IJG16_Compression, OF_error, "JPEG with 16 bits/sample only allowed with lossless compression"); /* break; */ } cinfo.smoothing_factor = cparam->getSmoothingFactor(); // initialize sampling factors if ((cinfo.jpeg_color_space == JCS_YCbCr) && (modeofOperation != EJM_lossless)) { switch(cparam->getSampleFactors()) { case ESS_444: /* 4:4:4 sampling (no subsampling) */ cinfo.comp_info[0].h_samp_factor = 1; cinfo.comp_info[0].v_samp_factor = 1; break; case ESS_422: /* 4:2:2 sampling (horizontal subsampling of chroma components) */ cinfo.comp_info[0].h_samp_factor = 2; cinfo.comp_info[0].v_samp_factor = 1; break; case ESS_411: /* 4:1:1 sampling (horizontal and vertical subsampling of chroma components) */ cinfo.comp_info[0].h_samp_factor = 2; cinfo.comp_info[0].v_samp_factor = 2; break; } } else { // JPEG color space is not YCbCr, or we are using lossless compression. // Disable subsampling. cinfo.comp_info[0].h_samp_factor = 1; cinfo.comp_info[0].v_samp_factor = 1; } // all other components are set to 1x1 for (int sfi=1; sfi< MAX_COMPONENTS; sfi++) { cinfo.comp_info[sfi].h_samp_factor = 1; cinfo.comp_info[sfi].v_samp_factor = 1; } JSAMPROW row_pointer[1]; jpeg_start_compress(&cinfo,TRUE); int row_stride = columns * samplesPerPixel; while (cinfo.next_scanline < cinfo.image_height) { // JSAMPLE might be signed, typecast to avoid a warning row_pointer[0] = OFreinterpret_cast(JSAMPLE*, image_buffer + (cinfo.next_scanline * row_stride)); jpeg_write_scanlines(&cinfo, row_pointer, 1); } jpeg_finish_compress(&cinfo); jpeg_destroy_compress(&cinfo); length = OFstatic_cast(Uint32, bytesInLastBlock); if (pixelDataList.size() > 1) length += OFstatic_cast(Uint32, (pixelDataList.size() - 1)*IJGE16_BLOCKSIZE); OFBool length_is_odd = (length % 2) > 0; if (length_is_odd) length++; // ensure even length to = new Uint8[length]; if (to == NULL) return EC_MemoryExhausted; size_t offset=0; OFListIterator(unsigned char *) first = pixelDataList.begin(); OFListIterator(unsigned char *) last = pixelDataList.end(); OFListIterator(unsigned char *) shortBlock = last; --shortBlock; while (first != last) { if (first == shortBlock) { memcpy(to+offset, *first, bytesInLastBlock); offset += bytesInLastBlock; } else { memcpy(to+offset, *first, IJGE16_BLOCKSIZE); offset += IJGE16_BLOCKSIZE; } ++first; } if (length_is_odd) DcmJpegHelper::fixPadding(to, length); cleanup(); return EC_Normal; } void DJCompressIJG16Bit::initDestination(jpeg_compress_struct *cinfo) { cleanup(); // erase old list of compressed blocks, if any unsigned char *newBlock = new unsigned char[IJGE16_BLOCKSIZE]; if (newBlock) { pixelDataList.push_back(newBlock); cinfo->dest->next_output_byte = newBlock; cinfo->dest->free_in_buffer = IJGE16_BLOCKSIZE; } else { cinfo->dest->next_output_byte = NULL; cinfo->dest->free_in_buffer = 0; } } int DJCompressIJG16Bit::emptyOutputBuffer(jpeg_compress_struct *cinfo) { bytesInLastBlock = 0; unsigned char *newBlock = new unsigned char[IJGE16_BLOCKSIZE]; if (newBlock) { pixelDataList.push_back(newBlock); cinfo->dest->next_output_byte = newBlock; cinfo->dest->free_in_buffer = IJGE16_BLOCKSIZE; } else { cinfo->dest->next_output_byte = NULL; cinfo->dest->free_in_buffer = 0; OF_ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, 0xFF); } return TRUE; } void DJCompressIJG16Bit::termDestination(jpeg_compress_struct *cinfo) { bytesInLastBlock = IJGE16_BLOCKSIZE - cinfo->dest->free_in_buffer; } void DJCompressIJG16Bit::cleanup() { OFListIterator(unsigned char *) first = pixelDataList.begin(); OFListIterator(unsigned char *) last = pixelDataList.end(); while (first != last) { delete[] *first; first = pixelDataList.erase(first); } bytesInLastBlock = 0; } void DJCompressIJG16Bit::emitMessage(void *arg, int msg_level) const { jpeg_common_struct *cinfo = OFreinterpret_cast(jpeg_common_struct*, arg); // This is how we map the message levels: // -1 - 0: Warning (could also be errors, but no way to find out) // 1 : Debug // Everything else: Trace (No point in splitting this further up) OFLogger::LogLevel level; switch (msg_level) { case -1: case 0: level = OFLogger::WARN_LOG_LEVEL; break; case 1: level = OFLogger::DEBUG_LOG_LEVEL; break; default: level = OFLogger::TRACE_LOG_LEVEL; break; } if (cinfo && DCM_dcmjpegLogger.isEnabledFor(level)) { char buffer[JMSG_LENGTH_MAX]; (*cinfo->err->format_message)(cinfo, buffer); /* Create the message */ DCM_dcmjpegLogger.forcedLog(level, buffer, __FILE__, __LINE__); } }
{ "pile_set_name": "Github" }
# # Solution to Project Euler problem 118 # Copyright (c) Project Nayuki. All rights reserved. # # https://www.nayuki.io/page/project-euler-solutions # https://github.com/nayuki/Project-Euler-solutions # import eulerlib def compute(): isprime = eulerlib.list_primality(10000) # Cache for small numbers digits = list(range(1, 10)) def count_prime_sets(startindex, prevnum): if startindex == len(digits): return 1 else: result = 0 for split in range(startindex + 1, len(digits) + 1): num = int("".join(map(str, digits[startindex : split]))) if num > prevnum and is_prime(num): result += count_prime_sets(split, num) return result def is_prime(n): if n < len(isprime): return isprime[n] else: return eulerlib.is_prime(n) ans = 0 while True: ans += count_prime_sets(0, 0) if not eulerlib.next_permutation(digits): break return str(ans) if __name__ == "__main__": print(compute())
{ "pile_set_name": "Github" }
/* * Copyright (c) 2008 Jakub Jermar * 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. * - The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. */ /** @addtogroup fat * @{ */ /** * @file fat_idx.c * @brief Layer for translating FAT entities to VFS node indices. */ #include "fat.h" #include "../../vfs/vfs.h" #include <errno.h> #include <str.h> #include <adt/hash_table.h> #include <adt/hash.h> #include <adt/list.h> #include <assert.h> #include <fibril_synch.h> #include <stdlib.h> /** Each instance of this type describes one interval of freed VFS indices. */ typedef struct { link_t link; fs_index_t first; fs_index_t last; } freed_t; /** * Each instance of this type describes state of all VFS indices that * are currently unused. */ typedef struct { link_t link; service_id_t service_id; /** Next unassigned index. */ fs_index_t next; /** Number of remaining unassigned indices. */ uint64_t remaining; /** Sorted list of intervals of freed indices. */ list_t freed_list; } unused_t; /** Mutex protecting the list of unused structures. */ static FIBRIL_MUTEX_INITIALIZE(unused_lock); /** List of unused structures. */ static LIST_INITIALIZE(unused_list); static void unused_initialize(unused_t *u, service_id_t service_id) { link_initialize(&u->link); u->service_id = service_id; u->next = 0; u->remaining = ((uint64_t)((fs_index_t)-1)) + 1; list_initialize(&u->freed_list); } static unused_t *unused_find(service_id_t service_id, bool lock) { if (lock) fibril_mutex_lock(&unused_lock); list_foreach(unused_list, link, unused_t, u) { if (u->service_id == service_id) return u; } if (lock) fibril_mutex_unlock(&unused_lock); return NULL; } /** Mutex protecting the up_hash and ui_hash. */ static FIBRIL_MUTEX_INITIALIZE(used_lock); /** * Global hash table of all used fat_idx_t structures. * The index structures are hashed by the service_id, parent node's first * cluster and index within the parent directory. */ static hash_table_t up_hash; typedef struct { service_id_t service_id; fat_cluster_t pfc; unsigned pdi; } pos_key_t; static inline size_t pos_key_hash(const void *key) { const pos_key_t *pos = key; size_t hash = 0; hash = hash_combine(pos->pfc, pos->pdi); return hash_combine(hash, pos->service_id); } static size_t pos_hash(const ht_link_t *item) { fat_idx_t *fidx = hash_table_get_inst(item, fat_idx_t, uph_link); pos_key_t pkey = { .service_id = fidx->service_id, .pfc = fidx->pfc, .pdi = fidx->pdi, }; return pos_key_hash(&pkey); } static bool pos_key_equal(const void *key, const ht_link_t *item) { const pos_key_t *pos = key; fat_idx_t *fidx = hash_table_get_inst(item, fat_idx_t, uph_link); return pos->service_id == fidx->service_id && pos->pdi == fidx->pdi && pos->pfc == fidx->pfc; } static hash_table_ops_t uph_ops = { .hash = pos_hash, .key_hash = pos_key_hash, .key_equal = pos_key_equal, .equal = NULL, .remove_callback = NULL, }; /** * Global hash table of all used fat_idx_t structures. * The index structures are hashed by the service_id and index. */ static hash_table_t ui_hash; typedef struct { service_id_t service_id; fs_index_t index; } idx_key_t; static size_t idx_key_hash(const void *key_arg) { const idx_key_t *key = key_arg; return hash_combine(key->service_id, key->index); } static size_t idx_hash(const ht_link_t *item) { fat_idx_t *fidx = hash_table_get_inst(item, fat_idx_t, uih_link); return hash_combine(fidx->service_id, fidx->index); } static bool idx_key_equal(const void *key_arg, const ht_link_t *item) { fat_idx_t *fidx = hash_table_get_inst(item, fat_idx_t, uih_link); const idx_key_t *key = key_arg; return key->index == fidx->index && key->service_id == fidx->service_id; } static void idx_remove_callback(ht_link_t *item) { fat_idx_t *fidx = hash_table_get_inst(item, fat_idx_t, uih_link); free(fidx); } static hash_table_ops_t uih_ops = { .hash = idx_hash, .key_hash = idx_key_hash, .key_equal = idx_key_equal, .equal = NULL, .remove_callback = idx_remove_callback, }; /** Allocate a VFS index which is not currently in use. */ static bool fat_index_alloc(service_id_t service_id, fs_index_t *index) { unused_t *u; assert(index); u = unused_find(service_id, true); if (!u) return false; if (list_empty(&u->freed_list)) { if (u->remaining) { /* * There are no freed indices, allocate one directly * from the counter. */ *index = u->next++; --u->remaining; fibril_mutex_unlock(&unused_lock); return true; } } else { /* There are some freed indices which we can reuse. */ freed_t *f = list_get_instance(list_first(&u->freed_list), freed_t, link); *index = f->first; if (f->first++ == f->last) { /* Destroy the interval. */ list_remove(&f->link); free(f); } fibril_mutex_unlock(&unused_lock); return true; } /* * We ran out of indices, which is extremely unlikely with FAT16, but * theoretically still possible (e.g. too many open unlinked nodes or * too many zero-sized nodes). */ fibril_mutex_unlock(&unused_lock); return false; } /** If possible, coalesce two intervals of freed indices. */ static void try_coalesce_intervals(link_t *l, link_t *r, link_t *cur) { freed_t *fl = list_get_instance(l, freed_t, link); freed_t *fr = list_get_instance(r, freed_t, link); if (fl->last + 1 == fr->first) { if (cur == l) { fl->last = fr->last; list_remove(r); free(r); } else { fr->first = fl->first; list_remove(l); free(l); } } } /** Free a VFS index, which is no longer in use. */ static void fat_index_free(service_id_t service_id, fs_index_t index) { unused_t *u; u = unused_find(service_id, true); assert(u); if (u->next == index + 1) { /* The index can be returned directly to the counter. */ u->next--; u->remaining++; } else { /* * The index must be returned either to an existing freed * interval or a new interval must be created. */ link_t *lnk; freed_t *n; for (lnk = u->freed_list.head.next; lnk != &u->freed_list.head; lnk = lnk->next) { freed_t *f = list_get_instance(lnk, freed_t, link); if (f->first == index + 1) { f->first--; if (lnk->prev != &u->freed_list.head) try_coalesce_intervals(lnk->prev, lnk, lnk); fibril_mutex_unlock(&unused_lock); return; } if (f->last == index - 1) { f->last++; if (lnk->next != &u->freed_list.head) try_coalesce_intervals(lnk, lnk->next, lnk); fibril_mutex_unlock(&unused_lock); return; } if (index > f->first) { n = malloc(sizeof(freed_t)); /* TODO: sleep until allocation succeeds */ assert(n); link_initialize(&n->link); n->first = index; n->last = index; list_insert_before(&n->link, lnk); fibril_mutex_unlock(&unused_lock); return; } } /* The index will form the last interval. */ n = malloc(sizeof(freed_t)); /* TODO: sleep until allocation succeeds */ assert(n); link_initialize(&n->link); n->first = index; n->last = index; list_append(&n->link, &u->freed_list); } fibril_mutex_unlock(&unused_lock); } static errno_t fat_idx_create(fat_idx_t **fidxp, service_id_t service_id) { fat_idx_t *fidx; fidx = (fat_idx_t *) malloc(sizeof(fat_idx_t)); if (!fidx) return ENOMEM; if (!fat_index_alloc(service_id, &fidx->index)) { free(fidx); return ENOSPC; } fibril_mutex_initialize(&fidx->lock); fidx->service_id = service_id; fidx->pfc = FAT_CLST_RES0; /* no parent yet */ fidx->pdi = 0; fidx->nodep = NULL; *fidxp = fidx; return EOK; } errno_t fat_idx_get_new(fat_idx_t **fidxp, service_id_t service_id) { fat_idx_t *fidx; errno_t rc; fibril_mutex_lock(&used_lock); rc = fat_idx_create(&fidx, service_id); if (rc != EOK) { fibril_mutex_unlock(&used_lock); return rc; } hash_table_insert(&ui_hash, &fidx->uih_link); fibril_mutex_lock(&fidx->lock); fibril_mutex_unlock(&used_lock); *fidxp = fidx; return EOK; } fat_idx_t * fat_idx_get_by_pos(service_id_t service_id, fat_cluster_t pfc, unsigned pdi) { fat_idx_t *fidx; pos_key_t pos_key = { .service_id = service_id, .pfc = pfc, .pdi = pdi, }; fibril_mutex_lock(&used_lock); ht_link_t *l = hash_table_find(&up_hash, &pos_key); if (l) { fidx = hash_table_get_inst(l, fat_idx_t, uph_link); } else { errno_t rc; rc = fat_idx_create(&fidx, service_id); if (rc != EOK) { fibril_mutex_unlock(&used_lock); return NULL; } fidx->pfc = pfc; fidx->pdi = pdi; hash_table_insert(&up_hash, &fidx->uph_link); hash_table_insert(&ui_hash, &fidx->uih_link); } fibril_mutex_lock(&fidx->lock); fibril_mutex_unlock(&used_lock); return fidx; } void fat_idx_hashin(fat_idx_t *idx) { fibril_mutex_lock(&used_lock); hash_table_insert(&up_hash, &idx->uph_link); fibril_mutex_unlock(&used_lock); } void fat_idx_hashout(fat_idx_t *idx) { fibril_mutex_lock(&used_lock); hash_table_remove_item(&up_hash, &idx->uph_link); fibril_mutex_unlock(&used_lock); } fat_idx_t * fat_idx_get_by_index(service_id_t service_id, fs_index_t index) { fat_idx_t *fidx = NULL; idx_key_t idx_key = { .service_id = service_id, .index = index, }; fibril_mutex_lock(&used_lock); ht_link_t *l = hash_table_find(&ui_hash, &idx_key); if (l) { fidx = hash_table_get_inst(l, fat_idx_t, uih_link); fibril_mutex_lock(&fidx->lock); } fibril_mutex_unlock(&used_lock); return fidx; } /** Destroy the index structure. * * @param idx The index structure to be destroyed. */ void fat_idx_destroy(fat_idx_t *idx) { idx_key_t idx_key = { .service_id = idx->service_id, .index = idx->index, }; assert(idx->pfc == FAT_CLST_RES0); fibril_mutex_lock(&used_lock); /* * Since we can only free unlinked nodes, the index structure is not * present in the position hash (uph). We therefore hash it out from * the index hash only. */ hash_table_remove(&ui_hash, &idx_key); fibril_mutex_unlock(&used_lock); /* Release the VFS index. */ fat_index_free(idx_key.service_id, idx_key.index); /* The index structure itself is freed in idx_remove_callback(). */ } errno_t fat_idx_init(void) { if (!hash_table_create(&up_hash, 0, 0, &uph_ops)) return ENOMEM; if (!hash_table_create(&ui_hash, 0, 0, &uih_ops)) { hash_table_destroy(&up_hash); return ENOMEM; } return EOK; } void fat_idx_fini(void) { /* We assume the hash tables are empty. */ assert(hash_table_empty(&up_hash) && hash_table_empty(&ui_hash)); hash_table_destroy(&up_hash); hash_table_destroy(&ui_hash); } errno_t fat_idx_init_by_service_id(service_id_t service_id) { unused_t *u; errno_t rc = EOK; u = (unused_t *) malloc(sizeof(unused_t)); if (!u) return ENOMEM; unused_initialize(u, service_id); fibril_mutex_lock(&unused_lock); if (!unused_find(service_id, false)) { list_append(&u->link, &unused_list); } else { free(u); rc = EEXIST; } fibril_mutex_unlock(&unused_lock); return rc; } static bool rm_pos_service_id(ht_link_t *item, void *arg) { service_id_t service_id = *(service_id_t *)arg; fat_idx_t *fidx = hash_table_get_inst(item, fat_idx_t, uph_link); if (fidx->service_id == service_id) { hash_table_remove_item(&up_hash, item); } return true; } static bool rm_idx_service_id(ht_link_t *item, void *arg) { service_id_t service_id = *(service_id_t *)arg; fat_idx_t *fidx = hash_table_get_inst(item, fat_idx_t, uih_link); if (fidx->service_id == service_id) { hash_table_remove_item(&ui_hash, item); } return true; } void fat_idx_fini_by_service_id(service_id_t service_id) { /* * Remove this instance's index structure from up_hash and ui_hash. * Process up_hash first and ui_hash second because the index structure * is actually removed in idx_remove_callback(). */ fibril_mutex_lock(&used_lock); hash_table_apply(&up_hash, rm_pos_service_id, &service_id); hash_table_apply(&ui_hash, rm_idx_service_id, &service_id); fibril_mutex_unlock(&used_lock); /* * Free the unused and freed structures for this instance. */ unused_t *u = unused_find(service_id, true); assert(u); list_remove(&u->link); fibril_mutex_unlock(&unused_lock); while (!list_empty(&u->freed_list)) { freed_t *f; f = list_get_instance(list_first(&u->freed_list), freed_t, link); list_remove(&f->link); free(f); } free(u); } /** * @} */
{ "pile_set_name": "Github" }
/* * Copyright (c) 2016 Intel Corporation, Inc. All rights reserved. * * This software is available to you under a choice of one of two * licenses. You may choose to be licensed under the terms of the GNU * General Public License (GPL) Version 2, available from the file * COPYING in the main directory of this source tree, or the * BSD license below: * * 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. * * 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. */ /* Do not remove this file. See fi_direct.h */
{ "pile_set_name": "Github" }
/* * Copyright Andrey Semashev 2007 - 2015. * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE_1_0.txt or copy at * http://www.boost.org/LICENSE_1_0.txt) */ /*! * \file timestamp.hpp * \author Andrey Semashev * \date 31.07.2011 * * \brief This header is the Boost.Log library implementation, see the library documentation * at http://www.boost.org/doc/libs/release/libs/log/doc/html/index.html. */ #ifndef BOOST_LOG_DETAIL_TIMESTAMP_HPP_INCLUDED_ #define BOOST_LOG_DETAIL_TIMESTAMP_HPP_INCLUDED_ #include <boost/cstdint.hpp> #include <boost/log/detail/config.hpp> #if defined(BOOST_WINDOWS) && !defined(__CYGWIN__) #include <boost/winapi/basic_types.hpp> #endif #include <boost/log/detail/header.hpp> #ifdef BOOST_HAS_PRAGMA_ONCE #pragma once #endif namespace boost { BOOST_LOG_OPEN_NAMESPACE namespace aux { /*! * Duration between two timestamps */ class duration { int64_t m_ticks; public: explicit duration(int64_t ticks = 0) : m_ticks(ticks) {} #if defined(BOOST_WINDOWS) && !defined(__CYGWIN__) int64_t milliseconds() const { return m_ticks; } #else BOOST_LOG_API int64_t milliseconds() const; #endif }; /*! * Opaque timestamp class */ class timestamp { uint64_t m_ticks; public: explicit timestamp(uint64_t ticks = 0) : m_ticks(ticks) {} duration operator- (timestamp that) const { return duration(m_ticks - that.m_ticks); } }; /*! * \fn get_timestamp * * The function returns a timestamp, in opaque units since an unspecified * time point. This timer is guaranteed to be monotonic, it should not * be affected by clock changes, either manual or seasonal. Also, it * should be as fast as possible. */ #if defined(BOOST_WINDOWS) && !defined(__CYGWIN__) typedef uint64_t (BOOST_WINAPI_WINAPI_CC* get_tick_count_t)(); extern BOOST_LOG_API get_tick_count_t get_tick_count; inline timestamp get_timestamp() { return timestamp(get_tick_count()); } #else typedef timestamp (*get_timestamp_t)(); extern BOOST_LOG_API get_timestamp_t get_timestamp; #endif } // namespace aux BOOST_LOG_CLOSE_NAMESPACE // namespace log } // namespace boost #include <boost/log/detail/footer.hpp> #endif // BOOST_LOG_DETAIL_TIMESTAMP_HPP_INCLUDED_
{ "pile_set_name": "Github" }
# 设备 > 设备标准 ## 设备标准 ### 设备标准 一整套关于估量、分辨率以及更多跨设备的全面资源[https://design.google.com/tool/devices/](https://design.google.com/tool/devices/)
{ "pile_set_name": "Github" }
{ "notes": "Firefox OS is reported to have partial support for this property as `x-inputmode`.\r\n\r\nBlink-based browsers appear to recognize the `inputMode` property on `input` & `textarea` fields though it is unclear what effect it currently has as the feature is still in development.", "support": { "Android Browser": "y 67", "Baidu Browser": "n 7.12", "Blackberry Browser": "n 10", "Chrome": "y 66", "Chrome for Android": "y 74", "Edge": "y 75", "Firefox": "n 69", "Firefox for Android": "n 66", "IE": "n 11", "IE Mobile": "n 11", "KaiOS Browser": "n 2.5", "Opera": "y 53", "Opera Mini": "n all", "Opera Mobile": "n 46", "QQ Browser": "n 1.2", "Safari": "n TP", "Samsung Internet": "y 9.2", "UC Browser for Android": "n 11.8", "iOS Safari": "y 12.2" }, "url": "https://html.spec.whatwg.org/multipage/forms.html#input-modalities:-the-inputmode-attribute" }
{ "pile_set_name": "Github" }
/*! * Bootstrap Responsive v2.3.1 * * Copyright 2012 Twitter, Inc * Licensed under the Apache License v2.0 * http://www.apache.org/licenses/LICENSE-2.0 * * Designed and built with all the love in the world @twitter by @mdo and @fat. */ .clearfix { *zoom: 1; } .clearfix:before, .clearfix:after { display: table; line-height: 0; content: ""; } .clearfix:after { clear: both; } .hide-text { font: 0/0 a; color: transparent; text-shadow: none; background-color: transparent; border: 0; } .input-block-level { display: block; width: 100%; min-height: 30px; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } @-ms-viewport { width: device-width; } .hidden { display: none; visibility: hidden; } .visible-phone { display: none !important; } .visible-tablet { display: none !important; } .hidden-desktop { display: none !important; } .visible-desktop { display: inherit !important; } @media (min-width: 768px) and (max-width: 979px) { .hidden-desktop { display: inherit !important; } .visible-desktop { display: none !important ; } .visible-tablet { display: inherit !important; } .hidden-tablet { display: none !important; } } @media (max-width: 767px) { .hidden-desktop { display: inherit !important; } .visible-desktop { display: none !important; } .visible-phone { display: inherit !important; } .hidden-phone { display: none !important; } } .visible-print { display: none !important; } @media print { .visible-print { display: inherit !important; } .hidden-print { display: none !important; } } @media (min-width: 1200px) { .row { margin-left: -30px; *zoom: 1; } .row:before, .row:after { display: table; line-height: 0; content: ""; } .row:after { clear: both; } [class*="span"] { float: left; min-height: 1px; margin-left: 30px; } .container, .navbar-static-top .container, .navbar-fixed-top .container, .navbar-fixed-bottom .container { width: 1170px; } .span12 { width: 1170px; } .span11 { width: 1070px; } .span10 { width: 970px; } .span9 { width: 870px; } .span8 { width: 770px; } .span7 { width: 670px; } .span6 { width: 570px; } .span5 { width: 470px; } .span4 { width: 370px; } .span3 { width: 270px; } .span2 { width: 170px; } .span1 { width: 70px; } .offset12 { margin-left: 1230px; } .offset11 { margin-left: 1130px; } .offset10 { margin-left: 1030px; } .offset9 { margin-left: 930px; } .offset8 { margin-left: 830px; } .offset7 { margin-left: 730px; } .offset6 { margin-left: 630px; } .offset5 { margin-left: 530px; } .offset4 { margin-left: 430px; } .offset3 { margin-left: 330px; } .offset2 { margin-left: 230px; } .offset1 { margin-left: 130px; } .row-fluid { width: 100%; *zoom: 1; } .row-fluid:before, .row-fluid:after { display: table; line-height: 0; content: ""; } .row-fluid:after { clear: both; } .row-fluid [class*="span"] { display: block; float: left; width: 100%; min-height: 30px; margin-left: 2.564102564102564%; *margin-left: 2.5109110747408616%; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } .row-fluid [class*="span"]:first-child { margin-left: 0; } .row-fluid .controls-row [class*="span"] + [class*="span"] { margin-left: 2.564102564102564%; } .row-fluid .span12 { width: 100%; *width: 99.94680851063829%; } .row-fluid .span11 { width: 91.45299145299145%; *width: 91.39979996362975%; } .row-fluid .span10 { width: 82.90598290598291%; *width: 82.8527914166212%; } .row-fluid .span9 { width: 74.35897435897436%; *width: 74.30578286961266%; } .row-fluid .span8 { width: 65.81196581196582%; *width: 65.75877432260411%; } .row-fluid .span7 { width: 57.26495726495726%; *width: 57.21176577559556%; } .row-fluid .span6 { width: 48.717948717948715%; *width: 48.664757228587014%; } .row-fluid .span5 { width: 40.17094017094017%; *width: 40.11774868157847%; } .row-fluid .span4 { width: 31.623931623931625%; *width: 31.570740134569924%; } .row-fluid .span3 { width: 23.076923076923077%; *width: 23.023731587561375%; } .row-fluid .span2 { width: 14.52991452991453%; *width: 14.476723040552828%; } .row-fluid .span1 { width: 5.982905982905983%; *width: 5.929714493544281%; } .row-fluid .offset12 { margin-left: 105.12820512820512%; *margin-left: 105.02182214948171%; } .row-fluid .offset12:first-child { margin-left: 102.56410256410257%; *margin-left: 102.45771958537915%; } .row-fluid .offset11 { margin-left: 96.58119658119658%; *margin-left: 96.47481360247316%; } .row-fluid .offset11:first-child { margin-left: 94.01709401709402%; *margin-left: 93.91071103837061%; } .row-fluid .offset10 { margin-left: 88.03418803418803%; *margin-left: 87.92780505546462%; } .row-fluid .offset10:first-child { margin-left: 85.47008547008548%; *margin-left: 85.36370249136206%; } .row-fluid .offset9 { margin-left: 79.48717948717949%; *margin-left: 79.38079650845607%; } .row-fluid .offset9:first-child { margin-left: 76.92307692307693%; *margin-left: 76.81669394435352%; } .row-fluid .offset8 { margin-left: 70.94017094017094%; *margin-left: 70.83378796144753%; } .row-fluid .offset8:first-child { margin-left: 68.37606837606839%; *margin-left: 68.26968539734497%; } .row-fluid .offset7 { margin-left: 62.393162393162385%; *margin-left: 62.28677941443899%; } .row-fluid .offset7:first-child { margin-left: 59.82905982905982%; *margin-left: 59.72267685033642%; } .row-fluid .offset6 { margin-left: 53.84615384615384%; *margin-left: 53.739770867430444%; } .row-fluid .offset6:first-child { margin-left: 51.28205128205128%; *margin-left: 51.175668303327875%; } .row-fluid .offset5 { margin-left: 45.299145299145295%; *margin-left: 45.1927623204219%; } .row-fluid .offset5:first-child { margin-left: 42.73504273504273%; *margin-left: 42.62865975631933%; } .row-fluid .offset4 { margin-left: 36.75213675213675%; *margin-left: 36.645753773413354%; } .row-fluid .offset4:first-child { margin-left: 34.18803418803419%; *margin-left: 34.081651209310785%; } .row-fluid .offset3 { margin-left: 28.205128205128204%; *margin-left: 28.0987452264048%; } .row-fluid .offset3:first-child { margin-left: 25.641025641025642%; *margin-left: 25.53464266230224%; } .row-fluid .offset2 { margin-left: 19.65811965811966%; *margin-left: 19.551736679396257%; } .row-fluid .offset2:first-child { margin-left: 17.094017094017094%; *margin-left: 16.98763411529369%; } .row-fluid .offset1 { margin-left: 11.11111111111111%; *margin-left: 11.004728132387708%; } .row-fluid .offset1:first-child { margin-left: 8.547008547008547%; *margin-left: 8.440625568285142%; } input, textarea, .uneditable-input { margin-left: 0; } .controls-row [class*="span"] + [class*="span"] { margin-left: 30px; } input.span12, textarea.span12, .uneditable-input.span12 { width: 1156px; } input.span11, textarea.span11, .uneditable-input.span11 { width: 1056px; } input.span10, textarea.span10, .uneditable-input.span10 { width: 956px; } input.span9, textarea.span9, .uneditable-input.span9 { width: 856px; } input.span8, textarea.span8, .uneditable-input.span8 { width: 756px; } input.span7, textarea.span7, .uneditable-input.span7 { width: 656px; } input.span6, textarea.span6, .uneditable-input.span6 { width: 556px; } input.span5, textarea.span5, .uneditable-input.span5 { width: 456px; } input.span4, textarea.span4, .uneditable-input.span4 { width: 356px; } input.span3, textarea.span3, .uneditable-input.span3 { width: 256px; } input.span2, textarea.span2, .uneditable-input.span2 { width: 156px; } input.span1, textarea.span1, .uneditable-input.span1 { width: 56px; } .thumbnails { margin-left: -30px; } .thumbnails > li { margin-left: 30px; } .row-fluid .thumbnails { margin-left: 0; } } @media (min-width: 768px) and (max-width: 979px) { .row { margin-left: -20px; *zoom: 1; } .row:before, .row:after { display: table; line-height: 0; content: ""; } .row:after { clear: both; } [class*="span"] { float: left; min-height: 1px; margin-left: 20px; } .container, .navbar-static-top .container, .navbar-fixed-top .container, .navbar-fixed-bottom .container { width: 724px; } .span12 { width: 724px; } .span11 { width: 662px; } .span10 { width: 600px; } .span9 { width: 538px; } .span8 { width: 476px; } .span7 { width: 414px; } .span6 { width: 352px; } .span5 { width: 290px; } .span4 { width: 228px; } .span3 { width: 166px; } .span2 { width: 104px; } .span1 { width: 42px; } .offset12 { margin-left: 764px; } .offset11 { margin-left: 702px; } .offset10 { margin-left: 640px; } .offset9 { margin-left: 578px; } .offset8 { margin-left: 516px; } .offset7 { margin-left: 454px; } .offset6 { margin-left: 392px; } .offset5 { margin-left: 330px; } .offset4 { margin-left: 268px; } .offset3 { margin-left: 206px; } .offset2 { margin-left: 144px; } .offset1 { margin-left: 82px; } .row-fluid { width: 100%; *zoom: 1; } .row-fluid:before, .row-fluid:after { display: table; line-height: 0; content: ""; } .row-fluid:after { clear: both; } .row-fluid [class*="span"] { display: block; float: left; width: 100%; min-height: 30px; margin-left: 2.7624309392265194%; *margin-left: 2.709239449864817%; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } .row-fluid [class*="span"]:first-child { margin-left: 0; } .row-fluid .controls-row [class*="span"] + [class*="span"] { margin-left: 2.7624309392265194%; } .row-fluid .span12 { width: 100%; *width: 99.94680851063829%; } .row-fluid .span11 { width: 91.43646408839778%; *width: 91.38327259903608%; } .row-fluid .span10 { width: 82.87292817679558%; *width: 82.81973668743387%; } .row-fluid .span9 { width: 74.30939226519337%; *width: 74.25620077583166%; } .row-fluid .span8 { width: 65.74585635359117%; *width: 65.69266486422946%; } .row-fluid .span7 { width: 57.18232044198895%; *width: 57.12912895262725%; } .row-fluid .span6 { width: 48.61878453038674%; *width: 48.56559304102504%; } .row-fluid .span5 { width: 40.05524861878453%; *width: 40.00205712942283%; } .row-fluid .span4 { width: 31.491712707182323%; *width: 31.43852121782062%; } .row-fluid .span3 { width: 22.92817679558011%; *width: 22.87498530621841%; } .row-fluid .span2 { width: 14.3646408839779%; *width: 14.311449394616199%; } .row-fluid .span1 { width: 5.801104972375691%; *width: 5.747913483013988%; } .row-fluid .offset12 { margin-left: 105.52486187845304%; *margin-left: 105.41847889972962%; } .row-fluid .offset12:first-child { margin-left: 102.76243093922652%; *margin-left: 102.6560479605031%; } .row-fluid .offset11 { margin-left: 96.96132596685082%; *margin-left: 96.8549429881274%; } .row-fluid .offset11:first-child { margin-left: 94.1988950276243%; *margin-left: 94.09251204890089%; } .row-fluid .offset10 { margin-left: 88.39779005524862%; *margin-left: 88.2914070765252%; } .row-fluid .offset10:first-child { margin-left: 85.6353591160221%; *margin-left: 85.52897613729868%; } .row-fluid .offset9 { margin-left: 79.8342541436464%; *margin-left: 79.72787116492299%; } .row-fluid .offset9:first-child { margin-left: 77.07182320441989%; *margin-left: 76.96544022569647%; } .row-fluid .offset8 { margin-left: 71.2707182320442%; *margin-left: 71.16433525332079%; } .row-fluid .offset8:first-child { margin-left: 68.50828729281768%; *margin-left: 68.40190431409427%; } .row-fluid .offset7 { margin-left: 62.70718232044199%; *margin-left: 62.600799341718584%; } .row-fluid .offset7:first-child { margin-left: 59.94475138121547%; *margin-left: 59.838368402492065%; } .row-fluid .offset6 { margin-left: 54.14364640883978%; *margin-left: 54.037263430116376%; } .row-fluid .offset6:first-child { margin-left: 51.38121546961326%; *margin-left: 51.27483249088986%; } .row-fluid .offset5 { margin-left: 45.58011049723757%; *margin-left: 45.47372751851417%; } .row-fluid .offset5:first-child { margin-left: 42.81767955801105%; *margin-left: 42.71129657928765%; } .row-fluid .offset4 { margin-left: 37.01657458563536%; *margin-left: 36.91019160691196%; } .row-fluid .offset4:first-child { margin-left: 34.25414364640884%; *margin-left: 34.14776066768544%; } .row-fluid .offset3 { margin-left: 28.45303867403315%; *margin-left: 28.346655695309746%; } .row-fluid .offset3:first-child { margin-left: 25.69060773480663%; *margin-left: 25.584224756083227%; } .row-fluid .offset2 { margin-left: 19.88950276243094%; *margin-left: 19.783119783707537%; } .row-fluid .offset2:first-child { margin-left: 17.12707182320442%; *margin-left: 17.02068884448102%; } .row-fluid .offset1 { margin-left: 11.32596685082873%; *margin-left: 11.219583872105325%; } .row-fluid .offset1:first-child { margin-left: 8.56353591160221%; *margin-left: 8.457152932878806%; } input, textarea, .uneditable-input { margin-left: 0; } .controls-row [class*="span"] + [class*="span"] { margin-left: 20px; } input.span12, textarea.span12, .uneditable-input.span12 { width: 710px; } input.span11, textarea.span11, .uneditable-input.span11 { width: 648px; } input.span10, textarea.span10, .uneditable-input.span10 { width: 586px; } input.span9, textarea.span9, .uneditable-input.span9 { width: 524px; } input.span8, textarea.span8, .uneditable-input.span8 { width: 462px; } input.span7, textarea.span7, .uneditable-input.span7 { width: 400px; } input.span6, textarea.span6, .uneditable-input.span6 { width: 338px; } input.span5, textarea.span5, .uneditable-input.span5 { width: 276px; } input.span4, textarea.span4, .uneditable-input.span4 { width: 214px; } input.span3, textarea.span3, .uneditable-input.span3 { width: 152px; } input.span2, textarea.span2, .uneditable-input.span2 { width: 90px; } input.span1, textarea.span1, .uneditable-input.span1 { width: 28px; } } @media (max-width: 767px) { body { padding-right: 20px; padding-left: 20px; } .navbar-fixed-top, .navbar-fixed-bottom, .navbar-static-top { margin-right: -20px; margin-left: -20px; } .container-fluid { padding: 0; } .dl-horizontal dt { float: none; width: auto; clear: none; text-align: left; } .dl-horizontal dd { margin-left: 0; } .container { width: auto; } .row-fluid { width: 100%; } .row, .thumbnails { margin-left: 0; } .thumbnails > li { float: none; margin-left: 0; } [class*="span"], .uneditable-input[class*="span"], .row-fluid [class*="span"] { display: block; float: none; width: 100%; margin-left: 0; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } .span12, .row-fluid .span12 { width: 100%; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } .row-fluid [class*="offset"]:first-child { margin-left: 0; } .input-large, .input-xlarge, .input-xxlarge, input[class*="span"], select[class*="span"], textarea[class*="span"], .uneditable-input { display: block; width: 100%; min-height: 30px; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } .input-prepend input, .input-append input, .input-prepend input[class*="span"], .input-append input[class*="span"] { display: inline-block; width: auto; } .controls-row [class*="span"] + [class*="span"] { margin-left: 0; } .modal { position: fixed; top: 20px; right: 20px; left: 20px; width: auto; margin: 0; } .modal.fade { top: -100px; } .modal.fade.in { top: 20px; } } @media (max-width: 480px) { .nav-collapse { -webkit-transform: translate3d(0, 0, 0); } .page-header h1 small { display: block; line-height: 20px; } input[type="checkbox"], input[type="radio"] { border: 1px solid #ccc; } .form-horizontal .control-label { float: none; width: auto; padding-top: 0; text-align: left; } .form-horizontal .controls { margin-left: 0; } .form-horizontal .control-list { padding-top: 0; } .form-horizontal .form-actions { padding-right: 10px; padding-left: 10px; } .media .pull-left, .media .pull-right { display: block; float: none; margin-bottom: 10px; } .media-object { margin-right: 0; margin-left: 0; } .modal { top: 10px; right: 10px; left: 10px; } .modal-header .close { padding: 10px; margin: -10px; } .carousel-caption { position: static; } } @media (max-width: 979px) { body { padding-top: 0; } .navbar-fixed-top, .navbar-fixed-bottom { position: static; } .navbar-fixed-top { margin-bottom: 20px; } .navbar-fixed-bottom { margin-top: 20px; } .navbar-fixed-top .navbar-inner, .navbar-fixed-bottom .navbar-inner { padding: 5px; } .navbar .container { width: auto; padding: 0; } .navbar .brand { padding-right: 10px; padding-left: 10px; margin: 0 0 0 -5px; } .nav-collapse { clear: both; } .nav-collapse .nav { float: none; margin: 0 0 10px; } .nav-collapse .nav > li { float: none; } .nav-collapse .nav > li > a { margin-bottom: 2px; } .nav-collapse .nav > .divider-vertical { display: none; } .nav-collapse .nav .nav-header { color: #777777; text-shadow: none; } .nav-collapse .nav > li > a, .nav-collapse .dropdown-menu a { padding: 9px 15px; font-weight: bold; color: #777777; -webkit-border-radius: 3px; -moz-border-radius: 3px; border-radius: 3px; } .nav-collapse .btn { padding: 4px 10px 4px; font-weight: normal; -webkit-border-radius: 4px; -moz-border-radius: 4px; border-radius: 4px; } .nav-collapse .dropdown-menu li + li a { margin-bottom: 2px; } .nav-collapse .nav > li > a:hover, .nav-collapse .nav > li > a:focus, .nav-collapse .dropdown-menu a:hover, .nav-collapse .dropdown-menu a:focus { background-color: #f2f2f2; } .navbar-inverse .nav-collapse .nav > li > a, .navbar-inverse .nav-collapse .dropdown-menu a { color: #999999; } .navbar-inverse .nav-collapse .nav > li > a:hover, .navbar-inverse .nav-collapse .nav > li > a:focus, .navbar-inverse .nav-collapse .dropdown-menu a:hover, .navbar-inverse .nav-collapse .dropdown-menu a:focus { background-color: #111111; } .nav-collapse.in .btn-group { padding: 0; margin-top: 5px; } .nav-collapse .dropdown-menu { position: static; top: auto; left: auto; display: none; float: none; max-width: none; padding: 0; margin: 0 15px; background-color: transparent; border: none; -webkit-border-radius: 0; -moz-border-radius: 0; border-radius: 0; -webkit-box-shadow: none; -moz-box-shadow: none; box-shadow: none; } .nav-collapse .open > .dropdown-menu { display: block; } .nav-collapse .dropdown-menu:before, .nav-collapse .dropdown-menu:after { display: none; } .nav-collapse .dropdown-menu .divider { display: none; } .nav-collapse .nav > li > .dropdown-menu:before, .nav-collapse .nav > li > .dropdown-menu:after { display: none; } .nav-collapse .navbar-form, .nav-collapse .navbar-search { float: none; padding: 10px 15px; margin: 10px 0; border-top: 1px solid #f2f2f2; border-bottom: 1px solid #f2f2f2; -webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.1), 0 1px 0 rgba(255, 255, 255, 0.1); -moz-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.1), 0 1px 0 rgba(255, 255, 255, 0.1); box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.1), 0 1px 0 rgba(255, 255, 255, 0.1); } .navbar-inverse .nav-collapse .navbar-form, .navbar-inverse .nav-collapse .navbar-search { border-top-color: #111111; border-bottom-color: #111111; } .navbar .nav-collapse .nav.pull-right { float: none; margin-left: 0; } .nav-collapse, .nav-collapse.collapse { height: 0; overflow: hidden; } .navbar .btn-navbar { display: block; } .navbar-static .navbar-inner { padding-right: 10px; padding-left: 10px; } } @media (min-width: 980px) { .nav-collapse.collapse { height: auto !important; overflow: visible !important; } }
{ "pile_set_name": "Github" }
#sidebar { width: 280px; }
{ "pile_set_name": "Github" }
# # DO NOT EDIT THIS FILE!!! Edit .\sources. if you want to add a new source # file to this component. This file merely indirects to the real make file # that is shared by all the components of NT # !INCLUDE $(NTMAKEENV)\makefile.def
{ "pile_set_name": "Github" }
package com.in28minutes.soap.webservices.soapcoursemanagement.soap; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.ws.server.endpoint.annotation.Endpoint; import org.springframework.ws.server.endpoint.annotation.PayloadRoot; import org.springframework.ws.server.endpoint.annotation.RequestPayload; import org.springframework.ws.server.endpoint.annotation.ResponsePayload; import com.in28minutes.courses.CourseDetails; import com.in28minutes.courses.DeleteCourseDetailsRequest; import com.in28minutes.courses.DeleteCourseDetailsResponse; import com.in28minutes.courses.GetAllCourseDetailsRequest; import com.in28minutes.courses.GetAllCourseDetailsResponse; import com.in28minutes.courses.GetCourseDetailsRequest; import com.in28minutes.courses.GetCourseDetailsResponse; import com.in28minutes.soap.webservices.soapcoursemanagement.soap.bean.Course; import com.in28minutes.soap.webservices.soapcoursemanagement.soap.exception.CourseNotFoundException; import com.in28minutes.soap.webservices.soapcoursemanagement.soap.service.CourseDetailsService; import com.in28minutes.soap.webservices.soapcoursemanagement.soap.service.CourseDetailsService.Status; @Endpoint public class CourseDetailsEndpoint { @Autowired CourseDetailsService service; // method // input - GetCourseDetailsRequest // output - GetCourseDetailsResponse // http://in28minutes.com/courses // GetCourseDetailsRequest @PayloadRoot(namespace = "http://in28minutes.com/courses", localPart = "GetCourseDetailsRequest") @ResponsePayload public GetCourseDetailsResponse processCourseDetailsRequest(@RequestPayload GetCourseDetailsRequest request) { Course course = service.findById(request.getId()); if (course == null) throw new CourseNotFoundException("Invalid Course Id " + request.getId()); return mapCourseDetails(course); } private GetCourseDetailsResponse mapCourseDetails(Course course) { GetCourseDetailsResponse response = new GetCourseDetailsResponse(); response.setCourseDetails(mapCourse(course)); return response; } private GetAllCourseDetailsResponse mapAllCourseDetails(List<Course> courses) { GetAllCourseDetailsResponse response = new GetAllCourseDetailsResponse(); for (Course course : courses) { CourseDetails mapCourse = mapCourse(course); response.getCourseDetails().add(mapCourse); } return response; } private CourseDetails mapCourse(Course course) { CourseDetails courseDetails = new CourseDetails(); courseDetails.setId(course.getId()); courseDetails.setName(course.getName()); courseDetails.setDescription(course.getDescription()); return courseDetails; } @PayloadRoot(namespace = "http://in28minutes.com/courses", localPart = "GetAllCourseDetailsRequest") @ResponsePayload public GetAllCourseDetailsResponse processAllCourseDetailsRequest( @RequestPayload GetAllCourseDetailsRequest request) { List<Course> courses = service.findAll(); return mapAllCourseDetails(courses); } @PayloadRoot(namespace = "http://in28minutes.com/courses", localPart = "DeleteCourseDetailsRequest") @ResponsePayload public DeleteCourseDetailsResponse deleteCourseDetailsRequest(@RequestPayload DeleteCourseDetailsRequest request) { Status status = service.deleteById(request.getId()); DeleteCourseDetailsResponse response = new DeleteCourseDetailsResponse(); response.setStatus(mapStatus(status)); return response; } private com.in28minutes.courses.Status mapStatus(Status status) { if (status == Status.FAILURE) return com.in28minutes.courses.Status.FAILURE; return com.in28minutes.courses.Status.SUCCESS; } }
{ "pile_set_name": "Github" }
/* * Copyright (c) 2007 Mockito contributors * This program is made available under the terms of the MIT License. */ package org.mockito.internal.stubbing.answers; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail; import org.assertj.core.api.Assertions; import org.junit.Test; import org.mockito.exceptions.base.MockitoException; import org.mockito.exceptions.misusing.WrongTypeOfReturnValue; import org.mockito.internal.invocation.InvocationBuilder; import org.mockito.invocation.Invocation; import org.mockito.invocation.InvocationOnMock; public class ReturnsArgumentAtTest { @Test public void should_be_able_to_return_the_first_parameter() throws Throwable { assertThat(new ReturnsArgumentAt(0).answer(invocationWith("A", "B"))).isEqualTo("A"); } @Test public void should_be_able_to_return_the_second_parameter() throws Throwable { assertThat(new ReturnsArgumentAt(1).answer(invocationWith("A", "B", "C"))).isEqualTo("B"); } @Test public void should_be_able_to_return_the_last_parameter() throws Throwable { assertThat(new ReturnsArgumentAt(-1).answer(invocationWith("A"))).isEqualTo("A"); assertThat(new ReturnsArgumentAt(-1).answer(invocationWith("A", "B"))).isEqualTo("B"); } @Test public void should_be_able_to_return_the_specified_parameter() throws Throwable { assertThat(new ReturnsArgumentAt(0).answer(invocationWith("A", "B", "C"))).isEqualTo("A"); assertThat(new ReturnsArgumentAt(1).answer(invocationWith("A", "B", "C"))).isEqualTo("B"); assertThat(new ReturnsArgumentAt(2).answer(invocationWith("A", "B", "C"))).isEqualTo("C"); } @Test public void should_identify_bad_parameter_type_for_invocation() throws Exception { try { new ReturnsArgumentAt(1) .validateFor( new InvocationBuilder() .method("varargsReturningString") .argTypes(Object[].class) .args(new Object(), new Object(), new Object()) .toInvocation()); Assertions.fail("should scream"); } catch (WrongTypeOfReturnValue ignored) { } try { new ReturnsArgumentAt(0) .validateFor( new InvocationBuilder() .method("oneArray") .argTypes(boolean[].class) .args(true, false, false) .toInvocation()); Assertions.fail("should scream"); } catch (WrongTypeOfReturnValue ignored) { } try { new ReturnsArgumentAt(0) .validateFor( new InvocationBuilder() .method("mixedVarargsReturningString") .argTypes(Object.class, String[].class) .args(new Object(), new String[] {"A", "B", "C"}) .toInvocation()); Assertions.fail("should scream"); } catch (WrongTypeOfReturnValue ignored) { } } @Test public void should_not_scream_when_mixed_vararg_parameter_is_compatible_with_invocation() throws Exception { new ReturnsArgumentAt(1) .validateFor( new InvocationBuilder() .method("mixedVarargsReturningString") .argTypes(Object.class, String[].class) .args(new Object(), new String[] {"A", "B", "C"}) .toInvocation()); } @Test public void should_handle_returning_vararg_as_array() throws Throwable { Invocation mixedVarargsReturningStringArray = new InvocationBuilder() .method("mixedVarargsReturningStringArray") .argTypes(Object.class, String[].class) .args(new Object(), new String[] {"A", "B", "C"}) .toInvocation(); new ReturnsArgumentAt(1).validateFor(mixedVarargsReturningStringArray); assertThat(new ReturnsArgumentAt(1).answer(mixedVarargsReturningStringArray)) .isEqualTo(new String[] {"A", "B", "C"}); Invocation mixedVarargsReturningObjectArray = new InvocationBuilder() .method("mixedVarargsReturningStringArray") .argTypes(Object.class, String[].class) .args(new Object(), new String[] {"A", "B", "C"}) .toInvocation(); new ReturnsArgumentAt(1).validateFor(mixedVarargsReturningObjectArray); assertThat(new ReturnsArgumentAt(1).answer(mixedVarargsReturningObjectArray)) .isEqualTo(new String[] {"A", "B", "C"}); } @Test public void should_raise_an_exception_if_index_is_not_in_allowed_range_at_creation_time() throws Throwable { try { new ReturnsArgumentAt(-30); fail(); } catch (Exception e) { assertThat(e.getMessage()) .containsIgnoringCase("argument index") .containsIgnoringCase("positive number") .contains("1") .containsIgnoringCase("last argument"); } } @Test public void should_allow_possible_argument_types() throws Exception { new ReturnsArgumentAt(0) .validateFor( new InvocationBuilder() .method("intArgumentReturningInt") .argTypes(int.class) .arg(1000) .toInvocation()); new ReturnsArgumentAt(0) .validateFor( new InvocationBuilder() .method("toString") .argTypes(String.class) .arg("whatever") .toInvocation()); new ReturnsArgumentAt(2) .validateFor( new InvocationBuilder() .method("varargsObject") .argTypes(int.class, Object[].class) .args(1000, "Object", "Object") .toInvocation()); new ReturnsArgumentAt(1) .validateFor( new InvocationBuilder() .method("threeArgumentMethod") .argTypes(int.class, Object.class, String.class) .args(1000, "Object", "String") .toInvocation()); } @Test public void should_fail_if_index_is_not_in_range_for_one_arg_invocation() throws Throwable { try { new ReturnsArgumentAt(30) .validateFor(new InvocationBuilder().method("oneArg").arg("A").toInvocation()); fail(); } catch (MockitoException e) { assertThat(e.getMessage()) .containsIgnoringCase("invalid argument index") .containsIgnoringCase("iMethods.oneArg") .containsIgnoringCase("[0] String") .containsIgnoringCase("position") .contains("30"); } } @Test public void should_fail_if_index_is_not_in_range_for_example_with_no_arg_invocation() throws Throwable { try { new ReturnsArgumentAt(ReturnsArgumentAt.LAST_ARGUMENT) .validateFor(new InvocationBuilder().simpleMethod().toInvocation()); fail(); } catch (MockitoException e) { assertThat(e.getMessage()) .containsIgnoringCase("invalid argument index") .containsIgnoringCase("iMethods.simpleMethod") .containsIgnoringCase("no arguments") .containsIgnoringCase("last parameter wanted"); } } @Test public void should_fail_if_argument_type_of_signature_is_incompatible_with_return_type() throws Throwable { try { new ReturnsArgumentAt(2) .validateFor( new InvocationBuilder() .method("varargsReturningString") .argTypes(Object[].class) .args("anyString", new Object(), "anyString") .toInvocation()); fail(); } catch (WrongTypeOfReturnValue e) { assertThat(e.getMessage()) .containsIgnoringCase("argument of type") .containsIgnoringCase("Object") .containsIgnoringCase("varargsReturningString") .containsIgnoringCase("should return") .containsIgnoringCase("String") .containsIgnoringCase("possible argument indexes"); } } @Test public void shouldNotFailWhenArgumentIsGenericAndCompatibleWithReturnType() throws Exception { new ReturnsArgumentAt(0) .validateFor( new InvocationBuilder() .method("genericToString") .argTypes(Object.class) .args("anyString") .toInvocation()); } private static InvocationOnMock invocationWith(Object... parameters) { return new InvocationBuilder() .method("varargsReturningString") .argTypes(Object[].class) .args(new Object[] {parameters}) .toInvocation(); // one vararg param (sic!) } }
{ "pile_set_name": "Github" }
<!-- BEGIN MUNGE: UNVERSIONED_WARNING --> <!-- BEGIN STRIP_FOR_RELEASE --> <img src="http://kubernetes.io/kubernetes/img/warning.png" alt="WARNING" width="25" height="25"> <img src="http://kubernetes.io/kubernetes/img/warning.png" alt="WARNING" width="25" height="25"> <img src="http://kubernetes.io/kubernetes/img/warning.png" alt="WARNING" width="25" height="25"> <img src="http://kubernetes.io/kubernetes/img/warning.png" alt="WARNING" width="25" height="25"> <img src="http://kubernetes.io/kubernetes/img/warning.png" alt="WARNING" width="25" height="25"> <h2>PLEASE NOTE: This document applies to the HEAD of the source tree</h2> If you are using a released version of Kubernetes, you should refer to the docs that go with that version. <!-- TAG RELEASE_LINK, added by the munger automatically --> <strong> The latest release of this document can be found [here](http://releases.k8s.io/release-1.4/docs/devel/gubernator.md). Documentation for other releases can be found at [releases.k8s.io](http://releases.k8s.io). </strong> -- <!-- END STRIP_FOR_RELEASE --> <!-- END MUNGE: UNVERSIONED_WARNING --> # Gubernator *This document is oriented at developers who want to use Gubernator to debug while developing for Kubernetes.* <!-- BEGIN MUNGE: GENERATED_TOC --> - [Gubernator](#gubernator) - [What is Gubernator?](#what-is-gubernator) - [Gubernator Features](#gubernator-features) - [Test Failures list](#test-failures-list) - [Log Filtering](#log-filtering) - [Gubernator for Local Tests](#gubernator-for-local-tests) - [Future Work](#future-work) <!-- END MUNGE: GENERATED_TOC --> ## What is Gubernator? [Gubernator](https://k8s-gubernator.appspot.com/) is a webpage for viewing and filtering Kubernetes test results. Gubernator simplifies the debugging proccess and makes it easier to track down failures by automating many steps commonly taken in searching through logs, and by offering tools to filter through logs to find relevant lines. Gubernator automates the steps of finding the failed tests, displaying relevant logs, and determining the failed pods and the corresponing pod UID, namespace, and container ID. It also allows for filtering of the log files to display relevant lines based on selected keywords, and allows for multiple logs to be woven together by timestamp. Gubernator runs on Google App Engine and fetches logs stored on Google Cloud Storage. ## Gubernator Features ### Test Failures list Issues made by k8s-merge-robot will post a link to a page listing the failed tests. Each failed test comes with the corresponding error log from a junit file and a link to filter logs for that test. Based on the message logged in the junit file, the pod name may be displayed. ![alt text](gubernator-images/testfailures.png) [Test Failures List Example](https://k8s-gubernator.appspot.com/build/kubernetes-jenkins/logs/kubernetes-e2e-gke/11721) ### Log Filtering The log filtering page comes with checkboxes and textboxes to aid in filtering. Filtered keywords will be bolded and lines including keywords will be highlighted. Up to four lines around the line of interest will also be displayed. ![alt text](gubernator-images/filterpage.png) If less than 100 lines are skipped, the "... skipping xx lines ..." message can be clicked to expand and show the hidden lines. Before expansion: ![alt text](gubernator-images/skipping1.png) After expansion: ![alt text](gubernator-images/skipping2.png) If the pod name was displayed in the Test Failures list, it will automatically be included in the filters. If it is not found in the error message, it can be manually entered into the textbox. Once a pod name is entered, the Pod UID, Namespace, and ContainerID may be automatically filled in as well. These can be altered as well. To apply the filter, check off the options corresponding to the filter. ![alt text](gubernator-images/filterpage1.png) To add a filter, type the term to be filtered into the textbox labeled "Add filter:" and press enter. Additional filters will be displayed as checkboxes under the textbox. ![alt text](gubernator-images/filterpage3.png) To choose which logs to view check off the checkboxes corresponding to the logs of interest. If multiple logs are included, the "Weave by timestamp" option can weave the selected logs together based on the timestamp in each line. ![alt text](gubernator-images/filterpage2.png) [Log Filtering Example 1](https://k8s-gubernator.appspot.com/build/kubernetes-jenkins/logs/kubelet-gce-e2e-ci/5535/nodelog?pod=pod-configmaps-b5b876cb-3e1e-11e6-8956-42010af0001d&junit=junit_03.xml&wrap=on&logfiles=%2Fkubernetes-jenkins%2Flogs%2Fkubelet-gce-e2e-ci%2F5535%2Fartifacts%2Ftmp-node-e2e-7a5a3b40-e2e-node-coreos-stable20160622-image%2Fkube-apiserver.log&logfiles=%2Fkubernetes-jenkins%2Flogs%2Fkubelet-gce-e2e-ci%2F5535%2Fartifacts%2Ftmp-node-e2e-7a5a3b40-e2e-node-coreos-stable20160622-image%2Fkubelet.log&UID=on&poduid=b5b8a59e-3e1e-11e6-b358-42010af0001d&ns=e2e-tests-configmap-oi12h&cID=tmp-node-e2e-7a5a3b40-e2e-node-coreos-stable20160622-image) [Log Filtering Example 2](https://k8s-gubernator.appspot.com/build/kubernetes-jenkins/logs/kubernetes-e2e-gke/11721/nodelog?pod=client-containers-a53f813c-503e-11e6-88dd-0242ac110003&junit=junit_19.xml&wrap=on) ### Gubernator for Local Tests *Currently Gubernator can only be used with remote node e2e tests.* **NOTE: Using Gubernator with local tests will publically upload your test logs to Google Cloud Storage** To use Gubernator to view logs from local test runs, set the GUBERNATOR tag to true. A URL link to view the test results will be printed to the console. Please note that running with the Gubernator tag will bypass the user confirmation for uploading to GCS. ```console $ make test-e2e-node REMOTE=true GUBERNATOR=true ... ================================================================ Running gubernator.sh Gubernator linked below: k8s-gubernator.appspot.com/build/yourusername-g8r-logs/logs/e2e-node/timestamp ``` The gubernator.sh script can be run after running a remote node e2e test for the same effect. ```console $ ./test/e2e_node/gubernator.sh Do you want to run gubernator.sh and upload logs publicly to GCS? [y/n]y ... Gubernator linked below: k8s-gubernator.appspot.com/build/yourusername-g8r-logs/logs/e2e-node/timestamp ``` ## Future Work Gubernator provides a framework for debugging failures and introduces useful features. There is still a lot of room for more features and growth to make the debugging process more efficient. How to contribute (see https://github.com/kubernetes/test-infra/blob/master/gubernator/README.md) * Extend GUBERNATOR flag to all local tests * More accurate identification of pod name, container ID, etc. * Change content of logged strings for failures to include more information * Better regex in Gubernator * Automate discovery of more keywords * Volume Name * Disk Name * Pod IP * Clickable API objects in the displayed lines in order to add them as filters * Construct story of pod's lifetime * Have concise view of what a pod went through from when pod was started to failure * Improve UI * Have separate folders of logs in rows instead of in one long column * Improve interface for adding additional features (maybe instead of textbox and checkbox, have chips) <!-- BEGIN MUNGE: GENERATED_ANALYTICS --> [![Analytics](https://kubernetes-site.appspot.com/UA-36037335-10/GitHub/docs/devel/gubernator.md?pixel)]() <!-- END MUNGE: GENERATED_ANALYTICS -->
{ "pile_set_name": "Github" }
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/go-openapi/swag v0.17.0 h1:7wu+dZ5k83kvUWeAb+WUkFiUhDzwGqzTR/NhWzeo1JU= github.com/go-openapi/swag v0.17.0/go.mod h1:DXUve3Dpr1UfpPtxFw+EFuQ41HhCWZfha5jSVRG7C7I= github.com/mailru/easyjson v0.0.0-20180823135443-60711f1a8329 h1:2gxZ0XQIU/5z3Z3bUBu+FXuk2pFbkN6tcwi/pjyaDic= github.com/mailru/easyjson v0.0.0-20180823135443-60711f1a8329/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/stretchr/testify v1.2.2 h1:bSDNvY7ZPG5RlJ8otE/7V6gMiyenm9RtJ7IUVIAoJ1w= github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
{ "pile_set_name": "Github" }
//Copyright (c) 2020 Ultimaker B.V. //CuraEngine is released under the terms of the AGPLv3 or higher. #include "FMatrix4x3.h" //The definitions we're implementing. #include "floatpoint.h" //This matrix gets applied to floating point coordinates. #include "IntPoint.h" //Conversion directly into integer-based coordinates. #include "../settings/types/Ratio.h" //Scale factor. namespace cura { FMatrix4x3 FMatrix4x3::scale(const Ratio scale, const Point3 origin) { FMatrix4x3 result; result.m[0][0] = scale; //X scale. result.m[1][1] = scale; //Y scale. result.m[2][2] = scale; //Z scale. //Apply a transformation to scale it away from the origin. const Ratio delta_scale = scale - 1; result.m[3][0] = delta_scale * -origin.x; //Arrived at by manually applying an inverse move, the scale, then a move. result.m[3][1] = delta_scale * -origin.y; result.m[3][2] = delta_scale * -origin.z; return result; } FMatrix4x3::FMatrix4x3() { m[0][0] = 1.0; m[1][0] = 0.0; m[2][0] = 0.0; m[3][0] = 0.0; m[0][1] = 0.0; m[1][1] = 1.0; m[2][1] = 0.0; m[3][1] = 0.0; m[0][2] = 0.0; m[1][2] = 0.0; m[2][2] = 1.0; m[3][2] = 0.0; } Point3 FMatrix4x3::apply(const FPoint3& p) const { return Point3( MM2INT(p.x * m[0][0] + p.y * m[1][0] + p.z * m[2][0] + m[3][0]), MM2INT(p.x * m[0][1] + p.y * m[1][1] + p.z * m[2][1] + m[3][1]), MM2INT(p.x * m[0][2] + p.y * m[1][2] + p.z * m[2][2] + m[3][2]) ); } Point3 FMatrix4x3::apply(const Point3& p) const { return Point3( m[0][0] * p.x + m[1][0] * p.y + m[2][0] * p.z + m[3][0], m[0][1] * p.x + m[1][1] * p.y + m[2][1] * p.z + m[3][1], m[0][2] * p.x + m[1][2] * p.y + m[2][2] * p.z + m[3][2] ); } }
{ "pile_set_name": "Github" }